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

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