Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

RecurringInvoice.php 25KB

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