Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Invoice.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  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\Setting\Currency;
  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\Factories\HasFactory;
  28. use Illuminate\Database\Eloquent\Model;
  29. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  30. use Illuminate\Database\Eloquent\Relations\MorphMany;
  31. use Illuminate\Database\Eloquent\Relations\MorphOne;
  32. use Illuminate\Support\Carbon;
  33. #[ObservedBy(InvoiceObserver::class)]
  34. #[CollectedBy(DocumentCollection::class)]
  35. class Invoice extends Model
  36. {
  37. use Blamable;
  38. use CompanyOwned;
  39. use HasFactory;
  40. protected $table = 'invoices';
  41. protected $fillable = [
  42. 'company_id',
  43. 'client_id',
  44. 'logo',
  45. 'header',
  46. 'subheader',
  47. 'invoice_number',
  48. 'order_number',
  49. 'date',
  50. 'due_date',
  51. 'approved_at',
  52. 'paid_at',
  53. 'last_sent_at',
  54. 'status',
  55. 'currency_code',
  56. 'discount_method',
  57. 'discount_computation',
  58. 'discount_rate',
  59. 'subtotal',
  60. 'tax_total',
  61. 'discount_total',
  62. 'total',
  63. 'amount_paid',
  64. 'terms',
  65. 'footer',
  66. 'created_by',
  67. 'updated_by',
  68. ];
  69. protected $casts = [
  70. 'date' => 'date',
  71. 'due_date' => 'date',
  72. 'approved_at' => 'datetime',
  73. 'paid_at' => 'datetime',
  74. 'last_sent_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 currency(): BelongsTo
  91. {
  92. return $this->belongsTo(Currency::class, 'currency_code', 'code');
  93. }
  94. public function lineItems(): MorphMany
  95. {
  96. return $this->morphMany(DocumentLineItem::class, 'documentable');
  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. public function scopeUnpaid(Builder $query): Builder
  120. {
  121. return $query->whereNotIn('status', [
  122. InvoiceStatus::Paid,
  123. InvoiceStatus::Void,
  124. InvoiceStatus::Draft,
  125. InvoiceStatus::Overpaid,
  126. ]);
  127. }
  128. protected function isCurrentlyOverdue(): Attribute
  129. {
  130. return Attribute::get(function () {
  131. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  132. });
  133. }
  134. public function isDraft(): bool
  135. {
  136. return $this->status === InvoiceStatus::Draft;
  137. }
  138. public function canRecordPayment(): bool
  139. {
  140. return ! in_array($this->status, [
  141. InvoiceStatus::Draft,
  142. InvoiceStatus::Paid,
  143. InvoiceStatus::Void,
  144. ]);
  145. }
  146. public function canBulkRecordPayment(): bool
  147. {
  148. return ! in_array($this->status, [
  149. InvoiceStatus::Draft,
  150. InvoiceStatus::Paid,
  151. InvoiceStatus::Void,
  152. InvoiceStatus::Overpaid,
  153. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  154. }
  155. public function canBeOverdue(): bool
  156. {
  157. return in_array($this->status, InvoiceStatus::canBeOverdue());
  158. }
  159. public function hasPayments(): bool
  160. {
  161. return $this->payments->isNotEmpty();
  162. }
  163. public static function getNextDocumentNumber(): string
  164. {
  165. $company = auth()->user()->currentCompany;
  166. if (! $company) {
  167. throw new \RuntimeException('No current company is set for the user.');
  168. }
  169. $defaultInvoiceSettings = $company->defaultInvoice;
  170. $numberPrefix = $defaultInvoiceSettings->number_prefix;
  171. $numberDigits = $defaultInvoiceSettings->number_digits;
  172. $latestDocument = static::query()
  173. ->whereNotNull('invoice_number')
  174. ->latest('invoice_number')
  175. ->first();
  176. $lastNumberNumericPart = $latestDocument
  177. ? (int) substr($latestDocument->invoice_number, strlen($numberPrefix))
  178. : 0;
  179. $numberNext = $lastNumberNumericPart + 1;
  180. return $defaultInvoiceSettings->getNumberNext(
  181. padded: true,
  182. format: true,
  183. prefix: $numberPrefix,
  184. digits: $numberDigits,
  185. next: $numberNext
  186. );
  187. }
  188. public function recordPayment(array $data): void
  189. {
  190. $isRefund = $this->status === InvoiceStatus::Overpaid;
  191. if ($isRefund) {
  192. $transactionType = TransactionType::Withdrawal;
  193. $transactionDescription = "Invoice #{$this->invoice_number}: Refund to {$this->client->name}";
  194. } else {
  195. $transactionType = TransactionType::Deposit;
  196. $transactionDescription = "Invoice #{$this->invoice_number}: Payment from {$this->client->name}";
  197. }
  198. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  199. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  200. $invoiceCurrency = $this->currency_code;
  201. $requiresConversion = $invoiceCurrency !== $bankAccountCurrency;
  202. if ($requiresConversion) {
  203. $amountInInvoiceCurrencyCents = CurrencyConverter::convertToCents($data['amount'], $invoiceCurrency);
  204. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  205. $amountInInvoiceCurrencyCents,
  206. $invoiceCurrency,
  207. $bankAccountCurrency
  208. );
  209. $formattedAmountForBankCurrency = CurrencyConverter::convertCentsToFormatSimple(
  210. $amountInBankCurrencyCents,
  211. $bankAccountCurrency
  212. );
  213. } else {
  214. $formattedAmountForBankCurrency = $data['amount']; // Already in simple format
  215. }
  216. // Create transaction
  217. $this->transactions()->create([
  218. 'company_id' => $this->company_id,
  219. 'type' => $transactionType,
  220. 'is_payment' => true,
  221. 'posted_at' => $data['posted_at'],
  222. 'amount' => $formattedAmountForBankCurrency,
  223. 'payment_method' => $data['payment_method'],
  224. 'bank_account_id' => $data['bank_account_id'],
  225. 'account_id' => Account::getAccountsReceivableAccount()->id,
  226. 'description' => $transactionDescription,
  227. 'notes' => $data['notes'] ?? null,
  228. ]);
  229. }
  230. public function approveDraft(?Carbon $approvedAt = null): void
  231. {
  232. if (! $this->isDraft()) {
  233. throw new \RuntimeException('Invoice is not in draft status.');
  234. }
  235. $this->createApprovalTransaction();
  236. $approvedAt ??= now();
  237. $this->update([
  238. 'approved_at' => $approvedAt,
  239. 'status' => InvoiceStatus::Unsent,
  240. ]);
  241. }
  242. public function createApprovalTransaction(): void
  243. {
  244. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  245. $transaction = $this->transactions()->create([
  246. 'company_id' => $this->company_id,
  247. 'type' => TransactionType::Journal,
  248. 'posted_at' => $this->date,
  249. 'amount' => $total,
  250. 'description' => 'Invoice Approval for Invoice #' . $this->invoice_number,
  251. ]);
  252. $baseDescription = "{$this->client->name}: Invoice #{$this->invoice_number}";
  253. $transaction->journalEntries()->create([
  254. 'company_id' => $this->company_id,
  255. 'type' => JournalEntryType::Debit,
  256. 'account_id' => Account::getAccountsReceivableAccount()->id,
  257. 'amount' => $total,
  258. 'description' => $baseDescription,
  259. ]);
  260. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  261. $invoiceDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  262. $remainingDiscountCents = $invoiceDiscountTotalCents;
  263. foreach ($this->lineItems as $index => $lineItem) {
  264. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  265. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  266. $transaction->journalEntries()->create([
  267. 'company_id' => $this->company_id,
  268. 'type' => JournalEntryType::Credit,
  269. 'account_id' => $lineItem->offering->income_account_id,
  270. 'amount' => $lineItemSubtotal,
  271. 'description' => $lineItemDescription,
  272. ]);
  273. foreach ($lineItem->adjustments as $adjustment) {
  274. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  275. $transaction->journalEntries()->create([
  276. 'company_id' => $this->company_id,
  277. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Debit : JournalEntryType::Credit,
  278. 'account_id' => $adjustment->account_id,
  279. 'amount' => $adjustmentAmount,
  280. 'description' => $lineItemDescription,
  281. ]);
  282. }
  283. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  284. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  285. if ($index === $this->lineItems->count() - 1) {
  286. $lineItemDiscount = $remainingDiscountCents;
  287. } else {
  288. $lineItemDiscount = (int) round(
  289. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $invoiceDiscountTotalCents
  290. );
  291. $remainingDiscountCents -= $lineItemDiscount;
  292. }
  293. if ($lineItemDiscount > 0) {
  294. $transaction->journalEntries()->create([
  295. 'company_id' => $this->company_id,
  296. 'type' => JournalEntryType::Debit,
  297. 'account_id' => Account::getSalesDiscountAccount()->id,
  298. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  299. 'description' => "{$lineItemDescription} (Proportional Discount)",
  300. ]);
  301. }
  302. }
  303. }
  304. }
  305. public function updateApprovalTransaction(): void
  306. {
  307. $transaction = $this->approvalTransaction;
  308. if ($transaction) {
  309. $transaction->delete();
  310. }
  311. $this->createApprovalTransaction();
  312. }
  313. public function convertAmountToDefaultCurrency(int $amountCents): int
  314. {
  315. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  316. $needsConversion = $this->currency_code !== $defaultCurrency;
  317. if ($needsConversion) {
  318. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  319. }
  320. return $amountCents;
  321. }
  322. public function formatAmountToDefaultCurrency(int $amountCents): string
  323. {
  324. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  325. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  326. }
  327. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  328. {
  329. return $action::make('approveDraft')
  330. ->label('Approve')
  331. ->icon('heroicon-o-check-circle')
  332. ->visible(function (self $record) {
  333. return $record->isDraft();
  334. })
  335. ->databaseTransaction()
  336. ->successNotificationTitle('Invoice Approved')
  337. ->action(function (self $record, MountableAction $action) {
  338. $record->approveDraft();
  339. $action->success();
  340. });
  341. }
  342. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  343. {
  344. return $action::make('markAsSent')
  345. ->label('Mark as Sent')
  346. ->icon('heroicon-o-paper-airplane')
  347. ->visible(static function (self $record) {
  348. return ! $record->last_sent_at;
  349. })
  350. ->successNotificationTitle('Invoice Sent')
  351. ->action(function (self $record, MountableAction $action) {
  352. $record->update([
  353. 'status' => InvoiceStatus::Sent,
  354. 'last_sent_at' => now(),
  355. ]);
  356. $action->success();
  357. });
  358. }
  359. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  360. {
  361. return $action::make()
  362. ->excludeAttributes([
  363. 'status',
  364. 'amount_paid',
  365. 'amount_due',
  366. 'created_by',
  367. 'updated_by',
  368. 'created_at',
  369. 'updated_at',
  370. 'invoice_number',
  371. 'date',
  372. 'due_date',
  373. 'approved_at',
  374. 'paid_at',
  375. 'last_sent_at',
  376. ])
  377. ->modal(false)
  378. ->beforeReplicaSaved(function (self $original, self $replica) {
  379. $replica->status = InvoiceStatus::Draft;
  380. $replica->invoice_number = self::getNextDocumentNumber();
  381. $replica->date = now();
  382. $replica->due_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  383. })
  384. ->databaseTransaction()
  385. ->after(function (self $original, self $replica) {
  386. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  387. $replicaLineItem = $lineItem->replicate([
  388. 'documentable_id',
  389. 'documentable_type',
  390. 'subtotal',
  391. 'total',
  392. 'created_by',
  393. 'updated_by',
  394. 'created_at',
  395. 'updated_at',
  396. ]);
  397. $replicaLineItem->documentable_id = $replica->id;
  398. $replicaLineItem->documentable_type = $replica->getMorphClass();
  399. $replicaLineItem->save();
  400. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  401. });
  402. })
  403. ->successRedirectUrl(static function (self $replica) {
  404. return InvoiceResource::getUrl('edit', ['record' => $replica]);
  405. });
  406. }
  407. }