Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Invoice.php 18KB

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