Andrew Wallo 6 months ago
parent
commit
e63072e1c9

+ 46
- 14
app/Filament/Company/Resources/Accounting/BudgetResource/RelationManagers/BudgetItemsRelationManager.php View File

19
 use Filament\Tables\Table;
19
 use Filament\Tables\Table;
20
 use Illuminate\Database\Eloquent\Builder;
20
 use Illuminate\Database\Eloquent\Builder;
21
 use Illuminate\Database\Eloquent\Collection;
21
 use Illuminate\Database\Eloquent\Collection;
22
+use Illuminate\Support\Str;
22
 
23
 
23
 class BudgetItemsRelationManager extends RelationManager
24
 class BudgetItemsRelationManager extends RelationManager
24
 {
25
 {
26
 
27
 
27
     protected static bool $isLazy = false;
28
     protected static bool $isLazy = false;
28
 
29
 
30
+    protected const AMOUNT_PREFIX = 'amount_';
31
+
32
+    protected const TOTAL_COLUMN = 'total';
33
+
29
     public array $batchChanges = [];
34
     public array $batchChanges = [];
30
 
35
 
36
+    /**
37
+     * Generate a consistent key for the budget item and period
38
+     */
39
+    protected static function generatePeriodKey(int $recordId, string $period): string
40
+    {
41
+        return "{$recordId}." . self::AMOUNT_PREFIX . Str::snake($period);
42
+    }
43
+
44
+    /**
45
+     * Generate a consistent key for the budget item's total
46
+     */
47
+    protected static function generateTotalKey(int $recordId): string
48
+    {
49
+        return "{$recordId}." . self::TOTAL_COLUMN;
50
+    }
51
+
52
+    /**
53
+     * Extract the period from a column name
54
+     */
55
+    protected static function extractPeriodFromColumn(string $columnName): ?string
56
+    {
57
+        if (preg_match('/' . self::AMOUNT_PREFIX . '(.+)/', $columnName, $matches)) {
58
+            return str_replace('_', ' ', $matches[1] ?? '');
59
+        }
60
+
61
+        return null;
62
+    }
63
+
31
     public function handleBatchColumnChanged($data): void
64
     public function handleBatchColumnChanged($data): void
32
     {
65
     {
33
         $key = "{$data['recordKey']}.{$data['name']}";
66
         $key = "{$data['recordKey']}.{$data['name']}";
39
         foreach ($this->batchChanges as $key => $value) {
72
         foreach ($this->batchChanges as $key => $value) {
40
             [$recordKey, $column] = explode('.', $key, 2);
73
             [$recordKey, $column] = explode('.', $key, 2);
41
 
74
 
42
-            preg_match('/amount_(.+)/', $column, $matches);
43
-            $period = str_replace('_', ' ', $matches[1] ?? '');
44
-
75
+            $period = self::extractPeriodFromColumn($column);
45
             if (! $period) {
76
             if (! $period) {
46
                 continue;
77
                 continue;
47
             }
78
             }
94
 
125
 
95
         $batchTotal = 0;
126
         $batchTotal = 0;
96
         foreach ($budgetItemIds as $itemId) {
127
         foreach ($budgetItemIds as $itemId) {
97
-            $key = "{$itemId}.amount_" . str_replace(['-', '.', ' '], '_', $period);
128
+            $key = self::generatePeriodKey($itemId, $period);
98
             if (isset($this->batchChanges[$key])) {
129
             if (isset($this->batchChanges[$key])) {
99
                 $batchValue = CurrencyConverter::convertToCents($this->batchChanges[$key]);
130
                 $batchValue = CurrencyConverter::convertToCents($this->batchChanges[$key]);
100
                 $existingAmount = BudgetAllocation::where('budget_item_id', $itemId)
131
                 $existingAmount = BudgetAllocation::where('budget_item_id', $itemId)
124
                     ->leftJoin('budget_allocations', 'budget_allocations.budget_item_id', '=', 'budget_items.id');
155
                     ->leftJoin('budget_allocations', 'budget_allocations.budget_item_id', '=', 'budget_items.id');
125
 
156
 
126
                 foreach ($periods as $period) {
157
                 foreach ($periods as $period) {
127
-                    $alias = 'amount_' . str_replace(['-', '.', ' '], '_', $period);
158
+                    $alias = self::AMOUNT_PREFIX . Str::snake($period);
128
                     $query->selectRaw(
159
                     $query->selectRaw(
129
                         "SUM(CASE WHEN budget_allocations.period = ? THEN budget_allocations.amount ELSE 0 END) as {$alias}",
160
                         "SUM(CASE WHEN budget_allocations.period = ? THEN budget_allocations.amount ELSE 0 END) as {$alias}",
130
                         [$period]
161
                         [$period]
151
                     ->label('Account')
182
                     ->label('Account')
152
                     ->limit(30)
183
                     ->limit(30)
153
                     ->searchable(),
184
                     ->searchable(),
154
-                DeferredTextInputColumn::make('total')
185
+                DeferredTextInputColumn::make(self::TOTAL_COLUMN)
155
                     ->label('Total')
186
                     ->label('Total')
156
                     ->alignRight()
187
                     ->alignRight()
157
                     ->mask(RawJs::make('$money($input)'))
188
                     ->mask(RawJs::make('$money($input)'))
158
-                    ->getStateUsing(function (BudgetItem $record, DeferredTextInputColumn $column) {
159
-                        if (isset($this->batchChanges["{$record->getKey()}.{$column->getName()}"])) {
160
-                            return $this->batchChanges["{$record->getKey()}.{$column->getName()}"];
189
+                    ->getStateUsing(function (BudgetItem $record) {
190
+                        $key = self::generateTotalKey($record->getKey());
191
+                        if (isset($this->batchChanges[$key])) {
192
+                            return $this->batchChanges[$key];
161
                         }
193
                         }
162
 
194
 
163
                         $total = $record->allocations->sum(
195
                         $total = $record->allocations->sum(
190
                                     return;
222
                                     return;
191
                                 }
223
                                 }
192
 
224
 
193
-                                $totalKey = "{$record->getKey()}.total";
225
+                                $totalKey = self::generateTotalKey($record->getKey());
194
                                 $totalAmount = $this->batchChanges[$totalKey] ?? null;
226
                                 $totalAmount = $this->batchChanges[$totalKey] ?? null;
195
 
227
 
196
                                 if (isset($totalAmount)) {
228
                                 if (isset($totalAmount)) {
209
 
241
 
210
                                 if ($totalCents <= 0) {
242
                                 if ($totalCents <= 0) {
211
                                     foreach ($periods as $period) {
243
                                     foreach ($periods as $period) {
212
-                                        $periodKey = "{$record->getKey()}.amount_" . str_replace(['-', '.', ' '], '_', $period);
244
+                                        $periodKey = self::generatePeriodKey($record->getKey(), $period);
213
                                         $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
245
                                         $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
214
                                     }
246
                                     }
215
 
247
 
223
                                     $amount = $baseAmount + ($index === 0 ? $remainder : 0);
255
                                     $amount = $baseAmount + ($index === 0 ? $remainder : 0);
224
                                     $formattedAmount = CurrencyConverter::convertCentsToFormatSimple($amount);
256
                                     $formattedAmount = CurrencyConverter::convertCentsToFormatSimple($amount);
225
 
257
 
226
-                                    $periodKey = "{$record->getKey()}." . 'amount_' . str_replace(['-', '.', ' '], '_', $period);
258
+                                    $periodKey = self::generatePeriodKey($record->getKey(), $period);
227
                                     $this->batchChanges[$periodKey] = $formattedAmount;
259
                                     $this->batchChanges[$periodKey] = $formattedAmount;
228
                                 }
260
                                 }
229
                             }),
261
                             }),
230
                     ),
262
                     ),
231
                 ...array_map(function (string $period) {
263
                 ...array_map(function (string $period) {
232
-                    $alias = 'amount_' . str_replace(['-', '.', ' '], '_', $period); // Also replace space
264
+                    $alias = self::AMOUNT_PREFIX . Str::snake($period);
233
 
265
 
234
                     return DeferredTextInputColumn::make($alias)
266
                     return DeferredTextInputColumn::make($alias)
235
                         ->label($period)
267
                         ->label($period)
262
                     ->action(function (Collection $records) use ($periods) {
294
                     ->action(function (Collection $records) use ($periods) {
263
                         foreach ($records as $record) {
295
                         foreach ($records as $record) {
264
                             foreach ($periods as $period) {
296
                             foreach ($periods as $period) {
265
-                                $periodKey = "{$record->getKey()}.amount_" . str_replace(['-', '.', ' '], '_', $period);
297
+                                $periodKey = self::generatePeriodKey($record->getKey(), $period);
266
                                 $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
298
                                 $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
267
                             }
299
                             }
268
                         }
300
                         }

Loading…
Cancel
Save