Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Invoice.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. return ! in_array($this->status, [
  202. InvoiceStatus::Draft,
  203. InvoiceStatus::Paid,
  204. InvoiceStatus::Void,
  205. ]);
  206. }
  207. public function canBulkRecordPayment(): bool
  208. {
  209. return ! in_array($this->status, [
  210. InvoiceStatus::Draft,
  211. InvoiceStatus::Paid,
  212. InvoiceStatus::Void,
  213. InvoiceStatus::Overpaid,
  214. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  215. }
  216. public function canBeOverdue(): bool
  217. {
  218. return in_array($this->status, InvoiceStatus::canBeOverdue());
  219. }
  220. public function canBeApproved(): bool
  221. {
  222. return $this->isDraft() && ! $this->wasApproved();
  223. }
  224. public function canBeMarkedAsSent(): bool
  225. {
  226. return ! $this->hasBeenSent();
  227. }
  228. public function hasPayments(): bool
  229. {
  230. return $this->payments()->exists();
  231. }
  232. public static function getNextDocumentNumber(?Company $company = null): string
  233. {
  234. $company ??= auth()->user()?->currentCompany;
  235. if (! $company) {
  236. throw new \RuntimeException('No current company is set for the user.');
  237. }
  238. $defaultInvoiceSettings = $company->defaultInvoice;
  239. $numberPrefix = $defaultInvoiceSettings->number_prefix ?? '';
  240. $latestDocument = static::query()
  241. ->whereNotNull('invoice_number')
  242. ->latest('invoice_number')
  243. ->first();
  244. $lastNumberNumericPart = $latestDocument
  245. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  246. : DocumentDefault::getBaseNumber();
  247. $numberNext = $lastNumberNumericPart + 1;
  248. return $defaultInvoiceSettings->getNumberNext(
  249. prefix: $numberPrefix,
  250. next: $numberNext
  251. );
  252. }
  253. public function recordPayment(array $data): void
  254. {
  255. $isRefund = $this->status === InvoiceStatus::Overpaid;
  256. if ($isRefund) {
  257. $transactionType = TransactionType::Withdrawal;
  258. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  259. } else {
  260. $transactionType = TransactionType::Deposit;
  261. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  262. }
  263. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  264. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  265. $invoiceCurrency = $this->currency_code;
  266. $requiresConversion = $invoiceCurrency !== $bankAccountCurrency;
  267. // Store the original payment amount in invoice currency before any conversion
  268. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($data['amount'], $invoiceCurrency);
  269. if ($requiresConversion) {
  270. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  271. $amountInInvoiceCurrencyCents,
  272. $invoiceCurrency,
  273. $bankAccountCurrency
  274. );
  275. $formattedAmountForBankCurrency = CurrencyConverter::convertCentsToFormatSimple(
  276. $amountInBankCurrencyCents,
  277. $bankAccountCurrency
  278. );
  279. } else {
  280. $formattedAmountForBankCurrency = $data['amount']; // Already in simple format
  281. }
  282. // Create transaction
  283. $this->transactions()->create([
  284. 'company_id' => $this->company_id,
  285. 'type' => $transactionType,
  286. 'is_payment' => true,
  287. 'posted_at' => $data['posted_at'],
  288. 'amount' => $formattedAmountForBankCurrency,
  289. 'payment_method' => $data['payment_method'],
  290. 'bank_account_id' => $data['bank_account_id'],
  291. 'account_id' => Account::getAccountsReceivableAccount($this->company_id)->id,
  292. 'description' => $transactionDescription,
  293. 'notes' => $data['notes'] ?? null,
  294. 'meta' => [
  295. 'original_document_currency' => $invoiceCurrency,
  296. 'amount_in_document_currency_cents' => $amountInInvoiceCurrencyCents,
  297. ],
  298. ]);
  299. }
  300. public function approveDraft(?Carbon $approvedAt = null): void
  301. {
  302. if (! $this->isDraft()) {
  303. throw new \RuntimeException('Invoice is not in draft status.');
  304. }
  305. $this->createApprovalTransaction();
  306. $approvedAt ??= now();
  307. $this->update([
  308. 'approved_at' => $approvedAt,
  309. 'status' => InvoiceStatus::Unsent,
  310. ]);
  311. }
  312. public function createApprovalTransaction(): void
  313. {
  314. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  315. $transaction = $this->transactions()->create([
  316. 'company_id' => $this->company_id,
  317. 'type' => TransactionType::Journal,
  318. 'posted_at' => $this->date,
  319. 'amount' => $total,
  320. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  321. ]);
  322. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  323. $transaction->journalEntries()->create([
  324. 'company_id' => $this->company_id,
  325. 'type' => JournalEntryType::Debit,
  326. 'account_id' => Account::getAccountsReceivableAccount($this->company_id)->id,
  327. 'amount' => $total,
  328. 'description' => $baseDescription,
  329. ]);
  330. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  331. $invoiceDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  332. $remainingDiscountCents = $invoiceDiscountTotalCents;
  333. foreach ($this->lineItems as $index => $lineItem) {
  334. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  335. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  336. $transaction->journalEntries()->create([
  337. 'company_id' => $this->company_id,
  338. 'type' => JournalEntryType::Credit,
  339. 'account_id' => $lineItem->offering->income_account_id,
  340. 'amount' => $lineItemSubtotal,
  341. 'description' => $lineItemDescription,
  342. ]);
  343. foreach ($lineItem->adjustments as $adjustment) {
  344. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  345. $transaction->journalEntries()->create([
  346. 'company_id' => $this->company_id,
  347. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  348. 'account_id' => $adjustment->account_id,
  349. 'amount' => $adjustmentAmount,
  350. 'description' => $lineItemDescription,
  351. ]);
  352. }
  353. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  354. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  355. if ($index === $this->lineItems->count() - 1) {
  356. $lineItemDiscount = $remainingDiscountCents;
  357. } else {
  358. $lineItemDiscount = (int) round(
  359. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $invoiceDiscountTotalCents
  360. );
  361. $remainingDiscountCents -= $lineItemDiscount;
  362. }
  363. if ($lineItemDiscount > 0) {
  364. $transaction->journalEntries()->create([
  365. 'company_id' => $this->company_id,
  366. 'type' => JournalEntryType::Debit,
  367. 'account_id' => Account::getSalesDiscountAccount($this->company_id)->id,
  368. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  369. 'description' => "{$lineItemDescription} (Proportional Discount)",
  370. ]);
  371. }
  372. }
  373. }
  374. }
  375. public function updateApprovalTransaction(): void
  376. {
  377. $transaction = $this->approvalTransaction;
  378. if ($transaction) {
  379. $transaction->delete();
  380. }
  381. $this->createApprovalTransaction();
  382. }
  383. public function convertAmountToDefaultCurrency(int $amountCents): int
  384. {
  385. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  386. $needsConversion = $this->currency_code !== $defaultCurrency;
  387. if ($needsConversion) {
  388. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  389. }
  390. return $amountCents;
  391. }
  392. public function formatAmountToDefaultCurrency(int $amountCents): string
  393. {
  394. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  395. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  396. }
  397. // TODO: Potentially handle this another way
  398. public static function getBlockedApproveAction(string $action = Action::class): MountableAction
  399. {
  400. return $action::make('blockedApprove')
  401. ->label('Approve')
  402. ->icon('heroicon-m-check-circle')
  403. ->visible(fn (self $record) => $record->canBeApproved() && $record->hasInactiveAdjustments())
  404. ->requiresConfirmation()
  405. ->modalAlignment(Alignment::Start)
  406. ->modalIconColor('danger')
  407. ->modalDescription(function (self $record) {
  408. $inactiveAdjustments = collect();
  409. foreach ($record->lineItems as $lineItem) {
  410. foreach ($lineItem->adjustments as $adjustment) {
  411. if ($adjustment->isInactive() && $inactiveAdjustments->doesntContain($adjustment->name)) {
  412. $inactiveAdjustments->push($adjustment->name);
  413. }
  414. }
  415. }
  416. $output = "<p class='text-sm mb-4'>This invoice contains inactive adjustments that need to be addressed before approval:</p>";
  417. $output .= "<ul role='list' class='list-disc list-inside space-y-1 text-sm'>";
  418. foreach ($inactiveAdjustments as $name) {
  419. $output .= "<li class='py-1'><span class='font-medium'>{$name}</span></li>";
  420. }
  421. $output .= '</ul>';
  422. $output .= "<p class='text-sm mt-4'>Please update these adjustments before approving the invoice.</p>";
  423. return new HtmlString($output);
  424. })
  425. ->modalSubmitAction(function (StaticAction $action, self $record) {
  426. $action->label('Edit Invoice')
  427. ->url(InvoiceResource\Pages\EditInvoice::getUrl(['record' => $record->id]));
  428. });
  429. }
  430. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  431. {
  432. return $action::make('approveDraft')
  433. ->label('Approve')
  434. ->icon('heroicon-m-check-circle')
  435. ->visible(function (self $record) {
  436. return $record->canBeApproved();
  437. })
  438. ->requiresConfirmation()
  439. ->databaseTransaction()
  440. ->successNotificationTitle('Invoice approved')
  441. ->action(function (self $record, MountableAction $action, Component $livewire) {
  442. if ($record->hasInactiveAdjustments()) {
  443. $isViewPage = $livewire instanceof InvoiceResource\Pages\ViewInvoice;
  444. if (! $isViewPage) {
  445. redirect(InvoiceResource\Pages\ViewInvoice::getUrl(['record' => $record->id]));
  446. } else {
  447. Notification::make()
  448. ->warning()
  449. ->title('Cannot approve invoice')
  450. ->body('This invoice has inactive adjustments that must be addressed first.')
  451. ->persistent()
  452. ->send();
  453. }
  454. } else {
  455. $record->approveDraft();
  456. $action->success();
  457. }
  458. });
  459. }
  460. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  461. {
  462. return $action::make('markAsSent')
  463. ->label('Mark as sent')
  464. ->icon('heroicon-m-paper-airplane')
  465. ->visible(static function (self $record) {
  466. return $record->canBeMarkedAsSent();
  467. })
  468. ->successNotificationTitle('Invoice sent')
  469. ->action(function (self $record, MountableAction $action) {
  470. $record->markAsSent();
  471. $action->success();
  472. });
  473. }
  474. public function markAsSent(?Carbon $sentAt = null): void
  475. {
  476. $sentAt ??= now();
  477. $this->update([
  478. 'status' => InvoiceStatus::Sent,
  479. 'last_sent_at' => $sentAt,
  480. ]);
  481. }
  482. public function markAsViewed(?Carbon $viewedAt = null): void
  483. {
  484. $viewedAt ??= now();
  485. $this->update([
  486. 'status' => InvoiceStatus::Viewed,
  487. 'last_viewed_at' => $viewedAt,
  488. ]);
  489. }
  490. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  491. {
  492. return $action::make()
  493. ->excludeAttributes([
  494. 'status',
  495. 'amount_paid',
  496. 'amount_due',
  497. 'created_by',
  498. 'updated_by',
  499. 'created_at',
  500. 'updated_at',
  501. 'invoice_number',
  502. 'date',
  503. 'due_date',
  504. 'approved_at',
  505. 'paid_at',
  506. 'last_sent_at',
  507. 'last_viewed_at',
  508. ])
  509. ->modal(false)
  510. ->beforeReplicaSaved(function (self $original, self $replica) {
  511. $replica->status = InvoiceStatus::Draft;
  512. $replica->invoice_number = self::getNextDocumentNumber();
  513. $replica->date = now();
  514. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  515. })
  516. ->databaseTransaction()
  517. ->after(function (self $original, self $replica) {
  518. $original->replicateLineItems($replica);
  519. })
  520. ->successRedirectUrl(static function (self $replica) {
  521. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  522. });
  523. }
  524. public function replicateLineItems(Model $target): void
  525. {
  526. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  527. $replica = $lineItem->replicate([
  528. 'documentable_id',
  529. 'documentable_type',
  530. 'subtotal',
  531. 'total',
  532. 'created_by',
  533. 'updated_by',
  534. 'created_at',
  535. 'updated_at',
  536. ]);
  537. $replica->documentable_id = $target->id;
  538. $replica->documentable_type = $target->getMorphClass();
  539. $replica->save();
  540. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  541. });
  542. }
  543. }