| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- <?php
-
- namespace App\Jobs;
-
- use App\Ai\AiException;
- use App\Enums\GenerationStatus;
- use App\Enums\GenerationType;
- use App\Models\StoreGeneration;
- use App\StorePlan\Ai\PlanWriter;
- use Illuminate\Contracts\Queue\ShouldQueue;
- use Illuminate\Foundation\Queue\Queueable;
- use Throwable;
-
- /**
- * Runs one AI job in the background: a full store design or one chat edit.
- * The store's design only changes if the AI answer passes the store plan check.
- */
- class RunStoreGeneration implements ShouldQueue
- {
- use Queueable;
-
- /** AI calls cost money, so a failed job is never retried on its own. The merchant retries. */
- public int $tries = 1;
-
- /** Seconds. Must stay below DB_QUEUE_RETRY_AFTER in .env. */
- public int $timeout = 540;
-
- public function __construct(public int $generationId) {}
-
- public function handle(PlanWriter $writer): void
- {
- $generation = StoreGeneration::with('store')->find($this->generationId);
-
- if ($generation === null || $generation->status !== GenerationStatus::Queued) {
- return;
- }
-
- $generation->status = GenerationStatus::Running;
- $generation->started_at = now();
- $generation->save();
-
- try {
- $store = $generation->store;
-
- $result = $generation->type === GenerationType::Edit
- ? $writer->edit($store, (string) $generation->instruction)
- : $writer->generate($store);
-
- // Compare the design before and after, so the app (not the AI's reply) says whether anything changed.
- $changed = $result->plan != $store->plan;
-
- $store->plan = $result->plan;
- $store->save();
-
- $generation->status = GenerationStatus::Completed;
- $generation->reply = $result->reply;
- $generation->changed = $changed;
- $generation->provider = $result->provider;
- $generation->model = $result->model;
- $generation->input_tokens = $result->inputTokens;
- $generation->output_tokens = $result->outputTokens;
- $generation->finished_at = now();
- $generation->save();
- } catch (Throwable $e) {
- report($e);
-
- $generation->markFailed($e instanceof AiException
- ? $e->friendlyMessage()
- : 'Something went wrong. Please try again.');
- }
- }
-
- /**
- * Called when the job dies without reaching the catch block, for example on a timeout.
- */
- public function failed(?Throwable $e): void
- {
- StoreGeneration::query()
- ->whereKey($this->generationId)
- ->active()
- ->first()
- ?->markFailed('This took too long and was stopped. Please try again.');
- }
- }
|