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

Bill.php 15KB

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