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

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