Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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