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

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