You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BudgetItemsRelationManager.php 12KB

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