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.

EstimateFactory.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. <?php
  2. namespace Database\Factories\Accounting;
  3. use App\Enums\Accounting\AdjustmentComputation;
  4. use App\Enums\Accounting\DocumentDiscountMethod;
  5. use App\Enums\Accounting\EstimateStatus;
  6. use App\Models\Accounting\DocumentLineItem;
  7. use App\Models\Accounting\Estimate;
  8. use App\Models\Common\Client;
  9. use App\Models\Company;
  10. use App\Models\Setting\DocumentDefault;
  11. use App\Utilities\RateCalculator;
  12. use Illuminate\Database\Eloquent\Factories\Factory;
  13. use Illuminate\Support\Carbon;
  14. /**
  15. * @extends Factory<Estimate>
  16. */
  17. class EstimateFactory extends Factory
  18. {
  19. /**
  20. * The name of the factory's corresponding model.
  21. */
  22. protected $model = Estimate::class;
  23. /**
  24. * Define the model's default state.
  25. *
  26. * @return array<string, mixed>
  27. */
  28. public function definition(): array
  29. {
  30. $estimateDate = $this->faker->dateTimeBetween('-1 year');
  31. return [
  32. 'company_id' => 1,
  33. 'client_id' => fn (array $attributes) => Client::where('company_id', $attributes['company_id'])->inRandomOrder()->value('id'),
  34. 'header' => 'Estimate',
  35. 'subheader' => 'Estimate',
  36. 'estimate_number' => $this->faker->unique()->numerify('EST-####'),
  37. 'reference_number' => $this->faker->unique()->numerify('REF-####'),
  38. 'date' => $estimateDate,
  39. 'expiration_date' => Carbon::parse($estimateDate)->addDays($this->faker->numberBetween(14, 30)),
  40. 'status' => EstimateStatus::Draft,
  41. 'discount_method' => $this->faker->randomElement(DocumentDiscountMethod::class),
  42. 'discount_computation' => AdjustmentComputation::Percentage,
  43. 'discount_rate' => function (array $attributes) {
  44. $discountMethod = DocumentDiscountMethod::parse($attributes['discount_method']);
  45. if ($discountMethod?->isPerDocument()) {
  46. return $this->faker->numberBetween(50000, 200000); // 5% - 20%
  47. }
  48. return 0;
  49. },
  50. 'currency_code' => function (array $attributes) {
  51. $client = Client::find($attributes['client_id']);
  52. return $client->currency_code ??
  53. Company::find($attributes['company_id'])->default->currency_code ??
  54. 'USD';
  55. },
  56. 'terms' => $this->faker->sentence,
  57. 'footer' => $this->faker->sentence,
  58. 'created_by' => 1,
  59. 'updated_by' => 1,
  60. ];
  61. }
  62. public function withLineItems(int $count = 3): static
  63. {
  64. return $this->afterCreating(function (Estimate $estimate) use ($count) {
  65. DocumentLineItem::factory()
  66. ->count($count)
  67. ->forEstimate($estimate)
  68. ->create();
  69. $this->recalculateTotals($estimate);
  70. });
  71. }
  72. public function approved(): static
  73. {
  74. return $this->afterCreating(function (Estimate $estimate) {
  75. $this->ensureLineItems($estimate);
  76. if (! $estimate->canBeApproved()) {
  77. return;
  78. }
  79. $approvedAt = Carbon::parse($estimate->date)
  80. ->addHours($this->faker->numberBetween(1, 24));
  81. $estimate->approveDraft($approvedAt);
  82. });
  83. }
  84. public function accepted(): static
  85. {
  86. return $this->afterCreating(function (Estimate $estimate) {
  87. $this->ensureSent($estimate);
  88. $acceptedAt = Carbon::parse($estimate->last_sent_at)
  89. ->addDays($this->faker->numberBetween(1, 7));
  90. $estimate->markAsAccepted($acceptedAt);
  91. });
  92. }
  93. public function converted(): static
  94. {
  95. return $this->afterCreating(function (Estimate $estimate) {
  96. if (! $estimate->wasAccepted()) {
  97. $this->accepted()->callAfterCreating(collect([$estimate]));
  98. }
  99. $convertedAt = Carbon::parse($estimate->accepted_at)
  100. ->addDays($this->faker->numberBetween(1, 7));
  101. $estimate->convertToInvoice($convertedAt);
  102. });
  103. }
  104. public function declined(): static
  105. {
  106. return $this->afterCreating(function (Estimate $estimate) {
  107. $this->ensureSent($estimate);
  108. $declinedAt = Carbon::parse($estimate->last_sent_at)
  109. ->addDays($this->faker->numberBetween(1, 7));
  110. $estimate->markAsDeclined($declinedAt);
  111. });
  112. }
  113. public function sent(): static
  114. {
  115. return $this->afterCreating(function (Estimate $estimate) {
  116. $this->ensureApproved($estimate);
  117. $sentAt = Carbon::parse($estimate->approved_at)
  118. ->addHours($this->faker->numberBetween(1, 24));
  119. $estimate->markAsSent($sentAt);
  120. });
  121. }
  122. public function viewed(): static
  123. {
  124. return $this->afterCreating(function (Estimate $estimate) {
  125. $this->ensureSent($estimate);
  126. $viewedAt = Carbon::parse($estimate->last_sent_at)
  127. ->addHours($this->faker->numberBetween(1, 24));
  128. $estimate->markAsViewed($viewedAt);
  129. });
  130. }
  131. public function expired(): static
  132. {
  133. return $this
  134. ->state([
  135. 'expiration_date' => now()->subDays($this->faker->numberBetween(1, 30)),
  136. ])
  137. ->afterCreating(function (Estimate $estimate) {
  138. $this->ensureApproved($estimate);
  139. });
  140. }
  141. public function configure(): static
  142. {
  143. return $this->afterCreating(function (Estimate $estimate) {
  144. $this->ensureLineItems($estimate);
  145. $number = DocumentDefault::getBaseNumber() + $estimate->id;
  146. $estimate->updateQuietly([
  147. 'estimate_number' => "EST-{$number}",
  148. 'reference_number' => "REF-{$number}",
  149. ]);
  150. if ($estimate->wasApproved() && $estimate->shouldBeExpired()) {
  151. $estimate->updateQuietly([
  152. 'status' => EstimateStatus::Expired,
  153. ]);
  154. }
  155. });
  156. }
  157. protected function ensureLineItems(Estimate $estimate): void
  158. {
  159. if (! $estimate->hasLineItems()) {
  160. $this->withLineItems()->callAfterCreating(collect([$estimate]));
  161. }
  162. }
  163. protected function ensureApproved(Estimate $estimate): void
  164. {
  165. if (! $estimate->wasApproved()) {
  166. $this->approved()->callAfterCreating(collect([$estimate]));
  167. }
  168. }
  169. protected function ensureSent(Estimate $estimate): void
  170. {
  171. if (! $estimate->hasBeenSent()) {
  172. $this->sent()->callAfterCreating(collect([$estimate]));
  173. }
  174. }
  175. protected function recalculateTotals(Estimate $estimate): void
  176. {
  177. $estimate->refresh();
  178. if (! $estimate->hasLineItems()) {
  179. return;
  180. }
  181. $subtotalCents = $estimate->lineItems()->sum('subtotal');
  182. $taxTotalCents = $estimate->lineItems()->sum('tax_total');
  183. $discountTotalCents = 0;
  184. if ($estimate->discount_method?->isPerLineItem()) {
  185. $discountTotalCents = $estimate->lineItems()->sum('discount_total');
  186. } elseif ($estimate->discount_method?->isPerDocument() && $estimate->discount_rate) {
  187. if ($estimate->discount_computation?->isPercentage()) {
  188. $scaledRate = RateCalculator::parseLocalizedRate($estimate->discount_rate);
  189. $discountTotalCents = RateCalculator::calculatePercentage($subtotalCents, $scaledRate);
  190. } else {
  191. $discountTotalCents = $estimate->getRawOriginal('discount_rate');
  192. }
  193. }
  194. $grandTotalCents = $subtotalCents + $taxTotalCents - $discountTotalCents;
  195. $estimate->update([
  196. 'subtotal' => $subtotalCents,
  197. 'tax_total' => $taxTotalCents,
  198. 'discount_total' => $discountTotalCents,
  199. 'total' => $grandTotalCents,
  200. ]);
  201. }
  202. }