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 14KB

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