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 18KB

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