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.

BillFactory.php 7.0KB

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