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

CreateBudget.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. <?php
  2. namespace App\Filament\Company\Resources\Accounting\BudgetResource\Pages;
  3. use App\Enums\Accounting\BudgetIntervalType;
  4. use App\Facades\Accounting;
  5. use App\Filament\Company\Resources\Accounting\BudgetResource;
  6. use App\Models\Accounting\Account;
  7. use App\Models\Accounting\Budget;
  8. use App\Models\Accounting\BudgetAllocation;
  9. use App\Models\Accounting\BudgetItem;
  10. use Filament\Forms;
  11. use Filament\Forms\Components\Actions\Action;
  12. use Filament\Forms\Components\Wizard\Step;
  13. use Filament\Resources\Pages\CreateRecord;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Database\Eloquent\Model;
  16. use Illuminate\Support\Carbon;
  17. class CreateBudget extends CreateRecord
  18. {
  19. use CreateRecord\Concerns\HasWizard;
  20. protected static string $resource = BudgetResource::class;
  21. public function getSteps(): array
  22. {
  23. return [
  24. Step::make('General Information')
  25. ->columns(2)
  26. ->schema([
  27. Forms\Components\TextInput::make('name')
  28. ->required()
  29. ->maxLength(255),
  30. Forms\Components\Select::make('interval_type')
  31. ->label('Budget Interval')
  32. ->options(BudgetIntervalType::class)
  33. ->default(BudgetIntervalType::Month->value)
  34. ->required()
  35. ->live(),
  36. Forms\Components\DatePicker::make('start_date')
  37. ->required()
  38. ->default(now()->startOfYear())
  39. ->live(),
  40. Forms\Components\DatePicker::make('end_date')
  41. ->required()
  42. ->default(now()->endOfYear())
  43. ->live()
  44. ->disabled(static fn (Forms\Get $get) => blank($get('start_date')))
  45. ->minDate(fn (Forms\Get $get) => match (BudgetIntervalType::parse($get('interval_type'))) {
  46. BudgetIntervalType::Month => Carbon::parse($get('start_date'))->addMonth(),
  47. BudgetIntervalType::Quarter => Carbon::parse($get('start_date'))->addQuarter(),
  48. BudgetIntervalType::Year => Carbon::parse($get('start_date'))->addYear(),
  49. default => Carbon::parse($get('start_date'))->addDay(),
  50. })
  51. ->maxDate(fn (Forms\Get $get) => Carbon::parse($get('start_date'))->endOfYear()),
  52. ]),
  53. Step::make('Budget Setup & Settings')
  54. ->schema([
  55. // Prefill configuration
  56. Forms\Components\Toggle::make('prefill_data')
  57. ->label('Prefill Data')
  58. ->helperText('Enable this option to prefill the budget with historical data')
  59. ->default(false)
  60. ->live(),
  61. Forms\Components\Grid::make(1)
  62. ->schema([
  63. Forms\Components\Select::make('prefill_method')
  64. ->label('Prefill Method')
  65. ->options([
  66. 'previous_budget' => 'Copy from a previous budget',
  67. 'actuals' => 'Use historical actuals',
  68. ])
  69. ->live()
  70. ->required(),
  71. // If user selects to copy a previous budget
  72. Forms\Components\Select::make('source_budget_id')
  73. ->label('Source Budget')
  74. ->options(fn () => Budget::query()
  75. ->orderByDesc('end_date')
  76. ->pluck('name', 'id'))
  77. ->searchable()
  78. ->required()
  79. ->visible(fn (Forms\Get $get) => $get('prefill_method') === 'previous_budget'),
  80. // If user selects to use historical actuals
  81. Forms\Components\Select::make('actuals_fiscal_year')
  82. ->label('Reference Fiscal Year')
  83. ->options(function () {
  84. $options = [];
  85. $company = auth()->user()->currentCompany;
  86. $earliestDate = Carbon::parse(Accounting::getEarliestTransactionDate());
  87. $fiscalYearStartCurrent = Carbon::parse($company->locale->fiscalYearStartDate());
  88. for ($year = $fiscalYearStartCurrent->year; $year >= $earliestDate->year; $year--) {
  89. $options[$year] = $year;
  90. }
  91. return $options;
  92. })
  93. ->required()
  94. ->live()
  95. ->visible(fn (Forms\Get $get) => $get('prefill_method') === 'actuals'),
  96. ])->visible(fn (Forms\Get $get) => $get('prefill_data') === true),
  97. Forms\Components\Textarea::make('notes')
  98. ->label('Notes')
  99. ->columnSpanFull(),
  100. ]),
  101. Step::make('Modify Budget Structure')
  102. ->schema([
  103. Forms\Components\CheckboxList::make('selected_accounts')
  104. ->label('Select Accounts to Exclude')
  105. ->options(function (Forms\Get $get) {
  106. $fiscalYear = $get('actuals_fiscal_year');
  107. // Get all budgetable accounts
  108. $allAccounts = Account::query()->budgetable()->pluck('name', 'id')->toArray();
  109. // Get accounts that have actuals for the selected fiscal year
  110. $accountsWithActuals = Account::query()
  111. ->budgetable()
  112. ->whereHas('journalEntries.transaction', function (Builder $query) use ($fiscalYear) {
  113. $query->whereYear('posted_at', $fiscalYear);
  114. })
  115. ->pluck('name', 'id')
  116. ->toArray();
  117. return $allAccounts + $accountsWithActuals; // Merge both sets
  118. })
  119. ->columns(2) // Display in two columns
  120. ->searchable() // Allow searching for accounts
  121. ->bulkToggleable() // Enable "Select All" / "Deselect All"
  122. ->selectAllAction(
  123. fn (Action $action, Forms\Get $get) => $action
  124. ->label('Remove all items without past actuals (' .
  125. Account::query()->budgetable()->whereDoesntHave('journalEntries.transaction', function (Builder $query) use ($get) {
  126. $query->whereYear('posted_at', $get('actuals_fiscal_year'));
  127. })->count() . ' lines)')
  128. )
  129. ->disableOptionWhen(fn (string $value, Forms\Get $get) => in_array(
  130. $value,
  131. Account::query()->budgetable()->whereHas('journalEntries.transaction', function (Builder $query) use ($get) {
  132. $query->whereYear('posted_at', Carbon::parse($get('actuals_fiscal_year'))->year);
  133. })->pluck('id')->toArray()
  134. ))
  135. ->visible(fn (Forms\Get $get) => $get('prefill_method') === 'actuals'),
  136. ])
  137. ->visible(function (Forms\Get $get) {
  138. $prefillMethod = $get('prefill_method');
  139. if ($prefillMethod !== 'actuals' || blank($get('actuals_fiscal_year'))) {
  140. return false;
  141. }
  142. return Account::query()->budgetable()->whereDoesntHave('journalEntries.transaction', function (Builder $query) use ($get) {
  143. $query->whereYear('posted_at', $get('actuals_fiscal_year'));
  144. })->exists();
  145. }),
  146. ];
  147. }
  148. protected function handleRecordCreation(array $data): Model
  149. {
  150. /** @var Budget $budget */
  151. $budget = Budget::create([
  152. 'name' => $data['name'],
  153. 'interval_type' => $data['interval_type'],
  154. 'start_date' => $data['start_date'],
  155. 'end_date' => $data['end_date'],
  156. 'notes' => $data['notes'] ?? null,
  157. ]);
  158. $selectedAccounts = $data['selected_accounts'] ?? [];
  159. $accountsToInclude = Account::query()
  160. ->budgetable()
  161. ->whereNotIn('id', $selectedAccounts)
  162. ->get();
  163. foreach ($accountsToInclude as $account) {
  164. /** @var BudgetItem $budgetItem */
  165. $budgetItem = $budget->budgetItems()->create([
  166. 'account_id' => $account->id,
  167. ]);
  168. $allocationStart = Carbon::parse($data['start_date']);
  169. // Determine amounts based on the prefill method
  170. $amounts = match ($data['prefill_method'] ?? null) {
  171. 'actuals' => $this->getAmountsFromActuals($account, $data['actuals_fiscal_year'], BudgetIntervalType::parse($data['interval_type'])),
  172. 'previous_budget' => $this->getAmountsFromPreviousBudget($account, $data['source_budget_id'], BudgetIntervalType::parse($data['interval_type'])),
  173. default => $this->generateZeroAmounts($data['start_date'], $data['end_date'], BudgetIntervalType::parse($data['interval_type'])),
  174. };
  175. foreach ($amounts as $periodLabel => $amount) {
  176. $allocationEnd = self::calculateEndDate($allocationStart, BudgetIntervalType::parse($data['interval_type']));
  177. $budgetItem->allocations()->create([
  178. 'period' => $periodLabel,
  179. 'interval_type' => $data['interval_type'],
  180. 'start_date' => $allocationStart->toDateString(),
  181. 'end_date' => $allocationEnd->toDateString(),
  182. 'amount' => $amount,
  183. ]);
  184. $allocationStart = $allocationEnd->addDay();
  185. }
  186. }
  187. return $budget;
  188. }
  189. private function getAmountsFromActuals(Account $account, int $fiscalYear, BudgetIntervalType $intervalType): array
  190. {
  191. // Determine the fiscal year start and end dates
  192. $fiscalYearStart = Carbon::create($fiscalYear, 1, 1)->startOfYear();
  193. $fiscalYearEnd = $fiscalYearStart->copy()->endOfYear();
  194. $netMovement = Accounting::getNetMovement($account, $fiscalYearStart->toDateString(), $fiscalYearEnd->toDateString());
  195. return $this->distributeAmountAcrossPeriods($netMovement->getAmount(), $fiscalYearStart, $fiscalYearEnd, $intervalType);
  196. }
  197. private function distributeAmountAcrossPeriods(float $totalAmount, Carbon $startDate, Carbon $endDate, BudgetIntervalType $intervalType): array
  198. {
  199. $amounts = [];
  200. $periods = [];
  201. // Generate period labels based on interval type
  202. $currentPeriod = $startDate->copy();
  203. while ($currentPeriod->lte($endDate)) {
  204. $periods[] = $this->determinePeriod($currentPeriod, $intervalType);
  205. $currentPeriod->addUnit($intervalType->value);
  206. }
  207. // Evenly distribute total amount across periods
  208. $periodCount = count($periods);
  209. $amountPerPeriod = $periodCount > 0 ? round($totalAmount / $periodCount, 2) : 0;
  210. foreach ($periods as $periodLabel) {
  211. $amounts[$periodLabel] = $amountPerPeriod;
  212. }
  213. return $amounts;
  214. }
  215. private function getAmountsFromPreviousBudget(Account $account, int $sourceBudgetId, BudgetIntervalType $intervalType): array
  216. {
  217. $amounts = [];
  218. $previousAllocations = BudgetAllocation::query()
  219. ->whereHas('budgetItem', fn ($query) => $query->where('account_id', $account->id)->where('budget_id', $sourceBudgetId))
  220. ->get();
  221. foreach ($previousAllocations as $allocation) {
  222. $amounts[$allocation->period] = $allocation->amount;
  223. }
  224. return $amounts;
  225. }
  226. private function generateZeroAmounts(string $startDate, string $endDate, BudgetIntervalType $intervalType): array
  227. {
  228. $amounts = [];
  229. $currentPeriod = Carbon::parse($startDate);
  230. while ($currentPeriod->lte(Carbon::parse($endDate))) {
  231. $period = $this->determinePeriod($currentPeriod, $intervalType);
  232. $amounts[$period] = 0.00;
  233. $currentPeriod->addUnit($intervalType->value);
  234. }
  235. return $amounts;
  236. }
  237. private function determinePeriod(Carbon $date, BudgetIntervalType $intervalType): string
  238. {
  239. return match ($intervalType) {
  240. BudgetIntervalType::Month => $date->format('F Y'),
  241. BudgetIntervalType::Quarter => 'Q' . $date->quarter . ' ' . $date->year,
  242. BudgetIntervalType::Year => (string) $date->year,
  243. default => $date->format('Y-m-d'),
  244. };
  245. }
  246. private static function calculateEndDate(Carbon $startDate, BudgetIntervalType $intervalType): Carbon
  247. {
  248. return match ($intervalType) {
  249. BudgetIntervalType::Month => $startDate->copy()->endOfMonth(),
  250. BudgetIntervalType::Quarter => $startDate->copy()->endOfQuarter(),
  251. BudgetIntervalType::Year => $startDate->copy()->endOfYear(),
  252. };
  253. }
  254. }