|
@@ -3,6 +3,7 @@
|
3
|
3
|
namespace App\Filament\Company\Resources\Accounting\BudgetResource\RelationManagers;
|
4
|
4
|
|
5
|
5
|
use App\Filament\Tables\Columns\DeferredTextInputColumn;
|
|
6
|
+use App\Models\Accounting\Budget;
|
6
|
7
|
use App\Models\Accounting\BudgetAllocation;
|
7
|
8
|
use App\Models\Accounting\BudgetItem;
|
8
|
9
|
use App\Utilities\Currency\CurrencyConverter;
|
|
@@ -18,7 +19,6 @@ use Filament\Tables\Grouping\Group;
|
18
|
19
|
use Filament\Tables\Table;
|
19
|
20
|
use Illuminate\Database\Eloquent\Builder;
|
20
|
21
|
use Illuminate\Database\Eloquent\Collection;
|
21
|
|
-use Livewire\Attributes\On;
|
22
|
22
|
|
23
|
23
|
class BudgetItemsRelationManager extends RelationManager
|
24
|
24
|
{
|
|
@@ -26,39 +26,31 @@ class BudgetItemsRelationManager extends RelationManager
|
26
|
26
|
|
27
|
27
|
protected static bool $isLazy = false;
|
28
|
28
|
|
29
|
|
- // Store changes that are pending
|
30
|
29
|
public array $batchChanges = [];
|
31
|
30
|
|
32
|
|
- #[On('batch-column-changed')]
|
33
|
31
|
public function handleBatchColumnChanged($data): void
|
34
|
32
|
{
|
35
|
|
- // Store the changed value
|
36
|
33
|
$key = "{$data['recordKey']}.{$data['name']}";
|
37
|
34
|
$this->batchChanges[$key] = $data['value'];
|
38
|
35
|
}
|
39
|
36
|
|
40
|
|
- #[On('save-batch-changes')]
|
41
|
37
|
public function saveBatchChanges(): void
|
42
|
38
|
{
|
43
|
39
|
foreach ($this->batchChanges as $key => $value) {
|
44
|
|
- // Parse the composite key
|
45
|
40
|
[$recordKey, $column] = explode('.', $key, 2);
|
46
|
41
|
|
47
|
|
- // Extract period from the column name (e.g., "allocations_by_period.2023-Q1")
|
48
|
|
- preg_match('/allocations_by_period\.(.+)/', $column, $matches);
|
49
|
|
- $period = $matches[1] ?? null;
|
|
42
|
+ preg_match('/amount_(.+)/', $column, $matches);
|
|
43
|
+ $period = str_replace('_', ' ', $matches[1] ?? '');
|
50
|
44
|
|
51
|
45
|
if (! $period) {
|
52
|
46
|
continue;
|
53
|
47
|
}
|
54
|
48
|
|
55
|
|
- // Find the record
|
56
|
49
|
$record = BudgetItem::find($recordKey);
|
57
|
50
|
if (! $record) {
|
58
|
51
|
continue;
|
59
|
52
|
}
|
60
|
53
|
|
61
|
|
- // Update the allocation
|
62
|
54
|
$allocation = $record->allocations->firstWhere('period', $period);
|
63
|
55
|
if ($allocation) {
|
64
|
56
|
$allocation->update(['amount' => $value]);
|
|
@@ -66,15 +58,12 @@ class BudgetItemsRelationManager extends RelationManager
|
66
|
58
|
$record->allocations()->create([
|
67
|
59
|
'period' => $period,
|
68
|
60
|
'amount' => $value,
|
69
|
|
- // Add other required fields
|
70
|
61
|
]);
|
71
|
62
|
}
|
72
|
63
|
}
|
73
|
64
|
|
74
|
|
- // Clear the batch changes
|
75
|
65
|
$this->batchChanges = [];
|
76
|
66
|
|
77
|
|
- // Notify the user
|
78
|
67
|
Notification::make()
|
79
|
68
|
->title('Budget allocations updated')
|
80
|
69
|
->success()
|
|
@@ -83,7 +72,6 @@ class BudgetItemsRelationManager extends RelationManager
|
83
|
72
|
|
84
|
73
|
protected function calculateTotalSum(array $budgetItemIds): int
|
85
|
74
|
{
|
86
|
|
- // Get all applicable periods
|
87
|
75
|
$periods = BudgetAllocation::whereIn('budget_item_id', $budgetItemIds)
|
88
|
76
|
->pluck('period')
|
89
|
77
|
->unique()
|
|
@@ -91,8 +79,6 @@ class BudgetItemsRelationManager extends RelationManager
|
91
|
79
|
->toArray();
|
92
|
80
|
|
93
|
81
|
$total = 0;
|
94
|
|
-
|
95
|
|
- // Sum up each period
|
96
|
82
|
foreach ($periods as $period) {
|
97
|
83
|
$total += $this->calculatePeriodSum($budgetItemIds, $period);
|
98
|
84
|
}
|
|
@@ -102,26 +88,20 @@ class BudgetItemsRelationManager extends RelationManager
|
102
|
88
|
|
103
|
89
|
protected function calculatePeriodSum(array $budgetItemIds, string $period): int
|
104
|
90
|
{
|
105
|
|
- // First get database values
|
106
|
91
|
$dbTotal = BudgetAllocation::whereIn('budget_item_id', $budgetItemIds)
|
107
|
92
|
->where('period', $period)
|
108
|
93
|
->sum('amount');
|
109
|
94
|
|
110
|
|
- // Now add any batch changes
|
111
|
95
|
$batchTotal = 0;
|
112
|
96
|
foreach ($budgetItemIds as $itemId) {
|
113
|
|
- $key = "{$itemId}.allocations_by_period.{$period}";
|
|
97
|
+ $key = "{$itemId}.amount_" . str_replace(['-', '.', ' '], '_', $period);
|
114
|
98
|
if (isset($this->batchChanges[$key])) {
|
115
|
|
- // Get the current value from batch changes
|
116
|
99
|
$batchValue = CurrencyConverter::convertToCents($this->batchChanges[$key]);
|
117
|
|
-
|
118
|
|
- // Find if there's a current allocation in DB
|
119
|
100
|
$existingAmount = BudgetAllocation::where('budget_item_id', $itemId)
|
120
|
101
|
->where('period', $period)
|
121
|
102
|
->first()
|
122
|
|
- ->getRawOriginal('amount');
|
|
103
|
+ ?->getRawOriginal('amount') ?? 0;
|
123
|
104
|
|
124
|
|
- // Add the difference to our running total
|
125
|
105
|
$batchTotal += ($batchValue - $existingAmount);
|
126
|
106
|
}
|
127
|
107
|
}
|
|
@@ -131,59 +111,44 @@ class BudgetItemsRelationManager extends RelationManager
|
131
|
111
|
|
132
|
112
|
public function table(Table $table): Table
|
133
|
113
|
{
|
|
114
|
+ /** @var Budget $budget */
|
134
|
115
|
$budget = $this->getOwnerRecord();
|
135
|
|
-
|
136
|
|
- // Get distinct periods for this budget
|
137
|
|
- $periods = BudgetAllocation::query()
|
138
|
|
- ->join('budget_items', 'budget_allocations.budget_item_id', '=', 'budget_items.id')
|
139
|
|
- ->where('budget_items.budget_id', $budget->id)
|
140
|
|
- ->orderBy('start_date')
|
141
|
|
- ->pluck('period')
|
142
|
|
- ->unique()
|
143
|
|
- ->values()
|
144
|
|
- ->toArray();
|
|
116
|
+ $periods = $budget->getPeriods();
|
145
|
117
|
|
146
|
118
|
return $table
|
147
|
119
|
->recordTitleAttribute('account_id')
|
148
|
120
|
->paginated(false)
|
149
|
|
- ->modifyQueryUsing(
|
150
|
|
- fn (Builder $query) => $query->with(['account', 'allocations'])
|
151
|
|
- )
|
152
|
|
- ->headerActions([
|
153
|
|
- Action::make('saveBatchChanges')
|
154
|
|
- ->label('Save All Changes')
|
155
|
|
- ->action('saveBatchChanges')
|
156
|
|
- ->color('primary')
|
157
|
|
- ->icon('heroicon-o-check-circle'),
|
158
|
|
- ])
|
|
121
|
+ ->heading(null)
|
|
122
|
+ ->modifyQueryUsing(function (Builder $query) use ($periods) {
|
|
123
|
+ $query->select('budget_items.*')
|
|
124
|
+ ->leftJoin('budget_allocations', 'budget_allocations.budget_item_id', '=', 'budget_items.id');
|
|
125
|
+
|
|
126
|
+ foreach ($periods as $period) {
|
|
127
|
+ $alias = 'amount_' . str_replace(['-', '.', ' '], '_', $period);
|
|
128
|
+ $query->selectRaw(
|
|
129
|
+ "SUM(CASE WHEN budget_allocations.period = ? THEN budget_allocations.amount ELSE 0 END) as {$alias}",
|
|
130
|
+ [$period]
|
|
131
|
+ );
|
|
132
|
+ }
|
|
133
|
+
|
|
134
|
+ return $query->groupBy('budget_items.id');
|
|
135
|
+ })
|
159
|
136
|
->groups([
|
160
|
137
|
Group::make('account.category')
|
161
|
138
|
->titlePrefixedWithLabel(false)
|
162
|
139
|
->collapsible(),
|
163
|
140
|
])
|
|
141
|
+ ->recordClasses(['budget-items-relation-manager'])
|
164
|
142
|
->defaultGroup('account.category')
|
165
|
|
- ->bulkActions([
|
166
|
|
- BulkAction::make('clearAllocations')
|
167
|
|
- ->label('Clear Allocations')
|
168
|
|
- ->icon('heroicon-o-trash')
|
169
|
|
- ->color('danger')
|
170
|
|
- ->requiresConfirmation()
|
171
|
|
- ->deselectRecordsAfterCompletion()
|
172
|
|
- ->action(function (Collection $records) use ($periods) {
|
173
|
|
- foreach ($records as $record) {
|
174
|
|
- foreach ($periods as $period) {
|
175
|
|
- $periodKey = "{$record->getKey()}.allocations_by_period.{$period}";
|
176
|
|
- $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
|
177
|
|
- }
|
178
|
|
-
|
179
|
|
- $totalKey = "{$record->getKey()}.total";
|
180
|
|
- $this->batchChanges[$totalKey] = CurrencyConverter::convertCentsToFormatSimple(0);
|
181
|
|
- }
|
182
|
|
- }),
|
|
143
|
+ ->headerActions([
|
|
144
|
+ Action::make('saveBatchChanges')
|
|
145
|
+ ->label('Save all changes')
|
|
146
|
+ ->action('saveBatchChanges')
|
|
147
|
+ ->color('primary'),
|
183
|
148
|
])
|
184
|
|
- ->columns(array_merge([
|
|
149
|
+ ->columns([
|
185
|
150
|
TextColumn::make('account.name')
|
186
|
|
- ->label('Accounts')
|
|
151
|
+ ->label('Account')
|
187
|
152
|
->limit(30)
|
188
|
153
|
->searchable(),
|
189
|
154
|
DeferredTextInputColumn::make('total')
|
|
@@ -195,9 +160,9 @@ class BudgetItemsRelationManager extends RelationManager
|
195
|
160
|
return $this->batchChanges["{$record->getKey()}.{$column->getName()}"];
|
196
|
161
|
}
|
197
|
162
|
|
198
|
|
- $total = $record->allocations->sum(function (BudgetAllocation $budgetAllocation) {
|
199
|
|
- return $budgetAllocation->getRawOriginal('amount');
|
200
|
|
- });
|
|
163
|
+ $total = $record->allocations->sum(
|
|
164
|
+ fn (BudgetAllocation $allocation) => $allocation->getRawOriginal('amount')
|
|
165
|
+ );
|
201
|
166
|
|
202
|
167
|
return CurrencyConverter::convertCentsToFormatSimple($total);
|
203
|
168
|
})
|
|
@@ -219,9 +184,6 @@ class BudgetItemsRelationManager extends RelationManager
|
219
|
184
|
->action(
|
220
|
185
|
Action::make('disperse')
|
221
|
186
|
->label('Disperse')
|
222
|
|
- ->icon('heroicon-m-chevron-double-right')
|
223
|
|
- ->color('primary')
|
224
|
|
- ->iconButton()
|
225
|
187
|
->action(function (BudgetItem $record) use ($periods) {
|
226
|
188
|
if (empty($periods)) {
|
227
|
189
|
return;
|
|
@@ -246,7 +208,7 @@ class BudgetItemsRelationManager extends RelationManager
|
246
|
208
|
|
247
|
209
|
if ($totalCents <= 0) {
|
248
|
210
|
foreach ($periods as $period) {
|
249
|
|
- $periodKey = "{$record->getKey()}.allocations_by_period.{$period}";
|
|
211
|
+ $periodKey = "{$record->getKey()}.amount_" . str_replace(['-', '.', ' '], '_', $period);
|
250
|
212
|
$this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
|
251
|
213
|
}
|
252
|
214
|
|
|
@@ -260,36 +222,50 @@ class BudgetItemsRelationManager extends RelationManager
|
260
|
222
|
$amount = $baseAmount + ($index === 0 ? $remainder : 0);
|
261
|
223
|
$formattedAmount = CurrencyConverter::convertCentsToFormatSimple($amount);
|
262
|
224
|
|
263
|
|
- $periodKey = "{$record->getKey()}.allocations_by_period.{$period}";
|
|
225
|
+ $periodKey = "{$record->getKey()}." . 'amount_' . str_replace(['-', '.', ' '], '_', $period);
|
264
|
226
|
$this->batchChanges[$periodKey] = $formattedAmount;
|
265
|
227
|
}
|
266
|
228
|
}),
|
267
|
229
|
),
|
268
|
|
- ], collect($periods)->map(
|
269
|
|
- fn ($period) => DeferredTextInputColumn::make("allocations_by_period.{$period}")
|
270
|
|
- ->label($period)
|
271
|
|
- ->alignRight()
|
272
|
|
- ->mask(RawJs::make('$money($input)'))
|
273
|
|
- ->summarize(
|
274
|
|
- Summarizer::make()
|
275
|
|
- ->using(function (\Illuminate\Database\Query\Builder $query) use ($period) {
|
276
|
|
- $budgetItemIds = $query->pluck('id')->toArray();
|
277
|
|
- $total = $this->calculatePeriodSum($budgetItemIds, $period);
|
278
|
|
-
|
279
|
|
- return CurrencyConverter::convertCentsToFormatSimple($total);
|
280
|
|
- })
|
281
|
|
- )
|
282
|
|
- ->getStateUsing(function ($record, DeferredTextInputColumn $column) use ($period) {
|
283
|
|
- $key = "{$record->getKey()}.{$column->getName()}";
|
284
|
|
-
|
285
|
|
- // Check if batch change exists
|
286
|
|
- if (isset($this->batchChanges[$key])) {
|
287
|
|
- return $this->batchChanges[$key];
|
|
230
|
+ ...array_map(function (string $period) {
|
|
231
|
+ $alias = 'amount_' . str_replace(['-', '.', ' '], '_', $period); // Also replace space
|
|
232
|
+
|
|
233
|
+ return DeferredTextInputColumn::make($alias)
|
|
234
|
+ ->label($period)
|
|
235
|
+ ->alignRight()
|
|
236
|
+ ->batchMode()
|
|
237
|
+ ->mask(RawJs::make('$money($input)'))
|
|
238
|
+ ->getStateUsing(function ($record) use ($alias) {
|
|
239
|
+ $key = "{$record->getKey()}.{$alias}";
|
|
240
|
+
|
|
241
|
+ return $this->batchChanges[$key] ?? CurrencyConverter::convertCentsToFormatSimple($record->{$alias} ?? 0);
|
|
242
|
+ })
|
|
243
|
+ ->summarize(
|
|
244
|
+ Summarizer::make()
|
|
245
|
+ ->using(function (\Illuminate\Database\Query\Builder $query) use ($period) {
|
|
246
|
+ $budgetItemIds = $query->pluck('id')->toArray();
|
|
247
|
+ $total = $this->calculatePeriodSum($budgetItemIds, $period);
|
|
248
|
+
|
|
249
|
+ return CurrencyConverter::convertCentsToFormatSimple($total);
|
|
250
|
+ })
|
|
251
|
+ );
|
|
252
|
+ }, $periods),
|
|
253
|
+ ])
|
|
254
|
+ ->bulkActions([
|
|
255
|
+ BulkAction::make('clearAllocations')
|
|
256
|
+ ->label('Clear Allocations')
|
|
257
|
+ ->icon('heroicon-o-trash')
|
|
258
|
+ ->color('danger')
|
|
259
|
+ ->requiresConfirmation()
|
|
260
|
+ ->deselectRecordsAfterCompletion()
|
|
261
|
+ ->action(function (Collection $records) use ($periods) {
|
|
262
|
+ foreach ($records as $record) {
|
|
263
|
+ foreach ($periods as $period) {
|
|
264
|
+ $periodKey = "{$record->getKey()}.amount_" . str_replace(['-', '.', ' '], '_', $period);
|
|
265
|
+ $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
|
|
266
|
+ }
|
288
|
267
|
}
|
289
|
|
-
|
290
|
|
- return $record->allocations->firstWhere('period', $period)?->amount;
|
291
|
|
- })
|
292
|
|
- ->batchMode(),
|
293
|
|
- )->all()));
|
|
268
|
+ }),
|
|
269
|
+ ]);
|
294
|
270
|
}
|
295
|
271
|
}
|