You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Bill.php 15KB

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