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

Invoice.php 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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 static function getNextDocumentNumber(): string
  111. {
  112. $company = auth()->user()->currentCompany;
  113. if (! $company) {
  114. throw new \RuntimeException('No current company is set for the user.');
  115. }
  116. $defaultInvoiceSettings = $company->defaultInvoice;
  117. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  118. $numberDigits = $defaultInvoiceSettings->number_digits;
  119. $latestDocument = static::query()
  120. ->whereNotNull('invoice_number')
  121. ->latest('invoice_number')
  122. ->first();
  123. $lastNumberNumericPart = $latestDocument
  124. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  125. : 0;
  126. $numberNext = $lastNumberNumericPart + 1;
  127. return $defaultInvoiceSettings->getNumberNext(
  128. padded: true,
  129. format: true,
  130. prefix: $numberPrefix,
  131. digits: $numberDigits,
  132. next: $numberNext
  133. );
  134. }
  135. public function recordPayment(array $data): void
  136. {
  137. $isRefund = $this->status === InvoiceStatus::Overpaid;
  138. if ($isRefund) {
  139. $transactionType = TransactionType::Withdrawal;
  140. $transactionDescription = 'Refund for Overpayment on Invoice #' . $this->invoice_number;
  141. } else {
  142. $transactionType = TransactionType::Deposit;
  143. $transactionDescription = 'Payment for Invoice #' . $this->invoice_number;
  144. }
  145. // Create transaction
  146. $this->transactions()->create([
  147. 'company_id' => $this->company_id,
  148. 'type' => $transactionType,
  149. 'is_payment' => true,
  150. 'posted_at' => $data['posted_at'],
  151. 'amount' => $data['amount'],
  152. 'payment_method' => $data['payment_method'],
  153. 'bank_account_id' => $data['bank_account_id'],
  154. 'account_id' => Account::getAccountsReceivableAccount()->id,
  155. 'description' => $transactionDescription,
  156. 'notes' => $data['notes'] ?? null,
  157. ]);
  158. }
  159. public function approveDraft(): void
  160. {
  161. if (! $this->isDraft()) {
  162. throw new \RuntimeException('Invoice is not in draft status.');
  163. }
  164. $transaction = $this->transactions()->create([
  165. 'company_id' => $this->company_id,
  166. 'type' => TransactionType::Journal,
  167. 'posted_at' => now(),
  168. 'amount' => $this->total,
  169. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  170. ]);
  171. $transaction->journalEntries()->create([
  172. 'company_id' => $this->company_id,
  173. 'type' => JournalEntryType::Debit,
  174. 'account_id' => Account::getAccountsReceivableAccount()->id,
  175. 'amount' => $this->total,
  176. 'description' => $transaction->description,
  177. ]);
  178. foreach ($this->lineItems as $lineItem) {
  179. $transaction->journalEntries()->create([
  180. 'company_id' => $this->company_id,
  181. 'type' => JournalEntryType::Credit,
  182. 'account_id' => $lineItem->offering->income_account_id,
  183. 'amount' => $lineItem->subtotal,
  184. 'description' => $transaction->description,
  185. ]);
  186. foreach ($lineItem->adjustments as $adjustment) {
  187. $transaction->journalEntries()->create([
  188. 'company_id' => $this->company_id,
  189. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  190. 'account_id' => $adjustment->account_id,
  191. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  192. 'description' => $transaction->description,
  193. ]);
  194. }
  195. }
  196. $this->updateQuietly([
  197. 'status' => InvoiceStatus::Unsent,
  198. ]);
  199. }
  200. }