Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Bill.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\RateCast;
  4. use App\Collections\Accounting\DocumentCollection;
  5. use App\Enums\Accounting\AdjustmentComputation;
  6. use App\Enums\Accounting\BillStatus;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\JournalEntryType;
  10. use App\Enums\Accounting\TransactionType;
  11. use App\Filament\Company\Resources\Purchases\BillResource;
  12. use App\Models\Banking\BankAccount;
  13. use App\Models\Common\Vendor;
  14. use App\Models\Company;
  15. use App\Models\Setting\DocumentDefault;
  16. use App\Observers\BillObserver;
  17. use App\Utilities\Currency\CurrencyAccessor;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use Filament\Actions\MountableAction;
  20. use Filament\Actions\ReplicateAction;
  21. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  22. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  23. use Illuminate\Database\Eloquent\Builder;
  24. use Illuminate\Database\Eloquent\Casts\Attribute;
  25. use Illuminate\Database\Eloquent\Model;
  26. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  27. use Illuminate\Database\Eloquent\Relations\MorphMany;
  28. use Illuminate\Database\Eloquent\Relations\MorphOne;
  29. use Illuminate\Support\Carbon;
  30. #[CollectedBy(DocumentCollection::class)]
  31. #[ObservedBy(BillObserver::class)]
  32. class Bill extends Document
  33. {
  34. protected $table = 'bills';
  35. protected $fillable = [
  36. 'company_id',
  37. 'vendor_id',
  38. 'bill_number',
  39. 'order_number',
  40. 'date',
  41. 'due_date',
  42. 'paid_at',
  43. 'status',
  44. 'currency_code',
  45. 'discount_method',
  46. 'discount_computation',
  47. 'discount_rate',
  48. 'subtotal',
  49. 'tax_total',
  50. 'discount_total',
  51. 'total',
  52. 'amount_paid',
  53. 'notes',
  54. 'created_by',
  55. 'updated_by',
  56. ];
  57. protected $casts = [
  58. 'date' => 'date',
  59. 'due_date' => 'date',
  60. 'paid_at' => 'datetime',
  61. 'status' => BillStatus::class,
  62. 'discount_method' => DocumentDiscountMethod::class,
  63. 'discount_computation' => AdjustmentComputation::class,
  64. 'discount_rate' => RateCast::class,
  65. ];
  66. public function vendor(): BelongsTo
  67. {
  68. return $this->belongsTo(Vendor::class);
  69. }
  70. public function transactions(): MorphMany
  71. {
  72. return $this->morphMany(Transaction::class, 'transactionable');
  73. }
  74. public function payments(): MorphMany
  75. {
  76. return $this->transactions()->where('is_payment', true);
  77. }
  78. public function deposits(): MorphMany
  79. {
  80. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  81. }
  82. public function withdrawals(): MorphMany
  83. {
  84. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  85. }
  86. public function initialTransaction(): MorphOne
  87. {
  88. return $this->morphOne(Transaction::class, 'transactionable')
  89. ->where('type', TransactionType::Journal);
  90. }
  91. public static function documentType(): DocumentType
  92. {
  93. return DocumentType::Bill;
  94. }
  95. public function documentNumber(): ?string
  96. {
  97. return $this->bill_number;
  98. }
  99. public function documentDate(): ?string
  100. {
  101. return $this->date?->toDefaultDateFormat();
  102. }
  103. public function dueDate(): ?string
  104. {
  105. return $this->due_date?->toDefaultDateFormat();
  106. }
  107. public function referenceNumber(): ?string
  108. {
  109. return $this->order_number;
  110. }
  111. public function amountDue(): ?string
  112. {
  113. return $this->amount_due;
  114. }
  115. protected function isCurrentlyOverdue(): Attribute
  116. {
  117. return Attribute::get(function () {
  118. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  119. });
  120. }
  121. public function wasInitialized(): bool
  122. {
  123. return $this->hasInitialTransaction();
  124. }
  125. public function isPaid(): bool
  126. {
  127. return $this->paid_at !== null;
  128. }
  129. public function canBeOverdue(): bool
  130. {
  131. return in_array($this->status, BillStatus::canBeOverdue());
  132. }
  133. public function canRecordPayment(): bool
  134. {
  135. return ! in_array($this->status, [
  136. BillStatus::Paid,
  137. BillStatus::Void,
  138. ]);
  139. }
  140. public function hasPayments(): bool
  141. {
  142. return $this->payments->isNotEmpty();
  143. }
  144. public static function getNextDocumentNumber(?Company $company = null): string
  145. {
  146. $company ??= auth()->user()?->currentCompany;
  147. if (! $company) {
  148. throw new \RuntimeException('No current company is set for the user.');
  149. }
  150. $defaultBillSettings = $company->defaultBill;
  151. $numberPrefix = $defaultBillSettings->number_prefix ?? '';
  152. $latestDocument = static::query()
  153. ->whereNotNull('bill_number')
  154. ->latest('bill_number')
  155. ->first();
  156. $lastNumberNumericPart = $latestDocument
  157. ? (int) substr($latestDocument->bill_number, strlen($numberPrefix))
  158. : DocumentDefault::getBaseNumber();
  159. $numberNext = $lastNumberNumericPart + 1;
  160. return $defaultBillSettings->getNumberNext(
  161. prefix: $numberPrefix,
  162. next: $numberNext
  163. );
  164. }
  165. public function hasInitialTransaction(): bool
  166. {
  167. return $this->initialTransaction()->exists();
  168. }
  169. public function scopeUnpaid(Builder $query): Builder
  170. {
  171. return $query->whereIn('status', [
  172. BillStatus::Open,
  173. BillStatus::Partial,
  174. BillStatus::Overdue,
  175. ]);
  176. }
  177. public function recordPayment(array $data): void
  178. {
  179. $transactionType = TransactionType::Withdrawal;
  180. $transactionDescription = "Bill #{$this->bill_number}: Payment to {$this->vendor->name}";
  181. // Add multi-currency handling
  182. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  183. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  184. $billCurrency = $this->currency_code;
  185. $requiresConversion = $billCurrency !== $bankAccountCurrency;
  186. // Store the original payment amount in bill currency before any conversion
  187. $amountInBillCurrencyCents = $data['amount'];
  188. if ($requiresConversion) {
  189. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  190. $amountInBillCurrencyCents,
  191. $billCurrency,
  192. $bankAccountCurrency
  193. );
  194. $formattedAmountForBankCurrency = $amountInBankCurrencyCents;
  195. } else {
  196. $formattedAmountForBankCurrency = $amountInBillCurrencyCents;
  197. }
  198. // Create transaction with converted amount
  199. $this->transactions()->create([
  200. 'company_id' => $this->company_id,
  201. 'type' => $transactionType,
  202. 'is_payment' => true,
  203. 'posted_at' => $data['posted_at'],
  204. 'amount' => $formattedAmountForBankCurrency,
  205. 'payment_method' => $data['payment_method'],
  206. 'bank_account_id' => $data['bank_account_id'],
  207. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  208. 'description' => $transactionDescription,
  209. 'notes' => $data['notes'] ?? null,
  210. 'meta' => [
  211. 'original_document_currency' => $billCurrency,
  212. 'amount_in_document_currency_cents' => $amountInBillCurrencyCents,
  213. ],
  214. ]);
  215. }
  216. public function createInitialTransaction(?Carbon $postedAt = null): void
  217. {
  218. $postedAt ??= $this->date;
  219. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  220. $journalEntryData = [];
  221. $totalInBillCurrency = $this->total;
  222. $journalEntryData[] = [
  223. 'type' => JournalEntryType::Credit,
  224. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  225. 'amount_in_bill_currency' => $totalInBillCurrency,
  226. 'description' => $baseDescription,
  227. ];
  228. $totalLineItemSubtotalInBillCurrency = (int) $this->lineItems()->sum('subtotal');
  229. $billDiscountTotalInBillCurrency = (int) $this->discount_total;
  230. $remainingDiscountInBillCurrency = $billDiscountTotalInBillCurrency;
  231. foreach ($this->lineItems as $index => $lineItem) {
  232. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  233. $lineItemSubtotalInBillCurrency = $lineItem->getRawOriginal('subtotal');
  234. $journalEntryData[] = [
  235. 'type' => JournalEntryType::Debit,
  236. 'account_id' => $lineItem->offering->expense_account_id,
  237. 'amount_in_bill_currency' => $lineItemSubtotalInBillCurrency,
  238. 'description' => $lineItemDescription,
  239. ];
  240. foreach ($lineItem->adjustments as $adjustment) {
  241. $adjustmentAmountInBillCurrency = $lineItem->calculateAdjustmentTotalAmount($adjustment);
  242. if ($adjustment->isNonRecoverablePurchaseTax()) {
  243. $journalEntryData[] = [
  244. 'type' => JournalEntryType::Debit,
  245. 'account_id' => $lineItem->offering->expense_account_id,
  246. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  247. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  248. ];
  249. } elseif ($adjustment->account_id) {
  250. $journalEntryData[] = [
  251. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  252. 'account_id' => $adjustment->account_id,
  253. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  254. 'description' => $lineItemDescription,
  255. ];
  256. }
  257. }
  258. // Handle per-document discount allocation
  259. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalInBillCurrency > 0) {
  260. $lineItemSubtotalInBillCurrency = (int) $lineItem->getRawOriginal('subtotal');
  261. if ($index === $this->lineItems->count() - 1) {
  262. $lineItemDiscountInBillCurrency = $remainingDiscountInBillCurrency;
  263. } else {
  264. $lineItemDiscountInBillCurrency = (int) round(
  265. ($lineItemSubtotalInBillCurrency / $totalLineItemSubtotalInBillCurrency) * $billDiscountTotalInBillCurrency
  266. );
  267. $remainingDiscountInBillCurrency -= $lineItemDiscountInBillCurrency;
  268. }
  269. if ($lineItemDiscountInBillCurrency > 0) {
  270. $journalEntryData[] = [
  271. 'type' => JournalEntryType::Credit,
  272. 'account_id' => Account::getPurchaseDiscountAccount($this->company_id)->id,
  273. 'amount_in_bill_currency' => $lineItemDiscountInBillCurrency,
  274. 'description' => "{$lineItemDescription} (Proportional Discount)",
  275. ];
  276. }
  277. }
  278. }
  279. // Convert amounts to default currency
  280. $totalDebitsInDefaultCurrency = 0;
  281. $totalCreditsInDefaultCurrency = 0;
  282. foreach ($journalEntryData as &$entry) {
  283. $entry['amount_in_default_currency'] = $this->formatAmountToDefaultCurrency($entry['amount_in_bill_currency']);
  284. if ($entry['type'] === JournalEntryType::Debit) {
  285. $totalDebitsInDefaultCurrency += $entry['amount_in_default_currency'];
  286. } else {
  287. $totalCreditsInDefaultCurrency += $entry['amount_in_default_currency'];
  288. }
  289. }
  290. unset($entry);
  291. // Handle currency conversion imbalance
  292. $imbalance = $totalDebitsInDefaultCurrency - $totalCreditsInDefaultCurrency;
  293. if ($imbalance !== 0) {
  294. $targetType = $imbalance > 0 ? JournalEntryType::Credit : JournalEntryType::Debit;
  295. $adjustmentAmount = abs($imbalance);
  296. // Find last entry of target type and adjust it
  297. $lastKey = array_key_last(array_filter($journalEntryData, fn ($entry) => $entry['type'] === $targetType, ARRAY_FILTER_USE_BOTH));
  298. $journalEntryData[$lastKey]['amount_in_default_currency'] += $adjustmentAmount;
  299. if ($targetType === JournalEntryType::Debit) {
  300. $totalDebitsInDefaultCurrency += $adjustmentAmount;
  301. } else {
  302. $totalCreditsInDefaultCurrency += $adjustmentAmount;
  303. }
  304. }
  305. if ($totalDebitsInDefaultCurrency !== $totalCreditsInDefaultCurrency) {
  306. throw new \Exception('Journal entries do not balance for Bill #' . $this->bill_number . '. Debits: ' . $totalDebitsInDefaultCurrency . ', Credits: ' . $totalCreditsInDefaultCurrency);
  307. }
  308. // Create the transaction using the sum of debits
  309. $transaction = $this->transactions()->create([
  310. 'company_id' => $this->company_id,
  311. 'type' => TransactionType::Journal,
  312. 'posted_at' => $postedAt,
  313. 'amount' => $totalDebitsInDefaultCurrency,
  314. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  315. ]);
  316. // Create all journal entries
  317. foreach ($journalEntryData as $entry) {
  318. $transaction->journalEntries()->create([
  319. 'company_id' => $this->company_id,
  320. 'type' => $entry['type'],
  321. 'account_id' => $entry['account_id'],
  322. 'amount' => $entry['amount_in_default_currency'],
  323. 'description' => $entry['description'],
  324. ]);
  325. }
  326. }
  327. public function updateInitialTransaction(): void
  328. {
  329. $transaction = $this->initialTransaction;
  330. if ($transaction) {
  331. $transaction->delete();
  332. }
  333. $this->createInitialTransaction();
  334. }
  335. public function convertAmountToDefaultCurrency(int $amountCents): int
  336. {
  337. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  338. $needsConversion = $this->currency_code !== $defaultCurrency;
  339. if ($needsConversion) {
  340. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  341. }
  342. return $amountCents;
  343. }
  344. public function formatAmountToDefaultCurrency(int $amountCents): int
  345. {
  346. return $this->convertAmountToDefaultCurrency($amountCents);
  347. }
  348. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  349. {
  350. return $action::make()
  351. ->excludeAttributes([
  352. 'status',
  353. 'amount_paid',
  354. 'amount_due',
  355. 'created_by',
  356. 'updated_by',
  357. 'created_at',
  358. 'updated_at',
  359. 'bill_number',
  360. 'date',
  361. 'due_date',
  362. 'paid_at',
  363. ])
  364. ->modal(false)
  365. ->beforeReplicaSaved(function (self $original, self $replica) {
  366. $replica->status = BillStatus::Open;
  367. $replica->bill_number = self::getNextDocumentNumber();
  368. $replica->date = now();
  369. $replica->due_date = now()->addDays($original->company->defaultBill->payment_terms->getDays());
  370. })
  371. ->databaseTransaction()
  372. ->after(function (self $original, self $replica) {
  373. $original->replicateLineItems($replica);
  374. })
  375. ->successRedirectUrl(static function (self $replica) {
  376. return BillResource::getUrl('edit', ['record' => $replica]);
  377. });
  378. }
  379. public function replicateLineItems(Model $target): void
  380. {
  381. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  382. $replica = $lineItem->replicate([
  383. 'documentable_id',
  384. 'documentable_type',
  385. 'subtotal',
  386. 'total',
  387. 'created_by',
  388. 'updated_by',
  389. 'created_at',
  390. 'updated_at',
  391. ]);
  392. $replica->documentable_id = $target->id;
  393. $replica->documentable_type = $target->getMorphClass();
  394. $replica->save();
  395. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  396. });
  397. }
  398. }