Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

CreateBudget.php 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. <?php
  2. namespace App\Filament\Company\Resources\Accounting\BudgetResource\Pages;
  3. use App\Enums\Accounting\BudgetIntervalType;
  4. use App\Enums\Accounting\BudgetSourceType;
  5. use App\Facades\Accounting;
  6. use App\Filament\Company\Resources\Accounting\BudgetResource;
  7. use App\Filament\Forms\Components\CustomSection;
  8. use App\Models\Accounting\Account;
  9. use App\Models\Accounting\Budget;
  10. use App\Models\Accounting\BudgetAllocation;
  11. use App\Models\Accounting\BudgetItem;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use Filament\Forms;
  14. use Filament\Forms\Components\Actions\Action;
  15. use Filament\Forms\Components\Wizard\Step;
  16. use Filament\Resources\Pages\CreateRecord;
  17. use Illuminate\Database\Eloquent\Builder;
  18. use Illuminate\Database\Eloquent\Model;
  19. use Illuminate\Support\Carbon;
  20. use Illuminate\Support\Collection;
  21. class CreateBudget extends CreateRecord
  22. {
  23. use CreateRecord\Concerns\HasWizard;
  24. protected static string $resource = BudgetResource::class;
  25. // Add computed properties
  26. public function getBudgetableAccounts(): Collection
  27. {
  28. return $this->getAccountsCache('budgetable', function () {
  29. return Account::query()->budgetable()->get();
  30. });
  31. }
  32. public function getAccountsWithActuals(): Collection
  33. {
  34. $fiscalYear = $this->data['source_fiscal_year'] ?? null;
  35. if (blank($fiscalYear)) {
  36. return collect();
  37. }
  38. return $this->getAccountsCache("actuals_{$fiscalYear}", function () use ($fiscalYear) {
  39. return Account::query()
  40. ->budgetable()
  41. ->whereHas('journalEntries.transaction', function (Builder $query) use ($fiscalYear) {
  42. $query->whereYear('posted_at', $fiscalYear);
  43. })
  44. ->get();
  45. });
  46. }
  47. public function getAccountsWithoutActuals(): Collection
  48. {
  49. $fiscalYear = $this->data['source_fiscal_year'] ?? null;
  50. if (blank($fiscalYear)) {
  51. return collect();
  52. }
  53. $budgetableAccounts = $this->getBudgetableAccounts();
  54. $accountsWithActuals = $this->getAccountsWithActuals();
  55. return $budgetableAccounts->whereNotIn('id', $accountsWithActuals->pluck('id'));
  56. }
  57. public function getAccountBalances(): Collection
  58. {
  59. $fiscalYear = $this->data['source_fiscal_year'] ?? null;
  60. if (blank($fiscalYear)) {
  61. return collect();
  62. }
  63. return $this->getAccountsCache("balances_{$fiscalYear}", function () use ($fiscalYear) {
  64. $fiscalYearStart = Carbon::create($fiscalYear, 1, 1)->startOfYear();
  65. $fiscalYearEnd = $fiscalYearStart->copy()->endOfYear();
  66. return Accounting::getAccountBalances(
  67. $fiscalYearStart->toDateString(),
  68. $fiscalYearEnd->toDateString(),
  69. $this->getBudgetableAccounts()->pluck('id')->toArray()
  70. )->get();
  71. });
  72. }
  73. // Cache helper to avoid duplicate queries
  74. private array $accountsCache = [];
  75. private function getAccountsCache(string $key, callable $callback): Collection
  76. {
  77. if (! isset($this->accountsCache[$key])) {
  78. $this->accountsCache[$key] = $callback();
  79. }
  80. return $this->accountsCache[$key];
  81. }
  82. public function getSteps(): array
  83. {
  84. return [
  85. Step::make('General Information')
  86. ->icon('heroicon-o-document-text')
  87. ->columns(2)
  88. ->schema([
  89. Forms\Components\TextInput::make('name')
  90. ->required()
  91. ->maxLength(255),
  92. Forms\Components\Select::make('interval_type')
  93. ->label('Budget Interval')
  94. ->options(BudgetIntervalType::class)
  95. ->default(BudgetIntervalType::Month->value)
  96. ->required()
  97. ->live(),
  98. Forms\Components\DatePicker::make('start_date')
  99. ->required()
  100. ->default(company_today()->startOfYear())
  101. ->live(),
  102. Forms\Components\DatePicker::make('end_date')
  103. ->required()
  104. ->default(company_today()->endOfYear())
  105. ->live()
  106. ->disabled(static fn (Forms\Get $get) => blank($get('start_date')))
  107. ->minDate(fn (Forms\Get $get) => match (BudgetIntervalType::parse($get('interval_type'))) {
  108. BudgetIntervalType::Month => Carbon::parse($get('start_date'))->addMonth(),
  109. BudgetIntervalType::Quarter => Carbon::parse($get('start_date'))->addQuarter(),
  110. BudgetIntervalType::Year => Carbon::parse($get('start_date'))->addYear(),
  111. default => Carbon::parse($get('start_date'))->addDay(),
  112. })
  113. ->maxDate(fn (Forms\Get $get) => Carbon::parse($get('start_date'))->endOfYear()),
  114. ]),
  115. Step::make('Budget Setup & Settings')
  116. ->icon('heroicon-o-cog-6-tooth')
  117. ->schema([
  118. // Prefill configuration
  119. Forms\Components\Toggle::make('prefill_data')
  120. ->label('Prefill Data')
  121. ->helperText('Enable this option to prefill the budget with historical data')
  122. ->default(false)
  123. ->live(),
  124. Forms\Components\Grid::make(1)
  125. ->schema([
  126. Forms\Components\Select::make('source_type')
  127. ->label('Prefill Method')
  128. ->options(BudgetSourceType::class)
  129. ->live()
  130. ->required(),
  131. // If user selects to copy a previous budget
  132. Forms\Components\Select::make('source_budget_id')
  133. ->label('Source Budget')
  134. ->options(fn () => Budget::query()
  135. ->orderByDesc('end_date')
  136. ->pluck('name', 'id'))
  137. ->searchable()
  138. ->required()
  139. ->visible(fn (Forms\Get $get) => BudgetSourceType::parse($get('source_type'))?->isBudget()),
  140. // If user selects to use historical actuals
  141. Forms\Components\Select::make('source_fiscal_year')
  142. ->label('Fiscal Year')
  143. ->options(function () {
  144. $options = [];
  145. $company = auth()->user()->currentCompany;
  146. $earliestDate = Carbon::parse(Accounting::getEarliestTransactionDate());
  147. $fiscalYearStartCurrent = Carbon::parse($company->locale->fiscalYearStartDate());
  148. for ($year = $fiscalYearStartCurrent->year; $year >= $earliestDate->year; $year--) {
  149. $options[$year] = $year;
  150. }
  151. return $options;
  152. })
  153. ->required()
  154. ->live()
  155. ->afterStateUpdated(function (Forms\Set $set) {
  156. // Clear the cache when the fiscal year changes
  157. $this->accountsCache = [];
  158. // Get all accounts without actuals
  159. $accountIdsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  160. // Set exclude_accounts_without_actuals to true by default
  161. $set('exclude_accounts_without_actuals', true);
  162. // Update the selected_accounts field to exclude accounts without actuals
  163. $set('selected_accounts', $accountIdsWithoutActuals);
  164. })
  165. ->visible(fn (Forms\Get $get) => BudgetSourceType::parse($get('source_type'))?->isActuals()),
  166. ])->visible(fn (Forms\Get $get) => $get('prefill_data') === true),
  167. CustomSection::make('Account Selection')
  168. ->contained(false)
  169. ->schema([
  170. Forms\Components\Checkbox::make('exclude_accounts_without_actuals')
  171. ->label('Exclude all accounts without actuals')
  172. ->helperText(function () {
  173. $count = $this->getAccountsWithoutActuals()->count();
  174. return "Will exclude {$count} accounts without transaction data in the selected fiscal year";
  175. })
  176. ->default(true)
  177. ->live()
  178. ->afterStateUpdated(function (Forms\Set $set, $state) {
  179. if ($state) {
  180. // When checked, select all accounts without actuals
  181. $accountsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  182. $set('selected_accounts', $accountsWithoutActuals);
  183. } else {
  184. // When unchecked, clear the selection
  185. $set('selected_accounts', []);
  186. }
  187. }),
  188. Forms\Components\CheckboxList::make('selected_accounts')
  189. ->label('Select Accounts to Exclude')
  190. ->options(function () {
  191. // Get all budgetable accounts
  192. return $this->getBudgetableAccounts()->pluck('name', 'id')->toArray();
  193. })
  194. ->descriptions(function (Forms\Components\CheckboxList $component) {
  195. $fiscalYear = $this->data['source_fiscal_year'] ?? null;
  196. if (blank($fiscalYear)) {
  197. return [];
  198. }
  199. $accountIds = array_keys($component->getOptions());
  200. $descriptions = [];
  201. if (empty($accountIds)) {
  202. return [];
  203. }
  204. // Get account balances
  205. $accountBalances = $this->getAccountBalances()->keyBy('id');
  206. // Get accounts with actuals
  207. $accountsWithActuals = $this->getAccountsWithActuals()->pluck('id')->toArray();
  208. // Process all accounts
  209. foreach ($accountIds as $accountId) {
  210. $balance = $accountBalances[$accountId] ?? null;
  211. $hasActuals = in_array($accountId, $accountsWithActuals);
  212. if ($balance && $hasActuals) {
  213. // Calculate net movement
  214. $netMovement = Accounting::calculateNetMovementByCategory(
  215. $balance->category,
  216. $balance->total_debit ?? 0,
  217. $balance->total_credit ?? 0
  218. );
  219. // Format the amount for display
  220. $formattedAmount = CurrencyConverter::formatCentsToMoney($netMovement);
  221. $descriptions[$accountId] = "{$formattedAmount} in {$fiscalYear}";
  222. } else {
  223. $descriptions[$accountId] = "No transactions in {$fiscalYear}";
  224. }
  225. }
  226. return $descriptions;
  227. })
  228. ->columns(2) // Display in two columns
  229. ->searchable() // Allow searching for accounts
  230. ->bulkToggleable() // Enable "Select All" / "Deselect All"
  231. ->selectAllAction(fn (Action $action) => $action->label('Exclude all accounts'))
  232. ->deselectAllAction(fn (Action $action) => $action->label('Include all accounts'))
  233. ->afterStateUpdated(function (Forms\Set $set, $state) {
  234. // Get all accounts without actuals
  235. $accountsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  236. // Check if all accounts without actuals are in the selected accounts
  237. $allAccountsWithoutActualsSelected = empty(array_diff($accountsWithoutActuals, $state));
  238. // Update the exclude_accounts_without_actuals checkbox state
  239. $set('exclude_accounts_without_actuals', $allAccountsWithoutActualsSelected);
  240. }),
  241. ])
  242. ->visible(function (Forms\Get $get) {
  243. // Only show when using actuals with valid fiscal year AND accounts without transactions exist
  244. $prefillSourceType = BudgetSourceType::parse($get('source_type'));
  245. if ($prefillSourceType !== BudgetSourceType::Actuals || blank($get('source_fiscal_year'))) {
  246. return false;
  247. }
  248. return $this->getAccountsWithoutActuals()->isNotEmpty();
  249. }),
  250. Forms\Components\Textarea::make('notes')
  251. ->label('Notes')
  252. ->columnSpanFull(),
  253. ]),
  254. ];
  255. }
  256. protected function handleRecordCreation(array $data): Model
  257. {
  258. /** @var Budget $budget */
  259. $budget = Budget::create([
  260. 'source_budget_id' => $data['source_budget_id'] ?? null,
  261. 'source_fiscal_year' => $data['source_fiscal_year'] ?? null,
  262. 'source_type' => $data['source_type'] ?? null,
  263. 'name' => $data['name'],
  264. 'interval_type' => $data['interval_type'],
  265. 'start_date' => $data['start_date'],
  266. 'end_date' => $data['end_date'],
  267. 'notes' => $data['notes'] ?? null,
  268. ]);
  269. $selectedAccounts = $data['selected_accounts'] ?? [];
  270. $accountsToInclude = Account::query()
  271. ->budgetable()
  272. ->whereNotIn('id', $selectedAccounts)
  273. ->get();
  274. foreach ($accountsToInclude as $account) {
  275. /** @var BudgetItem $budgetItem */
  276. $budgetItem = $budget->budgetItems()->create([
  277. 'account_id' => $account->id,
  278. ]);
  279. $allocationStart = Carbon::parse($data['start_date']);
  280. $budgetEndDate = Carbon::parse($data['end_date']);
  281. // Determine amounts based on the prefill method
  282. $amounts = match ($data['source_type'] ?? null) {
  283. 'actuals' => $this->getAmountsFromActuals($account, $data['source_fiscal_year'], BudgetIntervalType::parse($data['interval_type'])),
  284. 'previous_budget' => $this->getAmountsFromPreviousBudget($account, $data['source_budget_id'], BudgetIntervalType::parse($data['interval_type'])),
  285. default => $this->generateZeroAmounts($data['start_date'], $data['end_date'], BudgetIntervalType::parse($data['interval_type'])),
  286. };
  287. if (empty($amounts)) {
  288. $amounts = $this->generateZeroAmounts(
  289. $data['start_date'],
  290. $data['end_date'],
  291. BudgetIntervalType::parse($data['interval_type'])
  292. );
  293. }
  294. foreach ($amounts as $periodLabel => $amount) {
  295. if ($allocationStart->gt($budgetEndDate)) {
  296. break;
  297. }
  298. $allocationEnd = self::calculateEndDate($allocationStart, BudgetIntervalType::parse($data['interval_type']));
  299. if ($allocationEnd->gt($budgetEndDate)) {
  300. $allocationEnd = $budgetEndDate->copy();
  301. }
  302. $budgetItem->allocations()->create([
  303. 'period' => $periodLabel,
  304. 'interval_type' => $data['interval_type'],
  305. 'start_date' => $allocationStart->toDateString(),
  306. 'end_date' => $allocationEnd->toDateString(),
  307. 'amount' => CurrencyConverter::convertCentsToFloat($amount),
  308. ]);
  309. $allocationStart = $allocationEnd->addDay();
  310. }
  311. }
  312. return $budget;
  313. }
  314. private function getAmountsFromActuals(Account $account, int $fiscalYear, BudgetIntervalType $intervalType): array
  315. {
  316. $amounts = [];
  317. // Get the start and end date of the budget being created
  318. $budgetStartDate = Carbon::parse($this->data['start_date']);
  319. $budgetEndDate = Carbon::parse($this->data['end_date']);
  320. // Map to equivalent dates in the reference fiscal year
  321. $referenceStartDate = Carbon::create($fiscalYear, $budgetStartDate->month, $budgetStartDate->day);
  322. $referenceEndDate = Carbon::create($fiscalYear, $budgetEndDate->month, $budgetEndDate->day);
  323. // Handle year boundary case (if budget crosses year boundary)
  324. if ($budgetStartDate->month > $budgetEndDate->month ||
  325. ($budgetStartDate->month === $budgetEndDate->month && $budgetStartDate->day > $budgetEndDate->day)) {
  326. $referenceEndDate->year++;
  327. }
  328. if ($intervalType->isMonth()) {
  329. // Process month by month within the reference period
  330. $currentDate = $referenceStartDate->copy()->startOfMonth();
  331. $lastMonth = $referenceEndDate->copy()->startOfMonth();
  332. while ($currentDate->lte($lastMonth)) {
  333. $periodStart = $currentDate->copy()->startOfMonth();
  334. $periodEnd = $currentDate->copy()->endOfMonth();
  335. $periodLabel = $this->determinePeriod($periodStart, $intervalType);
  336. $netMovement = Accounting::getNetMovement(
  337. $account,
  338. $periodStart->toDateString(),
  339. $periodEnd->toDateString()
  340. );
  341. $amounts[$periodLabel] = $netMovement->getAmount();
  342. $currentDate->addMonth();
  343. }
  344. } elseif ($intervalType->isQuarter()) {
  345. // Process quarter by quarter within the reference period
  346. $currentDate = $referenceStartDate->copy()->startOfQuarter();
  347. $lastQuarter = $referenceEndDate->copy()->startOfQuarter();
  348. while ($currentDate->lte($lastQuarter)) {
  349. $periodStart = $currentDate->copy()->startOfQuarter();
  350. $periodEnd = $currentDate->copy()->endOfQuarter();
  351. $periodLabel = $this->determinePeriod($periodStart, $intervalType);
  352. $netMovement = Accounting::getNetMovement(
  353. $account,
  354. $periodStart->toDateString(),
  355. $periodEnd->toDateString()
  356. );
  357. $amounts[$periodLabel] = $netMovement->getAmount();
  358. $currentDate->addQuarter();
  359. }
  360. } else {
  361. // For yearly intervals
  362. $periodStart = $referenceStartDate->copy()->startOfYear();
  363. $periodEnd = $referenceEndDate->copy()->endOfYear();
  364. $periodLabel = $this->determinePeriod($periodStart, $intervalType);
  365. $netMovement = Accounting::getNetMovement(
  366. $account,
  367. $periodStart->toDateString(),
  368. $periodEnd->toDateString()
  369. );
  370. $amounts[$periodLabel] = $netMovement->getAmount();
  371. }
  372. return $amounts;
  373. }
  374. private function distributeAmountAcrossPeriods(int $totalAmountInCents, Carbon $startDate, Carbon $endDate, BudgetIntervalType $intervalType): array
  375. {
  376. $amounts = [];
  377. $periods = [];
  378. // Generate period labels based on interval type
  379. $currentPeriod = $startDate->copy();
  380. while ($currentPeriod->lte($endDate)) {
  381. $periods[] = $this->determinePeriod($currentPeriod, $intervalType);
  382. $currentPeriod->addUnit($intervalType->value);
  383. }
  384. // Evenly distribute total amount across periods
  385. $periodCount = count($periods);
  386. if ($periodCount === 0) {
  387. return $amounts;
  388. }
  389. $baseAmount = intdiv($totalAmountInCents, $periodCount); // Floor division to get the base amount in cents
  390. $remainder = $totalAmountInCents % $periodCount; // Remaining cents to distribute
  391. foreach ($periods as $index => $period) {
  392. $amounts[$period] = $baseAmount + ($index < $remainder ? 1 : 0); // Distribute remainder cents evenly
  393. }
  394. return $amounts;
  395. }
  396. private function getAmountsFromPreviousBudget(Account $account, int $sourceBudgetId, BudgetIntervalType $intervalType): array
  397. {
  398. $amounts = [];
  399. // Get the budget being created start and end dates
  400. $newBudgetStartDate = Carbon::parse($this->data['start_date']);
  401. $newBudgetEndDate = Carbon::parse($this->data['end_date']);
  402. // Get source budget's date information
  403. $sourceBudget = Budget::findOrFail($sourceBudgetId);
  404. $sourceBudgetType = $sourceBudget->interval_type;
  405. // Retrieve all previous allocations for this account
  406. $previousAllocations = BudgetAllocation::query()
  407. ->whereHas(
  408. 'budgetItem',
  409. fn ($query) => $query->where('account_id', $account->id)
  410. ->where('budget_id', $sourceBudgetId)
  411. )
  412. ->orderBy('start_date')
  413. ->get();
  414. if ($previousAllocations->isEmpty()) {
  415. return $this->generateZeroAmounts(
  416. $this->data['start_date'],
  417. $this->data['end_date'],
  418. $intervalType
  419. );
  420. }
  421. // Map previous budget periods to current budget periods
  422. if ($intervalType === $sourceBudgetType) {
  423. // Same interval type: direct mapping of equivalent periods
  424. foreach ($previousAllocations as $allocation) {
  425. $allocationDate = Carbon::parse($allocation->start_date);
  426. // Create an equivalent date in the new budget's time range
  427. $equivalentMonth = $allocationDate->month;
  428. $equivalentDay = $allocationDate->day;
  429. $equivalentYear = $newBudgetStartDate->year;
  430. // Adjust year if the budget spans multiple years
  431. if ($newBudgetStartDate->month > $newBudgetEndDate->month &&
  432. $equivalentMonth < $newBudgetStartDate->month) {
  433. $equivalentYear++;
  434. }
  435. $equivalentDate = Carbon::create($equivalentYear, $equivalentMonth, $equivalentDay);
  436. // Only include if the date falls within our new budget period
  437. if ($equivalentDate->between($newBudgetStartDate, $newBudgetEndDate)) {
  438. $periodLabel = $this->determinePeriod($equivalentDate, $intervalType);
  439. $amounts[$periodLabel] = $allocation->getRawOriginal('amount');
  440. }
  441. }
  442. } else {
  443. // Handle conversion between different interval types
  444. $newBudgetPeriods = $this->generateZeroAmounts(
  445. $this->data['start_date'],
  446. $this->data['end_date'],
  447. $intervalType
  448. );
  449. // Fill with zeros initially
  450. $amounts = array_fill_keys(array_keys($newBudgetPeriods), 0);
  451. // Group previous allocations by their date range
  452. $allocationsByRange = [];
  453. foreach ($previousAllocations as $allocation) {
  454. $allocationsByRange[] = [
  455. 'start' => Carbon::parse($allocation->start_date),
  456. 'end' => Carbon::parse($allocation->end_date),
  457. 'amount' => $allocation->getRawOriginal('amount'),
  458. ];
  459. }
  460. // Create new allocations based on interval type
  461. $currentDate = Carbon::parse($this->data['start_date']);
  462. $endDate = Carbon::parse($this->data['end_date']);
  463. while ($currentDate->lte($endDate)) {
  464. $periodStart = $currentDate->copy();
  465. $periodEnd = self::calculateEndDate($currentDate, $intervalType);
  466. if ($periodEnd->gt($endDate)) {
  467. $periodEnd = $endDate->copy();
  468. }
  469. $periodLabel = $this->determinePeriod($periodStart, $intervalType);
  470. // Calculate the proportional amount from the source budget
  471. $weightedAmount = 0;
  472. foreach ($allocationsByRange as $allocation) {
  473. // Find overlapping days between new period and source allocation
  474. $overlapStart = max($periodStart, $allocation['start']);
  475. $overlapEnd = min($periodEnd, $allocation['end']);
  476. if ($overlapStart <= $overlapEnd) {
  477. // Calculate overlapping days
  478. $overlapDays = $overlapStart->diffInDays($overlapEnd) + 1;
  479. $allocationTotalDays = $allocation['start']->diffInDays($allocation['end']) + 1;
  480. // Calculate proportional amount based on days
  481. $proportion = $overlapDays / $allocationTotalDays;
  482. $proportionalAmount = (int) ($allocation['amount'] * $proportion);
  483. $weightedAmount += $proportionalAmount;
  484. }
  485. }
  486. // Assign the calculated amount to the period
  487. if (array_key_exists($periodLabel, $amounts)) {
  488. $amounts[$periodLabel] = $weightedAmount;
  489. }
  490. // Move to the next period
  491. $currentDate = $periodEnd->copy()->addDay();
  492. }
  493. }
  494. return $amounts;
  495. }
  496. private function generateZeroAmounts(string $startDate, string $endDate, BudgetIntervalType $intervalType): array
  497. {
  498. $amounts = [];
  499. $currentPeriod = Carbon::parse($startDate);
  500. while ($currentPeriod->lte(Carbon::parse($endDate))) {
  501. $period = $this->determinePeriod($currentPeriod, $intervalType);
  502. $amounts[$period] = 0;
  503. $currentPeriod->addUnit($intervalType->value);
  504. }
  505. return $amounts;
  506. }
  507. private function determinePeriod(Carbon $date, BudgetIntervalType $intervalType): string
  508. {
  509. return match ($intervalType) {
  510. BudgetIntervalType::Month => $date->format('M Y'),
  511. BudgetIntervalType::Quarter => 'Q' . $date->quarter . ' ' . $date->year,
  512. BudgetIntervalType::Year => (string) $date->year,
  513. };
  514. }
  515. private static function calculateEndDate(Carbon $startDate, BudgetIntervalType $intervalType): Carbon
  516. {
  517. return match ($intervalType) {
  518. BudgetIntervalType::Month => $startDate->copy()->endOfMonth(),
  519. BudgetIntervalType::Quarter => $startDate->copy()->endOfQuarter(),
  520. BudgetIntervalType::Year => $startDate->copy()->endOfYear(),
  521. };
  522. }
  523. }