Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

BudgetResource.php 9.3KB

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