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

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