您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Invoice.php 7.2KB

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