ownedStore($request, $slug); $isRegeneration = $store->plan !== null; if ($this->isBusy($store)) { return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.')); } if ($isRegeneration && ! $usage->canRegenerate($request->user())) { return $this->refuse($store, __('You have used all the regenerations in your plan.')); } $this->start($request, $store, [ 'type' => GenerationType::Generate, 'is_regeneration' => $isRegeneration, ]); return to_route('stores.show', $store->slug); } /** * Ask the AI for one small change, in plain words. */ public function edit(Request $request, UsageLimits $usage, string $slug): RedirectResponse { $store = $this->ownedStore($request, $slug); abort_if($store->plan === null, 404); $validated = $request->validate([ 'instruction' => ['required', 'string', 'min:3', 'max:500'], ]); if ($this->isBusy($store)) { return $this->refuse($store, __('Your store is already being worked on. Please wait for it to finish.')); } if (! $usage->canEdit($request->user())) { return $this->refuse($store, __('You have used all the AI edits in your plan.')); } $this->start($request, $store, [ 'type' => GenerationType::Edit, 'instruction' => $validated['instruction'], ]); return to_route('stores.show', $store->slug); } /** * @param array $attributes */ private function start(Request $request, Store $store, array $attributes): void { $generation = $store->generations()->create([ ...$attributes, 'user_id' => $request->user()->id, 'status' => GenerationStatus::Queued, ]); RunStoreGeneration::dispatch($generation->id); } /** * One AI job per store at a time. */ private function isBusy(Store $store): bool { StoreGeneration::failStale($store->id); return $store->generations()->active()->exists(); } private function refuse(Store $store, string $message): RedirectResponse { Inertia::flash('toast', ['type' => 'error', 'message' => $message]); return to_route('stores.show', $store->slug); } private function ownedStore(Request $request, string $slug): Store { return $request->user()->stores()->where('slug', $slug)->firstOrFail(); } }