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.8KB

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