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.

BudgetResource.php 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace App\Filament\Company\Resources\Accounting;
  3. use App\Filament\Company\Resources\Accounting\BudgetResource\Pages;
  4. use App\Filament\Forms\Components\CustomSection;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Accounting\Budget;
  7. use App\Models\Accounting\BudgetItem;
  8. use Filament\Forms;
  9. use Filament\Forms\Form;
  10. use Filament\Resources\Resource;
  11. use Filament\Tables;
  12. use Filament\Tables\Table;
  13. use Illuminate\Support\Carbon;
  14. class BudgetResource extends Resource
  15. {
  16. protected static ?string $model = Budget::class;
  17. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  18. public static function form(Form $form): Form
  19. {
  20. return $form
  21. ->schema([
  22. Forms\Components\Section::make('Budget Details')
  23. ->columns()
  24. ->schema([
  25. Forms\Components\TextInput::make('name')
  26. ->required()
  27. ->maxLength(255),
  28. Forms\Components\Select::make('interval_type')
  29. ->label('Budget Interval')
  30. ->options([
  31. 'day' => 'Daily',
  32. 'week' => 'Weekly',
  33. 'month' => 'Monthly',
  34. 'quarter' => 'Quarterly',
  35. 'year' => 'Yearly',
  36. ])
  37. ->default('month')
  38. ->required()
  39. ->live(),
  40. Forms\Components\DatePicker::make('start_date')
  41. ->required()
  42. ->default(now()->startOfYear())
  43. ->live(),
  44. Forms\Components\DatePicker::make('end_date')
  45. ->required()
  46. ->default(now()->endOfYear())
  47. ->live(),
  48. Forms\Components\Textarea::make('notes')->columnSpanFull(),
  49. ]),
  50. Forms\Components\Section::make('Budget Items')
  51. ->schema([
  52. Forms\Components\Repeater::make('budgetItems')
  53. ->relationship()
  54. ->columns(4)
  55. ->hiddenLabel()
  56. ->schema([
  57. Forms\Components\Select::make('account_id')
  58. ->label('Account')
  59. ->options(Account::query()->pluck('name', 'id'))
  60. ->searchable()
  61. ->columnSpan(1)
  62. ->required(),
  63. Forms\Components\TextInput::make('total_amount')
  64. ->label('Total Amount')
  65. ->numeric()
  66. ->required()
  67. ->columnSpan(1)
  68. ->suffixAction(
  69. Forms\Components\Actions\Action::make('disperse')
  70. ->label('Disperse')
  71. ->icon('heroicon-m-bars-arrow-down')
  72. ->color('primary')
  73. ->action(fn (Forms\Set $set, Forms\Get $get, $state) => self::disperseTotalAmount($set, $get, $state))
  74. ),
  75. CustomSection::make('Budget Allocations')
  76. ->contained(false)
  77. ->columns(4)
  78. ->schema(static fn (Forms\Get $get) => self::getAllocationFields($get('../../start_date'), $get('../../end_date'), $get('../../interval_type'))),
  79. ])
  80. ->defaultItems(1)
  81. ->addActionLabel('Add Budget Item'),
  82. ]),
  83. ]);
  84. }
  85. public static function table(Table $table): Table
  86. {
  87. return $table
  88. ->columns([
  89. //
  90. ])
  91. ->filters([
  92. //
  93. ])
  94. ->actions([
  95. Tables\Actions\ViewAction::make(),
  96. Tables\Actions\EditAction::make(),
  97. ])
  98. ->bulkActions([
  99. Tables\Actions\BulkActionGroup::make([
  100. Tables\Actions\DeleteBulkAction::make(),
  101. ]),
  102. ]);
  103. }
  104. /**
  105. * Disperses the total amount across the budget items based on the selected interval.
  106. */
  107. private static function disperseTotalAmount(Forms\Set $set, Forms\Get $get, float $totalAmount): void
  108. {
  109. $startDate = $get('../../start_date');
  110. $endDate = $get('../../end_date');
  111. $intervalType = $get('../../interval_type');
  112. if (! $startDate || ! $endDate || ! $intervalType || $totalAmount <= 0) {
  113. return;
  114. }
  115. // Generate labels based on interval type (must match `getAllocationFields()`)
  116. $labels = self::generateFormattedLabels($startDate, $endDate, $intervalType);
  117. $numPeriods = count($labels);
  118. if ($numPeriods === 0) {
  119. return;
  120. }
  121. // Calculate base allocation and handle rounding
  122. $baseAmount = floor($totalAmount / $numPeriods);
  123. $remainder = $totalAmount - ($baseAmount * $numPeriods);
  124. // Assign amounts to the correct fields using labels
  125. foreach ($labels as $index => $label) {
  126. $amount = $baseAmount + ($index === 0 ? $remainder : 0);
  127. $set("amounts.{$label}", $amount); // Now correctly assigns to the right field
  128. }
  129. }
  130. /**
  131. * Generates formatted labels for the budget allocation fields based on the selected interval type.
  132. */
  133. private static function generateFormattedLabels(string $startDate, string $endDate, string $intervalType): array
  134. {
  135. $start = Carbon::parse($startDate);
  136. $end = Carbon::parse($endDate);
  137. $labels = [];
  138. while ($start->lte($end)) {
  139. $labels[] = match ($intervalType) {
  140. 'month' => $start->format('M'), // Example: Jan, Feb, Mar
  141. 'quarter' => 'Q' . $start->quarter, // Example: Q1, Q2, Q3
  142. 'year' => (string) $start->year, // Example: 2024, 2025
  143. default => '',
  144. };
  145. match ($intervalType) {
  146. 'month' => $start->addMonth(),
  147. 'quarter' => $start->addQuarter(),
  148. 'year' => $start->addYear(),
  149. default => null,
  150. };
  151. }
  152. return $labels;
  153. }
  154. private static function getAllocationFields(?string $startDate, ?string $endDate, ?string $intervalType): array
  155. {
  156. if (! $startDate || ! $endDate || ! $intervalType) {
  157. return [];
  158. }
  159. $start = Carbon::parse($startDate);
  160. $end = Carbon::parse($endDate);
  161. $fields = [];
  162. while ($start->lte($end)) {
  163. $label = match ($intervalType) {
  164. 'month' => $start->format('M'), // Example: Jan, Feb, Mar
  165. 'quarter' => 'Q' . $start->quarter, // Example: Q1, Q2, Q3
  166. 'year' => (string) $start->year, // Example: 2024, 2025
  167. default => '',
  168. };
  169. $fields[] = Forms\Components\TextInput::make("amounts.{$label}")
  170. ->label($label)
  171. ->numeric()
  172. ->required();
  173. // Move to the next period
  174. match ($intervalType) {
  175. 'month' => $start->addMonth(),
  176. 'quarter' => $start->addQuarter(),
  177. 'year' => $start->addYear(),
  178. default => null,
  179. };
  180. }
  181. return $fields;
  182. }
  183. /**
  184. * Generates an array of interval labels (e.g., Jan 2024, Q1 2024, etc.).
  185. */
  186. private static function generateIntervals(string $startDate, string $endDate, string $intervalType): array
  187. {
  188. $start = Carbon::parse($startDate);
  189. $end = Carbon::parse($endDate);
  190. $intervals = [];
  191. while ($start->lte($end)) {
  192. if ($intervalType === 'month') {
  193. $intervals[] = $start->format('M Y'); // Example: Jan 2024
  194. $start->addMonth();
  195. } elseif ($intervalType === 'quarter') {
  196. $intervals[] = 'Q' . $start->quarter . ' ' . $start->year; // Example: Q1 2024
  197. $start->addQuarter();
  198. } elseif ($intervalType === 'year') {
  199. $intervals[] = $start->year; // Example: 2024
  200. $start->addYear();
  201. }
  202. }
  203. return $intervals;
  204. }
  205. /**
  206. * Saves budget allocations correctly in `budget_allocations` table.
  207. */
  208. public static function saveBudgetAllocations(BudgetItem $record, array $data): void
  209. {
  210. $record->update($data);
  211. $intervals = self::generateIntervals($data['start_date'], $data['end_date'], $data['interval_type']);
  212. foreach ($intervals as $interval) {
  213. $record->allocations()->updateOrCreate(
  214. ['period' => $interval],
  215. [
  216. 'interval_type' => $data['interval_type'],
  217. 'start_date' => Carbon::parse($interval)->startOfMonth(),
  218. 'end_date' => Carbon::parse($interval)->endOfMonth(),
  219. 'amount' => $data['allocations'][$interval] ?? 0,
  220. ]
  221. );
  222. }
  223. }
  224. public static function getRelations(): array
  225. {
  226. return [
  227. //
  228. ];
  229. }
  230. public static function getPages(): array
  231. {
  232. return [
  233. 'index' => Pages\ListBudgets::route('/'),
  234. 'create' => Pages\CreateBudget::route('/create'),
  235. 'view' => Pages\ViewBudget::route('/{record}'),
  236. 'edit' => Pages\EditBudget::route('/{record}/edit'),
  237. ];
  238. }
  239. }