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.

RecurringInvoice.php 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  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\Banner;
  19. use App\Filament\Forms\Components\CustomSection;
  20. use App\Models\Common\Client;
  21. use App\Models\Setting\CompanyProfile;
  22. use App\Observers\RecurringInvoiceObserver;
  23. use App\Support\ScheduleHandler;
  24. use App\Utilities\Localization\Timezone;
  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 static 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, int $interval = 1): ?Carbon
  256. {
  257. return $lastDate->copy()
  258. ->addWeeks($interval - 1)
  259. ->next($this->day_of_week->value);
  260. }
  261. public function calculateNextMonthlyDate(Carbon $lastDate, int $interval = 1): ?Carbon
  262. {
  263. return $this->day_of_month->resolveDate(
  264. $lastDate->copy()->addMonthsNoOverflow($interval)
  265. );
  266. }
  267. public function calculateNextYearlyDate(Carbon $lastDate, int $interval = 1): ?Carbon
  268. {
  269. return $this->day_of_month->resolveDate(
  270. $lastDate->copy()->addYears($interval)->month($this->month->value)
  271. );
  272. }
  273. protected function calculateCustomNextDate(Carbon $lastDate): ?Carbon
  274. {
  275. $interval = $this->interval_value ?? 1;
  276. return match ($this->interval_type) {
  277. IntervalType::Day => $lastDate->copy()->addDays($interval),
  278. IntervalType::Week => $this->calculateNextWeeklyDate($lastDate, $interval),
  279. IntervalType::Month => $this->calculateNextMonthlyDate($lastDate, $interval),
  280. IntervalType::Year => $this->calculateNextYearlyDate($lastDate, $interval),
  281. default => null
  282. };
  283. }
  284. public function calculateNextDueDate(): ?Carbon
  285. {
  286. if (! $nextDate = $this->calculateNextDate()) {
  287. return null;
  288. }
  289. if (! $terms = $this->payment_terms) {
  290. return $nextDate;
  291. }
  292. return $nextDate->copy()->addDays($terms->getDays());
  293. }
  294. public function hasReachedEnd(?Carbon $nextDate = null): bool
  295. {
  296. if (! $this->end_type) {
  297. return false;
  298. }
  299. return match (true) {
  300. $this->end_type->isNever() => false,
  301. $this->end_type->isAfter() => ($this->occurrences_count ?? 0) >= ($this->max_occurrences ?? 0),
  302. $this->end_type->isOn() && $this->end_date && $nextDate => $nextDate->greaterThan($this->end_date),
  303. default => false
  304. };
  305. }
  306. public static function getManageScheduleAction(string $action = Action::class): MountableAction
  307. {
  308. return $action::make('manageSchedule')
  309. ->label(fn (self $record) => $record->hasSchedule() ? 'Edit schedule' : 'Set schedule')
  310. ->icon('heroicon-m-calendar-date-range')
  311. ->slideOver()
  312. ->successNotificationTitle('Schedule saved')
  313. ->mountUsing(function (self $record, Form $form) {
  314. $data = $record->attributesToArray();
  315. $data['day_of_month'] ??= DayOfMonth::First;
  316. $data['start_date'] ??= now()->addMonth()->startOfMonth();
  317. $form->fill($data);
  318. })
  319. ->form([
  320. CustomSection::make('Frequency')
  321. ->contained(false)
  322. ->schema(function (Forms\Get $get) {
  323. $frequency = Frequency::parse($get('frequency'));
  324. $intervalType = IntervalType::parse($get('interval_type'));
  325. $month = Month::parse($get('month'));
  326. $dayOfMonth = DayOfMonth::parse($get('day_of_month'));
  327. return [
  328. Forms\Components\Select::make('frequency')
  329. ->label('Repeats')
  330. ->options(Frequency::class)
  331. ->softRequired()
  332. ->live()
  333. ->afterStateUpdated(function (Forms\Set $set, $state) {
  334. $handler = new ScheduleHandler($set);
  335. $handler->handleFrequencyChange($state);
  336. }),
  337. Cluster::make([
  338. Forms\Components\TextInput::make('interval_value')
  339. ->softRequired()
  340. ->numeric()
  341. ->default(1),
  342. Forms\Components\Select::make('interval_type')
  343. ->options(IntervalType::class)
  344. ->softRequired()
  345. ->default(IntervalType::Month)
  346. ->live()
  347. ->afterStateUpdated(function (Forms\Set $set, $state) {
  348. $handler = new ScheduleHandler($set);
  349. $handler->handleIntervalTypeChange($state);
  350. }),
  351. ])
  352. ->live()
  353. ->label('Every')
  354. ->required()
  355. ->markAsRequired(false)
  356. ->visible($frequency->isCustom()),
  357. Forms\Components\Select::make('month')
  358. ->label('Month')
  359. ->options(Month::class)
  360. ->softRequired()
  361. ->visible($frequency->isYearly() || $intervalType?->isYear())
  362. ->live()
  363. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  364. $handler = new ScheduleHandler($set, $get);
  365. $handler->handleDateChange('month', $state);
  366. }),
  367. Forms\Components\Select::make('day_of_month')
  368. ->label('Day of Month')
  369. ->options(function () use ($month) {
  370. if (! $month) {
  371. return DayOfMonth::class;
  372. }
  373. $daysInMonth = Carbon::createFromDate(null, $month->value)->daysInMonth;
  374. return collect(DayOfMonth::cases())
  375. ->filter(static fn (DayOfMonth $dayOfMonth) => $dayOfMonth->value <= $daysInMonth || $dayOfMonth->isLast())
  376. ->mapWithKeys(fn (DayOfMonth $dayOfMonth) => [$dayOfMonth->value => $dayOfMonth->getLabel()]);
  377. })
  378. ->softRequired()
  379. ->visible(in_array($frequency, [Frequency::Monthly, Frequency::Yearly]) || in_array($intervalType, [IntervalType::Month, IntervalType::Year]))
  380. ->live()
  381. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  382. $handler = new ScheduleHandler($set, $get);
  383. $handler->handleDateChange('day_of_month', $state);
  384. }),
  385. Banner::make('dayOfMonthNotice')
  386. ->info()
  387. ->title(static function () use ($dayOfMonth) {
  388. return "For months with fewer than {$dayOfMonth->value} days, the last day of the month will be used.";
  389. })
  390. ->columnSpanFull()
  391. ->visible($dayOfMonth?->mayExceedMonthLength() && ($frequency->isMonthly() || $intervalType?->isMonth())),
  392. Forms\Components\Select::make('day_of_week')
  393. ->label('Day of Week')
  394. ->options(DayOfWeek::class)
  395. ->softRequired()
  396. ->visible(($frequency->isWeekly() || $intervalType?->isWeek()) ?? false)
  397. ->live()
  398. ->afterStateUpdated(function (Forms\Set $set, $state) {
  399. $handler = new ScheduleHandler($set);
  400. $handler->handleDateChange('day_of_week', $state);
  401. }),
  402. ];
  403. })->columns(2),
  404. CustomSection::make('Dates & Time')
  405. ->contained(false)
  406. ->schema([
  407. Forms\Components\DatePicker::make('start_date')
  408. ->label('First invoice date')
  409. ->softRequired()
  410. ->live()
  411. ->minDate(today())
  412. ->closeOnDateSelection()
  413. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  414. $handler = new ScheduleHandler($set, $get);
  415. $handler->handleDateChange('start_date', $state);
  416. }),
  417. Forms\Components\Group::make(function (Forms\Get $get) {
  418. $components = [];
  419. $components[] = Forms\Components\Select::make('end_type')
  420. ->label('End schedule')
  421. ->options(EndType::class)
  422. ->softRequired()
  423. ->live()
  424. ->afterStateUpdated(function (Forms\Set $set, $state) {
  425. $endType = EndType::parse($state);
  426. $set('max_occurrences', $endType?->isAfter() ? 1 : null);
  427. $set('end_date', $endType?->isOn() ? now()->addMonth()->startOfMonth() : null);
  428. });
  429. $endType = EndType::parse($get('end_type'));
  430. if ($endType?->isAfter()) {
  431. $components[] = Forms\Components\TextInput::make('max_occurrences')
  432. ->numeric()
  433. ->suffix('invoices')
  434. ->live();
  435. }
  436. if ($endType?->isOn()) {
  437. $components[] = Forms\Components\DatePicker::make('end_date')
  438. ->live();
  439. }
  440. return [
  441. Cluster::make($components)
  442. ->label('Schedule ends')
  443. ->required()
  444. ->markAsRequired(false),
  445. ];
  446. }),
  447. Forms\Components\Select::make('timezone')
  448. ->options(Timezone::getTimezoneOptions(CompanyProfile::first()->country))
  449. ->searchable()
  450. ->softRequired(),
  451. ])
  452. ->columns(2),
  453. ])
  454. ->action(function (self $record, array $data, MountableAction $action) {
  455. $record->update($data);
  456. $action->success();
  457. });
  458. }
  459. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  460. {
  461. return $action::make('approveDraft')
  462. ->label('Approve')
  463. ->icon('heroicon-o-check-circle')
  464. ->visible(function (self $record) {
  465. return $record->canBeApproved();
  466. })
  467. ->databaseTransaction()
  468. ->successNotificationTitle('Recurring invoice approved')
  469. ->action(function (self $record, MountableAction $action) {
  470. $record->approveDraft();
  471. $action->success();
  472. });
  473. }
  474. public function approveDraft(?Carbon $approvedAt = null): void
  475. {
  476. if (! $this->isDraft()) {
  477. throw new \RuntimeException('Invoice is not in draft status.');
  478. }
  479. $approvedAt ??= now();
  480. $this->update([
  481. 'approved_at' => $approvedAt,
  482. 'status' => RecurringInvoiceStatus::Active,
  483. ]);
  484. }
  485. public function generateInvoice(): ?Invoice
  486. {
  487. if (! $this->shouldGenerateInvoice()) {
  488. return null;
  489. }
  490. $nextDate = $this->next_date ?? $this->calculateNextDate();
  491. if (! $nextDate) {
  492. return null;
  493. }
  494. $dueDate = $this->calculateNextDueDate();
  495. $invoice = $this->invoices()->create([
  496. 'company_id' => $this->company_id,
  497. 'client_id' => $this->client_id,
  498. 'logo' => $this->logo,
  499. 'header' => $this->header,
  500. 'subheader' => $this->subheader,
  501. 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
  502. 'date' => $nextDate,
  503. 'due_date' => $dueDate,
  504. 'status' => InvoiceStatus::Draft,
  505. 'currency_code' => $this->currency_code,
  506. 'discount_method' => $this->discount_method,
  507. 'discount_computation' => $this->discount_computation,
  508. 'discount_rate' => $this->discount_rate,
  509. 'subtotal' => $this->subtotal,
  510. 'tax_total' => $this->tax_total,
  511. 'discount_total' => $this->discount_total,
  512. 'total' => $this->total,
  513. 'terms' => $this->terms,
  514. 'footer' => $this->footer,
  515. 'created_by' => auth()->id(),
  516. 'updated_by' => auth()->id(),
  517. ]);
  518. $this->replicateLineItems($invoice);
  519. $this->update([
  520. 'last_date' => $nextDate,
  521. 'next_date' => $this->calculateNextDate($nextDate),
  522. 'occurrences_count' => ($this->occurrences_count ?? 0) + 1,
  523. ]);
  524. return $invoice;
  525. }
  526. public function replicateLineItems(Model $target): void
  527. {
  528. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  529. $replica = $lineItem->replicate([
  530. 'documentable_id',
  531. 'documentable_type',
  532. 'subtotal',
  533. 'total',
  534. 'created_by',
  535. 'updated_by',
  536. 'created_at',
  537. 'updated_at',
  538. ]);
  539. $replica->documentable_id = $target->id;
  540. $replica->documentable_type = $target->getMorphClass();
  541. $replica->save();
  542. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  543. });
  544. }
  545. public function shouldGenerateInvoice(): bool
  546. {
  547. if (! $this->isActive() || $this->hasReachedEnd()) {
  548. return false;
  549. }
  550. $nextDate = $this->calculateNextDate();
  551. if (! $nextDate || $nextDate->startOfDay()->isFuture()) {
  552. return false;
  553. }
  554. return true;
  555. }
  556. public function generateDueInvoices(): void
  557. {
  558. $maxIterations = 100;
  559. for ($i = 0; $i < $maxIterations; $i++) {
  560. $result = $this->generateInvoice();
  561. if (! $result) {
  562. break;
  563. }
  564. $this->refresh();
  565. }
  566. }
  567. }