選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

InvoiceFactory.php 10.0KB

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