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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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\Concerns\Blamable;
  7. use App\Concerns\CompanyOwned;
  8. use App\Enums\Accounting\AdjustmentComputation;
  9. use App\Enums\Accounting\DayOfMonth;
  10. use App\Enums\Accounting\DayOfWeek;
  11. use App\Enums\Accounting\DocumentDiscountMethod;
  12. use App\Enums\Accounting\EndType;
  13. use App\Enums\Accounting\Frequency;
  14. use App\Enums\Accounting\IntervalType;
  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\Models\Setting\Currency;
  22. use App\Observers\RecurringInvoiceObserver;
  23. use App\Utilities\Localization\Timezone;
  24. use Filament\Actions\Action;
  25. use Filament\Actions\MountableAction;
  26. use Filament\Forms;
  27. use Filament\Forms\Form;
  28. use Filament\Support\Enums\MaxWidth;
  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\Factories\HasFactory;
  33. use Illuminate\Database\Eloquent\Model;
  34. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  35. use Illuminate\Database\Eloquent\Relations\HasMany;
  36. use Illuminate\Database\Eloquent\Relations\MorphMany;
  37. use Illuminate\Support\Carbon;
  38. #[CollectedBy(DocumentCollection::class)]
  39. #[ObservedBy(RecurringInvoiceObserver::class)]
  40. class RecurringInvoice extends Model
  41. {
  42. use Blamable;
  43. use CompanyOwned;
  44. use HasFactory;
  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. '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. 'subtotal' => MoneyCast::class,
  107. 'tax_total' => MoneyCast::class,
  108. 'discount_total' => MoneyCast::class,
  109. 'total' => MoneyCast::class,
  110. ];
  111. public function client(): BelongsTo
  112. {
  113. return $this->belongsTo(Client::class);
  114. }
  115. public function currency(): BelongsTo
  116. {
  117. return $this->belongsTo(Currency::class, 'currency_code', 'code');
  118. }
  119. public function invoices(): HasMany
  120. {
  121. return $this->hasMany(Invoice::class, 'recurring_invoice_id');
  122. }
  123. public function lineItems(): MorphMany
  124. {
  125. return $this->morphMany(DocumentLineItem::class, 'documentable');
  126. }
  127. public function isDraft(): bool
  128. {
  129. return $this->status === RecurringInvoiceStatus::Draft;
  130. }
  131. public function isActive(): bool
  132. {
  133. return $this->status === RecurringInvoiceStatus::Active;
  134. }
  135. public function wasApproved(): bool
  136. {
  137. return $this->approved_at !== null;
  138. }
  139. public function wasEnded(): bool
  140. {
  141. return $this->ended_at !== null;
  142. }
  143. public function isNeverEnding(): bool
  144. {
  145. return $this->end_type === EndType::Never;
  146. }
  147. public function canBeApproved(): bool
  148. {
  149. return $this->isDraft() && $this->hasSchedule() && ! $this->wasApproved();
  150. }
  151. public function canBeEnded(): bool
  152. {
  153. return $this->isActive() && ! $this->wasEnded();
  154. }
  155. public function hasLineItems(): bool
  156. {
  157. return $this->lineItems()->exists();
  158. }
  159. public function hasSchedule(): bool
  160. {
  161. return $this->start_date !== null;
  162. }
  163. public function getScheduleDescription(): string
  164. {
  165. $frequency = $this->frequency;
  166. return match (true) {
  167. $frequency->isDaily() => 'Repeat daily',
  168. $frequency->isWeekly() && $this->day_of_week => "Repeat weekly every {$this->day_of_week->getLabel()}",
  169. $frequency->isMonthly() && $this->day_of_month => "Repeat monthly on the {$this->day_of_month->getLabel()} day",
  170. $frequency->isYearly() && $this->month && $this->day_of_month => "Repeat yearly on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  171. $frequency->isCustom() => $this->getCustomScheduleDescription(),
  172. default => 'Not Configured',
  173. };
  174. }
  175. private function getCustomScheduleDescription(): string
  176. {
  177. $interval = $this->interval_value > 1
  178. ? "{$this->interval_value} {$this->interval_type->getPluralLabel()}"
  179. : $this->interval_type->getSingularLabel();
  180. $dayDescription = match (true) {
  181. $this->interval_type->isWeek() && $this->day_of_week => " on {$this->day_of_week->getLabel()}",
  182. $this->interval_type->isMonth() && $this->day_of_month => " on the {$this->day_of_month->getLabel()} day",
  183. $this->interval_type->isYear() && $this->month && $this->day_of_month => " on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  184. default => ''
  185. };
  186. return "Repeat every {$interval}{$dayDescription}";
  187. }
  188. /**
  189. * Get a human-readable description of when the schedule ends.
  190. */
  191. public function getEndDescription(): string
  192. {
  193. if (! $this->end_type) {
  194. return 'Not configured';
  195. }
  196. return match (true) {
  197. $this->end_type->isNever() => 'Never',
  198. $this->end_type->isAfter() && $this->max_occurrences => "After {$this->max_occurrences} " . str($this->max_occurrences === 1 ? 'invoice' : 'invoices'),
  199. $this->end_type->isOn() && $this->end_date => 'On ' . $this->end_date->toDefaultDateFormat(),
  200. default => 'Not configured'
  201. };
  202. }
  203. /**
  204. * Get the schedule timeline description.
  205. */
  206. public function getTimelineDescription(): string
  207. {
  208. $parts = [];
  209. if ($this->start_date) {
  210. $parts[] = 'First Invoice: ' . $this->start_date->toDefaultDateFormat();
  211. }
  212. if ($this->end_type) {
  213. $parts[] = 'Ends: ' . $this->getEndDescription();
  214. }
  215. return implode(', ', $parts);
  216. }
  217. /**
  218. * Get next occurrence date based on the schedule.
  219. */
  220. public function calculateNextDate(): ?Carbon
  221. {
  222. $lastDate = $this->last_date ?? $this->start_date;
  223. if (! $lastDate) {
  224. return null;
  225. }
  226. $nextDate = match (true) {
  227. $this->frequency->isDaily() => $lastDate->addDay(),
  228. $this->frequency->isWeekly() => $lastDate->addWeek(),
  229. $this->frequency->isMonthly() => $lastDate->addMonth(),
  230. $this->frequency->isYearly() => $lastDate->addYear(),
  231. $this->frequency->isCustom() => $this->calculateCustomNextDate($lastDate),
  232. default => null
  233. };
  234. // Check if we've reached the end
  235. if ($this->hasReachedEnd($nextDate)) {
  236. return null;
  237. }
  238. return $nextDate;
  239. }
  240. public function calculateNextDueDate(): ?Carbon
  241. {
  242. $nextDate = $this->calculateNextDate();
  243. if (! $nextDate) {
  244. return null;
  245. }
  246. $terms = $this->payment_terms;
  247. if (! $terms) {
  248. return $nextDate;
  249. }
  250. return $nextDate->addDays($terms->getDays());
  251. }
  252. /**
  253. * Calculate next date for custom intervals
  254. */
  255. protected function calculateCustomNextDate(Carbon $lastDate): ?\Carbon\Carbon
  256. {
  257. $value = $this->interval_value ?? 1;
  258. return match ($this->interval_type) {
  259. IntervalType::Day => $lastDate->addDays($value),
  260. IntervalType::Week => $lastDate->addWeeks($value),
  261. IntervalType::Month => $lastDate->addMonths($value),
  262. IntervalType::Year => $lastDate->addYears($value),
  263. default => null
  264. };
  265. }
  266. /**
  267. * Check if the schedule has reached its end
  268. */
  269. public function hasReachedEnd(?Carbon $nextDate = null): bool
  270. {
  271. if (! $this->end_type) {
  272. return false;
  273. }
  274. return match (true) {
  275. $this->end_type->isNever() => false,
  276. $this->end_type->isAfter() => ($this->occurrences_count ?? 0) >= ($this->max_occurrences ?? 0),
  277. $this->end_type->isOn() && $this->end_date && $nextDate => $nextDate->greaterThan($this->end_date),
  278. default => false
  279. };
  280. }
  281. public static function getUpdateScheduleAction(string $action = Action::class): MountableAction
  282. {
  283. return $action::make('updateSchedule')
  284. ->label(fn (self $record) => $record->hasSchedule() ? 'Update Schedule' : 'Set Schedule')
  285. ->icon('heroicon-o-calendar-date-range')
  286. ->slideOver()
  287. ->modalWidth(MaxWidth::FiveExtraLarge)
  288. ->successNotificationTitle('Schedule Updated')
  289. ->mountUsing(function (self $record, Form $form) {
  290. $data = $record->attributesToArray();
  291. $data['day_of_month'] ??= DayOfMonth::First;
  292. $data['start_date'] ??= now()->addMonth()->startOfMonth();
  293. $form->fill($data);
  294. })
  295. ->form([
  296. CustomSection::make('Frequency')
  297. ->contained(false)
  298. ->schema([
  299. Forms\Components\Select::make('frequency')
  300. ->label('Repeats')
  301. ->options(Frequency::class)
  302. ->softRequired()
  303. ->live()
  304. ->afterStateUpdated(function (Forms\Set $set, $state) {
  305. $frequency = Frequency::parse($state);
  306. if ($frequency->isDaily()) {
  307. $set('interval_value', null);
  308. $set('interval_type', null);
  309. }
  310. if ($frequency->isWeekly()) {
  311. $currentDayOfWeek = now()->dayOfWeek;
  312. $currentDayOfWeek = DayOfWeek::parse($currentDayOfWeek);
  313. $set('day_of_week', $currentDayOfWeek);
  314. $set('interval_value', null);
  315. $set('interval_type', null);
  316. }
  317. if ($frequency->isMonthly()) {
  318. $set('day_of_month', DayOfMonth::First);
  319. $set('interval_value', null);
  320. $set('interval_type', null);
  321. }
  322. if ($frequency->isYearly()) {
  323. $currentMonth = now()->month;
  324. $currentMonth = Month::parse($currentMonth);
  325. $set('month', $currentMonth);
  326. $currentDay = now()->dayOfMonth;
  327. $currentDay = DayOfMonth::parse($currentDay);
  328. $set('day_of_month', $currentDay);
  329. $set('interval_value', null);
  330. $set('interval_type', null);
  331. }
  332. if ($frequency->isCustom()) {
  333. $set('interval_value', 1);
  334. $set('interval_type', IntervalType::Month);
  335. $currentDay = now()->dayOfMonth;
  336. $currentDay = DayOfMonth::parse($currentDay);
  337. $set('day_of_month', $currentDay);
  338. }
  339. }),
  340. // Custom frequency fields in a nested grid
  341. Cluster::make([
  342. Forms\Components\TextInput::make('interval_value')
  343. ->label('every')
  344. ->softRequired()
  345. ->numeric()
  346. ->default(1),
  347. Forms\Components\Select::make('interval_type')
  348. ->label('Interval Type')
  349. ->options(IntervalType::class)
  350. ->softRequired()
  351. ->default(IntervalType::Month)
  352. ->live()
  353. ->afterStateUpdated(function (Forms\Set $set, $state) {
  354. $intervalType = IntervalType::parse($state);
  355. if ($intervalType->isWeek()) {
  356. $currentDayOfWeek = now()->dayOfWeek;
  357. $currentDayOfWeek = DayOfWeek::parse($currentDayOfWeek);
  358. $set('day_of_week', $currentDayOfWeek);
  359. }
  360. if ($intervalType->isMonth()) {
  361. $currentDay = now()->dayOfMonth;
  362. $currentDay = DayOfMonth::parse($currentDay);
  363. $set('day_of_month', $currentDay);
  364. }
  365. if ($intervalType->isYear()) {
  366. $currentMonth = now()->month;
  367. $currentMonth = Month::parse($currentMonth);
  368. $set('month', $currentMonth);
  369. $currentDay = now()->dayOfMonth;
  370. $currentDay = DayOfMonth::parse($currentDay);
  371. $set('day_of_month', $currentDay);
  372. }
  373. }),
  374. ])
  375. ->live()
  376. ->label('Interval')
  377. ->required()
  378. ->markAsRequired(false)
  379. ->visible(fn (Forms\Get $get) => Frequency::parse($get('frequency'))?->isCustom()),
  380. // Specific schedule details
  381. Forms\Components\Select::make('month')
  382. ->label('Month')
  383. ->options(Month::class)
  384. ->softRequired()
  385. ->visible(
  386. fn (Forms\Get $get) => Frequency::parse($get('frequency'))->isYearly() ||
  387. IntervalType::parse($get('interval_type'))?->isYear()
  388. ),
  389. Forms\Components\Select::make('day_of_month')
  390. ->label('Day of Month')
  391. ->options(DayOfMonth::class)
  392. ->softRequired()
  393. ->visible(
  394. fn (Forms\Get $get) => Frequency::parse($get('frequency'))?->isMonthly() ||
  395. Frequency::parse($get('frequency'))?->isYearly() ||
  396. IntervalType::parse($get('interval_type'))?->isMonth() ||
  397. IntervalType::parse($get('interval_type'))?->isYear()
  398. ),
  399. Forms\Components\Select::make('day_of_week')
  400. ->label('Day of Week')
  401. ->options(DayOfWeek::class)
  402. ->softRequired()
  403. ->visible(
  404. fn (Forms\Get $get) => Frequency::parse($get('frequency'))?->isWeekly() ||
  405. IntervalType::parse($get('interval_type'))?->isWeek()
  406. ),
  407. ])->columns(2),
  408. CustomSection::make('Dates')
  409. ->contained(false)
  410. ->schema([
  411. Forms\Components\DatePicker::make('start_date')
  412. ->label('Create First Invoice')
  413. ->softRequired(),
  414. Forms\Components\Group::make(function (Forms\Get $get) {
  415. $components = [];
  416. $components[] = Forms\Components\Select::make('end_type')
  417. ->label('End Schedule')
  418. ->options(EndType::class)
  419. ->softRequired()
  420. ->live()
  421. ->afterStateUpdated(function (Forms\Set $set, $state) {
  422. $endType = EndType::parse($state);
  423. if ($endType?->isNever()) {
  424. $set('max_occurrences', null);
  425. $set('end_date', null);
  426. }
  427. if ($endType?->isAfter()) {
  428. $set('max_occurrences', 1);
  429. $set('end_date', null);
  430. }
  431. if ($endType?->isOn()) {
  432. $set('max_occurrences', null);
  433. $set('end_date', now()->addMonth()->startOfMonth());
  434. }
  435. });
  436. $endType = EndType::parse($get('end_type'));
  437. if ($endType?->isAfter()) {
  438. $components[] = Forms\Components\TextInput::make('max_occurrences')
  439. ->numeric()
  440. ->live();
  441. }
  442. if ($endType?->isOn()) {
  443. $components[] = Forms\Components\DatePicker::make('end_date')
  444. ->live();
  445. }
  446. return [
  447. Cluster::make($components)
  448. ->label('Ends')
  449. ->required()
  450. ->markAsRequired(false),
  451. ];
  452. }),
  453. ])
  454. ->columns(2),
  455. CustomSection::make('Time Zone')
  456. ->contained(false)
  457. ->columns(2)
  458. ->schema([
  459. Forms\Components\Select::make('timezone')
  460. ->options(Timezone::getTimezoneOptions(CompanyProfile::first()->country))
  461. ->searchable()
  462. ->softRequired(),
  463. ]),
  464. ])
  465. ->action(function (self $record, array $data, MountableAction $action) {
  466. $record->update($data);
  467. $action->success();
  468. });
  469. }
  470. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  471. {
  472. return $action::make('approveDraft')
  473. ->label('Approve')
  474. ->icon('heroicon-o-check-circle')
  475. ->visible(function (self $record) {
  476. return $record->canBeApproved();
  477. })
  478. ->databaseTransaction()
  479. ->successNotificationTitle('Recurring Invoice Approved')
  480. ->action(function (self $record, MountableAction $action) {
  481. $record->approveDraft();
  482. $action->success();
  483. });
  484. }
  485. public function approveDraft(?Carbon $approvedAt = null): void
  486. {
  487. if (! $this->isDraft()) {
  488. throw new \RuntimeException('Invoice is not in draft status.');
  489. }
  490. $approvedAt ??= now();
  491. $this->update([
  492. 'approved_at' => $approvedAt,
  493. 'status' => RecurringInvoiceStatus::Active,
  494. ]);
  495. }
  496. }