AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

StoreController.php 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Billing\UsageLimits;
  4. use App\Enums\GenerationType;
  5. use App\Enums\StoreCategory;
  6. use App\Enums\StoreLanguage;
  7. use App\Http\Requests\Stores\CreateStoreRequest;
  8. use App\Models\Product;
  9. use App\Models\Store;
  10. use App\Models\StoreGeneration;
  11. use App\Storefront\Storefront;
  12. use App\StorePlan\FeaturedProducts;
  13. use App\StorePlan\HeroImages;
  14. use App\StorePlan\PlanSchema;
  15. use App\StorePlan\SectionEditor;
  16. use App\StorePlan\SectionLayouts;
  17. use Illuminate\Http\RedirectResponse;
  18. use Illuminate\Http\Request;
  19. use Inertia\Inertia;
  20. use Inertia\Response;
  21. class StoreController extends Controller
  22. {
  23. /**
  24. * Show the "create a store" form.
  25. */
  26. public function create(Request $request, UsageLimits $usage): Response|RedirectResponse
  27. {
  28. if (! $usage->canCreateStore($request->user())) {
  29. return $this->storeLimitReached($request, $usage);
  30. }
  31. return Inertia::render('stores/create', [
  32. 'categories' => StoreCategory::options(),
  33. 'languages' => StoreLanguage::options(),
  34. ]);
  35. }
  36. /**
  37. * Save a new store for the current user.
  38. */
  39. public function store(CreateStoreRequest $request, UsageLimits $usage): RedirectResponse
  40. {
  41. if (! $usage->canCreateStore($request->user())) {
  42. return $this->storeLimitReached($request, $usage);
  43. }
  44. $store = $request->user()->stores()->create($request->validated());
  45. Inertia::flash('toast', ['type' => 'success', 'message' => __('Store created.')]);
  46. return to_route('stores.show', $store->slug);
  47. }
  48. /**
  49. * Show one store. Looking it up through the user means other people's stores give a 404.
  50. */
  51. public function show(Request $request, UsageLimits $usage, string $slug): Response
  52. {
  53. $store = $request->user()->stores()->where('slug', $slug)->firstOrFail();
  54. StoreGeneration::failStale($store->id);
  55. $latest = $store->generations()->first();
  56. return Inertia::render('stores/show', [
  57. 'store' => $this->present($store),
  58. // The newest AI job. The page keeps refreshing while it is queued or running.
  59. 'generation' => $latest ? $this->presentGeneration($latest) : null,
  60. 'edits' => $store->generations()
  61. ->where('type', GenerationType::Edit)
  62. ->limit(5)
  63. ->get()
  64. ->map(fn (StoreGeneration $edit) => $this->presentGeneration($edit)),
  65. 'usage' => $usage->for($request->user()),
  66. // Featured product sections of the working design, and the products they can show.
  67. 'featuredSections' => $store->plan !== null ? FeaturedProducts::sections($store->plan) : [],
  68. // Hero sections of the working design, and the photos they can use.
  69. 'heroSections' => $store->plan !== null ? HeroImages::sections($store->plan) : [],
  70. 'heroChoices' => HeroImages::choices($store),
  71. // The design's style with every option filled in, and the ready-made looks to choose from.
  72. 'style' => $store->plan !== null ? [
  73. 'options' => [...PlanSchema::STYLE_DEFAULTS, ...($store->plan['theme']['style'] ?? [])],
  74. 'radius' => $store->plan['theme']['radius'] ?? 'medium',
  75. 'fonts' => $store->plan['theme']['fonts'] ?? null,
  76. ] : null,
  77. // Every section (heroes have their own box) with its layout, and the layouts each type allows.
  78. 'layoutSections' => $store->plan !== null ? SectionLayouts::sections($store->plan) : [],
  79. 'layoutOptions' => PlanSchema::SECTIONS,
  80. // For the Video and Bento boxes: those sections, and the home sections a new one can follow.
  81. 'videoSections' => $store->plan !== null ? array_map(fn (array $found) => [
  82. 'section_id' => $found['section']['id'],
  83. 'page_title' => $found['page_title'],
  84. 'variant' => $found['section']['variant'],
  85. ...$found['section']['content'],
  86. ], SectionEditor::ofType($store->plan, 'video')) : [],
  87. 'bentoSections' => $store->plan !== null ? array_map(fn (array $found) => [
  88. 'section_id' => $found['section']['id'],
  89. 'page_title' => $found['page_title'],
  90. 'variant' => $found['section']['variant'],
  91. 'heading' => $found['section']['content']['heading'] ?? null,
  92. 'tiles' => $found['section']['content']['tiles'] ?? [],
  93. ], SectionEditor::ofType($store->plan, 'bento')) : [],
  94. 'homeSections' => $store->plan !== null ? SectionEditor::homeSections($store->plan) : [],
  95. // Links a tile can point to, so the merchant picks instead of typing.
  96. 'linkSuggestions' => $store->plan !== null ? [
  97. ['href' => '/shop', 'label' => 'All products'],
  98. ...$store->collections()->get()->map(fn ($collection) => ['href' => '/collections/'.$collection->slug, 'label' => 'Collection: '.$collection->name])->all(),
  99. ...array_map(fn (array $page) => ['href' => '/'.$page['id'], 'label' => 'Page: '.$page['title']], array_slice($store->plan['pages'], 1)),
  100. ...array_map(fn (array $section) => ['href' => '#'.$section['id'], 'label' => 'Section: '.$section['label']], SectionEditor::homeSections($store->plan)),
  101. ] : [],
  102. 'stylePresets' => collect(PlanSchema::STYLE_PRESETS)
  103. ->map(fn (array $preset, string $key) => ['key' => $key, ...$preset])
  104. ->values(),
  105. 'productOptions' => $store->products()
  106. ->active()
  107. ->orderBy('name')
  108. ->get(['slug', 'name', 'price'])
  109. ->map(fn (Product $product) => ['slug' => $product->slug, 'name' => $product->name, 'price' => $product->price / 100]),
  110. ]);
  111. }
  112. /**
  113. * The plan does not allow another store. Send the user to the billing page with the reason.
  114. */
  115. private function storeLimitReached(Request $request, UsageLimits $usage): RedirectResponse
  116. {
  117. Inertia::flash('toast', ['type' => 'error', 'message' => $usage->hasPlan($request->user())
  118. ? __('Your plan does not allow more stores. Upgrade to add another.')
  119. : __('Your free trial has ended. Choose a plan to continue.')]);
  120. return to_route('billing');
  121. }
  122. /**
  123. * The store fields the frontend is allowed to see.
  124. *
  125. * @return array<string, mixed>
  126. */
  127. private function present(Store $store): array
  128. {
  129. return [
  130. 'id' => $store->id,
  131. 'name' => $store->name,
  132. 'slug' => $store->slug,
  133. 'category' => $store->category->value,
  134. 'category_label' => $store->category->label(),
  135. 'description' => $store->description,
  136. 'language' => $store->language->value,
  137. 'language_label' => $store->language->label(),
  138. 'status' => $store->status->value,
  139. 'status_label' => $store->status->label(),
  140. 'has_design' => $store->plan !== null,
  141. 'is_published' => $store->isPublished(),
  142. 'has_unpublished_changes' => $store->hasUnpublishedChanges(),
  143. 'published_at' => $store->published_at?->toIso8601String(),
  144. // Where shoppers open the store once it is published.
  145. 'live_url' => Storefront::liveUrl($store, request()),
  146. // Changes whenever the design is saved, so the preview knows to reload.
  147. 'design_version' => $store->updated_at?->getTimestamp(),
  148. 'created_at' => $store->created_at?->toIso8601String(),
  149. ];
  150. }
  151. /**
  152. * The AI job fields the frontend is allowed to see.
  153. *
  154. * @return array<string, mixed>
  155. */
  156. private function presentGeneration(StoreGeneration $generation): array
  157. {
  158. return [
  159. 'id' => $generation->id,
  160. 'type' => $generation->type->value,
  161. 'status' => $generation->status->value,
  162. 'instruction' => $generation->instruction,
  163. 'reply' => $generation->reply,
  164. 'changed' => $generation->changed,
  165. // Store changes waiting for (or given) the merchant's OK, in plain sentences.
  166. 'actions' => array_map(fn (array $action) => $action['summary'], $generation->actions ?? []),
  167. 'actions_status' => $generation->actions_status,
  168. 'error' => $generation->error,
  169. 'created_at' => $generation->created_at?->toIso8601String(),
  170. ];
  171. }
  172. }