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

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