您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Invoice.php 17KB

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