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

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