Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

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