您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

InvoiceFactory.php 9.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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');
  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. DocumentLineItem::factory()
  74. ->count($count)
  75. ->forInvoice($invoice)
  76. ->create();
  77. $this->recalculateTotals($invoice);
  78. });
  79. }
  80. public function approved(): static
  81. {
  82. return $this->afterCreating(function (Invoice $invoice) {
  83. $this->performApproval($invoice);
  84. });
  85. }
  86. public function sent(): static
  87. {
  88. return $this->afterCreating(function (Invoice $invoice) {
  89. $this->performSent($invoice);
  90. });
  91. }
  92. public function partial(int $maxPayments = 4): static
  93. {
  94. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  95. $this->performSent($invoice);
  96. $this->performPayments($invoice, $maxPayments, InvoiceStatus::Partial);
  97. });
  98. }
  99. public function paid(int $maxPayments = 4): static
  100. {
  101. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  102. $this->performSent($invoice);
  103. $this->performPayments($invoice, $maxPayments, InvoiceStatus::Paid);
  104. });
  105. }
  106. public function overpaid(int $maxPayments = 4): static
  107. {
  108. return $this->afterCreating(function (Invoice $invoice) use ($maxPayments) {
  109. $this->performSent($invoice);
  110. $this->performPayments($invoice, $maxPayments, InvoiceStatus::Overpaid);
  111. });
  112. }
  113. public function overdue(): static
  114. {
  115. return $this
  116. ->state([
  117. 'due_date' => now()->subDays($this->faker->numberBetween(1, 30)),
  118. ])
  119. ->afterCreating(function (Invoice $invoice) {
  120. $this->performApproval($invoice);
  121. });
  122. }
  123. protected function performApproval(Invoice $invoice): void
  124. {
  125. if (! $invoice->hasLineItems()) {
  126. throw new \InvalidArgumentException('Cannot approve invoice without line items. Use withLineItems() first.');
  127. }
  128. if (! $invoice->canBeApproved()) {
  129. throw new \InvalidArgumentException('Invoice cannot be approved. Current status: ' . $invoice->status->value);
  130. }
  131. $approvedAt = Carbon::parse($invoice->date)
  132. ->addHours($this->faker->numberBetween(1, 24));
  133. $invoice->approveDraft($approvedAt);
  134. }
  135. protected function performSent(Invoice $invoice): void
  136. {
  137. if (! $invoice->wasApproved()) {
  138. $this->performApproval($invoice);
  139. }
  140. $sentAt = Carbon::parse($invoice->approved_at)
  141. ->addHours($this->faker->numberBetween(1, 24));
  142. $invoice->markAsSent($sentAt);
  143. }
  144. /**
  145. * @throws RandomException
  146. */
  147. protected function performPayments(Invoice $invoice, int $maxPayments, InvoiceStatus $invoiceStatus): void
  148. {
  149. $invoice->refresh();
  150. $amountDue = $invoice->getRawOriginal('amount_due');
  151. $totalAmountDue = match ($invoiceStatus) {
  152. InvoiceStatus::Overpaid => $amountDue + random_int(1000, 10000),
  153. InvoiceStatus::Partial => (int) floor($amountDue * 0.5),
  154. default => $amountDue,
  155. };
  156. if ($totalAmountDue <= 0 || empty($totalAmountDue)) {
  157. return;
  158. }
  159. $paymentCount = $this->faker->numberBetween(1, $maxPayments);
  160. $paymentAmount = (int) floor($totalAmountDue / $paymentCount);
  161. $remainingAmount = $totalAmountDue;
  162. $paymentDate = Carbon::parse($invoice->approved_at);
  163. $paymentDates = [];
  164. for ($i = 0; $i < $paymentCount; $i++) {
  165. $amount = $i === $paymentCount - 1 ? $remainingAmount : $paymentAmount;
  166. if ($amount <= 0) {
  167. break;
  168. }
  169. $postedAt = $paymentDate->copy()->addDays($this->faker->numberBetween(1, 30));
  170. $paymentDates[] = $postedAt;
  171. $data = [
  172. 'posted_at' => $postedAt,
  173. 'amount' => $amount,
  174. 'payment_method' => $this->faker->randomElement(PaymentMethod::class),
  175. 'bank_account_id' => BankAccount::where('company_id', $invoice->company_id)->inRandomOrder()->value('id'),
  176. 'notes' => $this->faker->sentence,
  177. ];
  178. $invoice->recordPayment($data);
  179. $remainingAmount -= $amount;
  180. }
  181. if ($invoiceStatus === InvoiceStatus::Paid && ! empty($paymentDates)) {
  182. $latestPaymentDate = max($paymentDates);
  183. $invoice->updateQuietly([
  184. 'status' => $invoiceStatus,
  185. 'paid_at' => $latestPaymentDate,
  186. ]);
  187. }
  188. }
  189. public function configure(): static
  190. {
  191. return $this->afterCreating(function (Invoice $invoice) {
  192. $number = DocumentDefault::getBaseNumber() + $invoice->id;
  193. $invoice->updateQuietly([
  194. 'invoice_number' => "INV-{$number}",
  195. 'order_number' => "ORD-{$number}",
  196. ]);
  197. if ($invoice->wasApproved() && $invoice->shouldBeOverdue()) {
  198. $invoice->updateQuietly([
  199. 'status' => InvoiceStatus::Overdue,
  200. ]);
  201. }
  202. });
  203. }
  204. protected function recalculateTotals(Invoice $invoice): void
  205. {
  206. $invoice->refresh();
  207. if (! $invoice->hasLineItems()) {
  208. return;
  209. }
  210. $subtotalCents = $invoice->lineItems()->sum('subtotal');
  211. $taxTotalCents = $invoice->lineItems()->sum('tax_total');
  212. $discountTotalCents = 0;
  213. if ($invoice->discount_method?->isPerLineItem()) {
  214. $discountTotalCents = $invoice->lineItems()->sum('discount_total');
  215. } elseif ($invoice->discount_method?->isPerDocument() && $invoice->discount_rate) {
  216. if ($invoice->discount_computation?->isPercentage()) {
  217. $scaledRate = RateCalculator::parseLocalizedRate($invoice->discount_rate);
  218. $discountTotalCents = RateCalculator::calculatePercentage($subtotalCents, $scaledRate);
  219. } else {
  220. $discountTotalCents = $invoice->getRawOriginal('discount_rate');
  221. }
  222. }
  223. $grandTotalCents = $subtotalCents + $taxTotalCents - $discountTotalCents;
  224. $invoice->update([
  225. 'subtotal' => $subtotalCents,
  226. 'tax_total' => $taxTotalCents,
  227. 'discount_total' => $discountTotalCents,
  228. 'total' => $grandTotalCents,
  229. ]);
  230. }
  231. }