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

CreditNote.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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\CreditNoteStatus;
  8. use App\Enums\Accounting\DocumentDiscountMethod;
  9. use App\Enums\Accounting\DocumentType;
  10. use App\Enums\Accounting\JournalEntryType;
  11. use App\Enums\Accounting\TransactionType;
  12. use App\Filament\Company\Resources\Sales\CreditNoteResource;
  13. use App\Models\Common\Client;
  14. use App\Models\Company;
  15. use App\Models\Setting\DocumentDefault;
  16. use App\Utilities\Currency\CurrencyAccessor;
  17. use App\Utilities\Currency\CurrencyConverter;
  18. use Filament\Actions\Action;
  19. use Filament\Actions\MountableAction;
  20. use Filament\Actions\ReplicateAction;
  21. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  22. use Illuminate\Database\Eloquent\Casts\Attribute;
  23. use Illuminate\Database\Eloquent\Model;
  24. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  25. use Illuminate\Database\Eloquent\Relations\MorphMany;
  26. use Illuminate\Database\Eloquent\Relations\MorphOne;
  27. use Illuminate\Support\Carbon;
  28. use Illuminate\Support\Collection;
  29. #[CollectedBy(DocumentCollection::class)]
  30. class CreditNote extends Document
  31. {
  32. protected $table = 'credit_notes';
  33. protected $fillable = [
  34. 'company_id',
  35. 'client_id',
  36. 'logo',
  37. 'header',
  38. 'subheader',
  39. 'credit_note_number',
  40. 'reference_number',
  41. 'date',
  42. 'approved_at',
  43. 'last_sent_at',
  44. 'last_viewed_at',
  45. 'status',
  46. 'currency_code',
  47. 'discount_method',
  48. 'discount_computation',
  49. 'discount_rate',
  50. 'subtotal',
  51. 'tax_total',
  52. 'discount_total',
  53. 'total',
  54. 'amount_used',
  55. 'terms',
  56. 'footer',
  57. 'created_by',
  58. 'updated_by',
  59. ];
  60. protected $casts = [
  61. 'date' => 'date',
  62. 'approved_at' => 'datetime',
  63. 'last_sent_at' => 'datetime',
  64. 'last_viewed_at' => 'datetime',
  65. 'status' => CreditNoteStatus::class,
  66. 'discount_method' => DocumentDiscountMethod::class,
  67. 'discount_computation' => AdjustmentComputation::class,
  68. 'discount_rate' => RateCast::class,
  69. 'subtotal' => MoneyCast::class,
  70. 'tax_total' => MoneyCast::class,
  71. 'discount_total' => MoneyCast::class,
  72. 'total' => MoneyCast::class,
  73. 'amount_used' => MoneyCast::class,
  74. ];
  75. // Basic Relationships
  76. public function client(): BelongsTo
  77. {
  78. return $this->belongsTo(Client::class);
  79. }
  80. public function company(): BelongsTo
  81. {
  82. return $this->belongsTo(Company::class);
  83. }
  84. // Transaction Relationships
  85. public function transactions(): MorphMany
  86. {
  87. return $this->morphMany(Transaction::class, 'transactionable');
  88. }
  89. public function initialTransaction(): MorphOne
  90. {
  91. return $this->morphOne(Transaction::class, 'transactionable')
  92. ->where('type', TransactionType::Journal);
  93. }
  94. // Track where this credit note has been applied
  95. public function applications(): Collection
  96. {
  97. // Find all invoice transactions that reference this credit note
  98. return Transaction::where('type', TransactionType::CreditNote)
  99. ->where('is_payment', true)
  100. ->whereJsonContains('meta->credit_note_id', $this->id)
  101. ->get()
  102. ->map(function ($transaction) {
  103. return [
  104. 'invoice' => $transaction->transactionable,
  105. 'amount' => $transaction->amount,
  106. 'date' => $transaction->posted_at,
  107. 'transaction' => $transaction,
  108. ];
  109. })
  110. ->filter(function ($item) {
  111. return ! is_null($item['invoice']);
  112. });
  113. }
  114. public function appliedInvoices(): Collection
  115. {
  116. return $this->applications()->pluck('invoice');
  117. }
  118. // Document Interface Implementation
  119. public static function documentType(): DocumentType
  120. {
  121. return DocumentType::CreditNote;
  122. }
  123. public function documentNumber(): ?string
  124. {
  125. return $this->credit_note_number;
  126. }
  127. public function documentDate(): ?string
  128. {
  129. return $this->date?->toDefaultDateFormat();
  130. }
  131. public function dueDate(): ?string
  132. {
  133. return null;
  134. }
  135. public function amountDue(): ?string
  136. {
  137. return null;
  138. }
  139. public function referenceNumber(): ?string
  140. {
  141. return $this->reference_number;
  142. }
  143. // Computed Properties
  144. protected function availableBalance(): Attribute
  145. {
  146. return Attribute::get(function () {
  147. $totalCents = (int) $this->getRawOriginal('total');
  148. $amountUsedCents = (int) $this->getRawOriginal('amount_used');
  149. return CurrencyConverter::convertCentsToFormatSimple($totalCents - $amountUsedCents);
  150. });
  151. }
  152. protected function availableBalanceCents(): Attribute
  153. {
  154. return Attribute::get(function () {
  155. $totalCents = (int) $this->getRawOriginal('total');
  156. $amountUsedCents = (int) $this->getRawOriginal('amount_used');
  157. return $totalCents - $amountUsedCents;
  158. });
  159. }
  160. // Status Methods
  161. public function isFullyApplied(): bool
  162. {
  163. return $this->availableBalanceCents <= 0;
  164. }
  165. public function isPartiallyApplied(): bool
  166. {
  167. $amountUsedCents = (int) $this->getRawOriginal('amount_used');
  168. return $amountUsedCents > 0 && ! $this->isFullyApplied();
  169. }
  170. public function isDraft(): bool
  171. {
  172. return $this->status === CreditNoteStatus::Draft;
  173. }
  174. public function wasApproved(): bool
  175. {
  176. return $this->approved_at !== null;
  177. }
  178. public function hasBeenSent(): bool
  179. {
  180. return $this->last_sent_at !== null;
  181. }
  182. public function hasBeenViewed(): bool
  183. {
  184. return $this->last_viewed_at !== null;
  185. }
  186. public function canBeAppliedToInvoice(): bool
  187. {
  188. return in_array($this->status->value, CreditNoteStatus::canBeApplied()) &&
  189. $this->availableBalanceCents > 0;
  190. }
  191. // Application Methods
  192. public function applyToInvoice(Invoice $invoice, string $amount): void
  193. {
  194. // Validate currencies match
  195. if ($this->currency_code !== $invoice->currency_code) {
  196. throw new \RuntimeException('Cannot apply credit note with different currency to invoice.');
  197. }
  198. // Validate available amount
  199. $amountCents = CurrencyConverter::convertToCents($amount, $this->currency_code);
  200. if ($amountCents > $this->availableBalanceCents) {
  201. throw new \RuntimeException('Cannot apply more than the available credit note amount.');
  202. }
  203. // Create transaction on the invoice
  204. $invoice->transactions()->create([
  205. 'company_id' => $this->company_id,
  206. 'type' => TransactionType::CreditNote,
  207. 'is_payment' => true,
  208. 'posted_at' => now(),
  209. 'amount' => $amount,
  210. 'account_id' => Account::getAccountsReceivableAccount()->id,
  211. 'description' => "Credit Note #{$this->credit_note_number} applied to Invoice #{$invoice->invoice_number}",
  212. 'meta' => [
  213. 'credit_note_id' => $this->id,
  214. ],
  215. ]);
  216. // Update amount used on credit note
  217. $this->amount_used = CurrencyConverter::convertCentsToFormatSimple(
  218. (int) $this->getRawOriginal('amount_used') + $amountCents
  219. );
  220. $this->save();
  221. // Update status if needed
  222. $this->updateStatusBasedOnUsage();
  223. // Update invoice payment status
  224. $invoice->updatePaymentStatus();
  225. }
  226. protected function updateStatusBasedOnUsage(): void
  227. {
  228. if ($this->isFullyApplied()) {
  229. $this->status = CreditNoteStatus::Applied;
  230. } elseif ($this->isPartiallyApplied()) {
  231. $this->status = CreditNoteStatus::Partial;
  232. }
  233. $this->save();
  234. }
  235. public function autoApplyToInvoices(): void
  236. {
  237. // Skip if no available amount
  238. if ($this->availableBalanceCents <= 0) {
  239. return;
  240. }
  241. // Find unpaid invoices for this client, ordered by due date (oldest first)
  242. $unpaidInvoices = Invoice::where('client_id', $this->client_id)
  243. ->where('currency_code', $this->currency_code)
  244. ->unpaid()
  245. ->orderBy('due_date')
  246. ->get();
  247. // Apply to invoices until amount is used up
  248. foreach ($unpaidInvoices as $invoice) {
  249. $invoiceAmountDueCents = (int) $invoice->getRawOriginal('amount_due');
  250. if ($invoiceAmountDueCents <= 0 || $this->availableBalanceCents <= 0) {
  251. continue;
  252. }
  253. // Calculate amount to apply to this invoice
  254. $applyAmountCents = min($this->availableBalanceCents, $invoiceAmountDueCents);
  255. $applyAmount = CurrencyConverter::convertCentsToFormatSimple($applyAmountCents);
  256. // Apply to invoice
  257. $this->applyToInvoice($invoice, $applyAmount);
  258. if ($this->availableBalanceCents <= 0) {
  259. break;
  260. }
  261. }
  262. }
  263. // Accounting Methods
  264. public function createInitialTransaction(?Carbon $postedAt = null): void
  265. {
  266. $postedAt ??= $this->date;
  267. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  268. $transaction = $this->transactions()->create([
  269. 'company_id' => $this->company_id,
  270. 'type' => TransactionType::Journal,
  271. 'posted_at' => $postedAt,
  272. 'amount' => $total,
  273. 'description' => 'Credit Note Creation for Credit Note #' . $this->credit_note_number,
  274. ]);
  275. $baseDescription = "{$this->client->name}: Credit Note #{$this->credit_note_number}";
  276. // Credit AR (opposite of invoice)
  277. $transaction->journalEntries()->create([
  278. 'company_id' => $this->company_id,
  279. 'type' => JournalEntryType::Credit,
  280. 'account_id' => Account::getAccountsReceivableAccount()->id,
  281. 'amount' => $total,
  282. 'description' => $baseDescription,
  283. ]);
  284. // Handle line items - debit revenue accounts (reverse of invoice)
  285. foreach ($this->lineItems as $lineItem) {
  286. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  287. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  288. $transaction->journalEntries()->create([
  289. 'company_id' => $this->company_id,
  290. 'type' => JournalEntryType::Debit,
  291. 'account_id' => $lineItem->offering->income_account_id,
  292. 'amount' => $lineItemSubtotal,
  293. 'description' => $lineItemDescription,
  294. ]);
  295. // Handle adjustments
  296. foreach ($lineItem->adjustments as $adjustment) {
  297. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  298. $transaction->journalEntries()->create([
  299. 'company_id' => $this->company_id,
  300. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  301. 'account_id' => $adjustment->account_id,
  302. 'amount' => $adjustmentAmount,
  303. 'description' => $lineItemDescription,
  304. ]);
  305. }
  306. }
  307. }
  308. public function approveDraft(?Carbon $approvedAt = null): void
  309. {
  310. if (! $this->isDraft()) {
  311. throw new \RuntimeException('Credit note is not in draft status.');
  312. }
  313. $this->createInitialTransaction();
  314. $approvedAt ??= now();
  315. $this->update([
  316. 'approved_at' => $approvedAt,
  317. 'status' => CreditNoteStatus::Sent,
  318. ]);
  319. // Auto-apply if configured in settings
  320. if ($this->company->settings->auto_apply_credit_notes ?? true) {
  321. $this->autoApplyToInvoices();
  322. }
  323. }
  324. public function convertAmountToDefaultCurrency(int $amountCents): int
  325. {
  326. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  327. $needsConversion = $this->currency_code !== $defaultCurrency;
  328. if ($needsConversion) {
  329. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  330. }
  331. return $amountCents;
  332. }
  333. public function formatAmountToDefaultCurrency(int $amountCents): string
  334. {
  335. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  336. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  337. }
  338. // Other methods
  339. public function markAsSent(?Carbon $sentAt = null): void
  340. {
  341. $sentAt ??= now();
  342. $this->update([
  343. 'status' => CreditNoteStatus::Sent,
  344. 'last_sent_at' => $sentAt,
  345. ]);
  346. }
  347. public function markAsViewed(?Carbon $viewedAt = null): void
  348. {
  349. $viewedAt ??= now();
  350. $this->update([
  351. 'status' => CreditNoteStatus::Viewed,
  352. 'last_viewed_at' => $viewedAt,
  353. ]);
  354. }
  355. // Utility Methods
  356. public static function getNextDocumentNumber(?Company $company = null): string
  357. {
  358. $company ??= auth()->user()?->currentCompany;
  359. if (! $company) {
  360. throw new \RuntimeException('No current company is set for the user.');
  361. }
  362. $defaultSettings = $company->defaultCreditNote;
  363. $numberPrefix = $defaultSettings->number_prefix ?? 'CN-';
  364. $latestDocument = static::query()
  365. ->whereNotNull('credit_note_number')
  366. ->latest('credit_note_number')
  367. ->first();
  368. $lastNumberNumericPart = $latestDocument
  369. ? (int) substr($latestDocument->credit_note_number, strlen($numberPrefix))
  370. : DocumentDefault::getBaseNumber();
  371. $numberNext = $lastNumberNumericPart + 1;
  372. return $defaultSettings->getNumberNext(
  373. prefix: $numberPrefix,
  374. next: $numberNext
  375. );
  376. }
  377. // Action Methods
  378. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  379. {
  380. return $action::make()
  381. ->excludeAttributes([
  382. 'status',
  383. 'amount_used',
  384. 'created_by',
  385. 'updated_by',
  386. 'created_at',
  387. 'updated_at',
  388. 'credit_note_number',
  389. 'date',
  390. 'approved_at',
  391. 'last_sent_at',
  392. 'last_viewed_at',
  393. ])
  394. ->modal(false)
  395. ->beforeReplicaSaved(function (self $original, self $replica) {
  396. $replica->status = CreditNoteStatus::Draft;
  397. $replica->credit_note_number = self::getNextDocumentNumber();
  398. $replica->date = now();
  399. $replica->amount_used = 0;
  400. })
  401. ->databaseTransaction()
  402. ->after(function (self $original, self $replica) {
  403. $original->replicateLineItems($replica);
  404. })
  405. ->successRedirectUrl(static function (self $replica) {
  406. return CreditNoteResource::getUrl('edit', ['record' => $replica]);
  407. });
  408. }
  409. public static function getApproveAction(string $action = Action::class): MountableAction
  410. {
  411. return $action::make('approve')
  412. ->label('Approve')
  413. ->icon('heroicon-m-check-circle')
  414. ->visible(fn (self $record) => $record->isDraft())
  415. ->requiresConfirmation()
  416. ->databaseTransaction()
  417. ->successNotificationTitle('Credit note approved')
  418. ->action(function (self $record) {
  419. $record->approveDraft();
  420. });
  421. }
  422. public function replicateLineItems(Model $target): void
  423. {
  424. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  425. $replica = $lineItem->replicate([
  426. 'documentable_id',
  427. 'documentable_type',
  428. 'subtotal',
  429. 'total',
  430. 'created_by',
  431. 'updated_by',
  432. 'created_at',
  433. 'updated_at',
  434. ]);
  435. $replica->documentable_id = $target->id;
  436. $replica->documentable_type = $target->getMorphClass();
  437. $replica->save();
  438. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  439. });
  440. }
  441. }