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

RecurringInvoice.php 25KB

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