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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\MoneyCast;
  4. use App\Casts\RateCast;
  5. use App\Concerns\Blamable;
  6. use App\Concerns\CompanyOwned;
  7. use App\Enums\Accounting\AdjustmentComputation;
  8. use App\Enums\Accounting\BillStatus;
  9. use App\Enums\Accounting\DocumentDiscountMethod;
  10. use App\Enums\Accounting\JournalEntryType;
  11. use App\Enums\Accounting\TransactionType;
  12. use App\Filament\Company\Resources\Purchases\BillResource;
  13. use App\Models\Common\Vendor;
  14. use App\Observers\BillObserver;
  15. use App\Utilities\Currency\CurrencyConverter;
  16. use Filament\Actions\MountableAction;
  17. use Filament\Actions\ReplicateAction;
  18. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  19. use Illuminate\Database\Eloquent\Builder;
  20. use Illuminate\Database\Eloquent\Casts\Attribute;
  21. use Illuminate\Database\Eloquent\Factories\HasFactory;
  22. use Illuminate\Database\Eloquent\Model;
  23. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  24. use Illuminate\Database\Eloquent\Relations\MorphMany;
  25. use Illuminate\Database\Eloquent\Relations\MorphOne;
  26. use Illuminate\Support\Carbon;
  27. #[ObservedBy(BillObserver::class)]
  28. class Bill extends Model
  29. {
  30. use Blamable;
  31. use CompanyOwned;
  32. use HasFactory;
  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. 'subtotal' => MoneyCast::class,
  65. 'tax_total' => MoneyCast::class,
  66. 'discount_total' => MoneyCast::class,
  67. 'total' => MoneyCast::class,
  68. 'amount_paid' => MoneyCast::class,
  69. 'amount_due' => MoneyCast::class,
  70. ];
  71. public function vendor(): BelongsTo
  72. {
  73. return $this->belongsTo(Vendor::class);
  74. }
  75. public function lineItems(): MorphMany
  76. {
  77. return $this->morphMany(DocumentLineItem::class, 'documentable');
  78. }
  79. public function transactions(): MorphMany
  80. {
  81. return $this->morphMany(Transaction::class, 'transactionable');
  82. }
  83. public function payments(): MorphMany
  84. {
  85. return $this->transactions()->where('is_payment', true);
  86. }
  87. public function deposits(): MorphMany
  88. {
  89. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  90. }
  91. public function withdrawals(): MorphMany
  92. {
  93. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  94. }
  95. public function initialTransaction(): MorphOne
  96. {
  97. return $this->morphOne(Transaction::class, 'transactionable')
  98. ->where('type', TransactionType::Journal);
  99. }
  100. protected function isCurrentlyOverdue(): Attribute
  101. {
  102. return Attribute::get(function () {
  103. return $this->due_date->isBefore(today()) && $this->canBeOverdue();
  104. });
  105. }
  106. public function canBeOverdue(): bool
  107. {
  108. return in_array($this->status, BillStatus::canBeOverdue());
  109. }
  110. public function canRecordPayment(): bool
  111. {
  112. return ! in_array($this->status, [
  113. BillStatus::Paid,
  114. BillStatus::Void,
  115. ]);
  116. }
  117. public function hasPayments(): bool
  118. {
  119. return $this->payments->isNotEmpty();
  120. }
  121. public static function getNextDocumentNumber(): string
  122. {
  123. $company = auth()->user()->currentCompany;
  124. if (! $company) {
  125. throw new \RuntimeException('No current company is set for the user.');
  126. }
  127. $defaultBillSettings = $company->defaultBill;
  128. $numberPrefix = $defaultBillSettings->number_prefix;
  129. $numberDigits = $defaultBillSettings->number_digits;
  130. $latestDocument = static::query()
  131. ->whereNotNull('bill_number')
  132. ->latest('bill_number')
  133. ->first();
  134. $lastNumberNumericPart = $latestDocument
  135. ? (int) substr($latestDocument->bill_number, strlen($numberPrefix))
  136. : 0;
  137. $numberNext = $lastNumberNumericPart + 1;
  138. return $defaultBillSettings->getNumberNext(
  139. padded: true,
  140. format: true,
  141. prefix: $numberPrefix,
  142. digits: $numberDigits,
  143. next: $numberNext
  144. );
  145. }
  146. public function hasInitialTransaction(): bool
  147. {
  148. return $this->initialTransaction()->exists();
  149. }
  150. public function scopeOutstanding(Builder $query): Builder
  151. {
  152. return $query->whereIn('status', [
  153. BillStatus::Unpaid,
  154. BillStatus::Partial,
  155. BillStatus::Overdue,
  156. ]);
  157. }
  158. public function recordPayment(array $data): void
  159. {
  160. $transactionType = TransactionType::Withdrawal;
  161. $transactionDescription = "Bill #{$this->bill_number}: Payment to {$this->vendor->name}";
  162. // Create transaction
  163. $this->transactions()->create([
  164. 'company_id' => $this->company_id,
  165. 'type' => $transactionType,
  166. 'is_payment' => true,
  167. 'posted_at' => $data['posted_at'],
  168. 'amount' => $data['amount'],
  169. 'payment_method' => $data['payment_method'],
  170. 'bank_account_id' => $data['bank_account_id'],
  171. 'account_id' => Account::getAccountsPayableAccount()->id,
  172. 'description' => $transactionDescription,
  173. 'notes' => $data['notes'] ?? null,
  174. ]);
  175. }
  176. public function createInitialTransaction(?Carbon $postedAt = null): void
  177. {
  178. $postedAt ??= $this->date;
  179. $transaction = $this->transactions()->create([
  180. 'company_id' => $this->company_id,
  181. 'type' => TransactionType::Journal,
  182. 'posted_at' => $postedAt,
  183. 'amount' => $this->total,
  184. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  185. ]);
  186. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  187. $transaction->journalEntries()->create([
  188. 'company_id' => $this->company_id,
  189. 'type' => JournalEntryType::Credit,
  190. 'account_id' => Account::getAccountsPayableAccount()->id,
  191. 'amount' => $this->total,
  192. 'description' => $baseDescription,
  193. ]);
  194. $totalLineItemSubtotal = (int) $this->lineItems()->sum('subtotal');
  195. $billDiscountTotalCents = (int) $this->getRawOriginal('discount_total');
  196. $remainingDiscountCents = $billDiscountTotalCents;
  197. foreach ($this->lineItems as $index => $lineItem) {
  198. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  199. $transaction->journalEntries()->create([
  200. 'company_id' => $this->company_id,
  201. 'type' => JournalEntryType::Debit,
  202. 'account_id' => $lineItem->offering->expense_account_id,
  203. 'amount' => $lineItem->subtotal,
  204. 'description' => $lineItemDescription,
  205. ]);
  206. foreach ($lineItem->adjustments as $adjustment) {
  207. if ($adjustment->isNonRecoverablePurchaseTax()) {
  208. $transaction->journalEntries()->create([
  209. 'company_id' => $this->company_id,
  210. 'type' => JournalEntryType::Debit,
  211. 'account_id' => $lineItem->offering->expense_account_id,
  212. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  213. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  214. ]);
  215. } elseif ($adjustment->account_id) {
  216. $transaction->journalEntries()->create([
  217. 'company_id' => $this->company_id,
  218. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  219. 'account_id' => $adjustment->account_id,
  220. 'amount' => $lineItem->calculateAdjustmentTotal($adjustment)->getAmount(),
  221. 'description' => $lineItemDescription,
  222. ]);
  223. }
  224. }
  225. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotal > 0) {
  226. $lineItemSubtotalCents = (int) $lineItem->getRawOriginal('subtotal');
  227. if ($index === $this->lineItems->count() - 1) {
  228. $lineItemDiscount = $remainingDiscountCents;
  229. } else {
  230. $lineItemDiscount = (int) round(
  231. ($lineItemSubtotalCents / $totalLineItemSubtotal) * $billDiscountTotalCents
  232. );
  233. $remainingDiscountCents -= $lineItemDiscount;
  234. }
  235. if ($lineItemDiscount > 0) {
  236. $transaction->journalEntries()->create([
  237. 'company_id' => $this->company_id,
  238. 'type' => JournalEntryType::Credit,
  239. 'account_id' => Account::getPurchaseDiscountAccount()->id,
  240. 'amount' => CurrencyConverter::convertCentsToFormatSimple($lineItemDiscount),
  241. 'description' => "{$lineItemDescription} (Proportional Discount)",
  242. ]);
  243. }
  244. }
  245. }
  246. }
  247. public function updateInitialTransaction(): void
  248. {
  249. $transaction = $this->initialTransaction;
  250. if ($transaction) {
  251. $transaction->delete();
  252. }
  253. $this->createInitialTransaction();
  254. }
  255. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  256. {
  257. return $action::make()
  258. ->excludeAttributes([
  259. 'status',
  260. 'amount_paid',
  261. 'amount_due',
  262. 'created_by',
  263. 'updated_by',
  264. 'created_at',
  265. 'updated_at',
  266. 'bill_number',
  267. 'date',
  268. 'due_date',
  269. 'paid_at',
  270. ])
  271. ->modal(false)
  272. ->beforeReplicaSaved(function (self $original, self $replica) {
  273. $replica->status = BillStatus::Unpaid;
  274. $replica->bill_number = self::getNextDocumentNumber();
  275. $replica->date = now();
  276. $replica->due_date = now()->addDays($original->company->defaultBill->payment_terms->getDays());
  277. })
  278. ->databaseTransaction()
  279. ->after(function (self $original, self $replica) {
  280. $original->lineItems->each(function (DocumentLineItem $lineItem) use ($replica) {
  281. $replicaLineItem = $lineItem->replicate([
  282. 'documentable_id',
  283. 'documentable_type',
  284. 'subtotal',
  285. 'total',
  286. 'created_by',
  287. 'updated_by',
  288. 'created_at',
  289. 'updated_at',
  290. ]);
  291. $replicaLineItem->documentable_id = $replica->id;
  292. $replicaLineItem->documentable_type = $replica->getMorphClass();
  293. $replicaLineItem->save();
  294. $replicaLineItem->adjustments()->sync($lineItem->adjustments->pluck('id'));
  295. });
  296. })
  297. ->successRedirectUrl(static function (self $replica) {
  298. return BillResource::getUrl('edit', ['record' => $replica]);
  299. });
  300. }
  301. }