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

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