Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Bill.php 15KB

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