您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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