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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  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. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  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. if ($requiresConversion) {
  194. $amountInBillCurrencyCents = CurrencyConverter::convertToCents($data['amount'], $billCurrency);
  195. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  196. $amountInBillCurrencyCents,
  197. $billCurrency,
  198. $bankAccountCurrency
  199. );
  200. $formattedAmountForBankCurrency = CurrencyConverter::convertCentsToFormatSimple(
  201. $amountInBankCurrencyCents,
  202. $bankAccountCurrency
  203. );
  204. } else {
  205. $formattedAmountForBankCurrency = $data['amount']; // Already in simple format
  206. }
  207. // Create transaction with converted amount
  208. $this->transactions()->create([
  209. 'company_id' => $this->company_id,
  210. 'type' => $transactionType,
  211. 'is_payment' => true,
  212. 'posted_at' => $data['posted_at'],
  213. 'amount' => $formattedAmountForBankCurrency,
  214. 'payment_method' => $data['payment_method'],
  215. 'bank_account_id' => $data['bank_account_id'],
  216. 'account_id' => Account::getAccountsPayableAccount()->id,
  217. 'description' => $transactionDescription,
  218. 'notes' => $data['notes'] ?? null,
  219. ]);
  220. }
  221. public function createInitialTransaction(?Carbon $postedAt = null): void
  222. {
  223. $postedAt ??= $this->date;
  224. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  225. $transaction = $this->transactions()->create([
  226. 'company_id' => $this->company_id,
  227. 'type' => TransactionType::Journal,
  228. 'posted_at' => $postedAt,
  229. 'amount' => $total,
  230. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  231. ]);
  232. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  233. $transaction->journalEntries()->create([
  234. 'company_id' => $this->company_id,
  235. 'type' => JournalEntryType::Credit,
  236. 'account_id' => Account::getAccountsPayableAccount()->id,
  237. 'amount' => $total,
  238. 'description' => $baseDescription,
  239. ]);
  240. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  241. $billDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  242. $remainingDiscountCents = $billDiscountTotalCents;
  243. foreach ($this->lineItems as $index => $lineItem) {
  244. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  245. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  246. $transaction->journalEntries()->create([
  247. 'company_id' => $this->company_id,
  248. 'type' => JournalEntryType::Debit,
  249. 'account_id' => $lineItem->offering->expense_account_id,
  250. 'amount' => $lineItemSubtotal,
  251. 'description' => $lineItemDescription,
  252. ]);
  253. foreach ($lineItem->adjustments as $adjustment) {
  254. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  255. if ($adjustment->isNonRecoverablePurchaseTax()) {
  256. $transaction->journalEntries()->create([
  257. 'company_id' => $this->company_id,
  258. 'type' => JournalEntryType::Debit,
  259. 'account_id' => $lineItem->offering->expense_account_id,
  260. 'amount' => $adjustmentAmount,
  261. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  262. ]);
  263. } elseif ($adjustment->account_id) {
  264. $transaction->journalEntries()->create([
  265. 'company_id' => $this->company_id,
  266. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  267. 'account_id' => $adjustment->account_id,
  268. 'amount' => $adjustmentAmount,
  269. 'description' => $lineItemDescription,
  270. ]);
  271. }
  272. }
  273. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  274. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  275. if ($index === $this->lineItems->count() - 1) {
  276. $lineItemDiscount = $remainingDiscountCents;
  277. } else {
  278. $lineItemDiscount = (int) round(
  279. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $billDiscountTotalCents
  280. );
  281. $remainingDiscountCents -= $lineItemDiscount;
  282. }
  283. if ($lineItemDiscount > 0) {
  284. $transaction->journalEntries()->create([
  285. 'company_id' => $this->company_id,
  286. 'type' => JournalEntryType::Credit,
  287. 'account_id' => Account::getPurchaseDiscountAccount()->id,
  288. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  289. 'description' => "{$lineItemDescription} (Proportional Discount)",
  290. ]);
  291. }
  292. }
  293. }
  294. }
  295. public function updateInitialTransaction(): void
  296. {
  297. $transaction = $this->initialTransaction;
  298. if ($transaction) {
  299. $transaction->delete();
  300. }
  301. $this->createInitialTransaction();
  302. }
  303. public function convertAmountToDefaultCurrency(int $amountCents): int
  304. {
  305. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  306. $needsConversion = $this->currency_code !== $defaultCurrency;
  307. if ($needsConversion) {
  308. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  309. }
  310. return $amountCents;
  311. }
  312. public function formatAmountToDefaultCurrency(int $amountCents): string
  313. {
  314. $convertedCents = $this->convertAmountToDefaultCurrency($amountCents);
  315. return CurrencyConverter::convertCentsToFormatSimple($convertedCents);
  316. }
  317. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  318. {
  319. return $action::make()
  320. ->excludeAttributes([
  321. 'status',
  322. 'amount_paid',
  323. 'amount_due',
  324. 'created_by',
  325. 'updated_by',
  326. 'created_at',
  327. 'updated_at',
  328. 'bill_number',
  329. 'date',
  330. 'due_date',
  331. 'paid_at',
  332. ])
  333. ->modal(false)
  334. ->beforeReplicaSaved(function (self $original, self $replica) {
  335. $replica->status = BillStatus::Open;
  336. $replica->bill_number = self::getNextDocumentNumber();
  337. $replica->date = now();
  338. $replica->due_date = now()->addDays($original->company->defaultBill->payment_terms->getDays());
  339. })
  340. ->databaseTransaction()
  341. ->after(function (self $original, self $replica) {
  342. $original->replicateLineItems($replica);
  343. })
  344. ->successRedirectUrl(static function (self $replica) {
  345. return BillResource::getUrl('edit', ['record' => $replica]);
  346. });
  347. }
  348. public function replicateLineItems(Model $target): void
  349. {
  350. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  351. $replica = $lineItem->replicate([
  352. 'documentable_id',
  353. 'documentable_type',
  354. 'subtotal',
  355. 'total',
  356. 'created_by',
  357. 'updated_by',
  358. 'created_at',
  359. 'updated_at',
  360. ]);
  361. $replica->documentable_id = $target->id;
  362. $replica->documentable_type = $target->getMorphClass();
  363. $replica->save();
  364. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  365. });
  366. }
  367. }