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.

RecurringInvoice.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. if (! $this->hasSchedule()) {
  182. return null;
  183. }
  184. $frequency = $this->frequency;
  185. return match (true) {
  186. $frequency->isDaily() => 'Repeat daily',
  187. $frequency->isWeekly() && $this->day_of_week => "Repeat weekly every {$this->day_of_week->getLabel()}",
  188. $frequency->isMonthly() && $this->day_of_month => "Repeat monthly on the {$this->day_of_month->getLabel()} day",
  189. $frequency->isYearly() && $this->month && $this->day_of_month => "Repeat yearly on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  190. $frequency->isCustom() => $this->getCustomScheduleDescription(),
  191. default => null,
  192. };
  193. }
  194. private function getCustomScheduleDescription(): string
  195. {
  196. $interval = $this->interval_value > 1
  197. ? "{$this->interval_value} {$this->interval_type->getPluralLabel()}"
  198. : $this->interval_type->getSingularLabel();
  199. $dayDescription = match (true) {
  200. $this->interval_type->isWeek() && $this->day_of_week => " on {$this->day_of_week->getLabel()}",
  201. $this->interval_type->isMonth() && $this->day_of_month => " on the {$this->day_of_month->getLabel()} day",
  202. $this->interval_type->isYear() && $this->month && $this->day_of_month => " on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  203. default => ''
  204. };
  205. return "Repeat every {$interval}{$dayDescription}";
  206. }
  207. public function getEndDescription(): ?string
  208. {
  209. if (! $this->end_type) {
  210. return null;
  211. }
  212. return match (true) {
  213. $this->end_type->isNever() => 'Never',
  214. $this->end_type->isAfter() && $this->max_occurrences => "After {$this->max_occurrences} " . str($this->max_occurrences === 1 ? 'invoice' : 'invoices'),
  215. $this->end_type->isOn() && $this->end_date => 'On ' . $this->end_date->toDefaultDateFormat(),
  216. default => null,
  217. };
  218. }
  219. public function getTimelineDescription(): ?string
  220. {
  221. if (! $this->hasSchedule()) {
  222. return null;
  223. }
  224. $parts = [];
  225. if ($this->start_date) {
  226. $parts[] = 'First Invoice: ' . $this->start_date->toDefaultDateFormat();
  227. }
  228. if ($this->end_type) {
  229. $parts[] = 'Ends: ' . $this->getEndDescription();
  230. }
  231. return implode(', ', $parts);
  232. }
  233. public function calculateNextDate(?Carbon $lastDate = null): ?Carbon
  234. {
  235. $lastDate ??= $this->last_date;
  236. if (! $lastDate && $this->start_date && $this->wasApproved()) {
  237. return $this->start_date;
  238. }
  239. if (! $lastDate) {
  240. return null;
  241. }
  242. $nextDate = match (true) {
  243. $this->frequency->isDaily() => $lastDate->copy()->addDay(),
  244. $this->frequency->isWeekly() => $this->calculateNextWeeklyDate($lastDate),
  245. $this->frequency->isMonthly() => $this->calculateNextMonthlyDate($lastDate),
  246. $this->frequency->isYearly() => $this->calculateNextYearlyDate($lastDate),
  247. $this->frequency->isCustom() => $this->calculateCustomNextDate($lastDate),
  248. default => null
  249. };
  250. if (! $nextDate || $this->hasReachedEnd($nextDate)) {
  251. return null;
  252. }
  253. return $nextDate;
  254. }
  255. public function calculateNextWeeklyDate(Carbon $lastDate): ?Carbon
  256. {
  257. return $lastDate->copy()->next($this->day_of_week->name);
  258. }
  259. public function calculateNextMonthlyDate(Carbon $lastDate): ?Carbon
  260. {
  261. return $this->day_of_month->resolveDate($lastDate->copy()->addMonth());
  262. }
  263. public function calculateNextYearlyDate(Carbon $lastDate): ?Carbon
  264. {
  265. return $this->day_of_month->resolveDate($lastDate->copy()->addYear()->month($this->month->value));
  266. }
  267. protected function calculateCustomNextDate(Carbon $lastDate): ?Carbon
  268. {
  269. $interval = $this->interval_value ?? 1;
  270. return match ($this->interval_type) {
  271. IntervalType::Day => $lastDate->copy()->addDays($interval),
  272. IntervalType::Week => $lastDate->copy()->addWeeks($interval),
  273. IntervalType::Month => $this->day_of_month->resolveDate($lastDate->copy()->addMonths($interval)),
  274. IntervalType::Year => $this->day_of_month->resolveDate($lastDate->copy()->addYears($interval)->month($this->month->value)),
  275. default => null
  276. };
  277. }
  278. public function calculateNextDueDate(): ?Carbon
  279. {
  280. if (! $nextDate = $this->calculateNextDate()) {
  281. return null;
  282. }
  283. if (! $terms = $this->payment_terms) {
  284. return $nextDate;
  285. }
  286. return $nextDate->copy()->addDays($terms->getDays());
  287. }
  288. public function hasReachedEnd(?Carbon $nextDate = null): bool
  289. {
  290. if (! $this->end_type) {
  291. return false;
  292. }
  293. return match (true) {
  294. $this->end_type->isNever() => false,
  295. $this->end_type->isAfter() => ($this->occurrences_count ?? 0) >= ($this->max_occurrences ?? 0),
  296. $this->end_type->isOn() && $this->end_date && $nextDate => $nextDate->greaterThan($this->end_date),
  297. default => false
  298. };
  299. }
  300. public static function getUpdateScheduleAction(string $action = Action::class): MountableAction
  301. {
  302. return $action::make('updateSchedule')
  303. ->label(fn (self $record) => $record->hasSchedule() ? 'Update Schedule' : 'Set Schedule')
  304. ->icon('heroicon-o-calendar-date-range')
  305. ->slideOver()
  306. ->successNotificationTitle('Schedule Updated')
  307. ->mountUsing(function (self $record, Form $form) {
  308. $data = $record->attributesToArray();
  309. $data['day_of_month'] ??= DayOfMonth::First;
  310. $data['start_date'] ??= now()->addMonth()->startOfMonth();
  311. $form->fill($data);
  312. })
  313. ->form([
  314. CustomSection::make('Frequency')
  315. ->contained(false)
  316. ->schema(function (Forms\Get $get) {
  317. $frequency = Frequency::parse($get('frequency'));
  318. $intervalType = IntervalType::parse($get('interval_type'));
  319. $month = Month::parse($get('month'));
  320. $dayOfMonth = DayOfMonth::parse($get('day_of_month'));
  321. return [
  322. Forms\Components\Select::make('frequency')
  323. ->label('Repeats')
  324. ->options(Frequency::class)
  325. ->softRequired()
  326. ->live()
  327. ->afterStateUpdated(function (Forms\Set $set, $state) {
  328. $handler = new ScheduleHandler($set);
  329. $handler->handleFrequencyChange($state);
  330. }),
  331. // Custom frequency fields in a nested grid
  332. Cluster::make([
  333. Forms\Components\TextInput::make('interval_value')
  334. ->softRequired()
  335. ->numeric()
  336. ->default(1),
  337. Forms\Components\Select::make('interval_type')
  338. ->options(IntervalType::class)
  339. ->softRequired()
  340. ->default(IntervalType::Month)
  341. ->live()
  342. ->afterStateUpdated(function (Forms\Set $set, $state) {
  343. $handler = new ScheduleHandler($set);
  344. $handler->handleIntervalTypeChange($state);
  345. }),
  346. ])
  347. ->live()
  348. ->label('Every')
  349. ->required()
  350. ->markAsRequired(false)
  351. ->visible($frequency->isCustom()),
  352. // Specific schedule details
  353. Forms\Components\Select::make('month')
  354. ->label('Month')
  355. ->options(Month::class)
  356. ->softRequired()
  357. ->visible($frequency->isYearly() || $intervalType?->isYear())
  358. ->live()
  359. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  360. $handler = new ScheduleHandler($set, $get);
  361. $handler->handleDateChange('month', $state);
  362. }),
  363. Forms\Components\Select::make('day_of_month')
  364. ->label('Day of Month')
  365. ->options(function () use ($month) {
  366. if (! $month) {
  367. return DayOfMonth::class;
  368. }
  369. $daysInMonth = Carbon::createFromDate(null, $month->value)->daysInMonth;
  370. return collect(DayOfMonth::cases())
  371. ->filter(static fn (DayOfMonth $dayOfMonth) => $dayOfMonth->value <= $daysInMonth || $dayOfMonth->isLast())
  372. ->mapWithKeys(fn (DayOfMonth $dayOfMonth) => [$dayOfMonth->value => $dayOfMonth->getLabel()]);
  373. })
  374. ->softRequired()
  375. ->visible(in_array($frequency, [Frequency::Monthly, Frequency::Yearly]) || in_array($intervalType, [IntervalType::Month, IntervalType::Year]))
  376. ->live()
  377. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  378. $handler = new ScheduleHandler($set, $get);
  379. $handler->handleDateChange('day_of_month', $state);
  380. }),
  381. SimpleAlert::make('dayOfMonthNotice')
  382. ->title(function () use ($dayOfMonth) {
  383. return "The invoice will be created on the {$dayOfMonth->getLabel()} day of each month, or on the last day for months ending earlier.";
  384. })
  385. ->columnSpanFull()
  386. ->visible($dayOfMonth?->value > 28),
  387. Forms\Components\Select::make('day_of_week')
  388. ->label('Day of Week')
  389. ->options(DayOfWeek::class)
  390. ->softRequired()
  391. ->visible($frequency->isWeekly() || $intervalType?->isWeek())
  392. ->live()
  393. ->afterStateUpdated(function (Forms\Set $set, $state) {
  394. $handler = new ScheduleHandler($set);
  395. $handler->handleDateChange('day_of_week', $state);
  396. }),
  397. ];
  398. })->columns(2),
  399. CustomSection::make('Dates & Time')
  400. ->contained(false)
  401. ->schema([
  402. Forms\Components\DatePicker::make('start_date')
  403. ->label('First Invoice Date')
  404. ->softRequired()
  405. ->live()
  406. ->minDate(today())
  407. ->closeOnDateSelection()
  408. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  409. $handler = new ScheduleHandler($set, $get);
  410. $handler->handleDateChange('start_date', $state);
  411. }),
  412. Forms\Components\Group::make(function (Forms\Get $get) {
  413. $components = [];
  414. $components[] = Forms\Components\Select::make('end_type')
  415. ->label('End Schedule')
  416. ->options(EndType::class)
  417. ->softRequired()
  418. ->live()
  419. ->afterStateUpdated(function (Forms\Set $set, $state) {
  420. $endType = EndType::parse($state);
  421. $set('max_occurrences', $endType?->isAfter() ? 1 : null);
  422. $set('end_date', $endType?->isOn() ? now()->addMonth()->startOfMonth() : null);
  423. });
  424. $endType = EndType::parse($get('end_type'));
  425. if ($endType?->isAfter()) {
  426. $components[] = Forms\Components\TextInput::make('max_occurrences')
  427. ->numeric()
  428. ->suffix('invoices')
  429. ->live();
  430. }
  431. if ($endType?->isOn()) {
  432. $components[] = Forms\Components\DatePicker::make('end_date')
  433. ->live();
  434. }
  435. return [
  436. Cluster::make($components)
  437. ->label('Schedule Ends')
  438. ->required()
  439. ->markAsRequired(false),
  440. ];
  441. }),
  442. Forms\Components\Select::make('timezone')
  443. ->options(Timezone::getTimezoneOptions(CompanyProfile::first()->country))
  444. ->searchable()
  445. ->softRequired(),
  446. ])
  447. ->columns(2),
  448. ])
  449. ->action(function (self $record, array $data, MountableAction $action) {
  450. $record->update($data);
  451. $action->success();
  452. });
  453. }
  454. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  455. {
  456. return $action::make('approveDraft')
  457. ->label('Approve')
  458. ->icon('heroicon-o-check-circle')
  459. ->visible(function (self $record) {
  460. return $record->canBeApproved();
  461. })
  462. ->databaseTransaction()
  463. ->successNotificationTitle('Recurring Invoice Approved')
  464. ->action(function (self $record, MountableAction $action) {
  465. $record->approveDraft();
  466. $action->success();
  467. });
  468. }
  469. public function approveDraft(?Carbon $approvedAt = null): void
  470. {
  471. if (! $this->isDraft()) {
  472. throw new \RuntimeException('Invoice is not in draft status.');
  473. }
  474. $approvedAt ??= now();
  475. $this->update([
  476. 'approved_at' => $approvedAt,
  477. 'status' => RecurringInvoiceStatus::Active,
  478. ]);
  479. }
  480. public function generateInvoice(): ?Invoice
  481. {
  482. if (! $this->shouldGenerateInvoice()) {
  483. return null;
  484. }
  485. $nextDate = $this->next_date ?? $this->calculateNextDate();
  486. if (! $nextDate) {
  487. return null;
  488. }
  489. $dueDate = $this->calculateNextDueDate();
  490. $invoice = $this->invoices()->create([
  491. 'company_id' => $this->company_id,
  492. 'client_id' => $this->client_id,
  493. 'logo' => $this->logo,
  494. 'header' => $this->header,
  495. 'subheader' => $this->subheader,
  496. 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
  497. 'date' => $nextDate,
  498. 'due_date' => $dueDate,
  499. 'status' => InvoiceStatus::Draft,
  500. 'currency_code' => $this->currency_code,
  501. 'discount_method' => $this->discount_method,
  502. 'discount_computation' => $this->discount_computation,
  503. 'discount_rate' => $this->discount_rate,
  504. 'subtotal' => $this->subtotal,
  505. 'tax_total' => $this->tax_total,
  506. 'discount_total' => $this->discount_total,
  507. 'total' => $this->total,
  508. 'terms' => $this->terms,
  509. 'footer' => $this->footer,
  510. 'created_by' => auth()->id(),
  511. 'updated_by' => auth()->id(),
  512. ]);
  513. $this->replicateLineItems($invoice);
  514. $this->update([
  515. 'last_date' => $nextDate,
  516. 'next_date' => $this->calculateNextDate($nextDate),
  517. 'occurrences_count' => ($this->occurrences_count ?? 0) + 1,
  518. ]);
  519. return $invoice;
  520. }
  521. public function replicateLineItems(Model $target): void
  522. {
  523. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  524. $replica = $lineItem->replicate([
  525. 'documentable_id',
  526. 'documentable_type',
  527. 'subtotal',
  528. 'total',
  529. 'created_by',
  530. 'updated_by',
  531. 'created_at',
  532. 'updated_at',
  533. ]);
  534. $replica->documentable_id = $target->id;
  535. $replica->documentable_type = $target->getMorphClass();
  536. $replica->save();
  537. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  538. });
  539. }
  540. public function shouldGenerateInvoice(): bool
  541. {
  542. if (! $this->isActive() || $this->hasReachedEnd()) {
  543. return false;
  544. }
  545. $nextDate = $this->calculateNextDate();
  546. if (! $nextDate || $nextDate->startOfDay()->isFuture()) {
  547. return false;
  548. }
  549. return true;
  550. }
  551. public function generateDueInvoices(): void
  552. {
  553. $maxIterations = 100;
  554. for ($i = 0; $i < $maxIterations; $i++) {
  555. $result = $this->generateInvoice();
  556. if (! $result) {
  557. break;
  558. }
  559. $this->refresh();
  560. }
  561. }
  562. }