Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Invoice.php 24KB

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