You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RecurringInvoice.php 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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\Models\Common\Client;
  19. use App\Models\Setting\Currency;
  20. use App\Observers\RecurringInvoiceObserver;
  21. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  22. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  23. use Illuminate\Database\Eloquent\Factories\HasFactory;
  24. use Illuminate\Database\Eloquent\Model;
  25. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  26. use Illuminate\Database\Eloquent\Relations\HasMany;
  27. use Illuminate\Database\Eloquent\Relations\MorphMany;
  28. use Illuminate\Support\Carbon;
  29. #[CollectedBy(DocumentCollection::class)]
  30. #[ObservedBy(RecurringInvoiceObserver::class)]
  31. class RecurringInvoice extends Model
  32. {
  33. use Blamable;
  34. use CompanyOwned;
  35. use HasFactory;
  36. protected $table = 'recurring_invoices';
  37. protected $fillable = [
  38. 'company_id',
  39. 'client_id',
  40. 'logo',
  41. 'header',
  42. 'subheader',
  43. 'order_number',
  44. 'payment_terms',
  45. 'approved_at',
  46. 'ended_at',
  47. 'frequency',
  48. 'interval_type',
  49. 'interval_value',
  50. 'month',
  51. 'day_of_month',
  52. 'day_of_week',
  53. 'start_date',
  54. 'end_type',
  55. 'max_occurrences',
  56. 'end_date',
  57. 'occurrences_count',
  58. 'timezone',
  59. 'next_date',
  60. 'last_date',
  61. 'auto_send',
  62. 'send_time',
  63. 'status',
  64. 'currency_code',
  65. 'discount_method',
  66. 'discount_computation',
  67. 'discount_rate',
  68. 'subtotal',
  69. 'tax_total',
  70. 'discount_total',
  71. 'total',
  72. 'terms',
  73. 'footer',
  74. 'created_by',
  75. 'updated_by',
  76. ];
  77. protected $casts = [
  78. 'approved_at' => 'datetime',
  79. 'ended_at' => 'datetime',
  80. 'start_date' => 'date',
  81. 'end_date' => 'date',
  82. 'next_date' => 'date',
  83. 'last_date' => 'date',
  84. 'auto_send' => 'boolean',
  85. 'send_time' => 'datetime:H:i',
  86. 'payment_terms' => PaymentTerms::class,
  87. 'frequency' => Frequency::class,
  88. 'interval_type' => IntervalType::class,
  89. 'month' => Month::class,
  90. 'day_of_month' => DayOfMonth::class,
  91. 'day_of_week' => DayOfWeek::class,
  92. 'end_type' => EndType::class,
  93. 'status' => RecurringInvoiceStatus::class,
  94. 'discount_method' => DocumentDiscountMethod::class,
  95. 'discount_computation' => AdjustmentComputation::class,
  96. 'discount_rate' => RateCast::class,
  97. 'subtotal' => MoneyCast::class,
  98. 'tax_total' => MoneyCast::class,
  99. 'discount_total' => MoneyCast::class,
  100. 'total' => MoneyCast::class,
  101. ];
  102. public function client(): BelongsTo
  103. {
  104. return $this->belongsTo(Client::class);
  105. }
  106. public function currency(): BelongsTo
  107. {
  108. return $this->belongsTo(Currency::class, 'currency_code', 'code');
  109. }
  110. public function invoices(): HasMany
  111. {
  112. return $this->hasMany(Invoice::class, 'recurring_invoice_id');
  113. }
  114. public function lineItems(): MorphMany
  115. {
  116. return $this->morphMany(DocumentLineItem::class, 'documentable');
  117. }
  118. public function isDraft(): bool
  119. {
  120. return $this->status === RecurringInvoiceStatus::Draft;
  121. }
  122. public function isActive(): bool
  123. {
  124. return $this->status === RecurringInvoiceStatus::Active;
  125. }
  126. public function wasApproved(): bool
  127. {
  128. return $this->approved_at !== null;
  129. }
  130. public function wasEnded(): bool
  131. {
  132. return $this->ended_at !== null;
  133. }
  134. public function isNeverEnding(): bool
  135. {
  136. return $this->end_type === EndType::Never;
  137. }
  138. public function canBeApproved(): bool
  139. {
  140. return $this->isDraft() && ! $this->wasApproved();
  141. }
  142. public function canBeEnded(): bool
  143. {
  144. return $this->isActive() && ! $this->wasEnded();
  145. }
  146. public function hasLineItems(): bool
  147. {
  148. return $this->lineItems()->exists();
  149. }
  150. public function getScheduleDescription(): string
  151. {
  152. $frequency = $this->frequency;
  153. return match (true) {
  154. $frequency->isDaily() => 'Repeat daily',
  155. $frequency->isWeekly() && $this->day_of_week => "Repeat weekly every {$this->day_of_week->getLabel()}",
  156. $frequency->isMonthly() && $this->day_of_month => "Repeat monthly on the {$this->day_of_month->getLabel()} day",
  157. $frequency->isYearly() && $this->month && $this->day_of_month => "Repeat yearly on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  158. $frequency->isCustom() => $this->getCustomScheduleDescription(),
  159. default => 'Schedule not configured'
  160. };
  161. }
  162. private function getCustomScheduleDescription(): string
  163. {
  164. $interval = $this->interval_value > 1
  165. ? "{$this->interval_value} {$this->interval_type->getPluralLabel()}"
  166. : $this->interval_type->getSingularLabel();
  167. $dayDescription = match (true) {
  168. $this->interval_type->isWeek() && $this->day_of_week => " on {$this->day_of_week->getLabel()}",
  169. $this->interval_type->isMonth() && $this->day_of_month => " on the {$this->day_of_month->getLabel()} day",
  170. $this->interval_type->isYear() && $this->month && $this->day_of_month => " on {$this->month->getLabel()} {$this->day_of_month->getLabel()}",
  171. default => ''
  172. };
  173. return "Repeat every {$interval}{$dayDescription}";
  174. }
  175. /**
  176. * Get a human-readable description of when the schedule ends.
  177. */
  178. public function getEndDescription(): string
  179. {
  180. if (! $this->end_type) {
  181. return 'Not configured';
  182. }
  183. return match (true) {
  184. $this->end_type->isNever() => 'Never',
  185. $this->end_type->isAfter() && $this->max_occurrences => "After {$this->max_occurrences} " . str($this->max_occurrences === 1 ? 'invoice' : 'invoices'),
  186. $this->end_type->isOn() && $this->end_date => 'On ' . $this->end_date->toDefaultDateFormat(),
  187. default => 'Not configured'
  188. };
  189. }
  190. /**
  191. * Get the schedule timeline description.
  192. */
  193. public function getTimelineDescription(): string
  194. {
  195. $parts = [];
  196. if ($this->start_date) {
  197. $parts[] = 'First Invoice: ' . $this->start_date->toDefaultDateFormat();
  198. }
  199. if ($this->end_type) {
  200. $parts[] = 'Ends: ' . $this->getEndDescription();
  201. }
  202. return implode(', ', $parts);
  203. }
  204. /**
  205. * Get next occurrence date based on the schedule.
  206. */
  207. public function calculateNextDate(): ?\Carbon\Carbon
  208. {
  209. $lastDate = $this->last_date ?? $this->start_date;
  210. if (! $lastDate) {
  211. return null;
  212. }
  213. $nextDate = match (true) {
  214. $this->frequency->isDaily() => $lastDate->addDay(),
  215. $this->frequency->isWeekly() => $lastDate->addWeek(),
  216. $this->frequency->isMonthly() => $lastDate->addMonth(),
  217. $this->frequency->isYearly() => $lastDate->addYear(),
  218. $this->frequency->isCustom() => $this->calculateCustomNextDate($lastDate),
  219. default => null
  220. };
  221. // Check if we've reached the end
  222. if ($this->hasReachedEnd($nextDate)) {
  223. return null;
  224. }
  225. return $nextDate;
  226. }
  227. /**
  228. * Calculate next date for custom intervals
  229. */
  230. protected function calculateCustomNextDate(Carbon $lastDate): ?\Carbon\Carbon
  231. {
  232. $value = $this->interval_value ?? 1;
  233. return match ($this->interval_type) {
  234. IntervalType::Day => $lastDate->addDays($value),
  235. IntervalType::Week => $lastDate->addWeeks($value),
  236. IntervalType::Month => $lastDate->addMonths($value),
  237. IntervalType::Year => $lastDate->addYears($value),
  238. default => null
  239. };
  240. }
  241. /**
  242. * Check if the schedule has reached its end
  243. */
  244. public function hasReachedEnd(?Carbon $nextDate = null): bool
  245. {
  246. if (! $this->end_type) {
  247. return false;
  248. }
  249. return match (true) {
  250. $this->end_type->isNever() => false,
  251. $this->end_type->isAfter() => ($this->occurrences_count ?? 0) >= ($this->max_occurrences ?? 0),
  252. $this->end_type->isOn() && $this->end_date && $nextDate => $nextDate->greaterThan($this->end_date),
  253. default => false
  254. };
  255. }
  256. public function markAsApproved(): void
  257. {
  258. $this->update([
  259. 'approved_at' => now(),
  260. 'status' => RecurringInvoiceStatus::Active,
  261. ]);
  262. }
  263. }