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.

InvoiceFactory.php 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. <?php
  2. namespace Database\Factories\Accounting;
  3. use App\Enums\Accounting\InvoiceStatus;
  4. use App\Enums\Accounting\PaymentMethod;
  5. use App\Models\Accounting\DocumentLineItem;
  6. use App\Models\Accounting\Invoice;
  7. use App\Models\Banking\BankAccount;
  8. use App\Models\Common\Client;
  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<Invoice>
  15. */
  16. class InvoiceFactory extends Factory
  17. {
  18. /**
  19. * The name of the factory's corresponding model.
  20. */
  21. protected $model = Invoice::class;
  22. /**
  23. * Define the model's default state.
  24. *
  25. * @return array<string, mixed>
  26. */
  27. public function definition(): array
  28. {
  29. $invoiceDate = $this->faker->dateTimeBetween('-1 year');
  30. return [
  31. 'company_id' => 1,
  32. 'client_id' => Client::inRandomOrder()->value('id'),
  33. 'header' => 'Invoice',
  34. 'subheader' => 'Invoice',
  35. 'invoice_number' => $this->faker->unique()->numerify('INV-####'),
  36. 'order_number' => $this->faker->unique()->numerify('ORD-####'),
  37. 'date' => $invoiceDate,
  38. 'due_date' => Carbon::parse($invoiceDate)->addDays($this->faker->numberBetween(14, 60)),
  39. 'status' => InvoiceStatus::Draft,
  40. 'currency_code' => 'USD',
  41. 'terms' => $this->faker->sentence,
  42. 'footer' => $this->faker->sentence,
  43. 'created_by' => 1,
  44. 'updated_by' => 1,
  45. ];
  46. }
  47. public function withLineItems(int $count = 3): static
  48. {
  49. return $this->afterCreating(function (Invoice $invoice) use ($count) {
  50. DocumentLineItem::factory()
  51. ->count($count)
  52. ->forInvoice($invoice)
  53. ->create();
  54. $this->recalculateTotals($invoice);
  55. });
  56. }
  57. public function approved(): static
  58. {
  59. return $this->afterCreating(function (Invoice $invoice) {
  60. $this->ensureLineItems($invoice);
  61. if (! $invoice->canBeApproved()) {
  62. return;
  63. }
  64. $approvedAt = Carbon::parse($invoice->date)
  65. ->addHours($this->faker->numberBetween(1, 24));
  66. $invoice->approveDraft($approvedAt);
  67. });
  68. }
  69. public function sent(): static
  70. {
  71. return $this->afterCreating(function (Invoice $invoice) {
  72. $this->ensureApproved($invoice);
  73. $sentAt = Carbon::parse($invoice->approved_at)
  74. ->addHours($this->faker->numberBetween(1, 24));
  75. $invoice->markAsSent($sentAt);
  76. });
  77. }
  78. public function partial(int $maxPayments = 4): static
  79. {
  80. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  81. $this->ensureSent($invoice);
  82. $this->withPayments(max: $maxPayments, invoiceStatus: InvoiceStatus::Partial)
  83. ->callAfterCreating(collect([$invoice]));
  84. });
  85. }
  86. public function paid(int $maxPayments = 4): static
  87. {
  88. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  89. $this->ensureSent($invoice);
  90. $this->withPayments(max: $maxPayments)
  91. ->callAfterCreating(collect([$invoice]));
  92. });
  93. }
  94. public function overpaid(int $maxPayments = 4): static
  95. {
  96. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  97. $this->ensureSent($invoice);
  98. $this->withPayments(max: $maxPayments, invoiceStatus: InvoiceStatus::Overpaid)
  99. ->callAfterCreating(collect([$invoice]));
  100. });
  101. }
  102. public function overdue(): static
  103. {
  104. return $this
  105. ->state([
  106. 'due_date' => now()->subDays($this->faker->numberBetween(1, 30)),
  107. ])
  108. ->afterCreating(function (Invoice $invoice) {
  109. $this->ensureApproved($invoice);
  110. });
  111. }
  112. public function withPayments(?int $min = null, ?int $max = null, InvoiceStatus $invoiceStatus = InvoiceStatus::Paid): static
  113. {
  114. $min ??= 1;
  115. return $this->afterCreating(function (Invoice $invoice) use ($invoiceStatus, $max, $min) {
  116. $this->ensureSent($invoice);
  117. $invoice->refresh();
  118. $amountDue = $invoice->getRawOriginal('amount_due');
  119. $totalAmountDue = match ($invoiceStatus) {
  120. InvoiceStatus::Overpaid => $amountDue + random_int(1000, 10000),
  121. InvoiceStatus::Partial => (int) floor($amountDue * 0.5),
  122. default => $amountDue,
  123. };
  124. if ($totalAmountDue <= 0 || empty($totalAmountDue)) {
  125. return;
  126. }
  127. $paymentCount = $max && $min ? $this->faker->numberBetween($min, $max) : $min;
  128. $paymentAmount = (int) floor($totalAmountDue / $paymentCount);
  129. $remainingAmount = $totalAmountDue;
  130. $paymentDate = Carbon::parse($invoice->approved_at);
  131. $paymentDates = [];
  132. for ($i = 0; $i < $paymentCount; $i++) {
  133. $amount = $i === $paymentCount - 1 ? $remainingAmount : $paymentAmount;
  134. if ($amount <= 0) {
  135. break;
  136. }
  137. $postedAt = $paymentDate->copy()->addDays($this->faker->numberBetween(1, 30));
  138. $paymentDates[] = $postedAt;
  139. $data = [
  140. 'posted_at' => $postedAt,
  141. 'amount' => CurrencyConverter::convertCentsToFormatSimple($amount, $invoice->currency_code),
  142. 'payment_method' => $this->faker->randomElement(PaymentMethod::class),
  143. 'bank_account_id' => BankAccount::inRandomOrder()->value('id'),
  144. 'notes' => $this->faker->sentence,
  145. ];
  146. $invoice->recordPayment($data);
  147. $remainingAmount -= $amount;
  148. }
  149. if ($invoiceStatus !== InvoiceStatus::Paid) {
  150. return;
  151. }
  152. $latestPaymentDate = max($paymentDates);
  153. $invoice->updateQuietly([
  154. 'status' => $invoiceStatus,
  155. 'paid_at' => $latestPaymentDate,
  156. ]);
  157. });
  158. }
  159. public function configure(): static
  160. {
  161. return $this->afterCreating(function (Invoice $invoice) {
  162. $this->ensureLineItems($invoice);
  163. $number = DocumentDefault::getBaseNumber() + $invoice->id;
  164. $invoice->updateQuietly([
  165. 'invoice_number' => "INV-{$number}",
  166. 'order_number' => "ORD-{$number}",
  167. ]);
  168. if ($invoice->wasApproved() && $invoice->is_currently_overdue) {
  169. $invoice->updateQuietly([
  170. 'status' => InvoiceStatus::Overdue,
  171. ]);
  172. }
  173. });
  174. }
  175. protected function ensureLineItems(Invoice $invoice): void
  176. {
  177. if (! $invoice->hasLineItems()) {
  178. $this->withLineItems()->callAfterCreating(collect([$invoice]));
  179. }
  180. }
  181. protected function ensureApproved(Invoice $invoice): void
  182. {
  183. if (! $invoice->wasApproved()) {
  184. $this->approved()->callAfterCreating(collect([$invoice]));
  185. }
  186. }
  187. protected function ensureSent(Invoice $invoice): void
  188. {
  189. if (! $invoice->hasBeenSent()) {
  190. $this->sent()->callAfterCreating(collect([$invoice]));
  191. }
  192. }
  193. protected function recalculateTotals(Invoice $invoice): void
  194. {
  195. $invoice->refresh();
  196. if (! $invoice->hasLineItems()) {
  197. return;
  198. }
  199. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  200. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  201. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  202. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  203. $invoice->update([
  204. 'subtotal' => $subtotal,
  205. 'tax_total' => $taxTotal,
  206. 'discount_total' => $discountTotal,
  207. 'total' => $grandTotal,
  208. ]);
  209. }
  210. }