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

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