Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

InvoiceFactory.php 8.0KB

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