Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

CreateBudget.php 2.3KB

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