您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Bill.php 12KB

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