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

RecurringInvoiceFactory.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. <?php
  2. namespace Database\Factories\Accounting;
  3. use App\Enums\Accounting\DayOfMonth;
  4. use App\Enums\Accounting\DayOfWeek;
  5. use App\Enums\Accounting\EndType;
  6. use App\Enums\Accounting\Frequency;
  7. use App\Enums\Accounting\IntervalType;
  8. use App\Enums\Accounting\Month;
  9. use App\Enums\Accounting\RecurringInvoiceStatus;
  10. use App\Enums\Setting\PaymentTerms;
  11. use App\Models\Accounting\DocumentLineItem;
  12. use App\Models\Accounting\RecurringInvoice;
  13. use App\Models\Common\Client;
  14. use App\Models\Company;
  15. use App\Utilities\Currency\CurrencyConverter;
  16. use Illuminate\Database\Eloquent\Factories\Factory;
  17. use Illuminate\Support\Carbon;
  18. /**
  19. * @extends Factory<RecurringInvoice>
  20. */
  21. class RecurringInvoiceFactory extends Factory
  22. {
  23. /**
  24. * The name of the factory's corresponding model.
  25. */
  26. protected $model = RecurringInvoice::class;
  27. /**
  28. * Define the model's default state.
  29. *
  30. * @return array<string, mixed>
  31. */
  32. public function definition(): array
  33. {
  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. 'order_number' => $this->faker->unique()->numerify('ORD-####'),
  40. 'payment_terms' => PaymentTerms::Net30,
  41. 'status' => RecurringInvoiceStatus::Draft,
  42. 'currency_code' => function (array $attributes) {
  43. $client = Client::find($attributes['client_id']);
  44. return $client->currency_code ??
  45. Company::find($attributes['company_id'])->default->currency_code ??
  46. 'USD';
  47. },
  48. 'terms' => $this->faker->sentence,
  49. 'footer' => $this->faker->sentence,
  50. 'created_by' => 1,
  51. 'updated_by' => 1,
  52. ];
  53. }
  54. public function withLineItems(int $count = 3): static
  55. {
  56. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($count) {
  57. DocumentLineItem::factory()
  58. ->count($count)
  59. ->forInvoice($recurringInvoice)
  60. ->create();
  61. $this->recalculateTotals($recurringInvoice);
  62. });
  63. }
  64. public function withSchedule(
  65. ?Frequency $frequency = null,
  66. ?Carbon $startDate = null,
  67. ?EndType $endType = null
  68. ): static {
  69. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($frequency, $endType, $startDate) {
  70. $this->ensureLineItems($recurringInvoice);
  71. $frequency ??= $this->faker->randomElement(Frequency::class);
  72. $endType ??= EndType::Never;
  73. // Adjust the start date range based on frequency
  74. $startDate = match ($frequency) {
  75. Frequency::Daily => Carbon::parse($this->faker->dateTimeBetween('-30 days')), // At most 30 days back
  76. default => $startDate ?? Carbon::parse($this->faker->dateTimeBetween('-1 year')),
  77. };
  78. $state = match ($frequency) {
  79. Frequency::Daily => $this->withDailySchedule($startDate, $endType),
  80. Frequency::Weekly => $this->withWeeklySchedule($startDate, $endType),
  81. Frequency::Monthly => $this->withMonthlySchedule($startDate, $endType),
  82. Frequency::Yearly => $this->withYearlySchedule($startDate, $endType),
  83. Frequency::Custom => $this->withCustomSchedule($startDate, $endType),
  84. };
  85. $state->callAfterCreating(collect([$recurringInvoice]));
  86. });
  87. }
  88. public function withDailySchedule(Carbon $startDate, EndType $endType): static
  89. {
  90. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($startDate, $endType) {
  91. $this->ensureLineItems($recurringInvoice);
  92. $recurringInvoice->updateQuietly([
  93. 'frequency' => Frequency::Daily,
  94. 'start_date' => $startDate,
  95. 'end_type' => $endType,
  96. ]);
  97. });
  98. }
  99. public function withWeeklySchedule(Carbon $startDate, EndType $endType): static
  100. {
  101. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($startDate, $endType) {
  102. $this->ensureLineItems($recurringInvoice);
  103. $recurringInvoice->updateQuietly([
  104. 'frequency' => Frequency::Weekly,
  105. 'day_of_week' => DayOfWeek::from($startDate->dayOfWeek),
  106. 'start_date' => $startDate,
  107. 'end_type' => $endType,
  108. ]);
  109. });
  110. }
  111. public function withMonthlySchedule(Carbon $startDate, EndType $endType): static
  112. {
  113. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($startDate, $endType) {
  114. $this->ensureLineItems($recurringInvoice);
  115. $recurringInvoice->updateQuietly([
  116. 'frequency' => Frequency::Monthly,
  117. 'day_of_month' => DayOfMonth::from($startDate->day),
  118. 'start_date' => $startDate,
  119. 'end_type' => $endType,
  120. ]);
  121. });
  122. }
  123. public function withYearlySchedule(Carbon $startDate, EndType $endType): static
  124. {
  125. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($startDate, $endType) {
  126. $this->ensureLineItems($recurringInvoice);
  127. $recurringInvoice->updateQuietly([
  128. 'frequency' => Frequency::Yearly,
  129. 'month' => Month::from($startDate->month),
  130. 'day_of_month' => DayOfMonth::from($startDate->day),
  131. 'start_date' => $startDate,
  132. 'end_type' => $endType,
  133. ]);
  134. });
  135. }
  136. public function withCustomSchedule(
  137. Carbon $startDate,
  138. EndType $endType,
  139. ?IntervalType $intervalType = null,
  140. ?int $intervalValue = null
  141. ): static {
  142. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) use ($intervalType, $intervalValue, $startDate, $endType) {
  143. $this->ensureLineItems($recurringInvoice);
  144. $intervalType ??= $this->faker->randomElement(IntervalType::class);
  145. $intervalValue ??= match ($intervalType) {
  146. IntervalType::Day => $this->faker->numberBetween(1, 7),
  147. IntervalType::Week => $this->faker->numberBetween(1, 4),
  148. IntervalType::Month => $this->faker->numberBetween(1, 3),
  149. IntervalType::Year => 1,
  150. };
  151. $state = [
  152. 'frequency' => Frequency::Custom,
  153. 'interval_type' => $intervalType,
  154. 'interval_value' => $intervalValue,
  155. 'start_date' => $startDate,
  156. 'end_type' => $endType,
  157. ];
  158. // Add interval-specific attributes
  159. switch ($intervalType) {
  160. case IntervalType::Day:
  161. // No additional attributes needed
  162. break;
  163. case IntervalType::Week:
  164. $state['day_of_week'] = DayOfWeek::from($startDate->dayOfWeek);
  165. break;
  166. case IntervalType::Month:
  167. $state['day_of_month'] = DayOfMonth::from($startDate->day);
  168. break;
  169. case IntervalType::Year:
  170. $state['month'] = Month::from($startDate->month);
  171. $state['day_of_month'] = DayOfMonth::from($startDate->day);
  172. break;
  173. }
  174. return $recurringInvoice->updateQuietly($state);
  175. });
  176. }
  177. public function endAfter(int $occurrences = 12): static
  178. {
  179. return $this->state([
  180. 'end_type' => EndType::After,
  181. 'max_occurrences' => $occurrences,
  182. ]);
  183. }
  184. public function endOn(?Carbon $endDate = null): static
  185. {
  186. $endDate ??= now()->addMonths($this->faker->numberBetween(1, 12));
  187. return $this->state([
  188. 'end_type' => EndType::On,
  189. 'end_date' => $endDate,
  190. ]);
  191. }
  192. public function autoSend(string $sendTime = '09:00'): static
  193. {
  194. return $this->state([
  195. 'auto_send' => true,
  196. 'send_time' => $sendTime,
  197. ]);
  198. }
  199. public function approved(): static
  200. {
  201. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) {
  202. $this->ensureLineItems($recurringInvoice);
  203. if (! $recurringInvoice->hasSchedule()) {
  204. $this->withSchedule()->callAfterCreating(collect([$recurringInvoice]));
  205. $recurringInvoice->refresh();
  206. }
  207. $approvedAt = $recurringInvoice->start_date
  208. ? $recurringInvoice->start_date->copy()->subDays($this->faker->numberBetween(1, 7))
  209. : now()->subDays($this->faker->numberBetween(1, 30));
  210. $recurringInvoice->approveDraft($approvedAt);
  211. });
  212. }
  213. public function active(): static
  214. {
  215. return $this->withLineItems()
  216. ->withSchedule()
  217. ->approved();
  218. }
  219. public function ended(): static
  220. {
  221. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) {
  222. $this->ensureLineItems($recurringInvoice);
  223. if (! $recurringInvoice->canBeEnded()) {
  224. $this->active()->callAfterCreating(collect([$recurringInvoice]));
  225. }
  226. $endedAt = $recurringInvoice->last_date
  227. ? $recurringInvoice->last_date->copy()->addDays($this->faker->numberBetween(1, 7))
  228. : now()->subDays($this->faker->numberBetween(1, 30));
  229. $recurringInvoice->updateQuietly([
  230. 'ended_at' => $endedAt,
  231. 'status' => RecurringInvoiceStatus::Ended,
  232. ]);
  233. });
  234. }
  235. public function configure(): static
  236. {
  237. return $this->afterCreating(function (RecurringInvoice $recurringInvoice) {
  238. $this->ensureLineItems($recurringInvoice);
  239. });
  240. }
  241. protected function ensureLineItems(RecurringInvoice $recurringInvoice): void
  242. {
  243. if (! $recurringInvoice->hasLineItems()) {
  244. $this->withLineItems()->callAfterCreating(collect([$recurringInvoice]));
  245. }
  246. }
  247. protected function recalculateTotals(RecurringInvoice $recurringInvoice): void
  248. {
  249. $recurringInvoice->refresh();
  250. if (! $recurringInvoice->hasLineItems()) {
  251. return;
  252. }
  253. $subtotalCents = $recurringInvoice->lineItems()->sum('subtotal');
  254. $taxTotalCents = $recurringInvoice->lineItems()->sum('tax_total');
  255. $discountTotalCents = $recurringInvoice->lineItems()->sum('discount_total');
  256. $grandTotalCents = $subtotalCents + $taxTotalCents - $discountTotalCents;
  257. $currencyCode = $recurringInvoice->currency_code;
  258. $recurringInvoice->update([
  259. 'subtotal' => CurrencyConverter::convertCentsToFormatSimple($subtotalCents, $currencyCode),
  260. 'tax_total' => CurrencyConverter::convertCentsToFormatSimple($taxTotalCents, $currencyCode),
  261. 'discount_total' => CurrencyConverter::convertCentsToFormatSimple($discountTotalCents, $currencyCode),
  262. 'total' => CurrencyConverter::convertCentsToFormatSimple($grandTotalCents, $currencyCode),
  263. ]);
  264. }
  265. }