Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Invoice.php 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Casts\RateCast;
  5. use App\Collections\Accounting\DocumentCollection;
  6. use App\Enums\Accounting\AdjustmentComputation;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\InvoiceStatus;
  10. use App\Enums\Accounting\JournalEntryType;
  11. use App\Enums\Accounting\TransactionType;
  12. use App\Filament\Company\Resources\Sales\InvoiceResource;
  13. use App\Models\Banking\BankAccount;
  14. use App\Models\Common\Client;
  15. use App\Models\Company;
  16. use App\Models\Setting\DocumentDefault;
  17. use App\Observers\InvoiceObserver;
  18. use App\Utilities\Currency\CurrencyAccessor;
  19. use App\Utilities\Currency\CurrencyConverter;
  20. use Filament\Actions\Action;
  21. use Filament\Actions\MountableAction;
  22. use Filament\Actions\ReplicateAction;
  23. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  24. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  25. use Illuminate\Database\Eloquent\Builder;
  26. use Illuminate\Database\Eloquent\Casts\Attribute;
  27. use Illuminate\Database\Eloquent\Model;
  28. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  29. use Illuminate\Database\Eloquent\Relations\MorphMany;
  30. use Illuminate\Database\Eloquent\Relations\MorphOne;
  31. use Illuminate\Support\Carbon;
  32. #[CollectedBy(DocumentCollection::class)]
  33. #[ObservedBy(InvoiceObserver::class)]
  34. class Invoice extends Document
  35. {
  36. protected $table = 'invoices';
  37. protected $fillable = [
  38. 'company_id',
  39. 'client_id',
  40. 'estimate_id',
  41. 'recurring_invoice_id',
  42. 'logo',
  43. 'header',
  44. 'subheader',
  45. 'invoice_number',
  46. 'order_number',
  47. 'date',
  48. 'due_date',
  49. 'approved_at',
  50. 'paid_at',
  51. 'last_sent_at',
  52. 'last_viewed_at',
  53. 'status',
  54. 'currency_code',
  55. 'discount_method',
  56. 'discount_computation',
  57. 'discount_rate',
  58. 'subtotal',
  59. 'tax_total',
  60. 'discount_total',
  61. 'total',
  62. 'amount_paid',
  63. 'terms',
  64. 'footer',
  65. 'created_by',
  66. 'updated_by',
  67. ];
  68. protected $casts = [
  69. 'date' => 'date',
  70. 'due_date' => 'date',
  71. 'approved_at' => 'datetime',
  72. 'paid_at' => 'datetime',
  73. 'last_sent_at' => 'datetime',
  74. 'last_viewed_at' => 'datetime',
  75. 'status' => InvoiceStatus::class,
  76. 'discount_method' => DocumentDiscountMethod::class,
  77. 'discount_computation' => AdjustmentComputation::class,
  78. 'discount_rate' => RateCast::class,
  79. 'subtotal' => MoneyCast::class,
  80. 'tax_total' => MoneyCast::class,
  81. 'discount_total' => MoneyCast::class,
  82. 'total' => MoneyCast::class,
  83. 'amount_paid' => MoneyCast::class,
  84. 'amount_due' => MoneyCast::class,
  85. ];
  86. public function client(): BelongsTo
  87. {
  88. return $this->belongsTo(Client::class);
  89. }
  90. public function estimate(): BelongsTo
  91. {
  92. return $this->belongsTo(Estimate::class);
  93. }
  94. public function recurringInvoice(): BelongsTo
  95. {
  96. return $this->belongsTo(RecurringInvoice::class);
  97. }
  98. public function transactions(): MorphMany
  99. {
  100. return $this->morphMany(Transaction::class, 'transactionable');
  101. }
  102. public function payments(): MorphMany
  103. {
  104. return $this->transactions()->where('is_payment', true);
  105. }
  106. public function deposits(): MorphMany
  107. {
  108. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  109. }
  110. public function withdrawals(): MorphMany
  111. {
  112. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  113. }
  114. public function approvalTransaction(): MorphOne
  115. {
  116. return $this->morphOne(Transaction::class, 'transactionable')
  117. ->where('type', TransactionType::Journal);
  118. }
  119. protected function sourceType(): Attribute
  120. {
  121. return Attribute::get(function () {
  122. return match (true) {
  123. $this->estimate_id !== null => DocumentType::Estimate,
  124. $this->recurring_invoice_id !== null => DocumentType::RecurringInvoice,
  125. default => null,
  126. };
  127. });
  128. }
  129. public static function documentType(): DocumentType
  130. {
  131. return DocumentType::Invoice;
  132. }
  133. public function documentNumber(): ?string
  134. {
  135. return $this->invoice_number;
  136. }
  137. public function documentDate(): ?string
  138. {
  139. return $this->date?->toDefaultDateFormat();
  140. }
  141. public function dueDate(): ?string
  142. {
  143. return $this->due_date?->toDefaultDateFormat();
  144. }
  145. public function referenceNumber(): ?string
  146. {
  147. return $this->order_number;
  148. }
  149. public function amountDue(): ?string
  150. {
  151. return $this->amount_due;
  152. }
  153. public function scopeUnpaid(Builder $query): Builder
  154. {
  155. return $query->whereNotIn('status', [
  156. InvoiceStatus::Paid,
  157. InvoiceStatus::Void,
  158. InvoiceStatus::Draft,
  159. InvoiceStatus::Overpaid,
  160. ]);
  161. }
  162. public function scopeOverdue(Builder $query): Builder
  163. {
  164. return $query
  165. ->unpaid()
  166. ->where('status', InvoiceStatus::Overdue);
  167. }
  168. protected function isCurrentlyOverdue(): Attribute
  169. {
  170. return Attribute::get(function () {
  171. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  172. });
  173. }
  174. public function isDraft(): bool
  175. {
  176. return $this->status === InvoiceStatus::Draft;
  177. }
  178. public function wasApproved(): bool
  179. {
  180. return $this->approved_at !== null;
  181. }
  182. public function isPaid(): bool
  183. {
  184. return $this->paid_at !== null;
  185. }
  186. public function hasBeenSent(): bool
  187. {
  188. return $this->last_sent_at !== null;
  189. }
  190. public function hasBeenViewed(): bool
  191. {
  192. return $this->last_viewed_at !== null;
  193. }
  194. public function canRecordPayment(): bool
  195. {
  196. return ! in_array($this->status, [
  197. InvoiceStatus::Draft,
  198. InvoiceStatus::Paid,
  199. InvoiceStatus::Void,
  200. ]);
  201. }
  202. public function canBulkRecordPayment(): bool
  203. {
  204. return ! in_array($this->status, [
  205. InvoiceStatus::Draft,
  206. InvoiceStatus::Paid,
  207. InvoiceStatus::Void,
  208. InvoiceStatus::Overpaid,
  209. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  210. }
  211. public function canBeOverdue(): bool
  212. {
  213. return in_array($this->status, InvoiceStatus::canBeOverdue());
  214. }
  215. public function canBeApproved(): bool
  216. {
  217. return $this->isDraft() && ! $this->wasApproved();
  218. }
  219. public function canBeMarkedAsSent(): bool
  220. {
  221. return ! $this->hasBeenSent();
  222. }
  223. public function hasPayments(): bool
  224. {
  225. return $this->payments()->exists();
  226. }
  227. public static function getNextDocumentNumber(?Company $company = null): string
  228. {
  229. $company ??= auth()->user()?->currentCompany;
  230. if (! $company) {
  231. throw new \RuntimeException('No current company is set for the user.');
  232. }
  233. $defaultInvoiceSettings = $company->defaultInvoice;
  234. $numberPrefix = $defaultInvoiceSettings->number_prefix ?? '';
  235. $latestDocument = static::query()
  236. ->whereNotNull('invoice_number')
  237. ->latest('invoice_number')
  238. ->first();
  239. $lastNumberNumericPart = $latestDocument
  240. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  241. : DocumentDefault::getBaseNumber();
  242. $numberNext = $lastNumberNumericPart + 1;
  243. return $defaultInvoiceSettings->getNumberNext(
  244. prefix: $numberPrefix,
  245. next: $numberNext
  246. );
  247. }
  248. public function recordPayment(array $data): void
  249. {
  250. $isRefund = $this->status === InvoiceStatus::Overpaid;
  251. if ($isRefund) {
  252. $transactionType = TransactionType::Withdrawal;
  253. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  254. } else {
  255. $transactionType = TransactionType::Deposit;
  256. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  257. }
  258. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  259. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  260. $invoiceCurrency = $this->currency_code;
  261. $requiresConversion = $invoiceCurrency !== $bankAccountCurrency;
  262. if ($requiresConversion) {
  263. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($data['amount'], $invoiceCurrency);
  264. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  265. $amountInInvoiceCurrencyCents,
  266. $invoiceCurrency,
  267. $bankAccountCurrency
  268. );
  269. $formattedAmountForBankCurrency = CurrencyConverter::convertCentsToFormatSimple(
  270. $amountInBankCurrencyCents,
  271. $bankAccountCurrency
  272. );
  273. } else {
  274. $formattedAmountForBankCurrency = $data['amount']; // Already in simple format
  275. }
  276. // Create transaction
  277. $this->transactions()->create([
  278. 'company_id' => $this->company_id,
  279. 'type' => $transactionType,
  280. 'is_payment' => true,
  281. 'posted_at' => $data['posted_at'],
  282. 'amount' => $formattedAmountForBankCurrency,
  283. 'payment_method' => $data['payment_method'],
  284. 'bank_account_id' => $data['bank_account_id'],
  285. 'account_id' => Account::getAccountsReceivableAccount()->id,
  286. 'description' => $transactionDescription,
  287. 'notes' => $data['notes'] ?? null,
  288. ]);
  289. }
  290. public function approveDraft(?Carbon $approvedAt = null): void
  291. {
  292. if (! $this->isDraft()) {
  293. throw new \RuntimeException('Invoice is not in draft status.');
  294. }
  295. $this->createApprovalTransaction();
  296. $approvedAt ??= now();
  297. $this->update([
  298. 'approved_at' => $approvedAt,
  299. 'status' => InvoiceStatus::Unsent,
  300. ]);
  301. }
  302. public function createApprovalTransaction(): void
  303. {
  304. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  305. $transaction = $this->transactions()->create([
  306. 'company_id' => $this->company_id,
  307. 'type' => TransactionType::Journal,
  308. 'posted_at' => $this->date,
  309. 'amount' => $total,
  310. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  311. ]);
  312. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  313. $transaction->journalEntries()->create([
  314. 'company_id' => $this->company_id,
  315. 'type' => JournalEntryType::Debit,
  316. 'account_id' => Account::getAccountsReceivableAccount()->id,
  317. 'amount' => $total,
  318. 'description' => $baseDescription,
  319. ]);
  320. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  321. $invoiceDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  322. $remainingDiscountCents = $invoiceDiscountTotalCents;
  323. foreach ($this->lineItems as $index => $lineItem) {
  324. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  325. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  326. $transaction->journalEntries()->create([
  327. 'company_id' => $this->company_id,
  328. 'type' => JournalEntryType::Credit,
  329. 'account_id' => $lineItem->offering->income_account_id,
  330. 'amount' => $lineItemSubtotal,
  331. 'description' => $lineItemDescription,
  332. ]);
  333. foreach ($lineItem->adjustments as $adjustment) {
  334. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  335. $transaction->journalEntries()->create([
  336. 'company_id' => $this->company_id,
  337. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  338. 'account_id' => $adjustment->account_id,
  339. 'amount' => $adjustmentAmount,
  340. 'description' => $lineItemDescription,
  341. ]);
  342. }
  343. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  344. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  345. if ($index === $this->lineItems->count() - 1) {
  346. $lineItemDiscount = $remainingDiscountCents;
  347. } else {
  348. $lineItemDiscount = (int) round(
  349. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $invoiceDiscountTotalCents
  350. );
  351. $remainingDiscountCents -= $lineItemDiscount;
  352. }
  353. if ($lineItemDiscount > 0) {
  354. $transaction->journalEntries()->create([
  355. 'company_id' => $this->company_id,
  356. 'type' => JournalEntryType::Debit,
  357. 'account_id' => Account::getSalesDiscountAccount()->id,
  358. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  359. 'description' => "{$lineItemDescription} (Proportional Discount)",
  360. ]);
  361. }
  362. }
  363. }
  364. }
  365. public function updateApprovalTransaction(): void
  366. {
  367. $transaction = $this->approvalTransaction;
  368. if ($transaction) {
  369. $transaction->delete();
  370. }
  371. $this->createApprovalTransaction();
  372. }
  373. public function convertAmountToDefaultCurrency(int $amountCents): int
  374. {
  375. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  376. $needsConversion = $this->currency_code !== $defaultCurrency;
  377. if ($needsConversion) {
  378. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  379. }
  380. return $amountCents;
  381. }
  382. public function formatAmountToDefaultCurrency(int $amountCents): string
  383. {
  384. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  385. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  386. }
  387. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  388. {
  389. return $action::make('approveDraft')
  390. ->label('Approve')
  391. ->icon('heroicon-m-check-circle')
  392. ->visible(function (self $record) {
  393. return $record->canBeApproved();
  394. })
  395. ->databaseTransaction()
  396. ->successNotificationTitle('Invoice approved')
  397. ->action(function (self $record, MountableAction $action) {
  398. $record->approveDraft();
  399. $action->success();
  400. });
  401. }
  402. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  403. {
  404. return $action::make('markAsSent')
  405. ->label('Mark as sent')
  406. ->icon('heroicon-m-paper-airplane')
  407. ->visible(static function (self $record) {
  408. return $record->canBeMarkedAsSent();
  409. })
  410. ->successNotificationTitle('Invoice sent')
  411. ->action(function (self $record, MountableAction $action) {
  412. $record->markAsSent();
  413. $action->success();
  414. });
  415. }
  416. public function markAsSent(?Carbon $sentAt = null): void
  417. {
  418. $sentAt ??= now();
  419. $this->update([
  420. 'status' => InvoiceStatus::Sent,
  421. 'last_sent_at' => $sentAt,
  422. ]);
  423. }
  424. public function markAsViewed(?Carbon $viewedAt = null): void
  425. {
  426. $viewedAt ??= now();
  427. $this->update([
  428. 'status' => InvoiceStatus::Viewed,
  429. 'last_viewed_at' => $viewedAt,
  430. ]);
  431. }
  432. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  433. {
  434. return $action::make()
  435. ->excludeAttributes([
  436. 'status',
  437. 'amount_paid',
  438. 'amount_due',
  439. 'created_by',
  440. 'updated_by',
  441. 'created_at',
  442. 'updated_at',
  443. 'invoice_number',
  444. 'date',
  445. 'due_date',
  446. 'approved_at',
  447. 'paid_at',
  448. 'last_sent_at',
  449. 'last_viewed_at',
  450. ])
  451. ->modal(false)
  452. ->beforeReplicaSaved(function (self $original, self $replica) {
  453. $replica->status = InvoiceStatus::Draft;
  454. $replica->invoice_number = self::getNextDocumentNumber();
  455. $replica->date = now();
  456. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  457. })
  458. ->databaseTransaction()
  459. ->after(function (self $original, self $replica) {
  460. $original->replicateLineItems($replica);
  461. })
  462. ->successRedirectUrl(static function (self $replica) {
  463. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  464. });
  465. }
  466. public function replicateLineItems(Model $target): void
  467. {
  468. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  469. $replica = $lineItem->replicate([
  470. 'documentable_id',
  471. 'documentable_type',
  472. 'subtotal',
  473. 'total',
  474. 'created_by',
  475. 'updated_by',
  476. 'created_at',
  477. 'updated_at',
  478. ]);
  479. $replica->documentable_id = $target->id;
  480. $replica->documentable_type = $target->getMorphClass();
  481. $replica->save();
  482. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  483. });
  484. }
  485. }