選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Bill.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\RateCast;
  4. use App\Collections\Accounting\DocumentCollection;
  5. use App\Enums\Accounting\AdjustmentComputation;
  6. use App\Enums\Accounting\BillStatus;
  7. use App\Enums\Accounting\DocumentDiscountMethod;
  8. use App\Enums\Accounting\DocumentType;
  9. use App\Enums\Accounting\JournalEntryType;
  10. use App\Enums\Accounting\TransactionType;
  11. use App\Filament\Company\Resources\Purchases\BillResource;
  12. use App\Models\Banking\BankAccount;
  13. use App\Models\Common\Vendor;
  14. use App\Models\Company;
  15. use App\Models\Setting\DocumentDefault;
  16. use App\Observers\BillObserver;
  17. use App\Utilities\Currency\CurrencyAccessor;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use Filament\Actions\MountableAction;
  20. use Filament\Actions\ReplicateAction;
  21. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  22. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  23. use Illuminate\Database\Eloquent\Attributes\Scope;
  24. use Illuminate\Database\Eloquent\Builder;
  25. use Illuminate\Database\Eloquent\Model;
  26. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  27. use Illuminate\Database\Eloquent\Relations\MorphMany;
  28. use Illuminate\Database\Eloquent\Relations\MorphOne;
  29. use Illuminate\Support\Carbon;
  30. #[CollectedBy(DocumentCollection::class)]
  31. #[ObservedBy(BillObserver::class)]
  32. class Bill extends Document
  33. {
  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. ];
  66. public function vendor(): BelongsTo
  67. {
  68. return $this->belongsTo(Vendor::class);
  69. }
  70. public function transactions(): MorphMany
  71. {
  72. return $this->morphMany(Transaction::class, 'transactionable');
  73. }
  74. public function payments(): MorphMany
  75. {
  76. return $this->transactions()->where('is_payment', true);
  77. }
  78. public function deposits(): MorphMany
  79. {
  80. return $this->transactions()->where('type', TransactionType::Deposit)->where('is_payment', true);
  81. }
  82. public function withdrawals(): MorphMany
  83. {
  84. return $this->transactions()->where('type', TransactionType::Withdrawal)->where('is_payment', true);
  85. }
  86. public function initialTransaction(): MorphOne
  87. {
  88. return $this->morphOne(Transaction::class, 'transactionable')
  89. ->where('type', TransactionType::Journal);
  90. }
  91. public static function documentType(): DocumentType
  92. {
  93. return DocumentType::Bill;
  94. }
  95. public function documentNumber(): ?string
  96. {
  97. return $this->bill_number;
  98. }
  99. public function documentDate(): ?string
  100. {
  101. return $this->date?->toDefaultDateFormat();
  102. }
  103. public function dueDate(): ?string
  104. {
  105. return $this->due_date?->toDefaultDateFormat();
  106. }
  107. public function referenceNumber(): ?string
  108. {
  109. return $this->order_number;
  110. }
  111. public function amountDue(): ?string
  112. {
  113. return $this->amount_due;
  114. }
  115. public function shouldBeOverdue(): bool
  116. {
  117. return $this->due_date->isBefore(company_today()) && $this->canBeOverdue();
  118. }
  119. public function wasInitialized(): bool
  120. {
  121. return $this->hasInitialTransaction();
  122. }
  123. public function isPaid(): bool
  124. {
  125. return $this->paid_at !== null;
  126. }
  127. public function canBeOverdue(): bool
  128. {
  129. return in_array($this->status, BillStatus::canBeOverdue());
  130. }
  131. public function canRecordPayment(): bool
  132. {
  133. return ! in_array($this->status, [
  134. BillStatus::Paid,
  135. BillStatus::Void,
  136. ]);
  137. }
  138. public function hasPayments(): bool
  139. {
  140. return $this->payments->isNotEmpty();
  141. }
  142. public static function getNextDocumentNumber(?Company $company = null): string
  143. {
  144. $company ??= auth()->user()?->currentCompany;
  145. if (! $company) {
  146. throw new \RuntimeException('No current company is set for the user.');
  147. }
  148. $defaultBillSettings = $company->defaultBill;
  149. $numberPrefix = $defaultBillSettings->number_prefix ?? '';
  150. $latestDocument = static::query()
  151. ->whereNotNull('bill_number')
  152. ->latest('bill_number')
  153. ->first();
  154. $lastNumberNumericPart = $latestDocument
  155. ? (int) substr($latestDocument->bill_number, strlen($numberPrefix))
  156. : DocumentDefault::getBaseNumber();
  157. $numberNext = $lastNumberNumericPart + 1;
  158. return $defaultBillSettings->getNumberNext(
  159. prefix: $numberPrefix,
  160. next: $numberNext
  161. );
  162. }
  163. public function hasInitialTransaction(): bool
  164. {
  165. return $this->initialTransaction()->exists();
  166. }
  167. #[Scope]
  168. protected function unpaid(Builder $query): Builder
  169. {
  170. return $query->whereIn('status', [
  171. BillStatus::Open,
  172. BillStatus::Partial,
  173. BillStatus::Overdue,
  174. ]);
  175. }
  176. public function recordPayment(array $data): void
  177. {
  178. $transactionType = TransactionType::Withdrawal;
  179. $transactionDescription = "Bill #{$this->bill_number}: Payment to {$this->vendor->name}";
  180. // Add multi-currency handling
  181. $bankAccount = BankAccount::findOrFail($data['bank_account_id']);
  182. $bankAccountCurrency = $bankAccount->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  183. $billCurrency = $this->currency_code;
  184. $requiresConversion = $billCurrency !== $bankAccountCurrency;
  185. // Store the original payment amount in bill currency before any conversion
  186. $amountInBillCurrencyCents = $data['amount'];
  187. if ($requiresConversion) {
  188. $amountInBankCurrencyCents = CurrencyConverter::convertBalance(
  189. $amountInBillCurrencyCents,
  190. $billCurrency,
  191. $bankAccountCurrency
  192. );
  193. $formattedAmountForBankCurrency = $amountInBankCurrencyCents;
  194. } else {
  195. $formattedAmountForBankCurrency = $amountInBillCurrencyCents;
  196. }
  197. // Create transaction with converted amount
  198. $this->transactions()->create([
  199. 'company_id' => $this->company_id,
  200. 'type' => $transactionType,
  201. 'is_payment' => true,
  202. 'posted_at' => $data['posted_at'],
  203. 'amount' => $formattedAmountForBankCurrency,
  204. 'payment_method' => $data['payment_method'],
  205. 'bank_account_id' => $data['bank_account_id'],
  206. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  207. 'description' => $transactionDescription,
  208. 'notes' => $data['notes'] ?? null,
  209. 'meta' => [
  210. 'original_document_currency' => $billCurrency,
  211. 'amount_in_document_currency_cents' => $amountInBillCurrencyCents,
  212. ],
  213. ]);
  214. }
  215. public function createInitialTransaction(?Carbon $postedAt = null): void
  216. {
  217. $postedAt ??= $this->date;
  218. $baseDescription = "{$this->vendor->name}: Bill #{$this->bill_number}";
  219. $journalEntryData = [];
  220. $totalInBillCurrency = $this->total;
  221. $journalEntryData[] = [
  222. 'type' => JournalEntryType::Credit,
  223. 'account_id' => Account::getAccountsPayableAccount($this->company_id)->id,
  224. 'amount_in_bill_currency' => $totalInBillCurrency,
  225. 'description' => $baseDescription,
  226. ];
  227. $totalLineItemSubtotalInBillCurrency = (int) $this->lineItems()->sum('subtotal');
  228. $billDiscountTotalInBillCurrency = (int) $this->discount_total;
  229. $remainingDiscountInBillCurrency = $billDiscountTotalInBillCurrency;
  230. foreach ($this->lineItems as $index => $lineItem) {
  231. $lineItemDescription = "{$baseDescription} › {$lineItem->offering->name}";
  232. $lineItemSubtotalInBillCurrency = $lineItem->getRawOriginal('subtotal');
  233. $journalEntryData[] = [
  234. 'type' => JournalEntryType::Debit,
  235. 'account_id' => $lineItem->offering->expense_account_id,
  236. 'amount_in_bill_currency' => $lineItemSubtotalInBillCurrency,
  237. 'description' => $lineItemDescription,
  238. ];
  239. foreach ($lineItem->adjustments as $adjustment) {
  240. $adjustmentAmountInBillCurrency = $lineItem->calculateAdjustmentTotalAmount($adjustment);
  241. if ($adjustment->isNonRecoverablePurchaseTax()) {
  242. $journalEntryData[] = [
  243. 'type' => JournalEntryType::Debit,
  244. 'account_id' => $lineItem->offering->expense_account_id,
  245. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  246. 'description' => "{$lineItemDescription} ({$adjustment->name})",
  247. ];
  248. } elseif ($adjustment->account_id) {
  249. $journalEntryData[] = [
  250. 'type' => $adjustment->category->isDiscount() ? JournalEntryType::Credit : JournalEntryType::Debit,
  251. 'account_id' => $adjustment->account_id,
  252. 'amount_in_bill_currency' => $adjustmentAmountInBillCurrency,
  253. 'description' => $lineItemDescription,
  254. ];
  255. }
  256. }
  257. // Handle per-document discount allocation
  258. if ($this->discount_method->isPerDocument() && $totalLineItemSubtotalInBillCurrency > 0) {
  259. $lineItemSubtotalInBillCurrency = (int) $lineItem->getRawOriginal('subtotal');
  260. if ($index === $this->lineItems->count() - 1) {
  261. $lineItemDiscountInBillCurrency = $remainingDiscountInBillCurrency;
  262. } else {
  263. $lineItemDiscountInBillCurrency = (int) round(
  264. ($lineItemSubtotalInBillCurrency / $totalLineItemSubtotalInBillCurrency) * $billDiscountTotalInBillCurrency
  265. );
  266. $remainingDiscountInBillCurrency -= $lineItemDiscountInBillCurrency;
  267. }
  268. if ($lineItemDiscountInBillCurrency > 0) {
  269. $journalEntryData[] = [
  270. 'type' => JournalEntryType::Credit,
  271. 'account_id' => Account::getPurchaseDiscountAccount($this->company_id)->id,
  272. 'amount_in_bill_currency' => $lineItemDiscountInBillCurrency,
  273. 'description' => "{$lineItemDescription} (Proportional Discount)",
  274. ];
  275. }
  276. }
  277. }
  278. // Convert amounts to default currency
  279. $totalDebitsInDefaultCurrency = 0;
  280. $totalCreditsInDefaultCurrency = 0;
  281. foreach ($journalEntryData as &$entry) {
  282. $entry['amount_in_default_currency'] = $this->formatAmountToDefaultCurrency($entry['amount_in_bill_currency']);
  283. if ($entry['type'] === JournalEntryType::Debit) {
  284. $totalDebitsInDefaultCurrency += $entry['amount_in_default_currency'];
  285. } else {
  286. $totalCreditsInDefaultCurrency += $entry['amount_in_default_currency'];
  287. }
  288. }
  289. unset($entry);
  290. // Handle currency conversion imbalance
  291. $imbalance = $totalDebitsInDefaultCurrency - $totalCreditsInDefaultCurrency;
  292. if ($imbalance !== 0) {
  293. $targetType = $imbalance > 0 ? JournalEntryType::Credit : JournalEntryType::Debit;
  294. $adjustmentAmount = abs($imbalance);
  295. // Find last entry of target type and adjust it
  296. $lastKey = array_key_last(array_filter($journalEntryData, fn ($entry) => $entry['type'] === $targetType, ARRAY_FILTER_USE_BOTH));
  297. $journalEntryData[$lastKey]['amount_in_default_currency'] += $adjustmentAmount;
  298. if ($targetType === JournalEntryType::Debit) {
  299. $totalDebitsInDefaultCurrency += $adjustmentAmount;
  300. } else {
  301. $totalCreditsInDefaultCurrency += $adjustmentAmount;
  302. }
  303. }
  304. if ($totalDebitsInDefaultCurrency !== $totalCreditsInDefaultCurrency) {
  305. throw new \Exception('Journal entries do not balance for Bill #' . $this->bill_number . '. Debits: ' . $totalDebitsInDefaultCurrency . ', Credits: ' . $totalCreditsInDefaultCurrency);
  306. }
  307. // Create the transaction using the sum of debits
  308. $transaction = $this->transactions()->create([
  309. 'company_id' => $this->company_id,
  310. 'type' => TransactionType::Journal,
  311. 'posted_at' => $postedAt,
  312. 'amount' => $totalDebitsInDefaultCurrency,
  313. 'description' => 'Bill Creation for Bill #' . $this->bill_number,
  314. ]);
  315. // Create all journal entries
  316. foreach ($journalEntryData as $entry) {
  317. $transaction->journalEntries()->create([
  318. 'company_id' => $this->company_id,
  319. 'type' => $entry['type'],
  320. 'account_id' => $entry['account_id'],
  321. 'amount' => $entry['amount_in_default_currency'],
  322. 'description' => $entry['description'],
  323. ]);
  324. }
  325. }
  326. public function updateInitialTransaction(): void
  327. {
  328. $this->initialTransaction?->delete();
  329. $this->createInitialTransaction();
  330. }
  331. public function convertAmountToDefaultCurrency(int $amountCents): int
  332. {
  333. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  334. $needsConversion = $this->currency_code !== $defaultCurrency;
  335. if ($needsConversion) {
  336. return CurrencyConverter::convertBalance($amountCents, $this->currency_code, $defaultCurrency);
  337. }
  338. return $amountCents;
  339. }
  340. public function formatAmountToDefaultCurrency(int $amountCents): int
  341. {
  342. return $this->convertAmountToDefaultCurrency($amountCents);
  343. }
  344. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  345. {
  346. return $action::make()
  347. ->excludeAttributes([
  348. 'status',
  349. 'amount_paid',
  350. 'amount_due',
  351. 'created_by',
  352. 'updated_by',
  353. 'created_at',
  354. 'updated_at',
  355. 'bill_number',
  356. 'date',
  357. 'due_date',
  358. 'paid_at',
  359. ])
  360. ->modal(false)
  361. ->beforeReplicaSaved(function (self $original, self $replica) {
  362. $replica->status = BillStatus::Open;
  363. $replica->bill_number = self::getNextDocumentNumber();
  364. $replica->date = company_today();
  365. $replica->due_date = company_today()->addDays($original->company->defaultBill->payment_terms->getDays());
  366. })
  367. ->databaseTransaction()
  368. ->after(function (self $original, self $replica) {
  369. $original->replicateLineItems($replica);
  370. })
  371. ->successRedirectUrl(static function (self $replica) {
  372. return BillResource::getUrl('edit', ['record' => $replica]);
  373. });
  374. }
  375. public function replicateLineItems(Model $target): void
  376. {
  377. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  378. $replica = $lineItem->replicate([
  379. 'documentable_id',
  380. 'documentable_type',
  381. 'subtotal',
  382. 'total',
  383. 'created_by',
  384. 'updated_by',
  385. 'created_at',
  386. 'updated_at',
  387. ]);
  388. $replica->documentable_id = $target->id;
  389. $replica->documentable_type = $target->getMorphClass();
  390. $replica->save();
  391. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  392. });
  393. }
  394. }