You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Bill.php 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\DocumentType;
  5. use App\Enums\Accounting\JournalEntryType;
  6. use App\Enums\Accounting\TransactionType;
  7. use App\Filament\Company\Resources\Purchases\BillResource;
  8. use App\Models\Common\Vendor;
  9. use App\Models\Setting\DocumentDefault;
  10. use App\Observers\BillObserver;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use Filament\Actions\MountableAction;
  14. use Filament\Actions\ReplicateAction;
  15. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  16. use Illuminate\Database\Eloquent\Builder;
  17. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  18. use Illuminate\Database\Eloquent\Relations\MorphOne;
  19. use Illuminate\Support\Carbon;
  20. #[ObservedBy(BillObserver::class)]
  21. class Bill extends Document
  22. {
  23. protected $table = 'bills';
  24. protected $fillable = [
  25. ...self::COMMON_FILLABLE,
  26. ...self::BILL_FILLABLE,
  27. ];
  28. protected const BILL_FILLABLE = [
  29. 'vendor_id',
  30. 'bill_number',
  31. 'notes',
  32. ];
  33. protected function casts(): array
  34. {
  35. return [
  36. ...parent::casts(),
  37. 'status' => BillStatus::class,
  38. ];
  39. }
  40. public static function documentNumberColumn(): string
  41. {
  42. return 'bill_number';
  43. }
  44. public static function documentType(): DocumentType
  45. {
  46. return DocumentType::Bill;
  47. }
  48. public static function getDocumentSettings(): DocumentDefault
  49. {
  50. return auth()->user()->currentCompany->defaultBill;
  51. }
  52. public function vendor(): BelongsTo
  53. {
  54. return $this->belongsTo(Vendor::class);
  55. }
  56. public function initialTransaction(): MorphOne
  57. {
  58. return $this->morphOne(Transaction::class, 'transactionable')
  59. ->where('type', TransactionType::Journal);
  60. }
  61. public function canBeOverdue(): bool
  62. {
  63. return in_array($this->status, BillStatus::canBeOverdue());
  64. }
  65. public function canRecordPayment(): bool
  66. {
  67. return ! in_array($this->status, [
  68. BillStatus::Paid,
  69. BillStatus::Void,
  70. ]) && $this->currency_code === CurrencyAccessor::getDefaultCurrency();
  71. }
  72. public function hasInitialTransaction(): bool
  73. {
  74. return $this->initialTransaction()->exists();
  75. }
  76. public function scopeOutstanding(Builder $query): Builder
  77. {
  78. return $query->whereIn('status', [
  79. BillStatus::Unpaid,
  80. BillStatus::Partial,
  81. BillStatus::Overdue,
  82. ]);
  83. }
  84. public function recordPayment(array $data): void
  85. {
  86. $transactionDescription = "Bill #{$this->bill_number}: Payment to {$this->vendor->name}";
  87. $this->recordTransaction(
  88. $data,
  89. TransactionType::Withdrawal, // Always withdrawal for bills
  90. $transactionDescription,
  91. Account::getAccountsPayableAccount()->id // Account ID specific to bills
  92. );
  93. }
  94. public function createInitialTransaction(?Carbon $postedAt = null): void
  95. {
  96. $postedAt ??= $this->date;
  97. $total = $this->formatAmountToDefaultCurrency($this->getRawOriginal('total'));
  98. $transaction = $this->transactions()->create([
  99. 'company_id' => $this->company_id,
  100. 'type' => TransactionType::Journal,
  101. 'posted_at' => $postedAt,
  102. 'amount' => $total,
  103. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  104. ]);
  105. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  106. $transaction->journalEntries()->create([
  107. 'company_id' => $this->company_id,
  108. 'type' => JournalEntryType::Credit,
  109. 'account_id' => Account::getAccountsPayableAccount()->id,
  110. 'amount' => $total,
  111. 'description' => $baseDescription,
  112. ]);
  113. $totalLineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $this->lineItems()->sum('subtotal'));
  114. $billDiscountTotalCents = $this->convertAmountToDefaultCurrency((int) $this->getRawOriginal('discount_total'));
  115. $remainingDiscountCents = $billDiscountTotalCents;
  116. foreach ($this->lineItems as $index => $lineItem) {
  117. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  118. $lineItemSubtotal = $this->formatAmountToDefaultCurrency($lineItem->getRawOriginal('subtotal'));
  119. $transaction->journalEntries()->create([
  120. 'company_id' => $this->company_id,
  121. 'type' => JournalEntryType::Debit,
  122. 'account_id' => $lineItem->offering->expense_account_id,
  123. 'amount' => $lineItemSubtotal,
  124. 'description' => $lineItemDescription,
  125. ]);
  126. foreach ($lineItem->adjustments as $adjustment) {
  127. $adjustmentAmount = $this->formatAmountToDefaultCurrency($lineItem->calculateAdjustmentTotalAmount($adjustment));
  128. if ($adjustment->isNonRecoverablePurchaseTax()) {
  129. $transaction->journalEntries()->create([
  130. 'company_id' => $this->company_id,
  131. 'type' => JournalEntryType::Debit,
  132. 'account_id' => $lineItem->offering->expense_account_id,
  133. 'amount' => $adjustmentAmount,
  134. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  135. ]);
  136. } elseif ($adjustment->account_id) {
  137. $transaction->journalEntries()->create([
  138. 'company_id' => $this->company_id,
  139. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  140. 'account_id' => $adjustment->account_id,
  141. 'amount' => $adjustmentAmount,
  142. 'description' => $lineItemDescription,
  143. ]);
  144. }
  145. }
  146. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalCents > 0) {
  147. $lineItemSubtotalCents = $this->convertAmountToDefaultCurrency((int) $lineItem->getRawOriginal('subtotal'));
  148. if ($index === $this->lineItems->count() - 1) {
  149. $lineItemDiscount = $remainingDiscountCents;
  150. } else {
  151. $lineItemDiscount = (int) round(
  152. ($lineItemSubtotalCents / $totalLineItemSubtotalCents) * $billDiscountTotalCents
  153. );
  154. $remainingDiscountCents -= $lineItemDiscount;
  155. }
  156. if ($lineItemDiscount > 0) {
  157. $transaction->journalEntries()->create([
  158. 'company_id' => $this->company_id,
  159. 'type' => JournalEntryType::Credit,
  160. 'account_id' => Account::getPurchaseDiscountAccount()->id,
  161. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  162. 'description' => "{$lineItemDescription} (Proportional Discount)",
  163. ]);
  164. }
  165. }
  166. }
  167. }
  168. public function updateInitialTransaction(): void
  169. {
  170. $transaction = $this->initialTransaction;
  171. if ($transaction) {
  172. $transaction->delete();
  173. }
  174. $this->createInitialTransaction();
  175. }
  176. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  177. {
  178. return $action::make()
  179. ->excludeAttributes([
  180. 'status',
  181. 'amount_paid',
  182. 'amount_due',
  183. 'created_by',
  184. 'updated_by',
  185. 'created_at',
  186. 'updated_at',
  187. 'bill_number',
  188. 'date',
  189. 'due_date',
  190. 'paid_at',
  191. ])
  192. ->modal(false)
  193. ->beforeReplicaSaved(function (self $original, self $replica) {
  194. $replica->status = BillStatus::Unpaid;
  195. $replica->bill_number = self::getNextDocumentNumber();
  196. $replica->date = now();
  197. $replica->due_date = now()->addDays($original->company->defaultBill->payment_terms->getDays());
  198. })
  199. ->databaseTransaction()
  200. ->after(function (self $original, self $replica) {
  201. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  202. $replicaLineItem = $lineItem->replicate([
  203. 'documentable_id',
  204. 'documentable_type',
  205. 'subtotal',
  206. 'total',
  207. 'created_by',
  208. 'updated_by',
  209. 'created_at',
  210. 'updated_at',
  211. ]);
  212. $replicaLineItem->documentable_id = $replica->id;
  213. $replicaLineItem->documentable_type = $replica->getMorphClass();
  214. $replicaLineItem->save();
  215. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  216. });
  217. })
  218. ->successRedirectUrl(static function (self $replica) {
  219. return BillResource::getUrl('edit', ['record' => $replica]);
  220. });
  221. }
  222. }