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 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace App\Filament\Company\Resources\Accounting\BudgetResource\Pages;
  3. use App\Filament\Company\Resources\Accounting\BudgetResource;
  4. use App\Models\Accounting\Budget;
  5. use App\Models\Accounting\BudgetItem;
  6. use Filament\Resources\Pages\CreateRecord;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Carbon;
  9. class CreateBudget extends CreateRecord
  10. {
  11. protected static string $resource = BudgetResource::class;
  12. protected function handleRecordCreation(array $data): Model
  13. {
  14. /** @var Budget $budget */
  15. $budget = Budget::create([
  16. 'name' => $data['name'],
  17. 'interval_type' => $data['interval_type'],
  18. 'start_date' => $data['start_date'],
  19. 'end_date' => $data['end_date'],
  20. 'notes' => $data['notes'] ?? null,
  21. ]);
  22. foreach ($data['budgetItems'] as $itemData) {
  23. /** @var BudgetItem $budgetItem */
  24. $budgetItem = $budget->budgetItems()->create([
  25. 'account_id' => $itemData['account_id'],
  26. ]);
  27. $allocationStart = Carbon::parse($data['start_date']);
  28. foreach ($itemData['amounts'] as $periodLabel => $amount) {
  29. $allocationEnd = self::calculateEndDate($allocationStart, $data['interval_type']);
  30. $budgetItem->allocations()->create([
  31. 'period' => $periodLabel,
  32. 'interval_type' => $data['interval_type'],
  33. 'start_date' => $allocationStart->toDateString(),
  34. 'end_date' => $allocationEnd->toDateString(),
  35. 'amount' => $amount,
  36. ]);
  37. $allocationStart = $allocationEnd->addDay();
  38. }
  39. }
  40. return $budget;
  41. }
  42. private static function calculateEndDate(Carbon $startDate, string $intervalType): Carbon
  43. {
  44. return match ($intervalType) {
  45. 'quarter' => $startDate->copy()->addMonths(2)->endOfMonth(),
  46. 'year' => $startDate->copy()->endOfYear(),
  47. default => $startDate->copy()->endOfMonth(),
  48. };
  49. }
  50. }