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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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('-2 months', '-1 day');
  31. return [
  32. 'company_id' => 1,
  33. 'client_id' => function (array $attributes) {
  34. return Client::where('company_id', $attributes['company_id'])->inRandomOrder()->value('id')
  35. ?? Client::factory()->state([
  36. 'company_id' => $attributes['company_id'],
  37. ]);
  38. },
  39. 'header' => 'Estimate',
  40. 'subheader' => 'Estimate',
  41. 'estimate_number' => $this->faker->unique()->numerify('EST-####'),
  42. 'reference_number' => $this->faker->unique()->numerify('REF-####'),
  43. 'date' => $estimateDate,
  44. 'expiration_date' => $this->faker->dateTimeInInterval($estimateDate, '+3 months'),
  45. 'status' => EstimateStatus::Draft,
  46. 'discount_method' => $this->faker->randomElement(DocumentDiscountMethod::class),
  47. 'discount_computation' => AdjustmentComputation::Percentage,
  48. 'discount_rate' => function (array $attributes) {
  49. $discountMethod = DocumentDiscountMethod::parse($attributes['discount_method']);
  50. if ($discountMethod?->isPerDocument()) {
  51. return $this->faker->numberBetween(50000, 200000); // 5% - 20%
  52. }
  53. return 0;
  54. },
  55. 'currency_code' => function (array $attributes) {
  56. $client = Client::find($attributes['client_id']);
  57. return $client->currency_code ??
  58. Company::find($attributes['company_id'])->default->currency_code ??
  59. 'USD';
  60. },
  61. 'terms' => $this->faker->sentence,
  62. 'footer' => $this->faker->sentence,
  63. 'created_by' => 1,
  64. 'updated_by' => 1,
  65. ];
  66. }
  67. public function withLineItems(int $count = 3): static
  68. {
  69. return $this->afterCreating(function (Estimate $estimate) use ($count) {
  70. // Clear existing line items first
  71. $estimate->lineItems()->delete();
  72. DocumentLineItem::factory()
  73. ->count($count)
  74. ->forEstimate($estimate)
  75. ->create();
  76. $this->recalculateTotals($estimate);
  77. });
  78. }
  79. public function approved(): static
  80. {
  81. return $this->afterCreating(function (Estimate $estimate) {
  82. $this->performApproval($estimate);
  83. });
  84. }
  85. public function accepted(): static
  86. {
  87. return $this->afterCreating(function (Estimate $estimate) {
  88. $this->performSent($estimate);
  89. $acceptedAt = Carbon::parse($estimate->last_sent_at)
  90. ->addDays($this->faker->numberBetween(1, 7));
  91. if ($acceptedAt->isAfter(now())) {
  92. $acceptedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->last_sent_at, now()));
  93. }
  94. $estimate->markAsAccepted($acceptedAt);
  95. });
  96. }
  97. public function converted(): static
  98. {
  99. return $this->afterCreating(function (Estimate $estimate) {
  100. if (! $estimate->wasAccepted()) {
  101. $this->performSent($estimate);
  102. $acceptedAt = Carbon::parse($estimate->last_sent_at)
  103. ->addDays($this->faker->numberBetween(1, 7));
  104. if ($acceptedAt->isAfter(now())) {
  105. $acceptedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->last_sent_at, now()));
  106. }
  107. $estimate->markAsAccepted($acceptedAt);
  108. }
  109. $convertedAt = Carbon::parse($estimate->accepted_at)
  110. ->addDays($this->faker->numberBetween(1, 7));
  111. if ($convertedAt->isAfter(now())) {
  112. $convertedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->accepted_at, now()));
  113. }
  114. $estimate->convertToInvoice($convertedAt);
  115. });
  116. }
  117. public function declined(): static
  118. {
  119. return $this->afterCreating(function (Estimate $estimate) {
  120. $this->performSent($estimate);
  121. $declinedAt = Carbon::parse($estimate->last_sent_at)
  122. ->addDays($this->faker->numberBetween(1, 7));
  123. if ($declinedAt->isAfter(now())) {
  124. $declinedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->last_sent_at, now()));
  125. }
  126. $estimate->markAsDeclined($declinedAt);
  127. });
  128. }
  129. public function sent(): static
  130. {
  131. return $this->afterCreating(function (Estimate $estimate) {
  132. $this->performSent($estimate);
  133. });
  134. }
  135. public function viewed(): static
  136. {
  137. return $this->afterCreating(function (Estimate $estimate) {
  138. $this->performSent($estimate);
  139. $viewedAt = Carbon::parse($estimate->last_sent_at)
  140. ->addHours($this->faker->numberBetween(1, 24));
  141. if ($viewedAt->isAfter(now())) {
  142. $viewedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->last_sent_at, now()));
  143. }
  144. $estimate->markAsViewed($viewedAt);
  145. });
  146. }
  147. public function expired(): static
  148. {
  149. return $this
  150. ->state([
  151. 'expiration_date' => now()->subDays($this->faker->numberBetween(1, 30)),
  152. ])
  153. ->afterCreating(function (Estimate $estimate) {
  154. $this->performApproval($estimate);
  155. });
  156. }
  157. protected function performApproval(Estimate $estimate): void
  158. {
  159. if (! $estimate->canBeApproved()) {
  160. throw new \InvalidArgumentException('Estimate cannot be approved. Current status: ' . $estimate->status->value);
  161. }
  162. $approvedAt = Carbon::parse($estimate->date)
  163. ->addHours($this->faker->numberBetween(1, 24));
  164. if ($approvedAt->isAfter(now())) {
  165. $approvedAt = Carbon::parse($this->faker->dateTimeBetween($estimate->date, now()));
  166. }
  167. $estimate->approveDraft($approvedAt);
  168. }
  169. protected function performSent(Estimate $estimate): void
  170. {
  171. if (! $estimate->wasApproved()) {
  172. $this->performApproval($estimate);
  173. }
  174. $sentAt = Carbon::parse($estimate->approved_at)
  175. ->addHours($this->faker->numberBetween(1, 24));
  176. if ($sentAt->isAfter(now())) {
  177. $sentAt = Carbon::parse($this->faker->dateTimeBetween($estimate->approved_at, now()));
  178. }
  179. $estimate->markAsSent($sentAt);
  180. }
  181. public function configure(): static
  182. {
  183. return $this->afterCreating(function (Estimate $estimate) {
  184. DocumentLineItem::factory()
  185. ->count(3)
  186. ->forEstimate($estimate)
  187. ->create();
  188. $this->recalculateTotals($estimate);
  189. $number = DocumentDefault::getBaseNumber() + $estimate->id;
  190. $estimate->updateQuietly([
  191. 'estimate_number' => "EST-{$number}",
  192. 'reference_number' => "REF-{$number}",
  193. ]);
  194. if ($estimate->wasApproved() && $estimate->shouldBeExpired()) {
  195. $estimate->updateQuietly([
  196. 'status' => EstimateStatus::Expired,
  197. ]);
  198. }
  199. });
  200. }
  201. protected function recalculateTotals(Estimate $estimate): void
  202. {
  203. $estimate->refresh();
  204. if (! $estimate->hasLineItems()) {
  205. return;
  206. }
  207. $subtotalCents = $estimate->lineItems()->sum('subtotal');
  208. $taxTotalCents = $estimate->lineItems()->sum('tax_total');
  209. $discountTotalCents = 0;
  210. if ($estimate->discount_method?->isPerLineItem()) {
  211. $discountTotalCents = $estimate->lineItems()->sum('discount_total');
  212. } elseif ($estimate->discount_method?->isPerDocument() && $estimate->discount_rate) {
  213. if ($estimate->discount_computation?->isPercentage()) {
  214. $scaledRate = RateCalculator::parseLocalizedRate($estimate->discount_rate);
  215. $discountTotalCents = RateCalculator::calculatePercentage($subtotalCents, $scaledRate);
  216. } else {
  217. $discountTotalCents = $estimate->getRawOriginal('discount_rate');
  218. }
  219. }
  220. $grandTotalCents = $subtotalCents + $taxTotalCents - $discountTotalCents;
  221. $estimate->update([
  222. 'subtotal' => $subtotalCents,
  223. 'tax_total' => $taxTotalCents,
  224. 'discount_total' => $discountTotalCents,
  225. 'total' => $grandTotalCents,
  226. ]);
  227. }
  228. }