Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Bill.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  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 = $data['amount'];
  195. if ($requiresConversion) {
  196. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  197. $amountInBillCurrencyCents,
  198. $billCurrency,
  199. $bankAccountCurrency
  200. );
  201. $formattedAmountForBankCurrency = $amountInBankCurrencyCents;
  202. } else {
  203. $formattedAmountForBankCurrency = $amountInBillCurrencyCents;
  204. }
  205. // Create transaction with converted amount
  206. $this->transactions()->create([
  207. 'company_id' => $this->company_id,
  208. 'type' => $transactionType,
  209. 'is_payment' => true,
  210. 'posted_at' => $data['posted_at'],
  211. 'amount' => $formattedAmountForBankCurrency,
  212. 'payment_method' => $data['payment_method'],
  213. 'bank_account_id' => $data['bank_account_id'],
  214. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  215. 'description' => $transactionDescription,
  216. 'notes' => $data['notes'] ?? null,
  217. 'meta' => [
  218. 'original_document_currency' => $billCurrency,
  219. 'amount_in_document_currency_cents' => $amountInBillCurrencyCents,
  220. ],
  221. ]);
  222. }
  223. public function createInitialTransaction(?Carbon $postedAt = null): void
  224. {
  225. $postedAt ??= $this->date;
  226. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  227. $journalEntryData = [];
  228. $totalInBillCurrency = $this->total;
  229. $journalEntryData[] = [
  230. 'type' => JournalEntryType::Credit,
  231. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  232. 'amount_in_bill_currency' => $totalInBillCurrency,
  233. 'description' => $baseDescription,
  234. ];
  235. $totalLineItemSubtotalInBillCurrency = (int) $this->lineItems()->sum('subtotal');
  236. $billDiscountTotalInBillCurrency = (int) $this->discount_total;
  237. $remainingDiscountInBillCurrency = $billDiscountTotalInBillCurrency;
  238. foreach ($this->lineItems as $index => $lineItem) {
  239. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  240. $lineItemSubtotalInBillCurrency = $lineItem->getRawOriginal('subtotal');
  241. $journalEntryData[] = [
  242. 'type' => JournalEntryType::Debit,
  243. 'account_id' => $lineItem->offering->expense_account_id,
  244. 'amount_in_bill_currency' => $lineItemSubtotalInBillCurrency,
  245. 'description' => $lineItemDescription,
  246. ];
  247. foreach ($lineItem->adjustments as $adjustment) {
  248. $adjustmentAmountInBillCurrency = $lineItem->calculateAdjustmentTotalAmount($adjustment);
  249. if ($adjustment->isNonRecoverablePurchaseTax()) {
  250. $journalEntryData[] = [
  251. 'type' => JournalEntryType::Debit,
  252. 'account_id' => $lineItem->offering->expense_account_id,
  253. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  254. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  255. ];
  256. } elseif ($adjustment->account_id) {
  257. $journalEntryData[] = [
  258. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  259. 'account_id' => $adjustment->account_id,
  260. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  261. 'description' => $lineItemDescription,
  262. ];
  263. }
  264. }
  265. // Handle per-document discount allocation
  266. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalInBillCurrency > 0) {
  267. $lineItemSubtotalInBillCurrency = (int) $lineItem->getRawOriginal('subtotal');
  268. if ($index === $this->lineItems->count() - 1) {
  269. $lineItemDiscountInBillCurrency = $remainingDiscountInBillCurrency;
  270. } else {
  271. $lineItemDiscountInBillCurrency = (int) round(
  272. ($lineItemSubtotalInBillCurrency / $totalLineItemSubtotalInBillCurrency) * $billDiscountTotalInBillCurrency
  273. );
  274. $remainingDiscountInBillCurrency -= $lineItemDiscountInBillCurrency;
  275. }
  276. if ($lineItemDiscountInBillCurrency > 0) {
  277. $journalEntryData[] = [
  278. 'type' => JournalEntryType::Credit,
  279. 'account_id' => Account::getPurchaseDiscountAccount($this->company_id)->id,
  280. 'amount_in_bill_currency' => $lineItemDiscountInBillCurrency,
  281. 'description' => "{$lineItemDescription} (Proportional Discount)",
  282. ];
  283. }
  284. }
  285. }
  286. // Convert amounts to default currency
  287. $totalDebitsInDefaultCurrency = 0;
  288. $totalCreditsInDefaultCurrency = 0;
  289. foreach ($journalEntryData as &$entry) {
  290. $entry['amount_in_default_currency'] = $this->formatAmountToDefaultCurrency($entry['amount_in_bill_currency']);
  291. if ($entry['type'] === JournalEntryType::Debit) {
  292. $totalDebitsInDefaultCurrency += $entry['amount_in_default_currency'];
  293. } else {
  294. $totalCreditsInDefaultCurrency += $entry['amount_in_default_currency'];
  295. }
  296. }
  297. unset($entry);
  298. // Handle currency conversion imbalance
  299. $imbalance = $totalDebitsInDefaultCurrency - $totalCreditsInDefaultCurrency;
  300. if ($imbalance !== 0) {
  301. $targetType = $imbalance > 0 ? JournalEntryType::Credit : JournalEntryType::Debit;
  302. $adjustmentAmount = abs($imbalance);
  303. // Find last entry of target type and adjust it
  304. $lastKey = array_key_last(array_filter($journalEntryData, fn ($entry) => $entry['type'] === $targetType, ARRAY_FILTER_USE_BOTH));
  305. $journalEntryData[$lastKey]['amount_in_default_currency'] += $adjustmentAmount;
  306. if ($targetType === JournalEntryType::Debit) {
  307. $totalDebitsInDefaultCurrency += $adjustmentAmount;
  308. } else {
  309. $totalCreditsInDefaultCurrency += $adjustmentAmount;
  310. }
  311. }
  312. if ($totalDebitsInDefaultCurrency !== $totalCreditsInDefaultCurrency) {
  313. throw new \Exception('Journal entries do not balance for Bill #' . $this->bill_number . '. Debits: ' . $totalDebitsInDefaultCurrency . ', Credits: ' . $totalCreditsInDefaultCurrency);
  314. }
  315. // Create the transaction using the sum of debits
  316. $transaction = $this->transactions()->create([
  317. 'company_id' => $this->company_id,
  318. 'type' => TransactionType::Journal,
  319. 'posted_at' => $postedAt,
  320. 'amount' => $totalDebitsInDefaultCurrency,
  321. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  322. ]);
  323. // Create all journal entries
  324. foreach ($journalEntryData as $entry) {
  325. $transaction->journalEntries()->create([
  326. 'company_id' => $this->company_id,
  327. 'type' => $entry['type'],
  328. 'account_id' => $entry['account_id'],
  329. 'amount' => $entry['amount_in_default_currency'],
  330. 'description' => $entry['description'],
  331. ]);
  332. }
  333. }
  334. public function updateInitialTransaction(): void
  335. {
  336. $transaction = $this->initialTransaction;
  337. if ($transaction) {
  338. $transaction->delete();
  339. }
  340. $this->createInitialTransaction();
  341. }
  342. public function convertAmountToDefaultCurrency(int $amountCents): int
  343. {
  344. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  345. $needsConversion = $this->currency_code !== $defaultCurrency;
  346. if ($needsConversion) {
  347. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  348. }
  349. return $amountCents;
  350. }
  351. public function formatAmountToDefaultCurrency(int $amountCents): int
  352. {
  353. return $this->convertAmountToDefaultCurrency($amountCents);
  354. }
  355. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  356. {
  357. return $action::make()
  358. ->excludeAttributes([
  359. 'status',
  360. 'amount_paid',
  361. 'amount_due',
  362. 'created_by',
  363. 'updated_by',
  364. 'created_at',
  365. 'updated_at',
  366. 'bill_number',
  367. 'date',
  368. 'due_date',
  369. 'paid_at',
  370. ])
  371. ->modal(false)
  372. ->beforeReplicaSaved(function (self $original, self $replica) {
  373. $replica->status = BillStatus::Open;
  374. $replica->bill_number = self::getNextDocumentNumber();
  375. $replica->date = now();
  376. $replica->due_date = now()->addDays($original->company->defaultBill->payment_terms->getDays());
  377. })
  378. ->databaseTransaction()
  379. ->after(function (self $original, self $replica) {
  380. $original->replicateLineItems($replica);
  381. })
  382. ->successRedirectUrl(static function (self $replica) {
  383. return BillResource::getUrl('edit', ['record' => $replica]);
  384. });
  385. }
  386. public function replicateLineItems(Model $target): void
  387. {
  388. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  389. $replica = $lineItem->replicate([
  390. 'documentable_id',
  391. 'documentable_type',
  392. 'subtotal',
  393. 'total',
  394. 'created_by',
  395. 'updated_by',
  396. 'created_at',
  397. 'updated_at',
  398. ]);
  399. $replica->documentable_id = $target->id;
  400. $replica->documentable_type = $target->getMorphClass();
  401. $replica->save();
  402. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  403. });
  404. }
  405. }