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 21KB

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