Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

RecurringInvoice.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Casts\RateCast;
  5. use App\Collections\Accounting\DocumentCollection;
  6. use App\Enums\Accounting\AdjustmentComputation;
  7. use App\Enums\Accounting\DayOfMonth;
  8. use App\Enums\Accounting\DayOfWeek;
  9. use App\Enums\Accounting\DocumentDiscountMethod;
  10. use App\Enums\Accounting\DocumentType;
  11. use App\Enums\Accounting\EndType;
  12. use App\Enums\Accounting\Frequency;
  13. use App\Enums\Accounting\IntervalType;
  14. use App\Enums\Accounting\InvoiceStatus;
  15. use App\Enums\Accounting\Month;
  16. use App\Enums\Accounting\RecurringInvoiceStatus;
  17. use App\Enums\Setting\PaymentTerms;
  18. use App\Filament\Forms\Components\CustomSection;
  19. use App\Models\Common\Client;
  20. use App\Models\Setting\CompanyProfile;
  21. use App\Observers\RecurringInvoiceObserver;
  22. use App\Support\ScheduleHandler;
  23. use App\Utilities\Localization\Timezone;
  24. use CodeWithDennis\SimpleAlert\Components\Forms\SimpleAlert;
  25. use Filament\Actions\Action;
  26. use Filament\Actions\MountableAction;
  27. use Filament\Forms;
  28. use Filament\Forms\Form;
  29. use Guava\FilamentClusters\Forms\Cluster;
  30. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  31. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  32. use Illuminate\Database\Eloquent\Model;
  33. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  34. use Illuminate\Database\Eloquent\Relations\HasMany;
  35. use Illuminate\Support\Carbon;
  36. #[CollectedBy(DocumentCollection::class)]
  37. #[ObservedBy(RecurringInvoiceObserver::class)]
  38. class RecurringInvoice extends Document
  39. {
  40. protected $table = 'recurring_invoices';
  41. protected $fillable = [
  42. 'company_id',
  43. 'client_id',
  44. 'logo',
  45. 'header',
  46. 'subheader',
  47. 'order_number',
  48. 'payment_terms',
  49. 'approved_at',
  50. 'ended_at',
  51. 'frequency',
  52. 'interval_type',
  53. 'interval_value',
  54. 'month',
  55. 'day_of_month',
  56. 'day_of_week',
  57. 'start_date',
  58. 'end_type',
  59. 'max_occurrences',
  60. 'end_date',
  61. 'occurrences_count',
  62. 'timezone',
  63. 'next_date',
  64. 'last_date',
  65. 'auto_send',
  66. 'send_time',
  67. 'status',
  68. 'currency_code',
  69. 'discount_method',
  70. 'discount_computation',
  71. 'discount_rate',
  72. 'subtotal',
  73. 'tax_total',
  74. 'discount_total',
  75. 'total',
  76. 'terms',
  77. 'footer',
  78. 'created_by',
  79. 'updated_by',
  80. ];
  81. protected $casts = [
  82. 'approved_at' => 'datetime',
  83. 'ended_at' => 'datetime',
  84. 'start_date' => 'date',
  85. 'end_date' => 'date',
  86. 'next_date' => 'date',
  87. 'last_date' => 'date',
  88. 'auto_send' => 'boolean',
  89. 'send_time' => 'datetime:H:i',
  90. 'payment_terms' => PaymentTerms::class,
  91. 'frequency' => Frequency::class,
  92. 'interval_type' => IntervalType::class,
  93. 'interval_value' => 'integer',
  94. 'month' => Month::class,
  95. 'day_of_month' => DayOfMonth::class,
  96. 'day_of_week' => DayOfWeek::class,
  97. 'end_type' => EndType::class,
  98. 'status' => RecurringInvoiceStatus::class,
  99. 'discount_method' => DocumentDiscountMethod::class,
  100. 'discount_computation' => AdjustmentComputation::class,
  101. 'discount_rate' => RateCast::class,
  102. 'subtotal' => MoneyCast::class,
  103. 'tax_total' => MoneyCast::class,
  104. 'discount_total' => MoneyCast::class,
  105. 'total' => MoneyCast::class,
  106. ];
  107. public function client(): BelongsTo
  108. {
  109. return $this->belongsTo(Client::class);
  110. }
  111. public function invoices(): HasMany
  112. {
  113. return $this->hasMany(Invoice::class, 'recurring_invoice_id');
  114. }
  115. public function documentType(): DocumentType
  116. {
  117. return DocumentType::RecurringInvoice;
  118. }
  119. public function documentNumber(): ?string
  120. {
  121. return 'Auto-generated';
  122. }
  123. public function documentDate(): ?string
  124. {
  125. return $this->calculateNextDate()?->toDefaultDateFormat() ?? 'Auto-generated';
  126. }
  127. public function dueDate(): ?string
  128. {
  129. return $this->calculateNextDueDate()?->toDefaultDateFormat() ?? 'Auto-generated';
  130. }
  131. public function referenceNumber(): ?string
  132. {
  133. return $this->order_number;
  134. }
  135. public function amountDue(): ?string
  136. {
  137. return $this->total;
  138. }
  139. public function isDraft(): bool
  140. {
  141. return $this->status === RecurringInvoiceStatus::Draft;
  142. }
  143. public function isActive(): bool
  144. {
  145. return $this->status === RecurringInvoiceStatus::Active;
  146. }
  147. public function wasApproved(): bool
  148. {
  149. return $this->approved_at !== null;
  150. }
  151. public function wasEnded(): bool
  152. {
  153. return $this->ended_at !== null;
  154. }
  155. public function isNeverEnding(): bool
  156. {
  157. return $this->end_type === EndType::Never;
  158. }
  159. public function canBeApproved(): bool
  160. {
  161. return $this->isDraft() && $this->hasSchedule() && ! $this->wasApproved() && $this->hasValidStartDate();
  162. }
  163. public function canBeEnded(): bool
  164. {
  165. return $this->isActive() && ! $this->wasEnded();
  166. }
  167. public function hasSchedule(): bool
  168. {
  169. return $this->start_date !== null;
  170. }
  171. public function hasValidStartDate(): bool
  172. {
  173. if ($this->wasApproved()) {
  174. return true;
  175. }
  176. // For unapproved/draft invoices, start date must be today or in the future
  177. return $this->start_date?->gte(today()) ?? false;
  178. }
  179. public function getScheduleDescription(): string
  180. {
  181. $frequency = $this->frequency;
  182. return match (true) {
  183. $frequency->isDaily() => 'Repeat daily',
  184. $frequency->isWeekly() && $this->day_of_week => "Repeat weekly every {$this->day_of_week->getLabel()}",
  185. $frequency->isMonthly() && $this->day_of_month => "Repeat monthly on the {$this->day_of_month->getLabel()} day",
  186. $frequency->isYearly() && $this->month && $this->day_of_month => "Repeat yearly on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  187. $frequency->isCustom() => $this->getCustomScheduleDescription(),
  188. default => 'Not Configured',
  189. };
  190. }
  191. private function getCustomScheduleDescription(): string
  192. {
  193. $interval = $this->interval_value > 1
  194. ? "{$this->interval_value} {$this->interval_type->getPluralLabel()}"
  195. : $this->interval_type->getSingularLabel();
  196. $dayDescription = match (true) {
  197. $this->interval_type->isWeek() && $this->day_of_week => " on {$this->day_of_week->getLabel()}",
  198. $this->interval_type->isMonth() && $this->day_of_month => " on the {$this->day_of_month->getLabel()} day",
  199. $this->interval_type->isYear() && $this->month && $this->day_of_month => " on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  200. default => ''
  201. };
  202. return "Repeat every {$interval}{$dayDescription}";
  203. }
  204. public function getEndDescription(): string
  205. {
  206. if (! $this->end_type) {
  207. return 'Not configured';
  208. }
  209. return match (true) {
  210. $this->end_type->isNever() => 'Never',
  211. $this->end_type->isAfter() && $this->max_occurrences => "After {$this->max_occurrences} " . str($this->max_occurrences === 1 ? 'invoice' : 'invoices'),
  212. $this->end_type->isOn() && $this->end_date => 'On ' . $this->end_date->toDefaultDateFormat(),
  213. default => 'Not configured'
  214. };
  215. }
  216. public function getTimelineDescription(): string
  217. {
  218. $parts = [];
  219. if ($this->start_date) {
  220. $parts[] = 'First Invoice: ' . $this->start_date->toDefaultDateFormat();
  221. }
  222. if ($this->end_type) {
  223. $parts[] = 'Ends: ' . $this->getEndDescription();
  224. }
  225. return implode(', ', $parts);
  226. }
  227. public function calculateNextDate(?Carbon $lastDate = null): ?Carbon
  228. {
  229. $lastDate ??= $this->last_date;
  230. if (! $lastDate && $this->start_date && $this->wasApproved()) {
  231. return $this->start_date;
  232. }
  233. if (! $lastDate) {
  234. return null;
  235. }
  236. $nextDate = match (true) {
  237. $this->frequency->isDaily() => $lastDate->addDay(),
  238. $this->frequency->isWeekly() => $this->calculateNextWeeklyDate($lastDate),
  239. $this->frequency->isMonthly() => $this->calculateNextMonthlyDate($lastDate),
  240. $this->frequency->isYearly() => $this->calculateNextYearlyDate($lastDate),
  241. $this->frequency->isCustom() => $this->calculateCustomNextDate($lastDate),
  242. default => null
  243. };
  244. if (! $nextDate || $this->hasReachedEnd($nextDate)) {
  245. return null;
  246. }
  247. return $nextDate;
  248. }
  249. public function calculateNextWeeklyDate(Carbon $lastDate): ?Carbon
  250. {
  251. return $lastDate->copy()->next($this->day_of_week->name);
  252. }
  253. public function calculateNextMonthlyDate(Carbon $lastDate): ?Carbon
  254. {
  255. return $this->day_of_month->resolveDate($lastDate->copy()->addMonth());
  256. }
  257. public function calculateNextYearlyDate(Carbon $lastDate): ?Carbon
  258. {
  259. return $this->day_of_month->resolveDate($lastDate->copy()->addYear()->month($this->month->value));
  260. }
  261. protected function calculateCustomNextDate(Carbon $lastDate): ?Carbon
  262. {
  263. $interval = $this->interval_value ?? 1;
  264. return match ($this->interval_type) {
  265. IntervalType::Day => $lastDate->copy()->addDays($interval),
  266. IntervalType::Week => $lastDate->copy()->addWeeks($interval),
  267. IntervalType::Month => $this->day_of_month->resolveDate($lastDate->copy()->addMonths($interval)),
  268. IntervalType::Year => $this->day_of_month->resolveDate($lastDate->copy()->addYears($interval)->month($this->month->value)),
  269. default => null
  270. };
  271. }
  272. public function calculateNextDueDate(): ?Carbon
  273. {
  274. if (! $nextDate = $this->calculateNextDate()) {
  275. return null;
  276. }
  277. if (! $terms = $this->payment_terms) {
  278. return $nextDate;
  279. }
  280. return $nextDate->copy()->addDays($terms->getDays());
  281. }
  282. public function hasReachedEnd(?Carbon $nextDate = null): bool
  283. {
  284. if (! $this->end_type) {
  285. return false;
  286. }
  287. return match (true) {
  288. $this->end_type->isNever() => false,
  289. $this->end_type->isAfter() => ($this->occurrences_count ?? 0) >= ($this->max_occurrences ?? 0),
  290. $this->end_type->isOn() && $this->end_date && $nextDate => $nextDate->greaterThan($this->end_date),
  291. default => false
  292. };
  293. }
  294. public static function getUpdateScheduleAction(string $action = Action::class): MountableAction
  295. {
  296. return $action::make('updateSchedule')
  297. ->label(fn (self $record) => $record->hasSchedule() ? 'Update Schedule' : 'Set Schedule')
  298. ->icon('heroicon-o-calendar-date-range')
  299. ->slideOver()
  300. ->successNotificationTitle('Schedule Updated')
  301. ->mountUsing(function (self $record, Form $form) {
  302. $data = $record->attributesToArray();
  303. $data['day_of_month'] ??= DayOfMonth::First;
  304. $data['start_date'] ??= now()->addMonth()->startOfMonth();
  305. $form->fill($data);
  306. })
  307. ->form([
  308. CustomSection::make('Frequency')
  309. ->contained(false)
  310. ->schema(function (Forms\Get $get) {
  311. $frequency = Frequency::parse($get('frequency'));
  312. $intervalType = IntervalType::parse($get('interval_type'));
  313. $month = Month::parse($get('month'));
  314. $dayOfMonth = DayOfMonth::parse($get('day_of_month'));
  315. return [
  316. Forms\Components\Select::make('frequency')
  317. ->label('Repeats')
  318. ->options(Frequency::class)
  319. ->softRequired()
  320. ->live()
  321. ->afterStateUpdated(function (Forms\Set $set, $state) {
  322. $handler = new ScheduleHandler($set);
  323. $handler->handleFrequencyChange($state);
  324. }),
  325. // Custom frequency fields in a nested grid
  326. Cluster::make([
  327. Forms\Components\TextInput::make('interval_value')
  328. ->softRequired()
  329. ->numeric()
  330. ->default(1),
  331. Forms\Components\Select::make('interval_type')
  332. ->options(IntervalType::class)
  333. ->softRequired()
  334. ->default(IntervalType::Month)
  335. ->live()
  336. ->afterStateUpdated(function (Forms\Set $set, $state) {
  337. $handler = new ScheduleHandler($set);
  338. $handler->handleIntervalTypeChange($state);
  339. }),
  340. ])
  341. ->live()
  342. ->label('Every')
  343. ->required()
  344. ->markAsRequired(false)
  345. ->visible($frequency->isCustom()),
  346. // Specific schedule details
  347. Forms\Components\Select::make('month')
  348. ->label('Month')
  349. ->options(Month::class)
  350. ->softRequired()
  351. ->visible($frequency->isYearly() || $intervalType?->isYear())
  352. ->live()
  353. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  354. $handler = new ScheduleHandler($set, $get);
  355. $handler->handleDateChange('month', $state);
  356. }),
  357. Forms\Components\Select::make('day_of_month')
  358. ->label('Day of Month')
  359. ->options(function () use ($month) {
  360. if (! $month) {
  361. return DayOfMonth::class;
  362. }
  363. $daysInMonth = Carbon::createFromDate(null, $month->value)->daysInMonth;
  364. return collect(DayOfMonth::cases())
  365. ->filter(static fn (DayOfMonth $dayOfMonth) => $dayOfMonth->value <= $daysInMonth || $dayOfMonth->isLast())
  366. ->mapWithKeys(fn (DayOfMonth $dayOfMonth) => [$dayOfMonth->value => $dayOfMonth->getLabel()]);
  367. })
  368. ->softRequired()
  369. ->visible(in_array($frequency, [Frequency::Monthly, Frequency::Yearly]) || in_array($intervalType, [IntervalType::Month, IntervalType::Year]))
  370. ->live()
  371. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  372. $handler = new ScheduleHandler($set, $get);
  373. $handler->handleDateChange('day_of_month', $state);
  374. }),
  375. SimpleAlert::make('dayOfMonthNotice')
  376. ->title(function () use ($dayOfMonth) {
  377. return "The invoice will be created on the {$dayOfMonth->getLabel()} day of each month, or on the last day for months ending earlier.";
  378. })
  379. ->columnSpanFull()
  380. ->visible($dayOfMonth?->value > 28),
  381. Forms\Components\Select::make('day_of_week')
  382. ->label('Day of Week')
  383. ->options(DayOfWeek::class)
  384. ->softRequired()
  385. ->visible($frequency->isWeekly() || $intervalType?->isWeek())
  386. ->live()
  387. ->afterStateUpdated(function (Forms\Set $set, $state) {
  388. $handler = new ScheduleHandler($set);
  389. $handler->handleDateChange('day_of_week', $state);
  390. }),
  391. ];
  392. })->columns(2),
  393. CustomSection::make('Dates & Time')
  394. ->contained(false)
  395. ->schema([
  396. Forms\Components\DatePicker::make('start_date')
  397. ->label('First Invoice Date')
  398. ->softRequired()
  399. ->live()
  400. ->minDate(today())
  401. ->closeOnDateSelection()
  402. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  403. $handler = new ScheduleHandler($set, $get);
  404. $handler->handleDateChange('start_date', $state);
  405. }),
  406. Forms\Components\Group::make(function (Forms\Get $get) {
  407. $components = [];
  408. $components[] = Forms\Components\Select::make('end_type')
  409. ->label('End Schedule')
  410. ->options(EndType::class)
  411. ->softRequired()
  412. ->live()
  413. ->afterStateUpdated(function (Forms\Set $set, $state) {
  414. $endType = EndType::parse($state);
  415. $set('max_occurrences', $endType?->isAfter() ? 1 : null);
  416. $set('end_date', $endType?->isOn() ? now()->addMonth()->startOfMonth() : null);
  417. });
  418. $endType = EndType::parse($get('end_type'));
  419. if ($endType?->isAfter()) {
  420. $components[] = Forms\Components\TextInput::make('max_occurrences')
  421. ->numeric()
  422. ->suffix('invoices')
  423. ->live();
  424. }
  425. if ($endType?->isOn()) {
  426. $components[] = Forms\Components\DatePicker::make('end_date')
  427. ->live();
  428. }
  429. return [
  430. Cluster::make($components)
  431. ->label('Schedule Ends')
  432. ->required()
  433. ->markAsRequired(false),
  434. ];
  435. }),
  436. Forms\Components\Select::make('timezone')
  437. ->options(Timezone::getTimezoneOptions(CompanyProfile::first()->country))
  438. ->searchable()
  439. ->softRequired(),
  440. ])
  441. ->columns(2),
  442. ])
  443. ->action(function (self $record, array $data, MountableAction $action) {
  444. $record->update($data);
  445. $action->success();
  446. });
  447. }
  448. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  449. {
  450. return $action::make('approveDraft')
  451. ->label('Approve')
  452. ->icon('heroicon-o-check-circle')
  453. ->visible(function (self $record) {
  454. return $record->canBeApproved();
  455. })
  456. ->databaseTransaction()
  457. ->successNotificationTitle('Recurring Invoice Approved')
  458. ->action(function (self $record, MountableAction $action) {
  459. $record->approveDraft();
  460. $action->success();
  461. });
  462. }
  463. public function approveDraft(?Carbon $approvedAt = null): void
  464. {
  465. if (! $this->isDraft()) {
  466. throw new \RuntimeException('Invoice is not in draft status.');
  467. }
  468. $approvedAt ??= now();
  469. $this->update([
  470. 'approved_at' => $approvedAt,
  471. 'status' => RecurringInvoiceStatus::Active,
  472. ]);
  473. }
  474. public function generateInvoice(): ?Invoice
  475. {
  476. if (! $this->shouldGenerateInvoice()) {
  477. return null;
  478. }
  479. $nextDate = $this->next_date ?? $this->calculateNextDate();
  480. if (! $nextDate) {
  481. return null;
  482. }
  483. $dueDate = $this->calculateNextDueDate();
  484. $invoice = $this->invoices()->create([
  485. 'company_id' => $this->company_id,
  486. 'client_id' => $this->client_id,
  487. 'logo' => $this->logo,
  488. 'header' => $this->header,
  489. 'subheader' => $this->subheader,
  490. 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
  491. 'date' => $nextDate,
  492. 'due_date' => $dueDate,
  493. 'status' => InvoiceStatus::Draft,
  494. 'currency_code' => $this->currency_code,
  495. 'discount_method' => $this->discount_method,
  496. 'discount_computation' => $this->discount_computation,
  497. 'discount_rate' => $this->discount_rate,
  498. 'subtotal' => $this->subtotal,
  499. 'tax_total' => $this->tax_total,
  500. 'discount_total' => $this->discount_total,
  501. 'total' => $this->total,
  502. 'terms' => $this->terms,
  503. 'footer' => $this->footer,
  504. 'created_by' => auth()->id(),
  505. 'updated_by' => auth()->id(),
  506. ]);
  507. $this->replicateLineItems($invoice);
  508. $this->update([
  509. 'last_date' => $nextDate,
  510. 'next_date' => $this->calculateNextDate($nextDate),
  511. 'occurrences_count' => ($this->occurrences_count ?? 0) + 1,
  512. ]);
  513. return $invoice;
  514. }
  515. public function replicateLineItems(Model $target): void
  516. {
  517. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  518. $replica = $lineItem->replicate([
  519. 'documentable_id',
  520. 'documentable_type',
  521. 'subtotal',
  522. 'total',
  523. 'created_by',
  524. 'updated_by',
  525. 'created_at',
  526. 'updated_at',
  527. ]);
  528. $replica->documentable_id = $target->id;
  529. $replica->documentable_type = $target->getMorphClass();
  530. $replica->save();
  531. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  532. });
  533. }
  534. public function shouldGenerateInvoice(): bool
  535. {
  536. if (! $this->isActive() || $this->hasReachedEnd()) {
  537. return false;
  538. }
  539. $nextDate = $this->calculateNextDate();
  540. if (! $nextDate || $nextDate->startOfDay()->isFuture()) {
  541. return false;
  542. }
  543. return true;
  544. }
  545. public function generateDueInvoices(): void
  546. {
  547. $maxIterations = 100;
  548. for ($i = 0; $i < $maxIterations; $i++) {
  549. $result = $this->generateInvoice();
  550. if (! $result) {
  551. break;
  552. }
  553. $this->refresh();
  554. }
  555. }
  556. }