您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

BudgetItemsRelationManager.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. <?php
  2. namespace App\Filament\Company\Resources\Accounting\BudgetResource\RelationManagers;
  3. use App\Filament\Tables\Columns\CustomTextInputColumn;
  4. use App\Models\Accounting\Budget;
  5. use App\Models\Accounting\BudgetAllocation;
  6. use App\Models\Accounting\BudgetItem;
  7. use App\Utilities\Currency\CurrencyConverter;
  8. use Filament\Notifications\Notification;
  9. use Filament\Resources\RelationManagers\RelationManager;
  10. use Filament\Support\RawJs;
  11. use Filament\Tables\Actions\Action;
  12. use Filament\Tables\Actions\BulkAction;
  13. use Filament\Tables\Columns\IconColumn;
  14. use Filament\Tables\Columns\Summarizers\Summarizer;
  15. use Filament\Tables\Columns\TextColumn;
  16. use Filament\Tables\Grouping\Group;
  17. use Filament\Tables\Table;
  18. use Illuminate\Database\Eloquent\Builder;
  19. use Illuminate\Database\Eloquent\Collection;
  20. use Illuminate\Support\Carbon;
  21. use Illuminate\Support\Facades\DB;
  22. use stdClass;
  23. class BudgetItemsRelationManager extends RelationManager
  24. {
  25. protected static string $relationship = 'budgetItems';
  26. protected static bool $isLazy = false;
  27. protected const TOTAL_COLUMN = 'total';
  28. public array $batchChanges = [];
  29. /**
  30. * Generate a consistent key for the budget item and period
  31. */
  32. protected static function generatePeriodKey(int $recordId, string | Carbon $startDate): string
  33. {
  34. $formattedDate = $startDate instanceof Carbon
  35. ? $startDate->format('Y_m_d')
  36. : Carbon::parse($startDate)->format('Y_m_d');
  37. return "{$recordId}.{$formattedDate}";
  38. }
  39. /**
  40. * Generate a consistent key for the budget item's total
  41. */
  42. protected static function generateTotalKey(int $recordId): string
  43. {
  44. return "{$recordId}." . self::TOTAL_COLUMN;
  45. }
  46. public function handleBatchColumnChanged($data): void
  47. {
  48. $key = "{$data['recordKey']}.{$data['name']}";
  49. $this->batchChanges[$key] = $data['value'];
  50. }
  51. public function saveBatchChanges(): void
  52. {
  53. foreach ($this->batchChanges as $key => $value) {
  54. [$recordKey, $column] = explode('.', $key, 2);
  55. try {
  56. $startDate = Carbon::createFromFormat('Y_m_d', $column);
  57. } catch (\Exception) {
  58. continue;
  59. }
  60. $record = BudgetItem::find($recordKey);
  61. if (! $record) {
  62. continue;
  63. }
  64. $allocation = $record->allocations()
  65. ->whereDate('start_date', $startDate)
  66. ->first();
  67. $allocation?->update(['amount' => $value]);
  68. }
  69. $this->batchChanges = [];
  70. Notification::make()
  71. ->title('Budget allocations updated')
  72. ->success()
  73. ->send();
  74. }
  75. protected function calculatePeriodSum(array $budgetItemIds, string | Carbon $startDate): int
  76. {
  77. $allocations = DB::table('budget_allocations')
  78. ->whereIn('budget_item_id', $budgetItemIds)
  79. ->whereDate('start_date', $startDate)
  80. ->pluck('amount', 'budget_item_id');
  81. $dbTotal = $allocations->sum();
  82. $batchTotal = 0;
  83. foreach ($budgetItemIds as $itemId) {
  84. $key = self::generatePeriodKey($itemId, $startDate);
  85. if (isset($this->batchChanges[$key])) {
  86. $batchValue = CurrencyConverter::convertToCents($this->batchChanges[$key]);
  87. $existingAmount = $allocations[$itemId] ?? 0;
  88. $batchTotal += ($batchValue - $existingAmount);
  89. }
  90. }
  91. return $dbTotal + $batchTotal;
  92. }
  93. public function table(Table $table): Table
  94. {
  95. /** @var Budget $budget */
  96. $budget = $this->getOwnerRecord();
  97. $allocationPeriods = $budget->getPeriods();
  98. return $table
  99. ->recordTitleAttribute('account_id')
  100. ->paginated(false)
  101. ->heading(null)
  102. ->modifyQueryUsing(function (Builder $query) use ($allocationPeriods) {
  103. $query->select('budget_items.*')
  104. ->leftJoin('budget_allocations', 'budget_allocations.budget_item_id', '=', 'budget_items.id');
  105. foreach ($allocationPeriods as $period) {
  106. $alias = $period->start_date->format('Y_m_d');
  107. $query->selectRaw(
  108. "SUM(CASE WHEN budget_allocations.start_date = ? THEN budget_allocations.amount ELSE 0 END) as {$alias}",
  109. [$period->start_date->toDateString()]
  110. );
  111. }
  112. return $query->groupBy('budget_items.id');
  113. })
  114. ->groups([
  115. Group::make('account.category')
  116. ->titlePrefixedWithLabel(false)
  117. ->collapsible(),
  118. ])
  119. ->recordClasses(['is-spreadsheet'])
  120. ->defaultGroup('account.category')
  121. ->headerActions([
  122. Action::make('saveBatchChanges')
  123. ->label('Save all changes')
  124. ->action('saveBatchChanges')
  125. ->color('primary'),
  126. ])
  127. ->columns([
  128. TextColumn::make('account.name')
  129. ->label('Account')
  130. ->limit(30)
  131. ->searchable(),
  132. CustomTextInputColumn::make(self::TOTAL_COLUMN)
  133. ->label('Total')
  134. ->alignRight()
  135. ->mask(RawJs::make('$money($input)'))
  136. ->getStateUsing(function (BudgetItem $record) {
  137. $key = self::generateTotalKey($record->getKey());
  138. if (isset($this->batchChanges[$key])) {
  139. return $this->batchChanges[$key];
  140. }
  141. $total = $record->allocations->sum(
  142. fn (BudgetAllocation $allocation) => $allocation->getRawOriginal('amount')
  143. );
  144. return CurrencyConverter::convertCentsToFormatSimple($total);
  145. })
  146. ->deferred()
  147. ->navigable()
  148. ->summarize(
  149. Summarizer::make()
  150. ->using(function (\Illuminate\Database\Query\Builder $query) {
  151. $allocations = $query
  152. ->leftJoin('budget_allocations', 'budget_allocations.budget_item_id', '=', 'budget_items.id')
  153. ->select('budget_allocations.budget_item_id', 'budget_allocations.start_date', 'budget_allocations.amount')
  154. ->get();
  155. $allocationsByDate = $allocations->groupBy('start_date');
  156. $total = 0;
  157. /** @var \Illuminate\Support\Collection<string, \Illuminate\Support\Collection<int, stdClass>> $allocationsByDate */
  158. foreach ($allocationsByDate as $startDate => $group) {
  159. $dbTotal = $group->sum('amount');
  160. $amounts = $group->pluck('amount', 'budget_item_id');
  161. $batchTotal = 0;
  162. foreach ($amounts as $itemId => $existingAmount) {
  163. $key = self::generatePeriodKey($itemId, $startDate);
  164. if (isset($this->batchChanges[$key])) {
  165. $batchValue = CurrencyConverter::convertToCents($this->batchChanges[$key]);
  166. $batchTotal += ($batchValue - $existingAmount);
  167. }
  168. }
  169. $total += $dbTotal + $batchTotal;
  170. }
  171. return CurrencyConverter::convertCentsToFormatSimple($total);
  172. })
  173. ),
  174. IconColumn::make('disperseAction')
  175. ->icon('heroicon-m-chevron-double-right')
  176. ->color('primary')
  177. ->label('')
  178. ->default('')
  179. ->tooltip('Disperse total across periods')
  180. ->action(
  181. Action::make('disperse')
  182. ->label('Disperse')
  183. ->action(function (BudgetItem $record) use ($allocationPeriods) {
  184. if (empty($allocationPeriods)) {
  185. return;
  186. }
  187. $totalKey = self::generateTotalKey($record->getKey());
  188. $totalAmount = $this->batchChanges[$totalKey] ?? null;
  189. if (isset($totalAmount)) {
  190. $totalCents = CurrencyConverter::convertToCents($totalAmount);
  191. } else {
  192. $totalCents = $record->allocations->sum(function (BudgetAllocation $budgetAllocation) {
  193. return $budgetAllocation->getRawOriginal('amount');
  194. });
  195. }
  196. if ($totalCents <= 0) {
  197. foreach ($allocationPeriods as $period) {
  198. $periodKey = self::generatePeriodKey($record->getKey(), $period->start_date);
  199. $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
  200. }
  201. return;
  202. }
  203. $numPeriods = count($allocationPeriods);
  204. $baseAmount = floor($totalCents / $numPeriods);
  205. $remainder = $totalCents - ($baseAmount * $numPeriods);
  206. foreach ($allocationPeriods as $index => $period) {
  207. $amount = $baseAmount + ($index === 0 ? $remainder : 0);
  208. $formattedAmount = CurrencyConverter::convertCentsToFormatSimple($amount);
  209. $periodKey = self::generatePeriodKey($record->getKey(), $period->start_date);
  210. $this->batchChanges[$periodKey] = $formattedAmount;
  211. }
  212. }),
  213. ),
  214. ...$allocationPeriods->map(function (BudgetAllocation $period) {
  215. $alias = $period->start_date->format('Y_m_d');
  216. return CustomTextInputColumn::make($alias)
  217. ->label($period->period)
  218. ->alignRight()
  219. ->deferred()
  220. ->navigable()
  221. ->mask(RawJs::make('$money($input)'))
  222. ->getStateUsing(function ($record) use ($alias) {
  223. $key = "{$record->getKey()}.{$alias}";
  224. return $this->batchChanges[$key] ?? CurrencyConverter::convertCentsToFormatSimple($record->{$alias} ?? 0);
  225. })
  226. ->summarize(
  227. Summarizer::make()
  228. ->using(function (\Illuminate\Database\Query\Builder $query) use ($period) {
  229. $budgetItemIds = $query->pluck('id')->toArray();
  230. $total = $this->calculatePeriodSum($budgetItemIds, $period->start_date);
  231. return CurrencyConverter::convertCentsToFormatSimple($total);
  232. })
  233. );
  234. })->toArray(),
  235. ])
  236. ->bulkActions([
  237. BulkAction::make('clearAllocations')
  238. ->label('Clear Allocations')
  239. ->icon('heroicon-o-trash')
  240. ->color('danger')
  241. ->requiresConfirmation()
  242. ->deselectRecordsAfterCompletion()
  243. ->action(function (Collection $records) use ($allocationPeriods) {
  244. foreach ($records as $record) {
  245. foreach ($allocationPeriods as $period) {
  246. $periodKey = self::generatePeriodKey($record->getKey(), $period->start_date);
  247. $this->batchChanges[$periodKey] = CurrencyConverter::convertCentsToFormatSimple(0);
  248. }
  249. }
  250. }),
  251. ]);
  252. }
  253. }