Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Invoice.php 16KB

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