Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

BillFactory.php 7.0KB

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