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

Invoice.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Casts\RateCast;
  5. use App\Collections\Accounting\DocumentCollection;
  6. use App\Enums\Accounting\AdjustmentComputation;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\InvoiceStatus;
  10. use App\Enums\Accounting\JournalEntryType;
  11. use App\Enums\Accounting\TransactionType;
  12. use App\Filament\Company\Resources\Sales\InvoiceResource;
  13. use App\Models\Banking\BankAccount;
  14. use App\Models\Common\Client;
  15. use App\Models\Company;
  16. use App\Observers\InvoiceObserver;
  17. use App\Utilities\Currency\CurrencyAccessor;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use Filament\Actions\Action;
  20. use Filament\Actions\MountableAction;
  21. use Filament\Actions\ReplicateAction;
  22. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  23. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  24. use Illuminate\Database\Eloquent\Builder;
  25. use Illuminate\Database\Eloquent\Casts\Attribute;
  26. use Illuminate\Database\Eloquent\Model;
  27. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  28. use Illuminate\Database\Eloquent\Relations\MorphMany;
  29. use Illuminate\Database\Eloquent\Relations\MorphOne;
  30. use Illuminate\Support\Carbon;
  31. #[CollectedBy(DocumentCollection::class)]
  32. #[ObservedBy(InvoiceObserver::class)]
  33. class Invoice extends Document
  34. {
  35. protected $table = 'invoices';
  36. protected $fillable = [
  37. 'company_id',
  38. 'client_id',
  39. 'estimate_id',
  40. 'recurring_invoice_id',
  41. 'logo',
  42. 'header',
  43. 'subheader',
  44. 'invoice_number',
  45. 'order_number',
  46. 'date',
  47. 'due_date',
  48. 'approved_at',
  49. 'paid_at',
  50. 'last_sent_at',
  51. 'last_viewed_at',
  52. 'status',
  53. 'currency_code',
  54. 'discount_method',
  55. 'discount_computation',
  56. 'discount_rate',
  57. 'subtotal',
  58. 'tax_total',
  59. 'discount_total',
  60. 'total',
  61. 'amount_paid',
  62. 'terms',
  63. 'footer',
  64. 'created_by',
  65. 'updated_by',
  66. ];
  67. protected $casts = [
  68. 'date' => 'date',
  69. 'due_date' => 'date',
  70. 'approved_at' => 'datetime',
  71. 'paid_at' => 'datetime',
  72. 'last_sent_at' => 'datetime',
  73. 'last_viewed_at' => 'datetime',
  74. 'status' => InvoiceStatus::class,
  75. 'discount_method' => DocumentDiscountMethod::class,
  76. 'discount_computation' => AdjustmentComputation::class,
  77. 'discount_rate' => RateCast::class,
  78. 'subtotal' => MoneyCast::class,
  79. 'tax_total' => MoneyCast::class,
  80. 'discount_total' => MoneyCast::class,
  81. 'total' => MoneyCast::class,
  82. 'amount_paid' => MoneyCast::class,
  83. 'amount_due' => MoneyCast::class,
  84. ];
  85. public function client(): BelongsTo
  86. {
  87. return $this->belongsTo(Client::class);
  88. }
  89. public function estimate(): BelongsTo
  90. {
  91. return $this->belongsTo(Estimate::class);
  92. }
  93. public function recurringInvoice(): BelongsTo
  94. {
  95. return $this->belongsTo(RecurringInvoice::class);
  96. }
  97. public function transactions(): MorphMany
  98. {
  99. return $this->morphMany(Transaction::class, 'transactionable');
  100. }
  101. public function payments(): MorphMany
  102. {
  103. return $this->transactions()->where('is_payment', true);
  104. }
  105. public function deposits(): MorphMany
  106. {
  107. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  108. }
  109. public function withdrawals(): MorphMany
  110. {
  111. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  112. }
  113. public function approvalTransaction(): MorphOne
  114. {
  115. return $this->morphOne(Transaction::class, 'transactionable')
  116. ->where('type', TransactionType::Journal);
  117. }
  118. protected function sourceType(): Attribute
  119. {
  120. return Attribute::get(function () {
  121. return match (true) {
  122. $this->estimate_id !== null => DocumentType::Estimate,
  123. $this->recurring_invoice_id !== null => DocumentType::RecurringInvoice,
  124. default => null,
  125. };
  126. });
  127. }
  128. public function documentType(): DocumentType
  129. {
  130. return DocumentType::Invoice;
  131. }
  132. public function documentNumber(): ?string
  133. {
  134. return $this->invoice_number;
  135. }
  136. public function documentDate(): ?string
  137. {
  138. return $this->date?->toDefaultDateFormat();
  139. }
  140. public function dueDate(): ?string
  141. {
  142. return $this->due_date?->toDefaultDateFormat();
  143. }
  144. public function referenceNumber(): ?string
  145. {
  146. return $this->order_number;
  147. }
  148. public function amountDue(): ?string
  149. {
  150. return $this->amount_due;
  151. }
  152. public function scopeUnpaid(Builder $query): Builder
  153. {
  154. return $query->whereNotIn('status', [
  155. InvoiceStatus::Paid,
  156. InvoiceStatus::Void,
  157. InvoiceStatus::Draft,
  158. InvoiceStatus::Overpaid,
  159. ]);
  160. }
  161. protected function isCurrentlyOverdue(): Attribute
  162. {
  163. return Attribute::get(function () {
  164. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  165. });
  166. }
  167. public function isDraft(): bool
  168. {
  169. return $this->status === InvoiceStatus::Draft;
  170. }
  171. public function wasApproved(): bool
  172. {
  173. return $this->approved_at !== null;
  174. }
  175. public function isPaid(): bool
  176. {
  177. return $this->paid_at !== null;
  178. }
  179. public function hasBeenSent(): bool
  180. {
  181. return $this->last_sent_at !== null;
  182. }
  183. public function hasBeenViewed(): bool
  184. {
  185. return $this->last_viewed_at !== null;
  186. }
  187. public function canRecordPayment(): bool
  188. {
  189. return ! in_array($this->status, [
  190. InvoiceStatus::Draft,
  191. InvoiceStatus::Paid,
  192. InvoiceStatus::Void,
  193. ]);
  194. }
  195. public function canBulkRecordPayment(): bool
  196. {
  197. return ! in_array($this->status, [
  198. InvoiceStatus::Draft,
  199. InvoiceStatus::Paid,
  200. InvoiceStatus::Void,
  201. InvoiceStatus::Overpaid,
  202. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  203. }
  204. public function canBeOverdue(): bool
  205. {
  206. return in_array($this->status, InvoiceStatus::canBeOverdue());
  207. }
  208. public function canBeApproved(): bool
  209. {
  210. return $this->isDraft() && ! $this->wasApproved();
  211. }
  212. public function canBeMarkedAsSent(): bool
  213. {
  214. return ! $this->hasBeenSent();
  215. }
  216. public function hasPayments(): bool
  217. {
  218. return $this->payments()->exists();
  219. }
  220. public static function getNextDocumentNumber(?Company $company = null): string
  221. {
  222. $company ??= auth()->user()?->currentCompany;
  223. if (! $company) {
  224. throw new \RuntimeException('No current company is set for the user.');
  225. }
  226. $defaultInvoiceSettings = $company->defaultInvoice;
  227. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  228. $numberDigits = $defaultInvoiceSettings->number_digits;
  229. $latestDocument = static::query()
  230. ->whereNotNull('invoice_number')
  231. ->latest('invoice_number')
  232. ->first();
  233. $lastNumberNumericPart = $latestDocument
  234. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  235. : 0;
  236. $numberNext = $lastNumberNumericPart + 1;
  237. return $defaultInvoiceSettings->getNumberNext(
  238. padded: true,
  239. format: true,
  240. prefix: $numberPrefix,
  241. digits: $numberDigits,
  242. next: $numberNext
  243. );
  244. }
  245. public function recordPayment(array $data): void
  246. {
  247. $isRefund = $this->status === InvoiceStatus::Overpaid;
  248. if ($isRefund) {
  249. $transactionType = TransactionType::Withdrawal;
  250. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  251. } else {
  252. $transactionType = TransactionType::Deposit;
  253. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  254. }
  255. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  256. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  257. $invoiceCurrency = $this->currency_code;
  258. $requiresConversion = $invoiceCurrency !== $bankAccountCurrency;
  259. if ($requiresConversion) {
  260. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($data['amount'], $invoiceCurrency);
  261. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  262. $amountInInvoiceCurrencyCents,
  263. $invoiceCurrency,
  264. $bankAccountCurrency
  265. );
  266. $formattedAmountForBankCurrency = CurrencyConverter::convertCentsToFormatSimple(
  267. $amountInBankCurrencyCents,
  268. $bankAccountCurrency
  269. );
  270. } else {
  271. $formattedAmountForBankCurrency = $data['amount']; // Already in simple format
  272. }
  273. // Create transaction
  274. $this->transactions()->create([
  275. 'company_id' => $this->company_id,
  276. 'type' => $transactionType,
  277. 'is_payment' => true,
  278. 'posted_at' => $data['posted_at'],
  279. 'amount' => $formattedAmountForBankCurrency,
  280. 'payment_method' => $data['payment_method'],
  281. 'bank_account_id' => $data['bank_account_id'],
  282. 'account_id' => Account::getAccountsReceivableAccount()->id,
  283. 'description' => $transactionDescription,
  284. 'notes' => $data['notes'] ?? null,
  285. ]);
  286. }
  287. public function approveDraft(?Carbon $approvedAt = null): void
  288. {
  289. if (! $this->isDraft()) {
  290. throw new \RuntimeException('Invoice is not in draft status.');
  291. }
  292. $this->createApprovalTransaction();
  293. $approvedAt ??= now();
  294. $this->update([
  295. 'approved_at' => $approvedAt,
  296. 'status' => InvoiceStatus::Unsent,
  297. ]);
  298. }
  299. public function createApprovalTransaction(): void
  300. {
  301. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  302. $transaction = $this->transactions()->create([
  303. 'company_id' => $this->company_id,
  304. 'type' => TransactionType::Journal,
  305. 'posted_at' => $this->date,
  306. 'amount' => $total,
  307. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  308. ]);
  309. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  310. $transaction->journalEntries()->create([
  311. 'company_id' => $this->company_id,
  312. 'type' => JournalEntryType::Debit,
  313. 'account_id' => Account::getAccountsReceivableAccount()->id,
  314. 'amount' => $total,
  315. 'description' => $baseDescription,
  316. ]);
  317. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  318. $invoiceDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  319. $remainingDiscountCents = $invoiceDiscountTotalCents;
  320. foreach ($this->lineItems as $index => $lineItem) {
  321. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  322. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  323. $transaction->journalEntries()->create([
  324. 'company_id' => $this->company_id,
  325. 'type' => JournalEntryType::Credit,
  326. 'account_id' => $lineItem->offering->income_account_id,
  327. 'amount' => $lineItemSubtotal,
  328. 'description' => $lineItemDescription,
  329. ]);
  330. foreach ($lineItem->adjustments as $adjustment) {
  331. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  332. $transaction->journalEntries()->create([
  333. 'company_id' => $this->company_id,
  334. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  335. 'account_id' => $adjustment->account_id,
  336. 'amount' => $adjustmentAmount,
  337. 'description' => $lineItemDescription,
  338. ]);
  339. }
  340. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  341. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  342. if ($index === $this->lineItems->count() - 1) {
  343. $lineItemDiscount = $remainingDiscountCents;
  344. } else {
  345. $lineItemDiscount = (int) round(
  346. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $invoiceDiscountTotalCents
  347. );
  348. $remainingDiscountCents -= $lineItemDiscount;
  349. }
  350. if ($lineItemDiscount > 0) {
  351. $transaction->journalEntries()->create([
  352. 'company_id' => $this->company_id,
  353. 'type' => JournalEntryType::Debit,
  354. 'account_id' => Account::getSalesDiscountAccount()->id,
  355. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  356. 'description' => "{$lineItemDescription} (Proportional Discount)",
  357. ]);
  358. }
  359. }
  360. }
  361. }
  362. public function updateApprovalTransaction(): void
  363. {
  364. $transaction = $this->approvalTransaction;
  365. if ($transaction) {
  366. $transaction->delete();
  367. }
  368. $this->createApprovalTransaction();
  369. }
  370. public function convertAmountToDefaultCurrency(int $amountCents): int
  371. {
  372. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  373. $needsConversion = $this->currency_code !== $defaultCurrency;
  374. if ($needsConversion) {
  375. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  376. }
  377. return $amountCents;
  378. }
  379. public function formatAmountToDefaultCurrency(int $amountCents): string
  380. {
  381. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  382. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  383. }
  384. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  385. {
  386. return $action::make('approveDraft')
  387. ->label('Approve')
  388. ->icon('heroicon-o-check-circle')
  389. ->visible(function (self $record) {
  390. return $record->canBeApproved();
  391. })
  392. ->databaseTransaction()
  393. ->successNotificationTitle('Invoice Approved')
  394. ->action(function (self $record, MountableAction $action) {
  395. $record->approveDraft();
  396. $action->success();
  397. });
  398. }
  399. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  400. {
  401. return $action::make('markAsSent')
  402. ->label('Mark as Sent')
  403. ->icon('heroicon-o-paper-airplane')
  404. ->visible(static function (self $record) {
  405. return $record->canBeMarkedAsSent();
  406. })
  407. ->successNotificationTitle('Invoice Sent')
  408. ->action(function (self $record, MountableAction $action) {
  409. $record->markAsSent();
  410. $action->success();
  411. });
  412. }
  413. public function markAsSent(?Carbon $sentAt = null): void
  414. {
  415. $sentAt ??= now();
  416. $this->update([
  417. 'status' => InvoiceStatus::Sent,
  418. 'last_sent_at' => $sentAt,
  419. ]);
  420. }
  421. public function markAsViewed(?Carbon $viewedAt = null): void
  422. {
  423. $viewedAt ??= now();
  424. $this->update([
  425. 'status' => InvoiceStatus::Viewed,
  426. 'last_viewed_at' => $viewedAt,
  427. ]);
  428. }
  429. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  430. {
  431. return $action::make()
  432. ->excludeAttributes([
  433. 'status',
  434. 'amount_paid',
  435. 'amount_due',
  436. 'created_by',
  437. 'updated_by',
  438. 'created_at',
  439. 'updated_at',
  440. 'invoice_number',
  441. 'date',
  442. 'due_date',
  443. 'approved_at',
  444. 'paid_at',
  445. 'last_sent_at',
  446. 'last_viewed_at',
  447. ])
  448. ->modal(false)
  449. ->beforeReplicaSaved(function (self $original, self $replica) {
  450. $replica->status = InvoiceStatus::Draft;
  451. $replica->invoice_number = self::getNextDocumentNumber();
  452. $replica->date = now();
  453. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  454. })
  455. ->databaseTransaction()
  456. ->after(function (self $original, self $replica) {
  457. $original->replicateLineItems($replica);
  458. })
  459. ->successRedirectUrl(static function (self $replica) {
  460. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  461. });
  462. }
  463. public function replicateLineItems(Model $target): void
  464. {
  465. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  466. $replica = $lineItem->replicate([
  467. 'documentable_id',
  468. 'documentable_type',
  469. 'subtotal',
  470. 'total',
  471. 'created_by',
  472. 'updated_by',
  473. 'created_at',
  474. 'updated_at',
  475. ]);
  476. $replica->documentable_id = $target->id;
  477. $replica->documentable_type = $target->getMorphClass();
  478. $replica->save();
  479. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  480. });
  481. }
  482. }