AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

StoreController.php 8.9KB

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