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

RecurringInvoice.php 25KB

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