Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

RecurringInvoice.php 25KB

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