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

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