AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
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.

StoreGenerationController.php 6.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Billing\UsageLimits;
  4. use App\Commerce\ChatActions;
  5. use App\Enums\GenerationStatus;
  6. use App\Enums\GenerationType;
  7. use App\Jobs\RunStoreGeneration;
  8. use App\Models\Store;
  9. use App\Models\StoreGeneration;
  10. use App\StorePlan\Ai\PlanChanges;
  11. use Illuminate\Http\RedirectResponse;
  12. use Illuminate\Http\Request;
  13. use Illuminate\Validation\ValidationException;
  14. use Inertia\Inertia;
  15. /**
  16. * Starts AI jobs for a store. The work itself happens in the background (RunStoreGeneration).
  17. */
  18. class StoreGenerationController extends Controller
  19. {
  20. /**
  21. * Design the whole store with AI. The first design is free; later ones count as regenerations.
  22. */
  23. public function generate(Request $request, UsageLimits $usage, string $slug): RedirectResponse
  24. {
  25. $store = $this->ownedStore($request, $slug);
  26. $isRegeneration = $store->plan !== null;
  27. if ($this->isBusy($store)) {
  28. return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.'));
  29. }
  30. if (! $usage->hasPlan($request->user())) {
  31. return $this->refuse($store, __('Your free trial has ended. Choose a plan to keep using AI.'));
  32. }
  33. if ($isRegeneration && ! $usage->canRegenerate($request->user())) {
  34. return $this->refuse($store, __('You have used all the regenerations in your plan. Upgrade for more.'));
  35. }
  36. $this->start($request, $store, [
  37. 'type' => GenerationType::Generate,
  38. 'is_regeneration' => $isRegeneration,
  39. ]);
  40. return to_route('stores.show', $store->slug);
  41. }
  42. /**
  43. * Ask the AI for one small change, in plain words.
  44. */
  45. public function edit(Request $request, UsageLimits $usage, string $slug): RedirectResponse
  46. {
  47. $store = $this->ownedStore($request, $slug);
  48. abort_if($store->plan === null, 404);
  49. $validated = $request->validate([
  50. 'instruction' => ['required', 'string', 'min:3', 'max:500'],
  51. // The part of the store the merchant selected in the preview (optional).
  52. 'target_section' => ['nullable', 'string', 'max:64'],
  53. 'target_label' => ['nullable', 'required_with:target_section', 'string', 'max:80'],
  54. 'target_detail' => ['nullable', 'string', 'max:300'],
  55. ]);
  56. $target = null;
  57. if (filled($validated['target_section'] ?? null)) {
  58. if (PlanChanges::findSection($store->plan, $validated['target_section']) === null) {
  59. return back()->withErrors(['instruction' => __('That part of your store has changed. Please select it again.')]);
  60. }
  61. $target = [
  62. 'section' => $validated['target_section'],
  63. 'label' => $validated['target_label'],
  64. 'detail' => $validated['target_detail'] ?? null,
  65. ];
  66. }
  67. if ($this->isBusy($store)) {
  68. return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.'));
  69. }
  70. if (! $usage->canEdit($request->user())) {
  71. return $this->refuse($store, $usage->hasPlan($request->user())
  72. ? __('You have used all the AI edits in your plan. Upgrade for more.')
  73. : __('Your free trial has ended. Choose a plan to keep using AI.'));
  74. }
  75. $this->start($request, $store, [
  76. 'type' => GenerationType::Edit,
  77. 'instruction' => $validated['instruction'],
  78. 'target' => $target,
  79. ]);
  80. return to_route('stores.show', $store->slug);
  81. }
  82. /**
  83. * Do the store changes the AI proposed in a chat edit. They are checked again first,
  84. * and either all of them happen or none.
  85. */
  86. public function confirm(Request $request, string $slug, int $generation): RedirectResponse
  87. {
  88. $store = $this->ownedStore($request, $slug);
  89. $edit = $this->pendingActions($store, $generation);
  90. try {
  91. ChatActions::apply($store, $edit->actions ?? []);
  92. } catch (ValidationException $e) {
  93. // Something changed since the AI proposed it, such as a code made by hand in the meantime.
  94. return $this->refuse($store, __('Nothing was changed: :problem', ['problem' => collect($e->errors())->flatten()->first()]));
  95. }
  96. $edit->actions_status = StoreGeneration::ACTIONS_CONFIRMED;
  97. $edit->save();
  98. Inertia::flash('toast', ['type' => 'success', 'message' => __('Done. Your store is updated.')]);
  99. return to_route('stores.show', $store->slug);
  100. }
  101. public function cancel(Request $request, string $slug, int $generation): RedirectResponse
  102. {
  103. $store = $this->ownedStore($request, $slug);
  104. $edit = $this->pendingActions($store, $generation);
  105. $edit->actions_status = StoreGeneration::ACTIONS_CANCELLED;
  106. $edit->save();
  107. return to_route('stores.show', $store->slug);
  108. }
  109. private function pendingActions(Store $store, int $id): StoreGeneration
  110. {
  111. return $store->generations()
  112. ->whereKey($id)
  113. ->where('actions_status', StoreGeneration::ACTIONS_PENDING)
  114. ->firstOrFail();
  115. }
  116. /**
  117. * @param array<string, mixed> $attributes
  118. */
  119. private function start(Request $request, Store $store, array $attributes): void
  120. {
  121. $generation = $store->generations()->create([
  122. ...$attributes,
  123. 'user_id' => $request->user()->id,
  124. 'status' => GenerationStatus::Queued,
  125. ]);
  126. RunStoreGeneration::dispatch($generation->id);
  127. }
  128. /**
  129. * One AI job per store at a time.
  130. */
  131. private function isBusy(Store $store): bool
  132. {
  133. StoreGeneration::failStale($store->id);
  134. return $store->generations()->active()->exists();
  135. }
  136. private function refuse(Store $store, string $message): RedirectResponse
  137. {
  138. Inertia::flash('toast', ['type' => 'error', 'message' => $message]);
  139. return to_route('stores.show', $store->slug);
  140. }
  141. private function ownedStore(Request $request, string $slug): Store
  142. {
  143. return $request->user()->stores()->where('slug', $slug)->firstOrFail();
  144. }
  145. }