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.

Invoice.php 7.5KB

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