您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

RecurringInvoice.php 23KB

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