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.7KB

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