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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Collections\Accounting\InvoiceCollection;
  5. use App\Concerns\Blamable;
  6. use App\Concerns\CompanyOwned;
  7. use App\Enums\Accounting\InvoiceStatus;
  8. use App\Enums\Accounting\JournalEntryType;
  9. use App\Enums\Accounting\TransactionType;
  10. use App\Models\Common\Client;
  11. use App\Observers\InvoiceObserver;
  12. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  13. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  14. use Illuminate\Database\Eloquent\Casts\Attribute;
  15. use Illuminate\Database\Eloquent\Factories\HasFactory;
  16. use Illuminate\Database\Eloquent\Model;
  17. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  18. use Illuminate\Database\Eloquent\Relations\HasMany;
  19. use Illuminate\Database\Eloquent\Relations\MorphMany;
  20. use Illuminate\Database\Eloquent\Relations\MorphOne;
  21. use Illuminate\Support\Carbon;
  22. #[ObservedBy(InvoiceObserver::class)]
  23. #[CollectedBy(InvoiceCollection::class)]
  24. class Invoice extends Model
  25. {
  26. use Blamable;
  27. use CompanyOwned;
  28. use HasFactory;
  29. protected $table = 'invoices';
  30. protected $fillable = [
  31. 'company_id',
  32. 'client_id',
  33. 'logo',
  34. 'header',
  35. 'subheader',
  36. 'invoice_number',
  37. 'order_number',
  38. 'date',
  39. 'due_date',
  40. 'status',
  41. 'currency_code',
  42. 'subtotal',
  43. 'tax_total',
  44. 'discount_total',
  45. 'total',
  46. 'amount_paid',
  47. 'terms',
  48. 'footer',
  49. 'created_by',
  50. 'updated_by',
  51. ];
  52. protected $casts = [
  53. 'date' => 'date',
  54. 'due_date' => 'date',
  55. 'status' => InvoiceStatus::class,
  56. 'subtotal' => MoneyCast::class,
  57. 'tax_total' => MoneyCast::class,
  58. 'discount_total' => MoneyCast::class,
  59. 'total' => MoneyCast::class,
  60. 'amount_paid' => MoneyCast::class,
  61. 'amount_due' => MoneyCast::class,
  62. ];
  63. public function client(): BelongsTo
  64. {
  65. return $this->belongsTo(Client::class);
  66. }
  67. public function lineItems(): MorphMany
  68. {
  69. return $this->morphMany(DocumentLineItem::class, 'documentable');
  70. }
  71. public function transactions(): MorphMany
  72. {
  73. return $this->morphMany(Transaction::class, 'transactionable');
  74. }
  75. public function payments(): MorphMany
  76. {
  77. return $this->transactions()->where('is_payment', true);
  78. }
  79. public function deposits(): MorphMany
  80. {
  81. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  82. }
  83. public function withdrawals(): MorphMany
  84. {
  85. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  86. }
  87. protected function lastSent(): Attribute
  88. {
  89. return Attribute::get(function () {
  90. return $this->getStatusChangedAt(InvoiceStatus::Sent);
  91. });
  92. }
  93. protected function approvedAt(): Attribute
  94. {
  95. return Attribute::get(function () {
  96. return $this->getStatusChangedAt(InvoiceStatus::Unsent);
  97. });
  98. }
  99. protected function paidAt(): Attribute
  100. {
  101. return Attribute::get(function () {
  102. return $this->getStatusChangedAt(InvoiceStatus::Paid);
  103. });
  104. }
  105. protected function getStatusChangedAt(InvoiceStatus $status): ?Carbon
  106. {
  107. return $this->statusHistories
  108. ->where('new_status', $status)
  109. ->sortByDesc('changed_at')
  110. ->first()?->changed_at;
  111. }
  112. public function approvalTransaction(): MorphOne
  113. {
  114. return $this->morphOne(Transaction::class, 'transactionable')
  115. ->where('type', TransactionType::Journal);
  116. }
  117. public function statusHistories(): HasMany
  118. {
  119. return $this->hasMany(InvoiceStatusHistory::class);
  120. }
  121. protected function isCurrentlyOverdue(): Attribute
  122. {
  123. return Attribute::get(function () {
  124. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  125. });
  126. }
  127. public function isDraft(): bool
  128. {
  129. return $this->status === InvoiceStatus::Draft;
  130. }
  131. public function canRecordPayment(): bool
  132. {
  133. return ! in_array($this->status, [
  134. InvoiceStatus::Draft,
  135. InvoiceStatus::Paid,
  136. InvoiceStatus::Void,
  137. ]);
  138. }
  139. public function canBulkRecordPayment(): bool
  140. {
  141. return ! in_array($this->status, [
  142. InvoiceStatus::Draft,
  143. InvoiceStatus::Paid,
  144. InvoiceStatus::Void,
  145. InvoiceStatus::Overpaid,
  146. ]);
  147. }
  148. public function canBeOverdue(): bool
  149. {
  150. return in_array($this->status, InvoiceStatus::canBeOverdue());
  151. }
  152. public static function getNextDocumentNumber(): string
  153. {
  154. $company = auth()->user()->currentCompany;
  155. if (! $company) {
  156. throw new \RuntimeException('No current company is set for the user.');
  157. }
  158. $defaultInvoiceSettings = $company->defaultInvoice;
  159. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  160. $numberDigits = $defaultInvoiceSettings->number_digits;
  161. $latestDocument = static::query()
  162. ->whereNotNull('invoice_number')
  163. ->latest('invoice_number')
  164. ->first();
  165. $lastNumberNumericPart = $latestDocument
  166. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  167. : 0;
  168. $numberNext = $lastNumberNumericPart + 1;
  169. return $defaultInvoiceSettings->getNumberNext(
  170. padded: true,
  171. format: true,
  172. prefix: $numberPrefix,
  173. digits: $numberDigits,
  174. next: $numberNext
  175. );
  176. }
  177. public function recordPayment(array $data): void
  178. {
  179. $isRefund = $this->status === InvoiceStatus::Overpaid;
  180. if ($isRefund) {
  181. $transactionType = TransactionType::Withdrawal;
  182. $transactionDescription = 'Refund for Overpayment on Invoice #' . $this->invoice_number;
  183. } else {
  184. $transactionType = TransactionType::Deposit;
  185. $transactionDescription = 'Payment for Invoice #' . $this->invoice_number;
  186. }
  187. // Create transaction
  188. $this->transactions()->create([
  189. 'company_id' => $this->company_id,
  190. 'type' => $transactionType,
  191. 'is_payment' => true,
  192. 'posted_at' => $data['posted_at'],
  193. 'amount' => $data['amount'],
  194. 'payment_method' => $data['payment_method'],
  195. 'bank_account_id' => $data['bank_account_id'],
  196. 'account_id' => Account::getAccountsReceivableAccount()->id,
  197. 'description' => $transactionDescription,
  198. 'notes' => $data['notes'] ?? null,
  199. ]);
  200. }
  201. public function approveDraft(): void
  202. {
  203. if (! $this->isDraft()) {
  204. throw new \RuntimeException('Invoice is not in draft status.');
  205. }
  206. $transaction = $this->transactions()->create([
  207. 'company_id' => $this->company_id,
  208. 'type' => TransactionType::Journal,
  209. 'posted_at' => now(),
  210. 'amount' => $this->total,
  211. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  212. ]);
  213. $transaction->journalEntries()->create([
  214. 'company_id' => $this->company_id,
  215. 'type' => JournalEntryType::Debit,
  216. 'account_id' => Account::getAccountsReceivableAccount()->id,
  217. 'amount' => $this->total,
  218. 'description' => $transaction->description,
  219. ]);
  220. foreach ($this->lineItems as $lineItem) {
  221. $transaction->journalEntries()->create([
  222. 'company_id' => $this->company_id,
  223. 'type' => JournalEntryType::Credit,
  224. 'account_id' => $lineItem->offering->income_account_id,
  225. 'amount' => $lineItem->subtotal,
  226. 'description' => $transaction->description,
  227. ]);
  228. foreach ($lineItem->adjustments as $adjustment) {
  229. $transaction->journalEntries()->create([
  230. 'company_id' => $this->company_id,
  231. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  232. 'account_id' => $adjustment->account_id,
  233. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  234. 'description' => $transaction->description,
  235. ]);
  236. }
  237. }
  238. $this->update([
  239. 'status' => InvoiceStatus::Unsent,
  240. ]);
  241. }
  242. }