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

Invoice.php 21KB

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