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

BillFactory.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. <?php
  2. namespace Database\Factories\Accounting;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Models\Accounting\Bill;
  6. use App\Models\Accounting\DocumentLineItem;
  7. use App\Models\Banking\BankAccount;
  8. use App\Models\Common\Vendor;
  9. use App\Models\Company;
  10. use App\Models\Setting\DocumentDefault;
  11. use App\Utilities\Currency\CurrencyConverter;
  12. use Illuminate\Database\Eloquent\Factories\Factory;
  13. use Illuminate\Support\Carbon;
  14. /**
  15. * @extends Factory<Bill>
  16. */
  17. class BillFactory extends Factory
  18. {
  19. /**
  20. * The name of the factory's corresponding model.
  21. */
  22. protected $model = Bill::class;
  23. /**
  24. * Define the model's default state.
  25. *
  26. * @return array<string, mixed>
  27. */
  28. public function definition(): array
  29. {
  30. $isFutureBill = $this->faker->boolean();
  31. if ($isFutureBill) {
  32. $billDate = $this->faker->dateTimeBetween('-10 days', '+10 days');
  33. } else {
  34. $billDate = $this->faker->dateTimeBetween('-1 year', '-30 days');
  35. }
  36. $dueDays = $this->faker->numberBetween(14, 60);
  37. return [
  38. 'company_id' => 1,
  39. 'vendor_id' => fn (array $attributes) => Vendor::where('company_id', $attributes['company_id'])->inRandomOrder()->value('id'),
  40. 'bill_number' => $this->faker->unique()->numerify('BILL-####'),
  41. 'order_number' => $this->faker->unique()->numerify('PO-####'),
  42. 'date' => $billDate,
  43. 'due_date' => Carbon::parse($billDate)->addDays($dueDays),
  44. 'status' => BillStatus::Open,
  45. 'currency_code' => function (array $attributes) {
  46. $vendor = Vendor::find($attributes['vendor_id']);
  47. return $vendor->currency_code ??
  48. Company::find($attributes['company_id'])->default->currency_code ??
  49. 'USD';
  50. },
  51. 'notes' => $this->faker->sentence,
  52. 'created_by' => 1,
  53. 'updated_by' => 1,
  54. ];
  55. }
  56. public function withLineItems(int $count = 3): static
  57. {
  58. return $this->afterCreating(function (Bill $bill) use ($count) {
  59. DocumentLineItem::factory()
  60. ->count($count)
  61. ->forBill($bill)
  62. ->create();
  63. $this->recalculateTotals($bill);
  64. });
  65. }
  66. public function initialized(): static
  67. {
  68. return $this->afterCreating(function (Bill $bill) {
  69. $this->ensureLineItems($bill);
  70. if ($bill->wasInitialized()) {
  71. return;
  72. }
  73. $postedAt = Carbon::parse($bill->date)
  74. ->addHours($this->faker->numberBetween(1, 24));
  75. $bill->createInitialTransaction($postedAt);
  76. });
  77. }
  78. public function partial(int $maxPayments = 4): static
  79. {
  80. return $this->afterCreating(function (Bill $bill) use ($maxPayments) {
  81. $this->ensureInitialized($bill);
  82. $this->withPayments(max: $maxPayments, billStatus: BillStatus::Partial)
  83. ->callAfterCreating(collect([$bill]));
  84. });
  85. }
  86. public function paid(int $maxPayments = 4): static
  87. {
  88. return $this->afterCreating(function (Bill $bill) use ($maxPayments) {
  89. $this->ensureInitialized($bill);
  90. $this->withPayments(max: $maxPayments)
  91. ->callAfterCreating(collect([$bill]));
  92. });
  93. }
  94. public function overdue(): static
  95. {
  96. return $this
  97. ->state([
  98. 'due_date' => now()->subDays($this->faker->numberBetween(1, 30)),
  99. ])
  100. ->afterCreating(function (Bill $bill) {
  101. $this->ensureInitialized($bill);
  102. });
  103. }
  104. public function withPayments(?int $min = null, ?int $max = null, BillStatus $billStatus = BillStatus::Paid): static
  105. {
  106. $min ??= 1;
  107. return $this->afterCreating(function (Bill $bill) use ($billStatus, $max, $min) {
  108. $this->ensureInitialized($bill);
  109. $bill->refresh();
  110. $amountDue = $bill->getRawOriginal('amount_due');
  111. $totalAmountDue = match ($billStatus) {
  112. BillStatus::Partial => (int) floor($amountDue * 0.5),
  113. default => $amountDue,
  114. };
  115. if ($totalAmountDue <= 0 || empty($totalAmountDue)) {
  116. return;
  117. }
  118. $paymentCount = $max && $min ? $this->faker->numberBetween($min, $max) : $min;
  119. $paymentAmount = (int) floor($totalAmountDue / $paymentCount);
  120. $remainingAmount = $totalAmountDue;
  121. $paymentDate = Carbon::parse($bill->initialTransaction->posted_at);
  122. $paymentDates = [];
  123. for ($i = 0; $i < $paymentCount; $i++) {
  124. $amount = $i === $paymentCount - 1 ? $remainingAmount : $paymentAmount;
  125. if ($amount <= 0) {
  126. break;
  127. }
  128. $postedAt = $paymentDate->copy()->addDays($this->faker->numberBetween(1, 30));
  129. $paymentDates[] = $postedAt;
  130. $data = [
  131. 'posted_at' => $postedAt,
  132. 'amount' => CurrencyConverter::convertCentsToFormatSimple($amount, $bill->currency_code),
  133. 'payment_method' => $this->faker->randomElement(PaymentMethod::class),
  134. 'bank_account_id' => BankAccount::where('company_id', $bill->company_id)->inRandomOrder()->value('id'),
  135. 'notes' => $this->faker->sentence,
  136. ];
  137. $bill->recordPayment($data);
  138. $remainingAmount -= $amount;
  139. }
  140. if ($billStatus !== BillStatus::Paid) {
  141. return;
  142. }
  143. $latestPaymentDate = max($paymentDates);
  144. $bill->updateQuietly([
  145. 'status' => $billStatus,
  146. 'paid_at' => $latestPaymentDate,
  147. ]);
  148. });
  149. }
  150. public function configure(): static
  151. {
  152. return $this->afterCreating(function (Bill $bill) {
  153. $this->ensureInitialized($bill);
  154. $number = DocumentDefault::getBaseNumber() + $bill->id;
  155. $bill->updateQuietly([
  156. 'bill_number' => "BILL-{$number}",
  157. 'order_number' => "PO-{$number}",
  158. ]);
  159. if ($bill->wasInitialized() && $bill->is_currently_overdue) {
  160. $bill->updateQuietly([
  161. 'status' => BillStatus::Overdue,
  162. ]);
  163. }
  164. });
  165. }
  166. protected function ensureLineItems(Bill $bill): void
  167. {
  168. if (! $bill->hasLineItems()) {
  169. $this->withLineItems()->callAfterCreating(collect([$bill]));
  170. }
  171. }
  172. protected function ensureInitialized(Bill $bill): void
  173. {
  174. if (! $bill->wasInitialized()) {
  175. $this->initialized()->callAfterCreating(collect([$bill]));
  176. }
  177. }
  178. protected function recalculateTotals(Bill $bill): void
  179. {
  180. $bill->refresh();
  181. if (! $bill->hasLineItems()) {
  182. return;
  183. }
  184. $subtotalCents = $bill->lineItems()->sum('subtotal');
  185. $taxTotalCents = $bill->lineItems()->sum('tax_total');
  186. $discountTotalCents = $bill->lineItems()->sum('discount_total');
  187. $grandTotalCents = $subtotalCents + $taxTotalCents - $discountTotalCents;
  188. $currencyCode = $bill->currency_code;
  189. $bill->update([
  190. 'subtotal' => CurrencyConverter::convertCentsToFormatSimple($subtotalCents, $currencyCode),
  191. 'tax_total' => CurrencyConverter::convertCentsToFormatSimple($taxTotalCents, $currencyCode),
  192. 'discount_total' => CurrencyConverter::convertCentsToFormatSimple($discountTotalCents, $currencyCode),
  193. 'total' => CurrencyConverter::convertCentsToFormatSimple($grandTotalCents, $currencyCode),
  194. ]);
  195. }
  196. }