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.

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