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

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