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.

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