Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

CreateBudget.php 15KB

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