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

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