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.

CreateBudget.php 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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\CustomSection;
  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\Forms;
  13. use Filament\Forms\Components\Actions\Action;
  14. use Filament\Forms\Components\Wizard\Step;
  15. use Filament\Resources\Pages\CreateRecord;
  16. use Illuminate\Database\Eloquent\Builder;
  17. use Illuminate\Database\Eloquent\Model;
  18. use Illuminate\Support\Carbon;
  19. use Illuminate\Support\Collection;
  20. class CreateBudget extends CreateRecord
  21. {
  22. use CreateRecord\Concerns\HasWizard;
  23. protected static string $resource = BudgetResource::class;
  24. // Add computed properties
  25. public function getBudgetableAccounts(): Collection
  26. {
  27. return $this->getAccountsCache('budgetable', function () {
  28. return Account::query()->budgetable()->get();
  29. });
  30. }
  31. public function getAccountsWithActuals(): Collection
  32. {
  33. $fiscalYear = $this->data['actuals_fiscal_year'] ?? null;
  34. if (blank($fiscalYear)) {
  35. return collect();
  36. }
  37. return $this->getAccountsCache("actuals_{$fiscalYear}", function () use ($fiscalYear) {
  38. return Account::query()
  39. ->budgetable()
  40. ->whereHas('journalEntries.transaction', function (Builder $query) use ($fiscalYear) {
  41. $query->whereYear('posted_at', $fiscalYear);
  42. })
  43. ->get();
  44. });
  45. }
  46. public function getAccountsWithoutActuals(): Collection
  47. {
  48. $fiscalYear = $this->data['actuals_fiscal_year'] ?? null;
  49. if (blank($fiscalYear)) {
  50. return collect();
  51. }
  52. $budgetableAccounts = $this->getBudgetableAccounts();
  53. $accountsWithActuals = $this->getAccountsWithActuals();
  54. return $budgetableAccounts->whereNotIn('id', $accountsWithActuals->pluck('id'));
  55. }
  56. public function getAccountBalances(): Collection
  57. {
  58. $fiscalYear = $this->data['actuals_fiscal_year'] ?? null;
  59. if (blank($fiscalYear)) {
  60. return collect();
  61. }
  62. return $this->getAccountsCache("balances_{$fiscalYear}", function () use ($fiscalYear) {
  63. $fiscalYearStart = Carbon::create($fiscalYear, 1, 1)->startOfYear();
  64. $fiscalYearEnd = $fiscalYearStart->copy()->endOfYear();
  65. return Accounting::getAccountBalances(
  66. $fiscalYearStart->toDateString(),
  67. $fiscalYearEnd->toDateString(),
  68. $this->getBudgetableAccounts()->pluck('id')->toArray()
  69. )->get();
  70. });
  71. }
  72. // Cache helper to avoid duplicate queries
  73. private array $accountsCache = [];
  74. private function getAccountsCache(string $key, callable $callback): Collection
  75. {
  76. if (! isset($this->accountsCache[$key])) {
  77. $this->accountsCache[$key] = $callback();
  78. }
  79. return $this->accountsCache[$key];
  80. }
  81. public function getSteps(): array
  82. {
  83. return [
  84. Step::make('General Information')
  85. ->icon('heroicon-o-document-text')
  86. ->columns(2)
  87. ->schema([
  88. Forms\Components\TextInput::make('name')
  89. ->required()
  90. ->maxLength(255),
  91. Forms\Components\Select::make('interval_type')
  92. ->label('Budget Interval')
  93. ->options(BudgetIntervalType::class)
  94. ->default(BudgetIntervalType::Month->value)
  95. ->required()
  96. ->live(),
  97. Forms\Components\DatePicker::make('start_date')
  98. ->required()
  99. ->default(now()->startOfYear())
  100. ->live(),
  101. Forms\Components\DatePicker::make('end_date')
  102. ->required()
  103. ->default(now()->endOfYear())
  104. ->live()
  105. ->disabled(static fn (Forms\Get $get) => blank($get('start_date')))
  106. ->minDate(fn (Forms\Get $get) => match (BudgetIntervalType::parse($get('interval_type'))) {
  107. BudgetIntervalType::Month => Carbon::parse($get('start_date'))->addMonth(),
  108. BudgetIntervalType::Quarter => Carbon::parse($get('start_date'))->addQuarter(),
  109. BudgetIntervalType::Year => Carbon::parse($get('start_date'))->addYear(),
  110. default => Carbon::parse($get('start_date'))->addDay(),
  111. })
  112. ->maxDate(fn (Forms\Get $get) => Carbon::parse($get('start_date'))->endOfYear()),
  113. ]),
  114. Step::make('Budget Setup & Settings')
  115. ->icon('heroicon-o-cog-6-tooth')
  116. ->schema([
  117. // Prefill configuration
  118. Forms\Components\Toggle::make('prefill_data')
  119. ->label('Prefill Data')
  120. ->helperText('Enable this option to prefill the budget with historical data')
  121. ->default(false)
  122. ->live(),
  123. Forms\Components\Grid::make(1)
  124. ->schema([
  125. Forms\Components\Select::make('prefill_method')
  126. ->label('Prefill Method')
  127. ->options([
  128. 'previous_budget' => 'Copy from a previous budget',
  129. 'actuals' => 'Use historical actuals',
  130. ])
  131. ->live()
  132. ->required(),
  133. // If user selects to copy a previous budget
  134. Forms\Components\Select::make('source_budget_id')
  135. ->label('Source Budget')
  136. ->options(fn () => Budget::query()
  137. ->orderByDesc('end_date')
  138. ->pluck('name', 'id'))
  139. ->searchable()
  140. ->required()
  141. ->visible(fn (Forms\Get $get) => $get('prefill_method') === 'previous_budget'),
  142. // If user selects to use historical actuals
  143. Forms\Components\Select::make('actuals_fiscal_year')
  144. ->label('Reference Fiscal Year')
  145. ->options(function () {
  146. $options = [];
  147. $company = auth()->user()->currentCompany;
  148. $earliestDate = Carbon::parse(Accounting::getEarliestTransactionDate());
  149. $fiscalYearStartCurrent = Carbon::parse($company->locale->fiscalYearStartDate());
  150. for ($year = $fiscalYearStartCurrent->year; $year >= $earliestDate->year; $year--) {
  151. $options[$year] = $year;
  152. }
  153. return $options;
  154. })
  155. ->required()
  156. ->live()
  157. ->afterStateUpdated(function (Forms\Set $set) {
  158. // Clear the cache when the fiscal year changes
  159. $this->accountsCache = [];
  160. // Get all accounts without actuals
  161. $accountIdsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  162. // Set exclude_accounts_without_actuals to true by default
  163. $set('exclude_accounts_without_actuals', true);
  164. // Update the selected_accounts field to exclude accounts without actuals
  165. $set('selected_accounts', $accountIdsWithoutActuals);
  166. })
  167. ->visible(fn (Forms\Get $get) => $get('prefill_method') === 'actuals'),
  168. ])->visible(fn (Forms\Get $get) => $get('prefill_data') === true),
  169. CustomSection::make('Account Selection')
  170. ->contained(false)
  171. ->schema([
  172. Forms\Components\Checkbox::make('exclude_accounts_without_actuals')
  173. ->label('Exclude all accounts without actuals')
  174. ->helperText(function () {
  175. $count = $this->getAccountsWithoutActuals()->count();
  176. return "Will exclude {$count} accounts without transaction data in the selected fiscal year";
  177. })
  178. ->default(true)
  179. ->live()
  180. ->afterStateUpdated(function (Forms\Set $set, $state) {
  181. if ($state) {
  182. // When checked, select all accounts without actuals
  183. $accountsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  184. $set('selected_accounts', $accountsWithoutActuals);
  185. } else {
  186. // When unchecked, clear the selection
  187. $set('selected_accounts', []);
  188. }
  189. }),
  190. Forms\Components\CheckboxList::make('selected_accounts')
  191. ->label('Select Accounts to Exclude')
  192. ->options(function () {
  193. // Get all budgetable accounts
  194. return $this->getBudgetableAccounts()->pluck('name', 'id')->toArray();
  195. })
  196. ->descriptions(function (Forms\Components\CheckboxList $component) {
  197. $fiscalYear = $this->data['actuals_fiscal_year'] ?? null;
  198. if (blank($fiscalYear)) {
  199. return [];
  200. }
  201. $accountIds = array_keys($component->getOptions());
  202. $descriptions = [];
  203. if (empty($accountIds)) {
  204. return [];
  205. }
  206. // Get account balances
  207. $accountBalances = $this->getAccountBalances()->keyBy('id');
  208. // Get accounts with actuals
  209. $accountsWithActuals = $this->getAccountsWithActuals()->pluck('id')->toArray();
  210. // Process all accounts
  211. foreach ($accountIds as $accountId) {
  212. $balance = $accountBalances[$accountId] ?? null;
  213. $hasActuals = in_array($accountId, $accountsWithActuals);
  214. if ($balance && $hasActuals) {
  215. // Calculate net movement
  216. $netMovement = Accounting::calculateNetMovementByCategory(
  217. $balance->category,
  218. $balance->total_debit ?? 0,
  219. $balance->total_credit ?? 0
  220. );
  221. // Format the amount for display
  222. $formattedAmount = CurrencyConverter::formatCentsToMoney($netMovement);
  223. $descriptions[$accountId] = "{$formattedAmount} in {$fiscalYear}";
  224. } else {
  225. $descriptions[$accountId] = "No transactions in {$fiscalYear}";
  226. }
  227. }
  228. return $descriptions;
  229. })
  230. ->columns(2) // Display in two columns
  231. ->searchable() // Allow searching for accounts
  232. ->bulkToggleable() // Enable "Select All" / "Deselect All"
  233. ->selectAllAction(fn (Action $action) => $action->label('Exclude all accounts'))
  234. ->deselectAllAction(fn (Action $action) => $action->label('Include all accounts'))
  235. ->afterStateUpdated(function (Forms\Set $set, $state) {
  236. // Get all accounts without actuals
  237. $accountsWithoutActuals = $this->getAccountsWithoutActuals()->pluck('id')->toArray();
  238. // Check if all accounts without actuals are in the selected accounts
  239. $allAccountsWithoutActualsSelected = empty(array_diff($accountsWithoutActuals, $state));
  240. // Update the exclude_accounts_without_actuals checkbox state
  241. $set('exclude_accounts_without_actuals', $allAccountsWithoutActualsSelected);
  242. }),
  243. ])
  244. ->visible(function () {
  245. // Only show when using actuals with valid fiscal year AND accounts without transactions exist
  246. $prefillMethod = $this->data['prefill_method'] ?? null;
  247. if ($prefillMethod !== 'actuals' || blank($this->data['actuals_fiscal_year'] ?? null)) {
  248. return false;
  249. }
  250. return $this->getAccountsWithoutActuals()->isNotEmpty();
  251. }),
  252. Forms\Components\Textarea::make('notes')
  253. ->label('Notes')
  254. ->columnSpanFull(),
  255. ]),
  256. ];
  257. }
  258. protected function handleRecordCreation(array $data): Model
  259. {
  260. /** @var Budget $budget */
  261. $budget = Budget::create([
  262. 'name' => $data['name'],
  263. 'interval_type' => $data['interval_type'],
  264. 'start_date' => $data['start_date'],
  265. 'end_date' => $data['end_date'],
  266. 'notes' => $data['notes'] ?? null,
  267. ]);
  268. $selectedAccounts = $data['selected_accounts'] ?? [];
  269. $accountsToInclude = Account::query()
  270. ->budgetable()
  271. ->whereNotIn('id', $selectedAccounts)
  272. ->get();
  273. foreach ($accountsToInclude as $account) {
  274. /** @var BudgetItem $budgetItem */
  275. $budgetItem = $budget->budgetItems()->create([
  276. 'account_id' => $account->id,
  277. ]);
  278. $allocationStart = Carbon::parse($data['start_date']);
  279. // Determine amounts based on the prefill method
  280. $amounts = match ($data['prefill_method'] ?? null) {
  281. 'actuals' => $this->getAmountsFromActuals($account, $data['actuals_fiscal_year'], BudgetIntervalType::parse($data['interval_type'])),
  282. 'previous_budget' => $this->getAmountsFromPreviousBudget($account, $data['source_budget_id'], BudgetIntervalType::parse($data['interval_type'])),
  283. default => $this->generateZeroAmounts($data['start_date'], $data['end_date'], BudgetIntervalType::parse($data['interval_type'])),
  284. };
  285. foreach ($amounts as $periodLabel => $amount) {
  286. $allocationEnd = self::calculateEndDate($allocationStart, BudgetIntervalType::parse($data['interval_type']));
  287. $budgetItem->allocations()->create([
  288. 'period' => $periodLabel,
  289. 'interval_type' => $data['interval_type'],
  290. 'start_date' => $allocationStart->toDateString(),
  291. 'end_date' => $allocationEnd->toDateString(),
  292. 'amount' => CurrencyConverter::convertCentsToFloat($amount),
  293. ]);
  294. $allocationStart = $allocationEnd->addDay();
  295. }
  296. }
  297. return $budget;
  298. }
  299. private function getAmountsFromActuals(Account $account, int $fiscalYear, BudgetIntervalType $intervalType): array
  300. {
  301. // Determine the fiscal year start and end dates
  302. $fiscalYearStart = Carbon::create($fiscalYear, 1, 1)->startOfYear();
  303. $fiscalYearEnd = $fiscalYearStart->copy()->endOfYear();
  304. $netMovement = Accounting::getNetMovement($account, $fiscalYearStart->toDateString(), $fiscalYearEnd->toDateString());
  305. return $this->distributeAmountAcrossPeriods($netMovement->getAmount(), $fiscalYearStart, $fiscalYearEnd, $intervalType);
  306. }
  307. private function distributeAmountAcrossPeriods(int $totalAmountInCents, Carbon $startDate, Carbon $endDate, BudgetIntervalType $intervalType): array
  308. {
  309. $amounts = [];
  310. $periods = [];
  311. // Generate period labels based on interval type
  312. $currentPeriod = $startDate->copy();
  313. while ($currentPeriod->lte($endDate)) {
  314. $periods[] = $this->determinePeriod($currentPeriod, $intervalType);
  315. $currentPeriod->addUnit($intervalType->value);
  316. }
  317. // Evenly distribute total amount across periods
  318. $periodCount = count($periods);
  319. if ($periodCount === 0) {
  320. return $amounts;
  321. }
  322. $baseAmount = intdiv($totalAmountInCents, $periodCount); // Floor division to get the base amount in cents
  323. $remainder = $totalAmountInCents % $periodCount; // Remaining cents to distribute
  324. foreach ($periods as $index => $period) {
  325. $amounts[$period] = $baseAmount + ($index < $remainder ? 1 : 0); // Distribute remainder cents evenly
  326. }
  327. return $amounts;
  328. }
  329. private function getAmountsFromPreviousBudget(Account $account, int $sourceBudgetId, BudgetIntervalType $intervalType): array
  330. {
  331. $amounts = [];
  332. $previousAllocations = BudgetAllocation::query()
  333. ->whereHas('budgetItem', fn ($query) => $query->where('account_id', $account->id)->where('budget_id', $sourceBudgetId))
  334. ->get();
  335. foreach ($previousAllocations as $allocation) {
  336. $amounts[$allocation->period] = $allocation->getRawOriginal('amount');
  337. }
  338. return $amounts;
  339. }
  340. private function generateZeroAmounts(string $startDate, string $endDate, BudgetIntervalType $intervalType): array
  341. {
  342. $amounts = [];
  343. $currentPeriod = Carbon::parse($startDate);
  344. while ($currentPeriod->lte(Carbon::parse($endDate))) {
  345. $period = $this->determinePeriod($currentPeriod, $intervalType);
  346. $amounts[$period] = 0;
  347. $currentPeriod->addUnit($intervalType->value);
  348. }
  349. return $amounts;
  350. }
  351. private function determinePeriod(Carbon $date, BudgetIntervalType $intervalType): string
  352. {
  353. return match ($intervalType) {
  354. BudgetIntervalType::Month => $date->format('F Y'),
  355. BudgetIntervalType::Quarter => 'Q' . $date->quarter . ' ' . $date->year,
  356. BudgetIntervalType::Year => (string) $date->year,
  357. default => $date->format('Y-m-d'),
  358. };
  359. }
  360. private static function calculateEndDate(Carbon $startDate, BudgetIntervalType $intervalType): Carbon
  361. {
  362. return match ($intervalType) {
  363. BudgetIntervalType::Month => $startDate->copy()->endOfMonth(),
  364. BudgetIntervalType::Quarter => $startDate->copy()->endOfQuarter(),
  365. BudgetIntervalType::Year => $startDate->copy()->endOfYear(),
  366. };
  367. }
  368. }