Procházet zdrojové kódy

Add collections, shop by, bento and video sections

- Collections in the Products tab or by chat, with their own pages and links
- Shop by section: collections as round photos or tiles
- Bento section: 3-6 tiles of different sizes, with photos or brand colours
- Video section: YouTube or Vimeo, loads only when the shopper presses play
- Video and Bento boxes in the Design tab to add and edit without chat
- All Design tab boxes fold open and closed, with arrows
- AI only uses real collections and video links the merchant gave
- Reviews moved to part 8; main and redesign kept apart for comparison
redesign/part-7-collections-bento-video
fahmisaad před 4 dny
rodič
revize
255c51c4ce
44 změnil soubory, kde provedl 3275 přidání a 230 odebrání
  1. 51
    36
      PROGRESS.md
  2. 2
    1
      README.md
  3. 46
    1
      app/Commerce/ChatActions.php
  4. 109
    0
      app/Http/Controllers/BentoSectionController.php
  5. 146
    0
      app/Http/Controllers/CollectionController.php
  6. 57
    0
      app/Http/Controllers/Concerns/EditsDesignSections.php
  7. 9
    0
      app/Http/Controllers/Concerns/RendersStorefront.php
  8. 8
    0
      app/Http/Controllers/ProductController.php
  9. 23
    0
      app/Http/Controllers/StoreController.php
  10. 19
    0
      app/Http/Controllers/StoreDesignController.php
  11. 83
    0
      app/Http/Controllers/VideoSectionController.php
  12. 77
    0
      app/Models/Collection.php
  13. 10
    0
      app/Models/Store.php
  14. 33
    0
      app/StorePlan/Ai/PlanPrompt.php
  15. 71
    3
      app/StorePlan/Ai/PlanWriter.php
  16. 29
    1
      app/StorePlan/HeroImages.php
  17. 37
    2
      app/StorePlan/PlanSchema.php
  18. 23
    0
      app/StorePlan/SamplePlan.php
  19. 166
    0
      app/StorePlan/SectionEditor.php
  20. 40
    0
      database/migrations/2026_11_21_000001_create_collections_table.php
  21. 432
    0
      resources/js/components/stores/bento-box.tsx
  22. 87
    78
      resources/js/components/stores/featured-picker.tsx
  23. 22
    16
      resources/js/components/stores/hero-picker.tsx
  24. 15
    2
      resources/js/components/stores/layout-picker.tsx
  25. 87
    80
      resources/js/components/stores/style-picker.tsx
  26. 298
    0
      resources/js/components/stores/video-box.tsx
  27. 249
    0
      resources/js/pages/stores/collections/form.tsx
  28. 5
    3
      resources/js/pages/stores/preview.tsx
  29. 62
    1
      resources/js/pages/stores/products/index.tsx
  30. 33
    0
      resources/js/pages/stores/show.tsx
  31. 1
    0
      resources/js/storefront/context.tsx
  32. 87
    2
      resources/js/storefront/pages/shop.tsx
  33. 19
    1
      resources/js/storefront/renderer.tsx
  34. 118
    0
      resources/js/storefront/sections/bento.tsx
  35. 120
    0
      resources/js/storefront/sections/shop-by.tsx
  36. 119
    0
      resources/js/storefront/sections/video.tsx
  37. 4
    0
      resources/js/storefront/text.ts
  38. 58
    1
      resources/js/storefront/types.ts
  39. 34
    0
      resources/js/types/store.ts
  40. 17
    0
      routes/web.php
  41. 205
    0
      tests/Feature/Stores/CollectionsBentoVideoTest.php
  42. 161
    0
      tests/Feature/Stores/DesignSectionBoxesTest.php
  43. 2
    1
      tests/Feature/Stores/PlanValidatorTest.php
  44. 1
    1
      tests/Feature/Stores/StoreDesignTest.php

+ 51
- 36
PROGRESS.md Zobrazit soubor

@@ -4,8 +4,8 @@ This file is the single source of truth for the project plan and status.
4 4
 Update it at the end of every work session.
5 5
 
6 6
 **Last updated:** 2026-11-21
7
-**Current step:** Step 9 — Modern store design (parts 1–6 done; next: part 7, collections, bento, video and reviews)
8
-**Next action:** Commit part 6 on `redesign/part-6-category-guides` (do not merge into `main` yet). Then decide: part 7 (collections, bento, video, reviews) on `redesign/part-7-...`, or merge the redesign into `main` first. Step 7 part 2 still waits for an EasyParcel API key
7
+**Current step:** Step 9 — Modern store design (parts 1–7 done; next: part 8, real reviews)
8
+**Next action:** Commit part 7 on `redesign/part-7-collections-bento-video` (do not merge into `main`; it stays separate for comparison). Then create `redesign/part-8-reviews` from it and build real reviews. Step 7 part 2 still waits for an EasyParcel API key
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -246,6 +246,15 @@ Changing from Claude to another AI model (or back) must be a settings change, no
246 246
 - The Design tab has a **Layouts** box (closed by default) listing every section with its layout in plain words; heroes stay in their own Hero box. `App\StorePlan\SectionLayouts` finds and changes them; only layouts of the section's own type are accepted.
247 247
 - The AI is told what each new layout looks like and when it suits, and can switch layouts by chat ("make the products slide sideways").
248 248
 
249
+### How collections, bento and video work (added in Step 9 part 7)
250
+
251
+- **Collections** (`collections`, `collection_product`): groups of products such as "Sun care". Managed in a Collections box on the Products tab (name, short description, products) or by chat (`create_collection`, with the confirm step). The address `/collections/{slug}` is set when created and kept when renamed, so links keep working. Deleting a collection never deletes products.
252
+- Shoppers get a page per collection (`/collections/{slug}`, also in the preview) and links between collections on the shop page. Only collections with at least one active product are shown. `collections` is now a built-in address and cannot be a page id.
253
+- **Shop by** section (`shop_by`): the collections as round photos (`circles`) or photo tiles (`tiles`); the photo is the first active product's photo. It names collections in order, or shows all with an empty list, and shows nothing until a collection has products. The AI only adds it when given the list of collections; a made-up collection name goes back to it once.
254
+- **Bento** section (`bento`): 3 to 6 tiles, each with title, optional text, a link, and a photo name (like a hero's) or a colour (primary, accent, dark, surface). `mosaic` makes the first tile big; `even` makes them equal. Bento photos are resolved with hero photos (`HeroImages::refs`).
255
+- **Video** section (`video`): a YouTube or Vimeo address only (`PlanSchema::VIDEO_PATTERN`, which refuses look-alike addresses). Only a picture shows until the shopper presses play; then a privacy-friendly player loads (youtube-nocookie, Vimeo with do-not-track). The AI may only use a video address the merchant wrote in the chat or the brand description; any other is refused. The sample design has no video on purpose, so the AI never copies one. Uploading video files is not supported yet.
256
+- **Design tab boxes (added 2026-11-22):** a **Video** box (paste a YouTube or Vimeo link, heading, short text, layout, and where to put it; edit or remove later, with a preview picture) and a **Bento tiles** box ("Add tiles" puts in 3 starter tiles: the whole range with a product photo, the first collection or the products section, and the brand story; then edit each tile's title, text, link (with suggested links), photo and colour, add or remove tiles between 3 and 6, or remove the set). Both use `App\StorePlan\SectionEditor` and go through the plan checker, so a broken link or a photo from another store is refused.
257
+
249 258
 ### Category guides for the AI (agreed 2026-11-17)
250 259
 
251 260
 - The category the merchant picks on the Create store page (Fashion, Beauty, Food, Home, Electronics, Health, Kids, Digital, Other) chooses a short design guide that is sent to the AI with the brand description.
@@ -394,13 +403,15 @@ Agreed on 2026-11-17 after comparing our stores with 2026 design trends (researc
394 403
 - [x] Part 4 — Style options and motion (done 2026-11-19): six style options (buttons, cards, spacing, headings, backgrounds, motion), six ready-made looks in a Style box in the Design tab, 12 more fonts (20 in all), gentle fade-in motion, and AI rules so each brand gets a fitting style
395 404
 - [x] Part 5 — More layouts per section (done 2026-11-19): 7 new layouts, so the main sections have 3 or 4 each, and a Layouts box in the Design tab
396 405
 - [x] Part 6 — Category guides for the AI (done 2026-11-21): one guide per category with 2 or 3 directions each, plus the merchant's other stores (and the current design on a redesign) as looks not to repeat
397
-- [ ] Part 7 — Collections ("shop by need" tiles and menu links), bento grid section, video section, real reviews from buyers after delivery
406
+- [x] Part 7 — Collections, "shop by" section, bento grid and video (done 2026-11-22): collections managed in the Products tab or by chat, collection pages and links, "shop by" section (round photos or tiles), bento section (3 to 6 tiles), video section (YouTube or Vimeo, loads on play), and Video and Bento boxes in the Design tab so no chat is needed
407
+- [ ] Part 8 — Real reviews from buyers after delivery: review email, review form, merchant approval, stars on products (split out of part 7 on 2026-11-21)
398 408
 
399 409
 Branches (agreed 2026-11-18):
400 410
 
401 411
 - Each part has its own branch named `redesign/part-{number}-{short-title}`, such as `redesign/part-1-photo-hero` and `redesign/part-2-announcement-bar`. (Git does not allow spaces or ":" in branch names, so dashes are used.)
402 412
 - Each part branches from the part before it, not from `main`: part 2 from part 1, part 3 from part 2, and so on.
403 413
 - Nothing from Step 9 is merged into `main` until the merchant decides.
414
+- Decided 2026-11-21: keep `main` (the old design) and the redesign branches apart, so both can be shown to people to see which they prefer. Do not merge the redesign into `main` until the user says so.
404 415
 
405 416
 Notes:
406 417
 
@@ -508,6 +519,8 @@ Then, from the project folder:
508 519
 | Store styles                           | `PlanSchema::STYLE_OPTIONS` and `STYLE_PRESETS`, `StoreStyleController`, `storefront/theme.ts`, `storefront/reveal.tsx`, `resources/css/app.css`, `components/stores/style-picker.tsx` |
509 520
 | Section layouts                        | `PlanSchema::SECTIONS`, `app/StorePlan/SectionLayouts.php`, `SectionLayoutController`, `storefront/sections/*.tsx`, `components/stores/layout-picker.tsx`                              |
510 521
 | Category guides                        | `app/StorePlan/Ai/CategoryGuides.php`, `PlanPrompt::categoryGuide()` and `looksToAvoid()`                                                                                              |
522
+| Collections, bento, video              | `app/Models/Collection.php`, `CollectionController`, `storefront/sections/shop-by.tsx`, `bento.tsx`, `video.tsx`, `storefront/pages/shop.tsx`                                          |
523
+| Video and Bento boxes                  | `app/StorePlan/SectionEditor.php`, `VideoSectionController`, `BentoSectionController`, `components/stores/video-box.tsx`, `bento-box.tsx`                                              |
511 524
 | Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                                                                      |
512 525
 | Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                                                                     |
513 526
 | Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                                                            |
@@ -538,36 +551,38 @@ Moved into **Step 9 — Modern store design** on 2026-11-17.
538 551
 
539 552
 Add one line per work session: date, what was done, what is next.
540 553
 
541
-| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                               | Next                                                            |
542
-| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
543
-| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                                                                                | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
544
-| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                                                                           | Step 2: store plan format, sections, renderer                   |
545
-| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                                                                                    | Step 3: swappable AI layer and store generation                 |
546
-| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                                                                              | Step 3: swappable AI layer and store generation                 |
547
-| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                                                                            | Add API keys, run the real test, then Step 4                    |
548
-| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                                                                                 | Real AI test, then Step 4                                       |
549
-| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                                                                                  | Merge into `main`, then Step 4: products                        |
550
-| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                                                                        | Step 4 part 2: cart, Stripe checkout, orders, email             |
551
-| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                                                                              | Stripe checkout (needs test keys), orders, email                |
552
-| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                                                                                                                                                                              | Merge into `main`, then Step 5: publishing                      |
553
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                       | Step 5: publishing                                              |
554
-| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                                                                                                                                                 | Step 5: publishing                                              |
555
-| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                                                                                                                                       | Step 5: publishing                                              |
556
-| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                                                                                                                                               | Step 6: subscription billing                                    |
557
-| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                                                                       | Merge into `main`, then Step 7                                  |
558
-| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                                                                        | Merge, then Step 7 part 2 or Step 8                             |
559
-| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                | Merge both branches, then Step 7 part 2 or Step 8               |
560
-| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                         | Merge branches, then Step 7 part 2 or Step 8                    |
561
-| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                     | Merge, then product variants                                    |
562
-| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                          | Merge both branches, then bundles                               |
563
-| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                           | Merge, then chat commands                                       |
564
-| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                       | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
565
-| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                 | Merge; then Step 7 part 2 or Step 9                             |
566
-| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                      | Merge; then Step 7 part 2 or Step 9                             |
567
-| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                | Step 9 part 1: photos first                                     |
568
-| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                             | Merge, then part 2                                              |
569
-| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                 | Commit; part 3 branches from part 2                             |
570
-| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                        | Commit; part 4 branches from part 3                             |
571
-| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser. | Commit; part 5 branches from part 4                             |
572
-| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                    | Commit; part 6 branches from part 5                             |
573
-| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                | Commit; then part 7 or merge                                    |
554
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                                                                   | Next                                                            |
555
+| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
556
+| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                                                                                    | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
557
+| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                                                                               | Step 2: store plan format, sections, renderer                   |
558
+| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
559
+| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                                                                                  | Step 3: swappable AI layer and store generation                 |
560
+| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                                                                                | Add API keys, run the real test, then Step 4                    |
561
+| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                                                                                     | Real AI test, then Step 4                                       |
562
+| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                                                                                      | Merge into `main`, then Step 4: products                        |
563
+| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                                                                            | Step 4 part 2: cart, Stripe checkout, orders, email             |
564
+| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                                                                                  | Stripe checkout (needs test keys), orders, email                |
565
+| 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                                                                                                                                                                                  | Merge into `main`, then Step 5: publishing                      |
566
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                                                           | Step 5: publishing                                              |
567
+| 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                                                                                                                                                                                     | Step 5: publishing                                              |
568
+| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                                                                                                                                                                                           | Step 5: publishing                                              |
569
+| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                                                                                                                                                                                   | Step 6: subscription billing                                    |
570
+| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                                                                           | Merge into `main`, then Step 7                                  |
571
+| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                                                                            | Merge, then Step 7 part 2 or Step 8                             |
572
+| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                                                    | Merge both branches, then Step 7 part 2 or Step 8               |
573
+| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                                                             | Merge branches, then Step 7 part 2 or Step 8                    |
574
+| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                                                         | Merge, then product variants                                    |
575
+| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                                                              | Merge both branches, then bundles                               |
576
+| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                                                               | Merge, then chat commands                                       |
577
+| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                                                           | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
578
+| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled).                                     | Merge; then Step 7 part 2 or Step 9                             |
579
+| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                                                          | Merge; then Step 7 part 2 or Step 9                             |
580
+| 2026-11-17 | Researched 2026 store design trends and published a comparison page. Added Step 9 — Modern store design (6 parts) and the category guides decision; "Before launch" is now Step 10.                                                                                                                                                                                                                                                                                    | Step 9 part 1: photos first                                     |
581
+| 2026-11-18 | Step 9 part 1 on branch `redesign/part-1-photo-hero`: full-width and split photo heroes, hero photo upload and picker in the Design tab, automatic product photo, second photo on hover, letter placeholders, AI told about photos. 251 tests pass; checked in the browser at desktop and phone width with a test banner on Luna Skin.                                                                                                                                 | Merge, then part 2                                              |
582
+| 2026-11-18 | Step 9 part 2 on branch `redesign/part-2-announcement-bar` (from part 1): announcement bar (automatic lines + merchant lines, Settings card) and trust row section with live facts. Plan checker now supports "required if" rules. 257 tests pass; real DeepSeek added a trust row to Luna Skin correctly; checked in the browser.                                                                                                                                     | Commit; part 3 branches from part 2                             |
583
+| 2026-11-18 | Step 9 part 3 on branch `redesign/part-3-product-page` (from part 2): folding sections (form, chat with merge by title), trust points, sticky phone add-to-cart bar, pairs well with, phone menu, sticky photos. Found and fixed the sticky bar hiding under the header. 261 tests pass; real DeepSeek wrote a sensible "How to use" for the sunscreen (confirmed); checked at phone width.                                                                            | Commit; part 4 branches from part 3                             |
584
+| 2026-11-19 | Step 9 part 4 on branch `redesign/part-4-style-options` (from part 3): style options, six ready-made looks with a Style box, 12 more fonts, gentle motion, AI style rules. Fixed fade-in hiding a section that was already partly on screen. "More layouts per section" moved to a new part 5; category guides are now part 6 and collections part 7. 266 tests pass; Bold look and a real DeepSeek "more premium and elegant" change both checked in the browser.     | Commit; part 5 branches from part 4                             |
585
+| 2026-11-19 | Step 9 part 5 on branch `redesign/part-5-section-layouts` (from part 4): 7 new section layouts (products carousel and large, featured stacked, about statement, reviews wall, FAQ cards, newsletter split, footer columns) and a Layouts box. 270 tests pass; every layout checked in the browser on Luna Skin; long About statements now shown a step smaller.                                                                                                        | Commit; part 6 branches from part 5                             |
586
+| 2026-11-21 | Step 9 part 6 on branch `redesign/part-6-category-guides` (from part 5): category design guides and "looks to avoid" for the AI. 275 tests pass; generated two real test stores with Claude Sonnet (Dapur Mak Teh, food; Seri Anggun, fashion) and they came out clearly different.                                                                                                                                                                                    | Commit; then part 7 or merge                                    |
587
+| 2026-11-21 | Decided to keep `main` and the redesign apart for comparison. Split reviews out as part 8. Step 9 part 7 on branch `redesign/part-7-collections-bento-video` (from part 6): collections (Products tab, chat, pages, links), shop by, bento and video sections, with AI checks for collection names and video addresses. 282 tests pass; real DeepSeek created two collections for Luna Skin (confirmed) and added shop by and bento correctly; checked in the browser. | Commit; part 8 branches from part 7                             |
588
+| 2026-11-22 | Added Video and Bento boxes to the Design tab (same branch, part 7), so both can be added and edited without chat. The merchant added a real YouTube video to Luna Skin by chat; it plays in the preview. 286 tests pass.                                                                                                                                                                                                                                              | Commit part 7; then part 8                                      |

+ 2
- 1
README.md Zobrazit soubor

@@ -21,7 +21,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
21 21
 | 6    | Our own subscription billing                            | Done                                                           |
22 22
 | 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Part 1 done (shipping fees, WhatsApp); EasyParcel and FPX next |
23 23
 | 8    | Discounts and product options: codes, variants, bundles | Done                                                           |
24
-| 9    | Modern store design: photos, styles, category guides    | In progress: parts 1–6 done; part 7 next                       |
24
+| 9    | Modern store design: photos, styles, category guides    | In progress: parts 1–7 done; part 8 (reviews) next             |
25 25
 | 10   | Before launch: hosting, legal pages, backups            | Not started                                                    |
26 26
 
27 27
 ## What works today
@@ -40,6 +40,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
40 40
 - Trust row under the hero: shipping, secure payment and WhatsApp, always taken from the store's real settings
41 41
 - Product page: folding sections such as "How to use" (written in the form or by chat) plus shipping from real fees, trust points, "Pairs well with", and an add-to-cart bar that stays at the bottom on phones
42 42
 - Phone menu for the store header
43
+- Collections (such as "Sun care") with their own pages, a "Shop by" section, bento tiles and a YouTube/Vimeo video section. Video and bento can be added and edited in their own Design tab boxes or by chat
43 44
 - More layouts per section (3 or 4 for the main ones), such as a sliding product row, large product cards, a wall of reviews and a columns footer, changeable in the Layouts box of the Design tab or by chat
44 45
 - Store styles: six ready-made looks (Minimal, Soft, Elegant, Bold, Playful, Classic) in the Design tab, with fine-tuning for buttons, cards, spacing, headings, backgrounds and motion; 20 fonts. The AI picks a style that fits the brand and changes it by chat
45 46
 - Change the store by chat, for example "make a 10% code RAYA10 until the end of the month" or "set the 100ml moisturiser to RM 52", or "write descriptions for my products". The AI shows what it will do, and nothing changes until you press Confirm

+ 46
- 1
app/Commerce/ChatActions.php Zobrazit soubor

@@ -3,6 +3,7 @@
3 3
 namespace App\Commerce;
4 4
 
5 5
 use App\Enums\ProductStatus;
6
+use App\Http\Controllers\CollectionController;
6 7
 use App\Http\Requests\Products\SaveProductRequest;
7 8
 use App\Models\AutomaticDiscount;
8 9
 use App\Models\BundleItem;
@@ -32,7 +33,7 @@ final class ChatActions
32 33
     /** Product descriptions written in the chat stay short enough to read on the confirm card. */
33 34
     public const int MAX_DESCRIPTION = 1500;
34 35
 
35
-    public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle', 'create_automatic_discount'];
36
+    public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle', 'create_automatic_discount', 'create_collection'];
36 37
 
37 38
     /**
38 39
      * Check the actions in an AI answer. Returns each with its cleaned input and a sentence for the merchant.
@@ -107,6 +108,7 @@ final class ChatActions
107 108
                 'update_discount' => self::updateDiscount($store, $action),
108 109
                 'create_bundle' => self::createBundle($store, $action),
109 110
                 'create_automatic_discount' => self::createAutomaticDiscount($store, $action),
111
+                'create_collection' => self::createCollection($store, $action),
110 112
             };
111 113
         } catch (ValidationException $e) {
112 114
             // "price" becomes "actions.2.price", so it is clear which action has the problem.
@@ -522,6 +524,49 @@ final class ChatActions
522 524
         ];
523 525
     }
524 526
 
527
+    /**
528
+     * A group of products shoppers can browse, such as "Sun care".
529
+     *
530
+     * @param  array<string, mixed>  $input
531
+     * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
532
+     */
533
+    private static function createCollection(Store $store, array $input): array
534
+    {
535
+        $data = self::validate($input, [
536
+            'name' => ['required', 'string', 'min:2', 'max:60'],
537
+            'description' => ['nullable', 'string', 'max:500'],
538
+            'products' => ['required', 'array', 'list', 'min:1', 'max:'.CollectionController::MAX_PRODUCTS],
539
+            'products.*' => ['string'],
540
+        ]);
541
+
542
+        if ($store->collections()->where('name', $data['name'])->exists()) {
543
+            self::fail('name', 'This store already has a collection with that name.');
544
+        }
545
+
546
+        $products = [];
547
+
548
+        foreach ($data['products'] as $index => $slug) {
549
+            $products[] = self::findProduct($store, $slug, "products.$index");
550
+        }
551
+
552
+        $names = implode(', ', array_map(fn (Product $product) => $product->name, $products));
553
+        $ids = array_values(array_unique(array_map(fn (Product $product) => $product->id, $products)));
554
+
555
+        return [
556
+            'input' => $data,
557
+            'summary' => "Create the collection \"{$data['name']}\" with: {$names}",
558
+            'run' => function () use ($store, $data, $ids): void {
559
+                $collection = $store->collections()->create([
560
+                    'name' => $data['name'],
561
+                    'description' => self::cleanText($data['description'] ?? null),
562
+                    'position' => (int) $store->collections()->max('position') + 1,
563
+                ]);
564
+
565
+                $collection->products()->sync(array_map(fn (int $position) => ['position' => $position], array_flip($ids)));
566
+            },
567
+        ];
568
+    }
569
+
525 570
     /**
526 571
      * A discount with no code, such as "Raya Sale: buy 2 or more, get 10% off", for all or some products.
527 572
      *

+ 109
- 0
app/Http/Controllers/BentoSectionController.php Zobrazit soubor

@@ -0,0 +1,109 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Http\Controllers\Concerns\EditsDesignSections;
6
+use App\Models\Store;
7
+use App\StorePlan\HeroImages;
8
+use App\StorePlan\PlanSchema;
9
+use App\StorePlan\PlanValidator;
10
+use App\StorePlan\SectionEditor;
11
+use Illuminate\Http\RedirectResponse;
12
+use Illuminate\Http\Request;
13
+use Illuminate\Validation\Rule;
14
+use Illuminate\Validation\ValidationException;
15
+
16
+/**
17
+ * The Design tab's Bento box: add bento tiles (filled with a sensible start), edit every tile, or take them out.
18
+ */
19
+class BentoSectionController extends Controller
20
+{
21
+    use EditsDesignSections;
22
+
23
+    public function store(Request $request, PlanValidator $validator, string $slug): RedirectResponse
24
+    {
25
+        $store = $this->storeWithDesign($request, $slug);
26
+        $data = $request->validate([
27
+            'after' => ['nullable', 'string', Rule::in(array_column(SectionEditor::homeSections($store->plan), 'id'))],
28
+        ]);
29
+
30
+        [$plan] = SectionEditor::addToHome($store->plan, $data['after'] ?? null, 'highlights', [
31
+            'type' => 'bento',
32
+            'variant' => 'mosaic',
33
+            'content' => ['heading' => null, 'tiles' => $this->starterTiles($store)],
34
+        ]);
35
+
36
+        return $this->saveDesign($store, $validator, $plan, __('Bento tiles added. Change any tile below.'));
37
+    }
38
+
39
+    public function update(Request $request, PlanValidator $validator, string $slug, string $sectionId): RedirectResponse
40
+    {
41
+        $store = $this->storeWithDesign($request, $slug);
42
+        $this->assertSection($store, $sectionId, 'bento');
43
+
44
+        $data = $request->validate([
45
+            'heading' => ['nullable', 'string', 'max:80'],
46
+            'variant' => ['required', Rule::in(PlanSchema::SECTIONS['bento'])],
47
+            'tiles' => ['required', 'array', 'min:3', 'max:6'],
48
+            'tiles.*.title' => ['required', 'string', 'max:60'],
49
+            'tiles.*.text' => ['nullable', 'string', 'max:140'],
50
+            'tiles.*.href' => ['required', 'string', 'max:300', 'regex:'.PlanSchema::LINK_PATTERN],
51
+            'tiles.*.image' => ['nullable', 'string', 'regex:'.HeroImages::PATTERN],
52
+            'tiles.*.tone' => ['nullable', Rule::in(['primary', 'accent', 'dark', 'surface'])],
53
+        ], [
54
+            'tiles.min' => __('Keep at least 3 tiles.'),
55
+            'tiles.max' => __('Use at most 6 tiles.'),
56
+            'tiles.*.href.regex' => __('Use a link such as /shop, /collections/gift-sets, #about or https://...'),
57
+        ]);
58
+
59
+        $images = array_values(array_filter(array_column($data['tiles'], 'image')));
60
+
61
+        if (HeroImages::unknown($store, $images) !== []) {
62
+            throw ValidationException::withMessages(['section' => __('Choose photos from your products or uploads.')]);
63
+        }
64
+
65
+        $tiles = array_map(fn (array $tile) => [
66
+            'title' => trim($tile['title']),
67
+            'text' => filled($tile['text'] ?? null) ? trim($tile['text']) : null,
68
+            'href' => trim($tile['href']),
69
+            'image' => $tile['image'] ?? null,
70
+            'tone' => $tile['tone'] ?? 'surface',
71
+        ], array_values($data['tiles']));
72
+
73
+        $content = ['heading' => filled($data['heading'] ?? null) ? trim($data['heading']) : null, 'tiles' => $tiles];
74
+
75
+        return $this->saveDesign($store, $validator, SectionEditor::update($store->plan, $sectionId, $content, $data['variant']), __('Bento tiles saved.'));
76
+    }
77
+
78
+    public function destroy(Request $request, PlanValidator $validator, string $slug, string $sectionId): RedirectResponse
79
+    {
80
+        $store = $this->storeWithDesign($request, $slug);
81
+        $this->assertSection($store, $sectionId, 'bento');
82
+
83
+        return $this->saveDesign($store, $validator, SectionEditor::remove($store->plan, $sectionId), __('Bento tiles removed.'));
84
+    }
85
+
86
+    /**
87
+     * Three tiles that work for any store: the whole range (with a product photo when there is one),
88
+     * the first collection or the products section, and the brand story.
89
+     *
90
+     * @return list<array<string, mixed>>
91
+     */
92
+    private function starterTiles(Store $store): array
93
+    {
94
+        $photo = HeroImages::choices($store);
95
+        $productPhoto = collect($photo)->first(fn (array $choice) => str_starts_with($choice['ref'], 'product:'));
96
+        $collection = $store->collections()->first();
97
+        $sections = array_column(SectionEditor::homeSections($store->plan ?? []), 'id');
98
+        $about = collect(SectionEditor::ofType($store->plan ?? [], 'about'))->firstWhere('page_id', 'home');
99
+        $grid = collect(SectionEditor::ofType($store->plan ?? [], 'product_grid'))->firstWhere('page_id', 'home');
100
+
101
+        return [
102
+            ['title' => 'Shop the range', 'text' => null, 'href' => '/shop', 'image' => $productPhoto['ref'] ?? null, 'tone' => 'primary'],
103
+            $collection !== null
104
+                ? ['title' => $collection->name, 'text' => null, 'href' => '/collections/'.$collection->slug, 'image' => null, 'tone' => 'accent']
105
+                : ['title' => 'Bestsellers', 'text' => null, 'href' => $grid !== null && in_array($grid['section']['id'], $sections, true) ? '#'.$grid['section']['id'] : '/shop', 'image' => null, 'tone' => 'accent'],
106
+            ['title' => 'Our story', 'text' => null, 'href' => $about !== null ? '#'.$about['section']['id'] : '/shop', 'image' => null, 'tone' => 'dark'],
107
+        ];
108
+    }
109
+}

+ 146
- 0
app/Http/Controllers/CollectionController.php Zobrazit soubor

@@ -0,0 +1,146 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Models\Collection;
6
+use App\Models\Product;
7
+use App\Models\Store;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Validation\Rule;
11
+use Inertia\Inertia;
12
+use Inertia\Response;
13
+
14
+/**
15
+ * The merchant's collections: groups of products such as "Sun care". Listed on the Products tab.
16
+ */
17
+class CollectionController extends Controller
18
+{
19
+    public const int MAX_PRODUCTS = 200;
20
+
21
+    public function create(Request $request, string $slug): Response
22
+    {
23
+        $store = $this->ownedStore($request, $slug);
24
+
25
+        return Inertia::render('stores/collections/form', [
26
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
27
+            'collection' => null,
28
+            'products' => $this->productChoices($store),
29
+        ]);
30
+    }
31
+
32
+    public function store(Request $request, string $slug): RedirectResponse
33
+    {
34
+        $store = $this->ownedStore($request, $slug);
35
+        $data = $this->validated($request, $store);
36
+
37
+        $collection = $store->collections()->create([
38
+            'name' => $data['name'],
39
+            'description' => $data['description'] ?? null,
40
+            'position' => (int) $store->collections()->max('position') + 1,
41
+        ]);
42
+        $this->syncProducts($collection, $data['product_ids'] ?? []);
43
+
44
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Collection ":name" created.', ['name' => $collection->name])]);
45
+
46
+        return to_route('stores.products.index', $store->slug);
47
+    }
48
+
49
+    public function edit(Request $request, string $slug, int $collection): Response
50
+    {
51
+        $store = $this->ownedStore($request, $slug);
52
+        $model = $this->ownedCollection($store, $collection);
53
+
54
+        return Inertia::render('stores/collections/form', [
55
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
56
+            'collection' => [
57
+                'id' => $model->id,
58
+                'name' => $model->name,
59
+                'slug' => $model->slug,
60
+                'description' => $model->description,
61
+                'product_ids' => $model->products->modelKeys(),
62
+            ],
63
+            'products' => $this->productChoices($store),
64
+        ]);
65
+    }
66
+
67
+    public function update(Request $request, string $slug, int $collection): RedirectResponse
68
+    {
69
+        $store = $this->ownedStore($request, $slug);
70
+        $model = $this->ownedCollection($store, $collection);
71
+        $data = $this->validated($request, $store);
72
+
73
+        // The address (slug) stays the same, so menu links and shared links keep working after a rename.
74
+        $model->fill(['name' => $data['name'], 'description' => $data['description'] ?? null])->save();
75
+        $this->syncProducts($model, $data['product_ids'] ?? []);
76
+
77
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Collection saved.')]);
78
+
79
+        return to_route('stores.products.index', $store->slug);
80
+    }
81
+
82
+    public function destroy(Request $request, string $slug, int $collection): RedirectResponse
83
+    {
84
+        $store = $this->ownedStore($request, $slug);
85
+
86
+        // Products stay; only the group goes. A "shop by" section simply stops showing it.
87
+        $this->ownedCollection($store, $collection)->delete();
88
+
89
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Collection deleted.')]);
90
+
91
+        return to_route('stores.products.index', $store->slug);
92
+    }
93
+
94
+    /**
95
+     * @return array<string, mixed>
96
+     */
97
+    private function validated(Request $request, Store $store): array
98
+    {
99
+        return $request->validate([
100
+            'name' => ['required', 'string', 'min:2', 'max:60'],
101
+            'description' => ['nullable', 'string', 'max:500'],
102
+            'product_ids' => ['nullable', 'array', 'max:'.self::MAX_PRODUCTS],
103
+            'product_ids.*' => ['integer', Rule::exists('products', 'id')->where('store_id', $store->id)],
104
+        ], [
105
+            'product_ids.*.exists' => __('Choose products from this store.'),
106
+        ]);
107
+    }
108
+
109
+    /**
110
+     * @param  array<int, mixed>  $ids
111
+     */
112
+    private function syncProducts(Collection $collection, array $ids): void
113
+    {
114
+        $positions = [];
115
+
116
+        foreach (array_values(array_unique(array_map('intval', $ids))) as $position => $id) {
117
+            $positions[$id] = ['position' => $position];
118
+        }
119
+
120
+        $collection->products()->sync($positions);
121
+    }
122
+
123
+    /**
124
+     * @return list<array{id: int, name: string, image: string|null}>
125
+     */
126
+    private function productChoices(Store $store): array
127
+    {
128
+        return array_values($store->products()->with('images')->orderBy('name')->get()
129
+            ->map(fn (Product $product) => [
130
+                'id' => $product->id,
131
+                'name' => $product->name,
132
+                'image' => $product->images->first()?->url(),
133
+            ])
134
+            ->all());
135
+    }
136
+
137
+    private function ownedStore(Request $request, string $slug): Store
138
+    {
139
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
140
+    }
141
+
142
+    private function ownedCollection(Store $store, int $id): Collection
143
+    {
144
+        return $store->collections()->with('products')->whereKey($id)->firstOrFail();
145
+    }
146
+}

+ 57
- 0
app/Http/Controllers/Concerns/EditsDesignSections.php Zobrazit soubor

@@ -0,0 +1,57 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers\Concerns;
4
+
5
+use App\Models\Store;
6
+use App\StorePlan\PlanValidator;
7
+use App\StorePlan\SectionEditor;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Validation\ValidationException;
11
+use Inertia\Inertia;
12
+
13
+/**
14
+ * Shared steps for Design tab boxes that add, edit or remove a section.
15
+ */
16
+trait EditsDesignSections
17
+{
18
+    private function storeWithDesign(Request $request, string $slug): Store
19
+    {
20
+        $store = $request->user()->stores()->where('slug', $slug)->firstOrFail();
21
+
22
+        abort_if($store->plan === null, 404);
23
+
24
+        return $store;
25
+    }
26
+
27
+    /**
28
+     * 404 unless the design has a section with this id and type.
29
+     */
30
+    private function assertSection(Store $store, string $sectionId, string $type): void
31
+    {
32
+        abort_unless(SectionEditor::typeOf($store->plan ?? [], $sectionId) === $type, 404);
33
+    }
34
+
35
+    /**
36
+     * Check the changed design with the plan checker and save it. A problem is shown under the box,
37
+     * in the checker's own words, and nothing is saved.
38
+     *
39
+     * @param  array<string, mixed>  $plan
40
+     */
41
+    private function saveDesign(Store $store, PlanValidator $validator, array $plan, string $savedMessage): RedirectResponse
42
+    {
43
+        try {
44
+            $store->plan = $validator->validate($plan);
45
+        } catch (ValidationException $e) {
46
+            throw ValidationException::withMessages(['section' => collect($e->errors())->flatten()->first() ?? __('This change could not be saved.')]);
47
+        }
48
+
49
+        $store->save();
50
+
51
+        Inertia::flash('toast', ['type' => 'success', 'message' => $store->isPublished()
52
+            ? __('Saved. Click "Publish changes" to show it on your live store.')
53
+            : $savedMessage]);
54
+
55
+        return to_route('stores.show', $store->slug);
56
+    }
57
+}

+ 9
- 0
app/Http/Controllers/Concerns/RendersStorefront.php Zobrazit soubor

@@ -4,6 +4,7 @@ namespace App\Http\Controllers\Concerns;
4 4
 
5 5
 use App\Commerce\Cart;
6 6
 use App\Models\AutomaticDiscount;
7
+use App\Models\Collection;
7 8
 use App\Models\Product;
8 9
 use App\Models\Store;
9 10
 use App\Storefront\Announcements;
@@ -79,6 +80,14 @@ trait RendersStorefront
79 80
                 'shipping_from' => min($store->shipping_west, $store->shipping_east) / 100,
80 81
                 'shipping_west' => $store->shipping_west / 100,
81 82
                 'shipping_east' => $store->shipping_east / 100,
83
+                // Collections with at least one product shoppers can see, for "shop by" sections and the shop page.
84
+                'collections' => $store->collections()
85
+                    ->with(['products' => fn ($query) => $query->active()->with('images')])
86
+                    ->get()
87
+                    ->map(fn (Collection $collection) => $collection->toStorefront())
88
+                    ->filter(fn (array $collection) => $collection['count'] > 0)
89
+                    ->values()
90
+                    ->all(),
82 91
                 // Automatic discounts running now, so product pages can mention them.
83 92
                 'offers' => $cart->liveOffers()->map(fn (AutomaticDiscount $offer) => [
84 93
                     'name' => $offer->name,

+ 8
- 0
app/Http/Controllers/ProductController.php Zobrazit soubor

@@ -6,6 +6,7 @@ use App\Commerce\BundleStock;
6 6
 use App\Enums\ProductStatus;
7 7
 use App\Http\Requests\Products\SaveProductRequest;
8 8
 use App\Models\BundleItem;
9
+use App\Models\Collection;
9 10
 use App\Models\Product;
10 11
 use App\Models\ProductImage;
11 12
 use App\Models\ProductVariant;
@@ -35,6 +36,13 @@ class ProductController extends Controller
35 36
                 ->latest('id')
36 37
                 ->get()
37 38
                 ->map(fn (Product $product) => $this->present($product)),
39
+            'collections' => $store->collections()->withCount('products')->get()
40
+                ->map(fn (Collection $collection) => [
41
+                    'id' => $collection->id,
42
+                    'name' => $collection->name,
43
+                    'slug' => $collection->slug,
44
+                    'products_count' => (int) $collection->getAttribute('products_count'),
45
+                ]),
38 46
         ]);
39 47
     }
40 48
 

+ 23
- 0
app/Http/Controllers/StoreController.php Zobrazit soubor

@@ -14,6 +14,7 @@ use App\Storefront\Storefront;
14 14
 use App\StorePlan\FeaturedProducts;
15 15
 use App\StorePlan\HeroImages;
16 16
 use App\StorePlan\PlanSchema;
17
+use App\StorePlan\SectionEditor;
17 18
 use App\StorePlan\SectionLayouts;
18 19
 use Illuminate\Http\RedirectResponse;
19 20
 use Illuminate\Http\Request;
@@ -103,6 +104,28 @@ class StoreController extends Controller
103 104
             // Every section (heroes have their own box) with its layout, and the layouts each type allows.
104 105
             'layoutSections' => $store->plan !== null ? SectionLayouts::sections($store->plan) : [],
105 106
             'layoutOptions' => PlanSchema::SECTIONS,
107
+            // For the Video and Bento boxes: those sections, and the home sections a new one can follow.
108
+            'videoSections' => $store->plan !== null ? array_map(fn (array $found) => [
109
+                'section_id' => $found['section']['id'],
110
+                'page_title' => $found['page_title'],
111
+                'variant' => $found['section']['variant'],
112
+                ...$found['section']['content'],
113
+            ], SectionEditor::ofType($store->plan, 'video')) : [],
114
+            'bentoSections' => $store->plan !== null ? array_map(fn (array $found) => [
115
+                'section_id' => $found['section']['id'],
116
+                'page_title' => $found['page_title'],
117
+                'variant' => $found['section']['variant'],
118
+                'heading' => $found['section']['content']['heading'] ?? null,
119
+                'tiles' => $found['section']['content']['tiles'] ?? [],
120
+            ], SectionEditor::ofType($store->plan, 'bento')) : [],
121
+            'homeSections' => $store->plan !== null ? SectionEditor::homeSections($store->plan) : [],
122
+            // Links a tile can point to, so the merchant picks instead of typing.
123
+            'linkSuggestions' => $store->plan !== null ? [
124
+                ['href' => '/shop', 'label' => 'All products'],
125
+                ...$store->collections()->get()->map(fn ($collection) => ['href' => '/collections/'.$collection->slug, 'label' => 'Collection: '.$collection->name])->all(),
126
+                ...array_map(fn (array $page) => ['href' => '/'.$page['id'], 'label' => 'Page: '.$page['title']], array_slice($store->plan['pages'], 1)),
127
+                ...array_map(fn (array $section) => ['href' => '#'.$section['id'], 'label' => 'Section: '.$section['label']], SectionEditor::homeSections($store->plan)),
128
+            ] : [],
106 129
             'stylePresets' => collect(PlanSchema::STYLE_PRESETS)
107 130
                 ->map(fn (array $preset, string $key) => ['key' => $key, ...$preset])
108 131
                 ->values(),

+ 19
- 0
app/Http/Controllers/StoreDesignController.php Zobrazit soubor

@@ -46,6 +46,25 @@ class StoreDesignController extends Controller
46 46
         return $this->renderStorefront($request, $storefront, ['type' => 'page', 'pageId' => $pageId]);
47 47
     }
48 48
 
49
+    /**
50
+     * One collection's page: its name, description and active products.
51
+     */
52
+    public function collection(Request $request): Response
53
+    {
54
+        $storefront = $this->storefront($request);
55
+
56
+        $collection = $storefront->store->collections()
57
+            ->with(['products' => fn ($query) => $query->active()->with(Product::STOREFRONT_RELATIONS)])
58
+            ->where('slug', (string) $request->route('collectionSlug'))
59
+            ->firstOrFail();
60
+
61
+        return $this->renderStorefront($request, $storefront, [
62
+            'type' => 'collection',
63
+            'collection' => $collection->toStorefront(),
64
+            'collectionProducts' => $collection->products->map(fn (Product $product) => $product->toStorefront())->values()->all(),
65
+        ]);
66
+    }
67
+
49 68
     /**
50 69
      * The shop page: every product shoppers may see.
51 70
      */

+ 83
- 0
app/Http/Controllers/VideoSectionController.php Zobrazit soubor

@@ -0,0 +1,83 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Http\Controllers\Concerns\EditsDesignSections;
6
+use App\StorePlan\PlanSchema;
7
+use App\StorePlan\PlanValidator;
8
+use App\StorePlan\SectionEditor;
9
+use Illuminate\Http\RedirectResponse;
10
+use Illuminate\Http\Request;
11
+use Illuminate\Validation\Rule;
12
+
13
+/**
14
+ * The Design tab's Video box: add a YouTube or Vimeo video section, change it, or take it out.
15
+ */
16
+class VideoSectionController extends Controller
17
+{
18
+    use EditsDesignSections;
19
+
20
+    public function store(Request $request, PlanValidator $validator, string $slug): RedirectResponse
21
+    {
22
+        $store = $this->storeWithDesign($request, $slug);
23
+        $data = $this->validated($request, [
24
+            'after' => ['nullable', 'string', Rule::in(array_column(SectionEditor::homeSections($store->plan), 'id'))],
25
+        ]);
26
+
27
+        [$plan] = SectionEditor::addToHome($store->plan, $data['after'] ?? null, 'video', [
28
+            'type' => 'video',
29
+            'variant' => $data['variant'],
30
+            'content' => $this->content($data),
31
+        ]);
32
+
33
+        return $this->saveDesign($store, $validator, $plan, __('Video added.'));
34
+    }
35
+
36
+    public function update(Request $request, PlanValidator $validator, string $slug, string $sectionId): RedirectResponse
37
+    {
38
+        $store = $this->storeWithDesign($request, $slug);
39
+        $this->assertSection($store, $sectionId, 'video');
40
+        $data = $this->validated($request);
41
+
42
+        return $this->saveDesign($store, $validator, SectionEditor::update($store->plan, $sectionId, $this->content($data), $data['variant']), __('Video saved.'));
43
+    }
44
+
45
+    public function destroy(Request $request, PlanValidator $validator, string $slug, string $sectionId): RedirectResponse
46
+    {
47
+        $store = $this->storeWithDesign($request, $slug);
48
+        $this->assertSection($store, $sectionId, 'video');
49
+
50
+        return $this->saveDesign($store, $validator, SectionEditor::remove($store->plan, $sectionId), __('Video removed.'));
51
+    }
52
+
53
+    /**
54
+     * @param  array<string, list<mixed>>  $extra
55
+     * @return array<string, mixed>
56
+     */
57
+    private function validated(Request $request, array $extra = []): array
58
+    {
59
+        return $request->validate([
60
+            'video_url' => ['required', 'string', 'max:300', 'regex:'.PlanSchema::VIDEO_PATTERN],
61
+            'heading' => ['required', 'string', 'max:80'],
62
+            'text' => ['nullable', 'string', 'max:300'],
63
+            'variant' => ['required', Rule::in(PlanSchema::SECTIONS['video'])],
64
+            ...$extra,
65
+        ], [
66
+            'video_url.regex' => __('Paste a YouTube or Vimeo link, such as https://youtu.be/abc123.'),
67
+        ]);
68
+    }
69
+
70
+    /**
71
+     * @param  array<string, mixed>  $data
72
+     * @return array<string, mixed>
73
+     */
74
+    private function content(array $data): array
75
+    {
76
+        return [
77
+            'heading' => trim($data['heading']),
78
+            'text' => filled($data['text'] ?? null) ? trim($data['text']) : null,
79
+            'videoUrl' => trim($data['video_url']),
80
+            'cta' => null,
81
+        ];
82
+    }
83
+}

+ 77
- 0
app/Models/Collection.php Zobrazit soubor

@@ -0,0 +1,77 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use App\Enums\ProductStatus;
6
+use Illuminate\Database\Eloquent\Attributes\Fillable;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
+use Illuminate\Database\Eloquent\Relations\BelongsToMany;
10
+use Illuminate\Support\Str;
11
+
12
+/**
13
+ * A group of products shoppers can browse, such as "Sun care" or "Gifts under RM 50".
14
+ * Its page is /collections/{slug}; a "shop_by" section shows collections as tiles.
15
+ *
16
+ * @property int $id
17
+ * @property int $store_id
18
+ * @property string $name
19
+ * @property string $slug
20
+ * @property string|null $description
21
+ * @property int $position
22
+ * @property-read Store $store
23
+ * @property-read \Illuminate\Database\Eloquent\Collection<int, Product> $products
24
+ */
25
+#[Fillable(['name', 'description', 'position'])]
26
+class Collection extends Model
27
+{
28
+    protected static function booted(): void
29
+    {
30
+        static::creating(function (Collection $collection): void {
31
+            $base = Str::slug($collection->name) ?: 'collection';
32
+            $slug = $base;
33
+            $suffix = 2;
34
+
35
+            while (static::query()->where('store_id', $collection->store_id)->where('slug', $slug)->exists()) {
36
+                $slug = $base.'-'.$suffix++;
37
+            }
38
+
39
+            $collection->slug = $slug;
40
+        });
41
+    }
42
+
43
+    /**
44
+     * @return BelongsTo<Store, $this>
45
+     */
46
+    public function store(): BelongsTo
47
+    {
48
+        return $this->belongsTo(Store::class);
49
+    }
50
+
51
+    /**
52
+     * @return BelongsToMany<Product, $this>
53
+     */
54
+    public function products(): BelongsToMany
55
+    {
56
+        return $this->belongsToMany(Product::class)->withPivot('position')->orderByPivot('position');
57
+    }
58
+
59
+    /**
60
+     * What the storefront is allowed to see. The photo is the first active product's main photo.
61
+     *
62
+     * @return array{name: string, slug: string, description: string|null, image: string|null, count: int}
63
+     */
64
+    public function toStorefront(): array
65
+    {
66
+        $active = $this->products->filter(fn (Product $product) => $product->status === ProductStatus::Active);
67
+        $withPhoto = $active->first(fn (Product $product) => $product->images->isNotEmpty());
68
+
69
+        return [
70
+            'name' => $this->name,
71
+            'slug' => $this->slug,
72
+            'description' => $this->description,
73
+            'image' => $withPhoto?->images->first()?->url(),
74
+            'count' => $active->count(),
75
+        ];
76
+    }
77
+}

+ 10
- 0
app/Models/Store.php Zobrazit soubor

@@ -137,6 +137,16 @@ class Store extends Model
137 137
         return $this->hasMany(Product::class);
138 138
     }
139 139
 
140
+    /**
141
+     * Groups of products, such as "Sun care".
142
+     *
143
+     * @return HasMany<Collection, $this>
144
+     */
145
+    public function collections(): HasMany
146
+    {
147
+        return $this->hasMany(Collection::class)->orderBy('position')->orderBy('id');
148
+    }
149
+
140 150
     /**
141 151
      * Photos uploaded for the design, such as a hero banner.
142 152
      *

+ 33
- 0
app/StorePlan/Ai/PlanPrompt.php Zobrazit soubor

@@ -6,6 +6,7 @@ use App\Commerce\ChatActions;
6 6
 use App\Commerce\DiscountCodeRules;
7 7
 use App\Models\AutomaticDiscount;
8 8
 use App\Models\BundleItem;
9
+use App\Models\Collection;
9 10
 use App\Models\DiscountCode;
10 11
 use App\Models\Product;
11 12
 use App\Models\ProductVariant;
@@ -39,6 +40,7 @@ final class PlanPrompt
39 40
         - Design one page for now: the home page (id "home", title "Home"), with 5 to 8 sections. Start it with a "hero". Pick the other sections to suit the brand.
40 41
         - The header and footer are written once, at the top of the plan. Do not put them inside a page.
41 42
         - Choose a colour palette, fonts and a "style" that fit the brand's mood. Do not default to the same look for every store. The style changes buttons, cards, spacing, headings, backgrounds and motion, so two stores with similar colours still feel different. For example: a quiet skincare or homeware brand suits plain cards, airy spacing and outline or solid buttons; a premium or fashion brand suits spaced-capital headings, no-edge cards and a serif heading font; a loud streetwear, snack or kids brand suits heavy headings, bold shadow buttons, hard cards and alternating bands. Gentle motion suits most stores.
43
+        - Newer sections: "shop_by" shows the store's collections as round photos or tiles; only add it when a list of collections is given (an empty "collections" list shows them all). "bento" is 3 to 6 tiles of different sizes, each linking somewhere useful ("/shop", "/collections/...", "/products/...", "#section-id"), with "image" from the photo list or null plus a "tone" (primary, accent, dark, surface) for a colour tile; good under the hero to show bestsellers, gifts, an offer and the story. "video" plays a YouTube or Vimeo video; only add it when the merchant's description gives a video address, and never make one up.
42 44
         - Layouts to know: product_grid "carousel" (one row that scrolls sideways, good for many products) and "large" (2 big cards across, good for a few hero products); featured_product "stacked" (wide photo on top, words centred); about "statement" (the story as one large statement); testimonials "wall" (quotes of different lengths packed in columns; only with 3 or more quotes); faq "cards" (all answers showing, good for 2 to 6 short questions); newsletter "split" (big heading beside the form, calmer than a colour banner); footer "columns" (store name, links and help links).
43 45
         - Make the structure fit the brand too. Decide which sections this brand really needs, in which order, and pick each variant on purpose. You do not need every section type. A store with one main product may put "featured_product" right after the hero; a brand with a strong story may put "about" early; a small catalogue suits "product_grid" with the "minimal" variant. Do not reuse the section order or variants of the example below.
44 46
         - Text must be easy to read: strong contrast between "foreground" and "background", and between "primaryForeground" and "primary".
@@ -61,6 +63,7 @@ final class PlanPrompt
61 63
         $language = $store->language->value === 'ms' ? 'Bahasa Malaysia' : 'English';
62 64
         $products = self::productList($store);
63 65
         $photos = self::photoList($store);
66
+        $collections = self::collectionList($store);
64 67
         $guide = self::categoryGuide($store);
65 68
         $avoid = self::looksToAvoid($store);
66 69
 
@@ -78,10 +81,34 @@ final class PlanPrompt
78 81
         {$guide}
79 82
         {$avoid}
80 83
         {$products}
84
+        {$collections}
81 85
         {$photos}
82 86
         TEXT;
83 87
     }
84 88
 
89
+    /**
90
+     * The store's collections, by the name "shop_by" sections and "/collections/..." links use.
91
+     * Empty when it has none.
92
+     */
93
+    public static function collectionList(Store $store): string
94
+    {
95
+        $collections = $store->collections()->withCount('products')->limit(20)->get();
96
+
97
+        if ($collections->isEmpty()) {
98
+            return '';
99
+        }
100
+
101
+        $lines = $collections
102
+            ->map(fn (Collection $collection) => "- {$collection->slug}: {$collection->name} (".$collection->getAttribute('products_count').' products)')
103
+            ->implode("\n");
104
+
105
+        return <<<TEXT
106
+
107
+        The store's collections (web-address name: name). Use these names in a "shop_by" section's "collections", and link to one with "/collections/" followed by its name:
108
+        {$lines}
109
+        TEXT;
110
+    }
111
+
85 112
     /**
86 113
      * The design guide for the store's category, as a starting direction. Empty for "Other".
87 114
      */
@@ -199,6 +226,7 @@ final class PlanPrompt
199 226
             ->implode("\n");
200 227
 
201 228
         $photos = self::photoList($store);
229
+        $collections = self::collectionList($store);
202 230
         $offerLines = $store->automaticDiscounts()->orderBy('name')->limit(20)->get()
203 231
             ->map(fn (AutomaticDiscount $offer) => "- {$offer->name}: {$offer->describe()}, ".$offer->status())
204 232
             ->implode("\n");
@@ -250,6 +278,7 @@ final class PlanPrompt
250 278
             ->implode("\n");
251 279
 
252 280
         $photos = self::photoList($store);
281
+        $collections = self::collectionList($store);
253 282
         $offerLines = $store->automaticDiscounts()->orderBy('name')->limit(20)->get()
254 283
             ->map(fn (AutomaticDiscount $offer) => "- {$offer->name}: {$offer->describe()}, ".$offer->status())
255 284
             ->implode("\n");
@@ -269,6 +298,7 @@ final class PlanPrompt
269 298
 
270 299
         The store's automatic discounts (no code needed):
271 300
         {$offerLines}
301
+        {$collections}
272 302
         {$photos}
273 303
         TEXT;
274 304
     }
@@ -310,6 +340,8 @@ final class PlanPrompt
310 340
 
311 341
         Style: to make the store feel different ("more premium", "bolder", "more playful", "futuristic"), change "theme": "style", "fonts", "radius" and, if it fits, "colors". For example {"theme": {"style": {"buttons": "shadow", "cards": "hard", "headings": "heavy"}, "fonts": {"heading": "archivo-black"}, "radius": "none"}}. The merchant can also pick a ready-made look in the Style box of the Design tab.
312 342
 
343
+        Collections, bento and video: a "shop_by" section shows collections from the list you are given (never invent a collection name; the merchant creates collections in the Products tab). A "bento" section has 3 to 6 tiles, each with "title", optional "text", "href", "image" (a photo name or null) and "tone" (primary, accent, dark, surface). A "video" section needs "videoUrl", a YouTube or Vimeo address the merchant wrote in the request; if they ask for a video without giving the address, ask for it in "reply".
344
+
313 345
         Hero photos: a hero with the "split" or "image-full" layout shows a photo. Its "image" is a name from the photo list you are given, or null to use the store's product photos automatically. Never make up a photo name. If the merchant asks for their own banner photo, tell them to upload it in the "Hero" box of the Design tab.
314 346
 
315 347
         Featured products: when the merchant asks to feature one of their products, set "productSlug" on the "featured_product" section (or add one) using the product list you are given. Also rewrite that section's "eyebrow", "description" and "bullets" so they describe the new product. For example, to feature the product "light-water-gel-moisturiser" in the section with id "sunscreen":
@@ -324,6 +356,7 @@ final class PlanPrompt
324 356
         {"type": "create_discount", "code": "RAYA10", "discount_type": "percent" or "fixed", "value": 10 (a whole percentage, or ringgit), "minimum_spend": null or ringgit, "starts_on": null or "YYYY-MM-DD", "ends_on": null or "YYYY-MM-DD", "usage_limit": null or a number}
325 357
         {"type": "update_discount", "code": "RAYA10", then only what changes: "active": true or false, "ends_on": "YYYY-MM-DD" or null, "usage_limit": a number or null}
326 358
         {"type": "create_automatic_discount", "name": "Raya Sale", "discount_type": "percent" or "fixed", "value": 10, "minimum_quantity": null or a number of items, "minimum_spend": null or ringgit, "products": null for every product, or a list of web-address names, "starts_on": null or "YYYY-MM-DD", "ends_on": null or "YYYY-MM-DD"}
359
+        {"type": "create_collection", "name": "Sun care", "description": null or one sentence, "products": [web-address names]}
327 360
         {"type": "create_bundle", "name": "...", "price": 85, "compare_at_price": null or a higher "was" price, "description": "..." or null, "status": "active" or "draft", "items": [{"product": "web-address name", "variant": "the choice, only for products with choices", "quantity": 1}]}
328 361
 
329 362
         - Use only web-address names, choices and codes from the lists you are given. A product with choices needs "variant" for price and stock changes, and inside a bundle.

+ 71
- 3
app/StorePlan/Ai/PlanWriter.php Zobrazit soubor

@@ -40,6 +40,7 @@ class PlanWriter
40 40
             prompt: PlanPrompt::generatePrompt($store),
41 41
             build: fn (array $answer) => [$answer, null],
42 42
             store: $store,
43
+            merchantWords: (string) $store->description,
43 44
         );
44 45
     }
45 46
 
@@ -65,6 +66,7 @@ class PlanWriter
65 66
                 ChatActions::check($store, $answer['actions'] ?? null),
66 67
             ],
67 68
             store: $store,
69
+            merchantWords: $instruction.' '.$store->description,
68 70
         );
69 71
     }
70 72
 
@@ -75,7 +77,7 @@ class PlanWriter
75 77
      *
76 78
      * @throws AiException
77 79
      */
78
-    private function askAndCheck(string $task, string $system, string $prompt, Closure $build, Store $store): PlanResult
80
+    private function askAndCheck(string $task, string $system, string $prompt, Closure $build, Store $store, string $merchantWords): PlanResult
79 81
     {
80 82
         $inputTokens = 0;
81 83
         $outputTokens = 0;
@@ -93,6 +95,7 @@ class PlanWriter
93 95
 
94 96
                 $clean = $this->validator->validate($plan);
95 97
                 $this->assertProductsExist($store, $clean);
98
+                $this->assertVideosWereGiven($store, $clean, $merchantWords);
96 99
 
97 100
                 return new PlanResult(
98 101
                     plan: $clean,
@@ -125,6 +128,57 @@ class PlanWriter
125 128
         );
126 129
     }
127 130
 
131
+    /**
132
+     * A video section may only play a video the merchant gave: its address must appear in their words
133
+     * (the chat message or the brand description). The AI never picks a video by itself.
134
+     *
135
+     * @param  array<string, mixed>  $plan
136
+     *
137
+     * @throws ValidationException
138
+     */
139
+    private function assertVideosWereGiven(Store $store, array $plan, string $merchantWords): void
140
+    {
141
+        $urls = fn (array $design) => array_values(array_filter(array_map(
142
+            fn (mixed $section) => is_array($section) && ($section['type'] ?? null) === 'video' ? ($section['content']['videoUrl'] ?? null) : null,
143
+            array_merge(...array_map(fn (mixed $page) => is_array($page) && is_array($page['sections'] ?? null) ? array_values($page['sections']) : [], array_values(is_array($design['pages'] ?? null) ? $design['pages'] : []))),
144
+        ), 'is_string'));
145
+
146
+        $new = array_diff($urls($plan), $urls(is_array($store->plan) ? $store->plan : []));
147
+
148
+        foreach ($new as $url) {
149
+            if (! str_contains($merchantWords, $url)) {
150
+                throw ValidationException::withMessages([
151
+                    'videoUrl' => "The video address [$url] was not given by the merchant. Only use a video address the merchant wrote; otherwise leave the video section out and ask for the link in \"reply\".",
152
+                ]);
153
+            }
154
+        }
155
+    }
156
+
157
+    /**
158
+     * Every collection name the plan's "shop by" sections use.
159
+     *
160
+     * @param  array<mixed>  $plan
161
+     * @return list<string>
162
+     */
163
+    private static function collectionNames(array $plan): array
164
+    {
165
+        $names = [];
166
+
167
+        foreach (is_array($plan['pages'] ?? null) ? $plan['pages'] : [] as $page) {
168
+            foreach (is_array($page['sections'] ?? null) ? $page['sections'] : [] as $section) {
169
+                if (($section['type'] ?? null) === 'shop_by' && is_array($section['content']['collections'] ?? null)) {
170
+                    foreach ($section['content']['collections'] as $name) {
171
+                        if (is_string($name)) {
172
+                            $names[$name] = $name;
173
+                        }
174
+                    }
175
+                }
176
+            }
177
+        }
178
+
179
+        return array_values($names);
180
+    }
181
+
128 182
     /**
129 183
      * A featured product section may only point at one of this store's active products.
130 184
      * A made-up name is sent back to the AI as a problem to fix.
@@ -144,10 +198,24 @@ class PlanWriter
144 198
             ]);
145 199
         }
146 200
 
201
+        // A "shop by" section may only name the store's own collections. Names already in the design are left
202
+        // alone: a deleted collection just stops showing.
203
+        $newCollections = array_values(array_diff(self::collectionNames($plan), self::collectionNames(is_array($store->plan) ? $store->plan : [])));
204
+        $unknownCollections = $newCollections === [] ? [] : array_values(array_diff(
205
+            $newCollections,
206
+            $store->collections()->whereIn('slug', $newCollections)->pluck('slug')->all(),
207
+        ));
208
+
209
+        if ($unknownCollections !== []) {
210
+            throw ValidationException::withMessages([
211
+                'collections' => 'These are not collections of this store: '.implode(', ', $unknownCollections).'. Use a name from the list of collections, or an empty list.',
212
+            ]);
213
+        }
214
+
147 215
         // A hero photo must be one of the store's photos. Made-up names go back to the AI. Names already in
148 216
         // the design are left alone: a deleted photo only makes that hero fall back to product photos.
149
-        $before = is_array($store->plan) ? array_column(HeroImages::sections($store->plan), 'image') : [];
150
-        $images = array_values(array_diff(array_unique(array_filter(array_column(HeroImages::sections($plan), 'image'))), $before));
217
+        $before = is_array($store->plan) ? HeroImages::refs($store->plan) : [];
218
+        $images = array_values(array_diff(HeroImages::refs($plan), $before));
151 219
         $missing = $images === [] ? [] : HeroImages::unknown($store, $images);
152 220
 
153 221
         if ($missing !== []) {

+ 29
- 1
app/StorePlan/HeroImages.php Zobrazit soubor

@@ -51,6 +51,34 @@ final class HeroImages
51 51
         return $found;
52 52
     }
53 53
 
54
+    /**
55
+     * Every photo name the plan uses: hero photos and bento tile photos.
56
+     *
57
+     * @param  array<string, mixed>  $plan
58
+     * @return list<string>
59
+     */
60
+    public static function refs(array $plan): array
61
+    {
62
+        $refs = [];
63
+
64
+        foreach ($plan['pages'] ?? [] as $page) {
65
+            foreach ($page['sections'] ?? [] as $section) {
66
+                $content = is_array($section['content'] ?? null) ? $section['content'] : [];
67
+                $candidates = ($section['type'] ?? null) === 'bento'
68
+                    ? array_column(is_array($content['tiles'] ?? null) ? $content['tiles'] : [], 'image')
69
+                    : [$content['image'] ?? null];
70
+
71
+                foreach ($candidates as $ref) {
72
+                    if (is_string($ref) && $ref !== '') {
73
+                        $refs[$ref] = $ref;
74
+                    }
75
+                }
76
+            }
77
+        }
78
+
79
+        return array_values($refs);
80
+    }
81
+
54 82
     /**
55 83
      * The plan with one hero changed: its photo, its layout, or both. Null for $image means "automatic".
56 84
      *
@@ -114,7 +142,7 @@ final class HeroImages
114 142
      */
115 143
     public static function forStorefront(Store $store, array $plan): array
116 144
     {
117
-        $refs = array_values(array_unique(array_filter(array_column(self::sections($plan), 'image'))));
145
+        $refs = self::refs($plan);
118 146
 
119 147
         return [
120 148
             // An object even when empty, so the frontend always gets {} and never [].

+ 37
- 2
app/StorePlan/PlanSchema.php Zobrazit soubor

@@ -171,6 +171,12 @@ final class PlanSchema
171 171
         'hero' => ['centered', 'split', 'image-full'],
172 172
         // A row of short reassurances, such as free shipping and secure payment. row: a band. boxed: small cards.
173 173
         'trust_bar' => ['row', 'boxed'],
174
+        // The store's collections as round photos (circles) or larger photo tiles (tiles).
175
+        'shop_by' => ['circles', 'tiles'],
176
+        // Tiles of different sizes for products, collections, offers and stories. mosaic: the first tile is big.
177
+        'bento' => ['mosaic', 'even'],
178
+        // A YouTube or Vimeo video. wide: full width under the heading. split: words beside the video.
179
+        'video' => ['wide', 'split'],
174 180
         // carousel: one row that scrolls sideways. large: 2 big cards across, like a magazine.
175 181
         'product_grid' => ['grid', 'minimal', 'carousel', 'large'],
176 182
         // stacked: a wide photo on top, the words centred under it.
@@ -215,7 +221,7 @@ final class PlanSchema
215 221
      *
216 222
      * @var list<string>
217 223
      */
218
-    public const array BUILT_IN_PATHS = ['shop', 'products', 'cart'];
224
+    public const array BUILT_IN_PATHS = ['shop', 'products', 'cart', 'collections'];
219 225
 
220 226
     /** The first page of every plan. */
221 227
     public const string HOME_PAGE = 'home';
@@ -225,7 +231,7 @@ final class PlanSchema
225 231
      *
226 232
      * @var list<string>
227 233
      */
228
-    public const array RESERVED_PAGE_IDS = ['shop', 'products', 'cart', 'checkout', 'orders', 'account', 'search'];
234
+    public const array RESERVED_PAGE_IDS = ['shop', 'products', 'cart', 'checkout', 'orders', 'account', 'search', 'collections'];
229 235
 
230 236
     /**
231 237
      * Links may only point inside the page, inside the site, or to safe outside targets.
@@ -235,6 +241,9 @@ final class PlanSchema
235 241
 
236 242
     public const string COLOR_PATTERN = '/^#[0-9A-Fa-f]{6}$/';
237 243
 
244
+    /** YouTube (watch, shorts, youtu.be) and Vimeo addresses only, so no other site can be embedded. */
245
+    public const string VIDEO_PATTERN = '~^https://(?:(?:www\.|m\.)?youtube\.com/(?:watch\?v=|shorts/)[A-Za-z0-9_-]{6,20}|youtu\.be/[A-Za-z0-9_-]{6,20}|(?:www\.)?vimeo\.com/[0-9]{5,12})(?:[?&#][^\s]*)?$~';
246
+
238 247
     public const string PRODUCT_SLUG_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
239 248
 
240 249
     /** Used for both section ids and page ids. */
@@ -315,6 +324,32 @@ final class PlanSchema
315 324
                 'items.*.title' => ['required_if:items.*.kind,custom', 'nullable', 'string', 'max:40'],
316 325
                 'items.*.text' => ['nullable', 'string', 'max:80'],
317 326
             ],
327
+            'shop_by' => [
328
+                'heading' => $text(80),
329
+                'subheading' => $optionalText(200),
330
+                // Web-address names of the store's collections, in order. An empty list shows every collection.
331
+                'collections' => ['present', 'array', 'max:8'],
332
+                'collections.*' => ['string', 'max:80', 'regex:'.self::PRODUCT_SLUG_PATTERN],
333
+            ],
334
+            'bento' => [
335
+                'heading' => $optionalText(80),
336
+                'tiles' => ['required', 'array', 'min:3', 'max:6'],
337
+                'tiles.*.title' => $text(60),
338
+                'tiles.*.text' => $optionalText(140),
339
+                'tiles.*.href' => $link,
340
+                // A photo name like a hero's ("product:..." or "upload:..."), or null for a colour tile.
341
+                'tiles.*.image' => ['nullable', 'string', 'max:140', 'regex:'.HeroImages::PATTERN],
342
+                'tiles.*.tone' => ['nullable', 'string', 'in:primary,accent,dark,surface'],
343
+            ],
344
+            'video' => [
345
+                'heading' => $text(80),
346
+                'text' => $optionalText(300),
347
+                // A YouTube or Vimeo address. It only loads when the shopper presses play.
348
+                'videoUrl' => ['required', 'string', 'max:300', 'regex:'.self::VIDEO_PATTERN],
349
+                'cta' => ['nullable', 'array'],
350
+                'cta.label' => ['required_with:cta', 'string', 'max:30'],
351
+                'cta.href' => ['required_with:cta', 'string', 'max:300', 'regex:'.self::LINK_PATTERN],
352
+            ],
318 353
             'testimonials' => [
319 354
                 'heading' => $text(80),
320 355
                 'items' => ['required', 'array', 'min:1', 'max:6'],

+ 23
- 0
app/StorePlan/SamplePlan.php Zobrazit soubor

@@ -114,6 +114,29 @@ final class SamplePlan
114 114
                         ],
115 115
                     ],
116 116
                 ],
117
+                [
118
+                    'id' => 'highlights',
119
+                    'type' => 'bento',
120
+                    'variant' => 'mosaic',
121
+                    'content' => [
122
+                        'heading' => null,
123
+                        'tiles' => [
124
+                            ['title' => 'The full range', 'text' => 'Every sambal, cooked fresh each week', 'href' => '/shop', 'image' => null, 'tone' => 'primary'],
125
+                            ['title' => 'New: Sambal Petai', 'text' => null, 'href' => '#products', 'image' => null, 'tone' => 'accent'],
126
+                            ['title' => 'Our story', 'text' => 'Grandma\'s recipe', 'href' => '#about', 'image' => null, 'tone' => 'dark'],
127
+                        ],
128
+                    ],
129
+                ],
130
+                [
131
+                    'id' => 'shop-by',
132
+                    'type' => 'shop_by',
133
+                    'variant' => 'circles',
134
+                    'content' => [
135
+                        'heading' => 'Shop by taste',
136
+                        'subheading' => null,
137
+                        'collections' => [],
138
+                    ],
139
+                ],
117 140
                 [
118 141
                     'id' => 'featured',
119 142
                     'type' => 'featured_product',

+ 166
- 0
app/StorePlan/SectionEditor.php Zobrazit soubor

@@ -0,0 +1,166 @@
1
+<?php
2
+
3
+namespace App\StorePlan;
4
+
5
+/**
6
+ * Small changes to a plan's sections from Design tab boxes: find sections of one type, add one after
7
+ * another, change its content or layout, or take it out. Every result still goes through PlanValidator.
8
+ */
9
+final class SectionEditor
10
+{
11
+    /**
12
+     * Every section of one type, on any page.
13
+     *
14
+     * @param  array<string, mixed>  $plan
15
+     * @return list<array{page_id: string, page_title: string, section: array<string, mixed>}>
16
+     */
17
+    public static function ofType(array $plan, string $type): array
18
+    {
19
+        $found = [];
20
+
21
+        foreach ($plan['pages'] ?? [] as $page) {
22
+            foreach ($page['sections'] ?? [] as $section) {
23
+                if (($section['type'] ?? null) === $type) {
24
+                    $found[] = ['page_id' => (string) $page['id'], 'page_title' => (string) ($page['title'] ?? ''), 'section' => $section];
25
+                }
26
+            }
27
+        }
28
+
29
+        return $found;
30
+    }
31
+
32
+    /**
33
+     * The type of a section, or null when the plan has none with that id.
34
+     *
35
+     * @param  array<string, mixed>  $plan
36
+     */
37
+    public static function typeOf(array $plan, string $sectionId): ?string
38
+    {
39
+        foreach ($plan['pages'] ?? [] as $page) {
40
+            foreach ($page['sections'] ?? [] as $section) {
41
+                if (($section['id'] ?? null) === $sectionId) {
42
+                    return (string) ($section['type'] ?? '');
43
+                }
44
+            }
45
+        }
46
+
47
+        return null;
48
+    }
49
+
50
+    /**
51
+     * The home page's sections as id and a short label, for "put it after" choices.
52
+     *
53
+     * @param  array<string, mixed>  $plan
54
+     * @return list<array{id: string, label: string}>
55
+     */
56
+    public static function homeSections(array $plan): array
57
+    {
58
+        $list = [];
59
+
60
+        foreach ($plan['pages'][0]['sections'] ?? [] as $section) {
61
+            $content = is_array($section['content'] ?? null) ? $section['content'] : [];
62
+            $words = $content['heading'] ?? $content['headline'] ?? $content['name'] ?? null;
63
+
64
+            $list[] = [
65
+                'id' => (string) $section['id'],
66
+                'label' => str_replace('_', ' ', (string) $section['type']).(is_string($words) && $words !== '' ? ' · '.$words : ''),
67
+            ];
68
+        }
69
+
70
+        return $list;
71
+    }
72
+
73
+    /**
74
+     * Add a section to the home page after another one (or at the end), with an id no other section has.
75
+     * Returns the plan and the new section's id.
76
+     *
77
+     * @param  array<string, mixed>  $plan
78
+     * @param  array{type: string, variant: string, content: array<string, mixed>}  $section
79
+     * @return array{0: array<string, mixed>, 1: string}
80
+     */
81
+    public static function addToHome(array $plan, ?string $afterId, string $baseId, array $section): array
82
+    {
83
+        $id = self::freeId($plan, $baseId);
84
+        $sections = $plan['pages'][0]['sections'] ?? [];
85
+        $position = count($sections);
86
+
87
+        foreach ($sections as $index => $existing) {
88
+            if (($existing['id'] ?? null) === $afterId) {
89
+                $position = $index + 1;
90
+            }
91
+        }
92
+
93
+        array_splice($sections, $position, 0, [['id' => $id, ...$section]]);
94
+        $plan['pages'][0]['sections'] = $sections;
95
+
96
+        return [$plan, $id];
97
+    }
98
+
99
+    /**
100
+     * Replace a section's content (and optionally its layout).
101
+     *
102
+     * @param  array<string, mixed>  $plan
103
+     * @param  array<string, mixed>  $content
104
+     * @return array<string, mixed>
105
+     */
106
+    public static function update(array $plan, string $sectionId, array $content, ?string $variant = null): array
107
+    {
108
+        foreach ($plan['pages'] ?? [] as $pageIndex => $page) {
109
+            foreach ($page['sections'] ?? [] as $sectionIndex => $section) {
110
+                if (($section['id'] ?? null) === $sectionId) {
111
+                    $plan['pages'][$pageIndex]['sections'][$sectionIndex]['content'] = $content;
112
+
113
+                    if ($variant !== null) {
114
+                        $plan['pages'][$pageIndex]['sections'][$sectionIndex]['variant'] = $variant;
115
+                    }
116
+                }
117
+            }
118
+        }
119
+
120
+        return $plan;
121
+    }
122
+
123
+    /**
124
+     * Take a section out. A page never ends up empty: the last section of a page stays.
125
+     *
126
+     * @param  array<string, mixed>  $plan
127
+     * @return array<string, mixed>
128
+     */
129
+    public static function remove(array $plan, string $sectionId): array
130
+    {
131
+        foreach ($plan['pages'] ?? [] as $pageIndex => $page) {
132
+            $kept = array_values(array_filter($page['sections'] ?? [], fn (array $section) => ($section['id'] ?? null) !== $sectionId));
133
+
134
+            if ($kept !== [] && count($kept) !== count($page['sections'] ?? [])) {
135
+                $plan['pages'][$pageIndex]['sections'] = $kept;
136
+            }
137
+        }
138
+
139
+        return $plan;
140
+    }
141
+
142
+    /**
143
+     * "video", or "video-2" when "video" is taken, and so on.
144
+     *
145
+     * @param  array<string, mixed>  $plan
146
+     */
147
+    private static function freeId(array $plan, string $base): string
148
+    {
149
+        $taken = [];
150
+
151
+        foreach ($plan['pages'] ?? [] as $page) {
152
+            foreach ($page['sections'] ?? [] as $section) {
153
+                $taken[(string) ($section['id'] ?? '')] = true;
154
+            }
155
+        }
156
+
157
+        $id = $base;
158
+        $suffix = 2;
159
+
160
+        while (isset($taken[$id])) {
161
+            $id = $base.'-'.$suffix++;
162
+        }
163
+
164
+        return $id;
165
+    }
166
+}

+ 40
- 0
database/migrations/2026_11_21_000001_create_collections_table.php Zobrazit soubor

@@ -0,0 +1,40 @@
1
+<?php
2
+
3
+use Illuminate\Database\Migrations\Migration;
4
+use Illuminate\Database\Schema\Blueprint;
5
+use Illuminate\Support\Facades\Schema;
6
+
7
+return new class extends Migration
8
+{
9
+    public function up(): void
10
+    {
11
+        // Groups of products shoppers can browse, such as "Sun care" or "Gifts under RM 50".
12
+        Schema::create('collections', function (Blueprint $table) {
13
+            $table->id();
14
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
15
+            $table->string('name', 60);
16
+            // The collection's address: /collections/{slug}. Unique within the store.
17
+            $table->string('slug', 80);
18
+            $table->string('description', 500)->nullable();
19
+            $table->unsignedSmallInteger('position')->default(0);
20
+            $table->timestamps();
21
+
22
+            $table->unique(['store_id', 'slug']);
23
+        });
24
+
25
+        // A product can be in several collections.
26
+        Schema::create('collection_product', function (Blueprint $table) {
27
+            $table->foreignId('collection_id')->constrained()->cascadeOnDelete();
28
+            $table->foreignId('product_id')->constrained()->cascadeOnDelete();
29
+            $table->unsignedSmallInteger('position')->default(0);
30
+
31
+            $table->primary(['collection_id', 'product_id']);
32
+        });
33
+    }
34
+
35
+    public function down(): void
36
+    {
37
+        Schema::dropIfExists('collection_product');
38
+        Schema::dropIfExists('collections');
39
+    }
40
+};

+ 432
- 0
resources/js/components/stores/bento-box.tsx Zobrazit soubor

@@ -0,0 +1,432 @@
1
+import { router, useForm } from '@inertiajs/react';
2
+import { ChevronDown, LayoutGrid, Plus, Trash2, X } from 'lucide-react';
3
+import type { FormEvent } from 'react';
4
+import { useState } from 'react';
5
+import BentoSectionController from '@/actions/App/Http/Controllers/BentoSectionController';
6
+import InputError from '@/components/input-error';
7
+import { Button } from '@/components/ui/button';
8
+import { Input } from '@/components/ui/input';
9
+import { Label } from '@/components/ui/label';
10
+import type {
11
+    BentoSectionInfo,
12
+    BentoTileInfo,
13
+    HeroChoice,
14
+    HomeSectionInfo,
15
+    LinkSuggestion,
16
+    Store,
17
+} from '@/types';
18
+
19
+const selectClass =
20
+    'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
21
+
22
+const tones: Record<string, string> = {
23
+    primary: 'Main colour',
24
+    accent: 'Accent colour',
25
+    dark: 'Dark',
26
+    surface: 'Soft',
27
+};
28
+
29
+const MIN_TILES = 3;
30
+const MAX_TILES = 6;
31
+
32
+/**
33
+ * The Design tab's Bento box: add tiles of different sizes (filled with a sensible start), then change
34
+ * each tile's words, link, photo and colour.
35
+ */
36
+export default function BentoBox({
37
+    store,
38
+    bentos,
39
+    homeSections,
40
+    photos,
41
+    links,
42
+    busy,
43
+}: {
44
+    store: Store;
45
+    bentos: BentoSectionInfo[];
46
+    homeSections: HomeSectionInfo[];
47
+    photos: HeroChoice[];
48
+    links: LinkSuggestion[];
49
+    busy: boolean;
50
+}) {
51
+    const trust = homeSections.find((section) =>
52
+        section.label.startsWith('trust bar'),
53
+    );
54
+    const [after, setAfter] = useState(trust?.id ?? homeSections[0]?.id ?? '');
55
+    const [adding, setAdding] = useState(false);
56
+
57
+    function add() {
58
+        router.post(
59
+            BentoSectionController.store.url(store.slug),
60
+            { after },
61
+            {
62
+                preserveScroll: true,
63
+                onStart: () => setAdding(true),
64
+                onFinish: () => setAdding(false),
65
+            },
66
+        );
67
+    }
68
+
69
+    return (
70
+        <details className="group rounded-xl border p-4" data-test="bento-box">
71
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
72
+                <LayoutGrid className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
73
+                <div>
74
+                    <h3 className="font-medium">
75
+                        Bento tiles{' '}
76
+                        {bentos.length > 0 && (
77
+                            <span className="text-muted-foreground">
78
+                                ({bentos.length})
79
+                            </span>
80
+                        )}
81
+                    </h3>
82
+                    <p className="mt-0.5 text-sm text-muted-foreground">
83
+                        Tiles of different sizes that lead shoppers to your
84
+                        range, collections, offers or story. Open to add or
85
+                        change them.
86
+                    </p>
87
+                </div>
88
+                <ChevronDown
89
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
90
+                    aria-hidden="true"
91
+                />
92
+            </summary>
93
+
94
+            {/* Suggestions for every tile link field. */}
95
+            <datalist id="bento-links">
96
+                {links.map((link) => (
97
+                    <option key={link.href} value={link.href}>
98
+                        {link.label}
99
+                    </option>
100
+                ))}
101
+            </datalist>
102
+
103
+            <div className="mt-4 space-y-6">
104
+                {bentos.map((bento) => (
105
+                    <BentoForm
106
+                        key={bento.section_id}
107
+                        store={store}
108
+                        bento={bento}
109
+                        photos={photos}
110
+                        busy={busy}
111
+                    />
112
+                ))}
113
+
114
+                <div className="flex flex-wrap items-end gap-3 border-t pt-4">
115
+                    <div className="grid min-w-48 flex-1 gap-1.5">
116
+                        <Label htmlFor="bento-after">
117
+                            {bentos.length > 0
118
+                                ? 'Add another set of tiles after'
119
+                                : 'Add bento tiles after'}
120
+                        </Label>
121
+                        <select
122
+                            id="bento-after"
123
+                            value={after}
124
+                            onChange={(event) => setAfter(event.target.value)}
125
+                            className={selectClass}
126
+                        >
127
+                            {homeSections.map((section) => (
128
+                                <option key={section.id} value={section.id}>
129
+                                    {section.label}
130
+                                </option>
131
+                            ))}
132
+                        </select>
133
+                    </div>
134
+                    <Button
135
+                        type="button"
136
+                        size="sm"
137
+                        variant="outline"
138
+                        onClick={add}
139
+                        disabled={busy || adding}
140
+                    >
141
+                        <Plus />
142
+                        Add tiles
143
+                    </Button>
144
+                </div>
145
+            </div>
146
+        </details>
147
+    );
148
+}
149
+
150
+function BentoForm({
151
+    store,
152
+    bento,
153
+    photos,
154
+    busy,
155
+}: {
156
+    store: Store;
157
+    bento: BentoSectionInfo;
158
+    photos: HeroChoice[];
159
+    busy: boolean;
160
+}) {
161
+    const form = useForm<{
162
+        heading: string;
163
+        variant: 'mosaic' | 'even';
164
+        tiles: BentoTileInfo[];
165
+    }>({
166
+        heading: bento.heading ?? '',
167
+        variant: bento.variant,
168
+        tiles: bento.tiles.map((tile) => ({
169
+            ...tile,
170
+            text: tile.text ?? '',
171
+            tone: tile.tone ?? 'surface',
172
+        })),
173
+    });
174
+    const [removing, setRemoving] = useState(false);
175
+    const errors = form.errors as Record<string, string | undefined>;
176
+    const id = bento.section_id;
177
+
178
+    function setTile(index: number, field: keyof BentoTileInfo, value: string) {
179
+        form.setData(
180
+            'tiles',
181
+            form.data.tiles.map((tile, i) =>
182
+                i === index
183
+                    ? {
184
+                          ...tile,
185
+                          [field]:
186
+                              value === '' && field === 'image' ? null : value,
187
+                      }
188
+                    : tile,
189
+            ),
190
+        );
191
+    }
192
+
193
+    function submit(event: FormEvent) {
194
+        event.preventDefault();
195
+        form.put(
196
+            BentoSectionController.update.url({
197
+                slug: store.slug,
198
+                sectionId: id,
199
+            }),
200
+            { preserveScroll: true },
201
+        );
202
+    }
203
+
204
+    function remove() {
205
+        router.delete(
206
+            BentoSectionController.destroy.url({
207
+                slug: store.slug,
208
+                sectionId: id,
209
+            }),
210
+            { preserveScroll: true },
211
+        );
212
+    }
213
+
214
+    const tileError = (index: number) =>
215
+        Object.entries(errors).find(([key]) =>
216
+            key.startsWith(`tiles.${index}.`),
217
+        )?.[1];
218
+    const disabled = busy || form.processing;
219
+
220
+    return (
221
+        <form onSubmit={submit} className="space-y-4" noValidate>
222
+            <div className="grid gap-3 sm:grid-cols-2">
223
+                <div className="grid gap-1.5">
224
+                    <Label htmlFor={`bento-heading-${id}`}>
225
+                        Heading above the tiles (optional)
226
+                    </Label>
227
+                    <Input
228
+                        id={`bento-heading-${id}`}
229
+                        value={form.data.heading}
230
+                        maxLength={80}
231
+                        onChange={(event) =>
232
+                            form.setData('heading', event.target.value)
233
+                        }
234
+                    />
235
+                </div>
236
+                <div className="grid gap-1.5">
237
+                    <Label htmlFor={`bento-variant-${id}`}>Layout</Label>
238
+                    <select
239
+                        id={`bento-variant-${id}`}
240
+                        value={form.data.variant}
241
+                        onChange={(event) =>
242
+                            form.setData(
243
+                                'variant',
244
+                                event.target.value as 'mosaic' | 'even',
245
+                            )
246
+                        }
247
+                        className={selectClass}
248
+                    >
249
+                        <option value="mosaic">
250
+                            One big tile and smaller ones
251
+                        </option>
252
+                        <option value="even">Equal tiles</option>
253
+                    </select>
254
+                </div>
255
+            </div>
256
+
257
+            <ol className="space-y-3">
258
+                {form.data.tiles.map((tile, index) => (
259
+                    <li
260
+                        key={index}
261
+                        className="space-y-2 rounded-lg border p-3"
262
+                        data-test="bento-tile"
263
+                    >
264
+                        <div className="flex items-center justify-between gap-2">
265
+                            <p className="text-sm font-medium">
266
+                                Tile {index + 1}
267
+                                {index === 0 && form.data.variant === 'mosaic'
268
+                                    ? ' (the big one)'
269
+                                    : ''}
270
+                            </p>
271
+                            {form.data.tiles.length > MIN_TILES && (
272
+                                <Button
273
+                                    type="button"
274
+                                    variant="ghost"
275
+                                    size="icon"
276
+                                    aria-label={`Remove tile ${index + 1}`}
277
+                                    onClick={() =>
278
+                                        form.setData(
279
+                                            'tiles',
280
+                                            form.data.tiles.filter(
281
+                                                (_, i) => i !== index,
282
+                                            ),
283
+                                        )
284
+                                    }
285
+                                >
286
+                                    <X />
287
+                                </Button>
288
+                            )}
289
+                        </div>
290
+                        <div className="grid gap-2 sm:grid-cols-2">
291
+                            <Input
292
+                                aria-label={`Tile ${index + 1} title`}
293
+                                value={tile.title}
294
+                                maxLength={60}
295
+                                placeholder="Title"
296
+                                onChange={(event) =>
297
+                                    setTile(index, 'title', event.target.value)
298
+                                }
299
+                            />
300
+                            <Input
301
+                                aria-label={`Tile ${index + 1} short text`}
302
+                                value={tile.text ?? ''}
303
+                                maxLength={140}
304
+                                placeholder="Short text (optional)"
305
+                                onChange={(event) =>
306
+                                    setTile(index, 'text', event.target.value)
307
+                                }
308
+                            />
309
+                            <Input
310
+                                aria-label={`Tile ${index + 1} link`}
311
+                                list="bento-links"
312
+                                value={tile.href}
313
+                                placeholder="/shop"
314
+                                onChange={(event) =>
315
+                                    setTile(index, 'href', event.target.value)
316
+                                }
317
+                            />
318
+                            <div className="grid grid-cols-2 gap-2">
319
+                                <select
320
+                                    aria-label={`Tile ${index + 1} photo`}
321
+                                    value={tile.image ?? ''}
322
+                                    onChange={(event) =>
323
+                                        setTile(
324
+                                            index,
325
+                                            'image',
326
+                                            event.target.value,
327
+                                        )
328
+                                    }
329
+                                    className={selectClass}
330
+                                >
331
+                                    <option value="">No photo</option>
332
+                                    {photos.map((photo) => (
333
+                                        <option
334
+                                            key={photo.ref}
335
+                                            value={photo.ref}
336
+                                        >
337
+                                            {photo.label}
338
+                                        </option>
339
+                                    ))}
340
+                                </select>
341
+                                <select
342
+                                    aria-label={`Tile ${index + 1} colour`}
343
+                                    value={tile.tone ?? 'surface'}
344
+                                    disabled={Boolean(tile.image)}
345
+                                    onChange={(event) =>
346
+                                        setTile(
347
+                                            index,
348
+                                            'tone',
349
+                                            event.target.value,
350
+                                        )
351
+                                    }
352
+                                    className={selectClass}
353
+                                >
354
+                                    {Object.entries(tones).map(
355
+                                        ([value, label]) => (
356
+                                            <option key={value} value={value}>
357
+                                                {label}
358
+                                            </option>
359
+                                        ),
360
+                                    )}
361
+                                </select>
362
+                            </div>
363
+                        </div>
364
+                        <InputError message={tileError(index)} />
365
+                    </li>
366
+                ))}
367
+            </ol>
368
+
369
+            {form.data.tiles.length < MAX_TILES && (
370
+                <Button
371
+                    type="button"
372
+                    variant="outline"
373
+                    size="sm"
374
+                    onClick={() =>
375
+                        form.setData('tiles', [
376
+                            ...form.data.tiles,
377
+                            {
378
+                                title: '',
379
+                                text: '',
380
+                                href: '/shop',
381
+                                image: null,
382
+                                tone: 'surface',
383
+                            },
384
+                        ])
385
+                    }
386
+                >
387
+                    <Plus />
388
+                    Add a tile
389
+                </Button>
390
+            )}
391
+
392
+            <InputError message={errors.section ?? errors.tiles} />
393
+
394
+            <div className="flex flex-wrap items-center gap-2">
395
+                <Button size="sm" disabled={disabled}>
396
+                    Save tiles
397
+                </Button>
398
+                {removing ? (
399
+                    <>
400
+                        <Button
401
+                            type="button"
402
+                            size="sm"
403
+                            variant="destructive"
404
+                            onClick={remove}
405
+                            disabled={disabled}
406
+                        >
407
+                            Yes, remove these tiles
408
+                        </Button>
409
+                        <Button
410
+                            type="button"
411
+                            size="sm"
412
+                            variant="ghost"
413
+                            onClick={() => setRemoving(false)}
414
+                        >
415
+                            Keep them
416
+                        </Button>
417
+                    </>
418
+                ) : (
419
+                    <Button
420
+                        type="button"
421
+                        size="sm"
422
+                        variant="ghost"
423
+                        onClick={() => setRemoving(true)}
424
+                    >
425
+                        <Trash2 />
426
+                        Remove
427
+                    </Button>
428
+                )}
429
+            </div>
430
+        </form>
431
+    );
432
+}

+ 87
- 78
resources/js/components/stores/featured-picker.tsx Zobrazit soubor

@@ -1,5 +1,5 @@
1 1
 import { router } from '@inertiajs/react';
2
-import { Link2 } from 'lucide-react';
2
+import { ChevronDown, Link2 } from 'lucide-react';
3 3
 import { useState } from 'react';
4 4
 import FeaturedProductController from '@/actions/App/Http/Controllers/FeaturedProductController';
5 5
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
@@ -46,11 +46,11 @@ export default function FeaturedPicker({
46 46
     }
47 47
 
48 48
     return (
49
-        <div
50
-            className="space-y-4 rounded-xl border p-4"
49
+        <details
50
+            className="group rounded-xl border p-4"
51 51
             data-test="featured-picker"
52 52
         >
53
-            <div className="flex items-start gap-3">
53
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
54 54
                 <Link2 className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
55 55
                 <div>
56 56
                     <h3 className="font-medium">Featured product</h3>
@@ -60,83 +60,92 @@ export default function FeaturedPicker({
60 60
                         opens its page.
61 61
                     </p>
62 62
                 </div>
63
-            </div>
63
+                <ChevronDown
64
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
65
+                    aria-hidden="true"
66
+                />
67
+            </summary>
64 68
 
65
-            {products.length === 0 ? (
66
-                <p className="text-sm text-muted-foreground">
67
-                    You have no active products yet.{' '}
68
-                    <a
69
-                        href={ProductController.create.url(store.slug)}
70
-                        className="underline underline-offset-2"
71
-                    >
72
-                        Add a product
73
-                    </a>{' '}
74
-                    to show it here. Until then the section shows example text.
75
-                </p>
76
-            ) : (
77
-                <ul className="space-y-3">
78
-                    {sections.map((section) => {
79
-                        const id = `featured-${section.section_id}`;
80
-                        const missing =
81
-                            section.product_slug !== null &&
82
-                            !products.some(
83
-                                (product) =>
84
-                                    product.slug === section.product_slug,
85
-                            );
69
+            <div className="mt-4 space-y-4">
70
+                {products.length === 0 ? (
71
+                    <p className="text-sm text-muted-foreground">
72
+                        You have no active products yet.{' '}
73
+                        <a
74
+                            href={ProductController.create.url(store.slug)}
75
+                            className="underline underline-offset-2"
76
+                        >
77
+                            Add a product
78
+                        </a>{' '}
79
+                        to show it here. Until then the section shows example
80
+                        text.
81
+                    </p>
82
+                ) : (
83
+                    <ul className="space-y-3">
84
+                        {sections.map((section) => {
85
+                            const id = `featured-${section.section_id}`;
86
+                            const missing =
87
+                                section.product_slug !== null &&
88
+                                !products.some(
89
+                                    (product) =>
90
+                                        product.slug === section.product_slug,
91
+                                );
86 92
 
87
-                        return (
88
-                            <li
89
-                                key={section.section_id}
90
-                                className="grid gap-1.5"
91
-                            >
92
-                                <label htmlFor={id} className="text-sm">
93
-                                    “{section.name}”
94
-                                    {section.page_id !== 'home' && (
95
-                                        <span className="text-muted-foreground">
96
-                                            {' '}
97
-                                            on {section.page_title}
98
-                                        </span>
99
-                                    )}
100
-                                </label>
101
-                                <select
102
-                                    id={id}
103
-                                    value={
104
-                                        missing
105
-                                            ? ''
106
-                                            : (section.product_slug ?? '')
107
-                                    }
108
-                                    disabled={
109
-                                        busy || saving === section.section_id
110
-                                    }
111
-                                    onChange={(event) =>
112
-                                        choose(section, event.target.value)
113
-                                    }
114
-                                    className={fieldClass}
93
+                            return (
94
+                                <li
95
+                                    key={section.section_id}
96
+                                    className="grid gap-1.5"
115 97
                                 >
116
-                                    <option value="">
117
-                                        No product (hide the price)
118
-                                    </option>
119
-                                    {products.map((product) => (
120
-                                        <option
121
-                                            key={product.slug}
122
-                                            value={product.slug}
123
-                                        >
124
-                                            {product.name} ·{' '}
125
-                                            {formatRinggit(product.price)}
98
+                                    <label htmlFor={id} className="text-sm">
99
+                                        “{section.name}”
100
+                                        {section.page_id !== 'home' && (
101
+                                            <span className="text-muted-foreground">
102
+                                                {' '}
103
+                                                on {section.page_title}
104
+                                            </span>
105
+                                        )}
106
+                                    </label>
107
+                                    <select
108
+                                        id={id}
109
+                                        value={
110
+                                            missing
111
+                                                ? ''
112
+                                                : (section.product_slug ?? '')
113
+                                        }
114
+                                        disabled={
115
+                                            busy ||
116
+                                            saving === section.section_id
117
+                                        }
118
+                                        onChange={(event) =>
119
+                                            choose(section, event.target.value)
120
+                                        }
121
+                                        className={fieldClass}
122
+                                    >
123
+                                        <option value="">
124
+                                            No product (hide the price)
126 125
                                         </option>
127
-                                    ))}
128
-                                </select>
129
-                                {missing && (
130
-                                    <p className="text-xs text-amber-700 dark:text-amber-400">
131
-                                        The product this section showed is no
132
-                                        longer active. Choose another one.
133
-                                    </p>
134
-                                )}
135
-                            </li>
136
-                        );
137
-                    })}
138
-                </ul>
139
-            )}
140
-        </div>
126
+                                        {products.map((product) => (
127
+                                            <option
128
+                                                key={product.slug}
129
+                                                value={product.slug}
130
+                                            >
131
+                                                {product.name} ·{' '}
132
+                                                {formatRinggit(product.price)}
133
+                                            </option>
134
+                                        ))}
135
+                                    </select>
136
+                                    {missing && (
137
+                                        <p className="text-xs text-amber-700 dark:text-amber-400">
138
+                                            The product this section showed is
139
+                                            no longer active. Choose another
140
+                                            one.
141
+                                        </p>
142
+                                    )}
143
+                                </li>
144
+                            );
145
+                        })}
146
+                    </ul>
147
+                )}
148
+            </div>
149
+        </details>
141 150
     );
142 151
 }

+ 22
- 16
resources/js/components/stores/hero-picker.tsx Zobrazit soubor

@@ -1,5 +1,5 @@
1 1
 import { router, useForm } from '@inertiajs/react';
2
-import { Check, ImageIcon, Upload } from 'lucide-react';
2
+import { ChevronDown, Check, ImageIcon, Upload } from 'lucide-react';
3 3
 import type { FormEvent } from 'react';
4 4
 import { useState } from 'react';
5 5
 import HeroImageController from '@/actions/App/Http/Controllers/HeroImageController';
@@ -34,11 +34,11 @@ export default function HeroPicker({
34 34
     }
35 35
 
36 36
     return (
37
-        <div
38
-            className="space-y-5 rounded-xl border p-4"
37
+        <details
38
+            className="group rounded-xl border p-4"
39 39
             data-test="hero-picker"
40 40
         >
41
-            <div className="flex items-start gap-3">
41
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
42 42
                 <ImageIcon className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
43 43
                 <div>
44 44
                     <h3 className="font-medium">Hero</h3>
@@ -47,19 +47,25 @@ export default function HeroPicker({
47 47
                         or upload your own banner photo.
48 48
                     </p>
49 49
                 </div>
50
-            </div>
51
-
52
-            {sections.map((section) => (
53
-                <HeroRow
54
-                    key={section.section_id}
55
-                    store={store}
56
-                    section={section}
57
-                    choices={choices}
58
-                    busy={busy}
59
-                    showTitle={sections.length > 1}
50
+                <ChevronDown
51
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
52
+                    aria-hidden="true"
60 53
                 />
61
-            ))}
62
-        </div>
54
+            </summary>
55
+
56
+            <div className="mt-5 space-y-5">
57
+                {sections.map((section) => (
58
+                    <HeroRow
59
+                        key={section.section_id}
60
+                        store={store}
61
+                        section={section}
62
+                        choices={choices}
63
+                        busy={busy}
64
+                        showTitle={sections.length > 1}
65
+                    />
66
+                ))}
67
+            </div>
68
+        </details>
63 69
     );
64 70
 }
65 71
 

+ 15
- 2
resources/js/components/stores/layout-picker.tsx Zobrazit soubor

@@ -1,5 +1,5 @@
1 1
 import { router } from '@inertiajs/react';
2
-import { LayoutTemplate } from 'lucide-react';
2
+import { ChevronDown, LayoutTemplate } from 'lucide-react';
3 3
 import { useState } from 'react';
4 4
 import SectionLayoutController from '@/actions/App/Http/Controllers/SectionLayoutController';
5 5
 import type { LayoutSection, Store } from '@/types';
@@ -11,6 +11,9 @@ const fieldClass =
11 11
 const typeNames: Record<string, string> = {
12 12
     header: 'Header',
13 13
     trust_bar: 'Trust row',
14
+    shop_by: 'Shop by collection',
15
+    bento: 'Bento tiles',
16
+    video: 'Video',
14 17
     product_grid: 'Products',
15 18
     featured_product: 'Featured product',
16 19
     about: 'About',
@@ -24,6 +27,9 @@ const typeNames: Record<string, string> = {
24 27
 const layoutNames: Record<string, Record<string, string>> = {
25 28
     header: { simple: 'Logo on the left', centered: 'Logo in the middle' },
26 29
     trust_bar: { row: 'Icon row', boxed: 'Small cards' },
30
+    shop_by: { circles: 'Round photos', tiles: 'Photo tiles' },
31
+    bento: { mosaic: 'One big tile and smaller ones', even: 'Equal tiles' },
32
+    video: { wide: 'Wide video', split: 'Words beside the video' },
27 33
     product_grid: {
28 34
         grid: 'Grid',
29 35
         minimal: 'Centred grid',
@@ -96,7 +102,10 @@ export default function LayoutPicker({
96 102
     }
97 103
 
98 104
     return (
99
-        <details className="rounded-xl border p-4" data-test="layout-picker">
105
+        <details
106
+            className="group rounded-xl border p-4"
107
+            data-test="layout-picker"
108
+        >
100 109
             <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
101 110
                 <LayoutTemplate className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
102 111
                 <div>
@@ -106,6 +115,10 @@ export default function LayoutPicker({
106 115
                         one.
107 116
                     </p>
108 117
                 </div>
118
+                <ChevronDown
119
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
120
+                    aria-hidden="true"
121
+                />
109 122
             </summary>
110 123
 
111 124
             <ul className="mt-4 divide-y">

+ 87
- 80
resources/js/components/stores/style-picker.tsx Zobrazit soubor

@@ -1,5 +1,5 @@
1 1
 import { router } from '@inertiajs/react';
2
-import { Check, Palette } from 'lucide-react';
2
+import { ChevronDown, Check, Palette } from 'lucide-react';
3 3
 import type { CSSProperties } from 'react';
4 4
 import { useState } from 'react';
5 5
 import StoreStyleController from '@/actions/App/Http/Controllers/StoreStyleController';
@@ -105,11 +105,11 @@ export default function StylePicker({
105 105
     const disabled = busy || saving;
106 106
 
107 107
     return (
108
-        <div
109
-            className="space-y-5 rounded-xl border p-4"
108
+        <details
109
+            className="group rounded-xl border p-4"
110 110
             data-test="style-picker"
111 111
         >
112
-            <div className="flex items-start gap-3">
112
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
113 113
                 <Palette className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
114 114
                 <div>
115 115
                     <h3 className="font-medium">Style</h3>
@@ -118,86 +118,93 @@ export default function StylePicker({
118 118
                         spacing and motion. Your colours stay the same.
119 119
                     </p>
120 120
                 </div>
121
-            </div>
121
+                <ChevronDown
122
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
123
+                    aria-hidden="true"
124
+                />
125
+            </summary>
122 126
 
123
-            <ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
124
-                {presets.map((preset) => {
125
-                    const selected = active?.key === preset.key;
127
+            <div className="mt-5 space-y-5">
128
+                <ul className="grid grid-cols-2 gap-2 sm:grid-cols-3">
129
+                    {presets.map((preset) => {
130
+                        const selected = active?.key === preset.key;
126 131
 
127
-                    return (
128
-                        <li key={preset.key}>
129
-                            <button
130
-                                type="button"
131
-                                disabled={disabled}
132
-                                aria-pressed={selected}
133
-                                onClick={() => send({ preset: preset.key })}
134
-                                className={cn(
135
-                                    'relative flex h-full w-full flex-col gap-2 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50 disabled:opacity-50',
136
-                                    selected &&
137
-                                        'border-foreground ring-1 ring-foreground',
138
-                                )}
139
-                            >
140
-                                <span
141
-                                    aria-hidden="true"
142
-                                    className="inline-flex w-fit px-3 py-1 text-xs font-semibold"
143
-                                    style={sample(preset)}
132
+                        return (
133
+                            <li key={preset.key}>
134
+                                <button
135
+                                    type="button"
136
+                                    disabled={disabled}
137
+                                    aria-pressed={selected}
138
+                                    onClick={() => send({ preset: preset.key })}
139
+                                    className={cn(
140
+                                        'relative flex h-full w-full flex-col gap-2 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50 disabled:opacity-50',
141
+                                        selected &&
142
+                                            'border-foreground ring-1 ring-foreground',
143
+                                    )}
144 144
                                 >
145
-                                    Shop now
146
-                                </span>
147
-                                <span className="text-sm font-medium">
148
-                                    {preset.label}
149
-                                </span>
150
-                                <span className="text-xs text-muted-foreground">
151
-                                    {preset.hint}
152
-                                </span>
153
-                                {selected && (
154
-                                    <Check className="absolute top-2 right-2 size-4" />
155
-                                )}
156
-                            </button>
157
-                        </li>
158
-                    );
159
-                })}
160
-            </ul>
145
+                                    <span
146
+                                        aria-hidden="true"
147
+                                        className="inline-flex w-fit px-3 py-1 text-xs font-semibold"
148
+                                        style={sample(preset)}
149
+                                    >
150
+                                        Shop now
151
+                                    </span>
152
+                                    <span className="text-sm font-medium">
153
+                                        {preset.label}
154
+                                    </span>
155
+                                    <span className="text-xs text-muted-foreground">
156
+                                        {preset.hint}
157
+                                    </span>
158
+                                    {selected && (
159
+                                        <Check className="absolute top-2 right-2 size-4" />
160
+                                    )}
161
+                                </button>
162
+                            </li>
163
+                        );
164
+                    })}
165
+                </ul>
161 166
 
162
-            <details className="rounded-lg border px-3 py-2">
163
-                <summary className="cursor-pointer text-sm font-medium">
164
-                    Fine-tune
165
-                </summary>
166
-                <div className="grid gap-3 py-3 sm:grid-cols-2">
167
-                    {fineTune.map((option) => (
168
-                        <div key={option.key} className="grid gap-1.5">
169
-                            <label
170
-                                htmlFor={`style-${option.key}`}
171
-                                className="text-sm"
172
-                            >
173
-                                {option.label}
174
-                            </label>
175
-                            <select
176
-                                id={`style-${option.key}`}
177
-                                value={current.options[option.key]}
178
-                                disabled={disabled}
179
-                                onChange={(event) =>
180
-                                    send({
181
-                                        style: {
182
-                                            [option.key]: event.target.value,
183
-                                        },
184
-                                    })
185
-                                }
186
-                                className={fieldClass}
187
-                            >
188
-                                {Object.entries(option.choices).map(
189
-                                    ([value, label]) => (
190
-                                        <option key={value} value={value}>
191
-                                            {label}
192
-                                        </option>
193
-                                    ),
194
-                                )}
195
-                            </select>
196
-                        </div>
197
-                    ))}
198
-                </div>
199
-            </details>
200
-        </div>
167
+                <details className="rounded-lg border px-3 py-2">
168
+                    <summary className="cursor-pointer text-sm font-medium">
169
+                        Fine-tune
170
+                    </summary>
171
+                    <div className="grid gap-3 py-3 sm:grid-cols-2">
172
+                        {fineTune.map((option) => (
173
+                            <div key={option.key} className="grid gap-1.5">
174
+                                <label
175
+                                    htmlFor={`style-${option.key}`}
176
+                                    className="text-sm"
177
+                                >
178
+                                    {option.label}
179
+                                </label>
180
+                                <select
181
+                                    id={`style-${option.key}`}
182
+                                    value={current.options[option.key]}
183
+                                    disabled={disabled}
184
+                                    onChange={(event) =>
185
+                                        send({
186
+                                            style: {
187
+                                                [option.key]:
188
+                                                    event.target.value,
189
+                                            },
190
+                                        })
191
+                                    }
192
+                                    className={fieldClass}
193
+                                >
194
+                                    {Object.entries(option.choices).map(
195
+                                        ([value, label]) => (
196
+                                            <option key={value} value={value}>
197
+                                                {label}
198
+                                            </option>
199
+                                        ),
200
+                                    )}
201
+                                </select>
202
+                            </div>
203
+                        ))}
204
+                    </div>
205
+                </details>
206
+            </div>
207
+        </details>
201 208
     );
202 209
 }
203 210
 

+ 298
- 0
resources/js/components/stores/video-box.tsx Zobrazit soubor

@@ -0,0 +1,298 @@
1
+import { router, useForm } from '@inertiajs/react';
2
+import { ChevronDown, Clapperboard, Trash2 } from 'lucide-react';
3
+import type { FormEvent } from 'react';
4
+import { useState } from 'react';
5
+import VideoSectionController from '@/actions/App/Http/Controllers/VideoSectionController';
6
+import InputError from '@/components/input-error';
7
+import { Button } from '@/components/ui/button';
8
+import { Input } from '@/components/ui/input';
9
+import { Label } from '@/components/ui/label';
10
+import type { HomeSectionInfo, Store, VideoSectionInfo } from '@/types';
11
+
12
+const selectClass =
13
+    'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:opacity-50 md:text-sm';
14
+
15
+/** The picture YouTube shows for a video, to preview the link. Null for Vimeo or a link that is not a video yet. */
16
+function youtubePicture(url: string): string | null {
17
+    const match = url.match(
18
+        /^https:\/\/(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{6,20})/,
19
+    );
20
+
21
+    return match ? `https://i.ytimg.com/vi/${match[1]}/mqdefault.jpg` : null;
22
+}
23
+
24
+/**
25
+ * The Design tab's Video box: add a YouTube or Vimeo video, change it, or remove it.
26
+ */
27
+export default function VideoBox({
28
+    store,
29
+    videos,
30
+    homeSections,
31
+    busy,
32
+}: {
33
+    store: Store;
34
+    videos: VideoSectionInfo[];
35
+    homeSections: HomeSectionInfo[];
36
+    busy: boolean;
37
+}) {
38
+    return (
39
+        <details className="group rounded-xl border p-4" data-test="video-box">
40
+            <summary className="flex cursor-pointer list-none items-start gap-3 [&::-webkit-details-marker]:hidden">
41
+                <Clapperboard className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
42
+                <div>
43
+                    <h3 className="font-medium">
44
+                        Video{' '}
45
+                        {videos.length > 0 && (
46
+                            <span className="text-muted-foreground">
47
+                                ({videos.length})
48
+                            </span>
49
+                        )}
50
+                    </h3>
51
+                    <p className="mt-0.5 text-sm text-muted-foreground">
52
+                        Show a YouTube or Vimeo video, such as how your product
53
+                        is made. Open to add or change one.
54
+                    </p>
55
+                </div>
56
+                <ChevronDown
57
+                    className="mt-1 ml-auto size-4 shrink-0 text-muted-foreground transition-transform group-open:rotate-180"
58
+                    aria-hidden="true"
59
+                />
60
+            </summary>
61
+
62
+            <div className="mt-4 space-y-6">
63
+                {videos.map((video) => (
64
+                    <VideoForm
65
+                        key={video.section_id}
66
+                        store={store}
67
+                        video={video}
68
+                        homeSections={homeSections}
69
+                        busy={busy}
70
+                    />
71
+                ))}
72
+
73
+                <div className="space-y-3 border-t pt-4">
74
+                    <p className="text-sm font-medium">
75
+                        {videos.length > 0
76
+                            ? 'Add another video'
77
+                            : 'Add a video'}
78
+                    </p>
79
+                    <VideoForm
80
+                        store={store}
81
+                        video={null}
82
+                        homeSections={homeSections}
83
+                        busy={busy}
84
+                    />
85
+                </div>
86
+            </div>
87
+        </details>
88
+    );
89
+}
90
+
91
+function VideoForm({
92
+    store,
93
+    video,
94
+    homeSections,
95
+    busy,
96
+}: {
97
+    store: Store;
98
+    video: VideoSectionInfo | null;
99
+    homeSections: HomeSectionInfo[];
100
+    busy: boolean;
101
+}) {
102
+    const key = video?.section_id ?? 'new';
103
+    const about = homeSections.find((section) =>
104
+        section.label.startsWith('about'),
105
+    );
106
+    const form = useForm({
107
+        video_url: video?.videoUrl ?? '',
108
+        heading: video?.heading ?? '',
109
+        text: video?.text ?? '',
110
+        variant: video?.variant ?? 'wide',
111
+        after: about?.id ?? homeSections[homeSections.length - 1]?.id ?? '',
112
+    });
113
+    const [removing, setRemoving] = useState(false);
114
+    const picture = youtubePicture(form.data.video_url);
115
+    const errors = form.errors as Record<string, string | undefined>;
116
+
117
+    function submit(event: FormEvent) {
118
+        event.preventDefault();
119
+
120
+        const options = {
121
+            preserveScroll: true,
122
+            onSuccess: () => {
123
+                if (!video) {
124
+                    form.reset();
125
+                }
126
+            },
127
+        };
128
+
129
+        if (video) {
130
+            form.put(
131
+                VideoSectionController.update.url({
132
+                    slug: store.slug,
133
+                    sectionId: video.section_id,
134
+                }),
135
+                options,
136
+            );
137
+        } else {
138
+            form.post(VideoSectionController.store.url(store.slug), options);
139
+        }
140
+    }
141
+
142
+    function remove() {
143
+        if (!video) {
144
+            return;
145
+        }
146
+
147
+        router.delete(
148
+            VideoSectionController.destroy.url({
149
+                slug: store.slug,
150
+                sectionId: video.section_id,
151
+            }),
152
+            { preserveScroll: true },
153
+        );
154
+    }
155
+
156
+    const disabled = busy || form.processing;
157
+
158
+    return (
159
+        <form onSubmit={submit} className="space-y-3" noValidate>
160
+            <div className="grid gap-3 sm:grid-cols-[1fr_auto] sm:items-start">
161
+                <div className="grid gap-1.5">
162
+                    <Label htmlFor={`video-url-${key}`}>
163
+                        YouTube or Vimeo link
164
+                    </Label>
165
+                    <Input
166
+                        id={`video-url-${key}`}
167
+                        value={form.data.video_url}
168
+                        onChange={(event) =>
169
+                            form.setData('video_url', event.target.value)
170
+                        }
171
+                        placeholder="https://youtu.be/abc123"
172
+                        inputMode="url"
173
+                    />
174
+                    <InputError message={form.errors.video_url} />
175
+                </div>
176
+                {picture && (
177
+                    <img
178
+                        src={picture}
179
+                        alt="Video preview"
180
+                        className="aspect-video w-full rounded-md object-cover sm:w-40"
181
+                    />
182
+                )}
183
+            </div>
184
+
185
+            <div className="grid gap-1.5">
186
+                <Label htmlFor={`video-heading-${key}`}>Heading</Label>
187
+                <Input
188
+                    id={`video-heading-${key}`}
189
+                    value={form.data.heading}
190
+                    maxLength={80}
191
+                    onChange={(event) =>
192
+                        form.setData('heading', event.target.value)
193
+                    }
194
+                    placeholder="See how we make it"
195
+                />
196
+                <InputError message={form.errors.heading} />
197
+            </div>
198
+
199
+            <div className="grid gap-1.5">
200
+                <Label htmlFor={`video-text-${key}`}>
201
+                    Short text (optional)
202
+                </Label>
203
+                <textarea
204
+                    id={`video-text-${key}`}
205
+                    value={form.data.text}
206
+                    maxLength={300}
207
+                    rows={2}
208
+                    onChange={(event) =>
209
+                        form.setData('text', event.target.value)
210
+                    }
211
+                    className="w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm"
212
+                />
213
+                <InputError message={form.errors.text} />
214
+            </div>
215
+
216
+            <div className="grid gap-3 sm:grid-cols-2">
217
+                <div className="grid gap-1.5">
218
+                    <Label htmlFor={`video-variant-${key}`}>Layout</Label>
219
+                    <select
220
+                        id={`video-variant-${key}`}
221
+                        value={form.data.variant}
222
+                        onChange={(event) =>
223
+                            form.setData(
224
+                                'variant',
225
+                                event.target.value as 'wide' | 'split',
226
+                            )
227
+                        }
228
+                        className={selectClass}
229
+                    >
230
+                        <option value="wide">Wide video</option>
231
+                        <option value="split">Words beside the video</option>
232
+                    </select>
233
+                </div>
234
+                {!video && (
235
+                    <div className="grid gap-1.5">
236
+                        <Label htmlFor={`video-after-${key}`}>
237
+                            Put it after
238
+                        </Label>
239
+                        <select
240
+                            id={`video-after-${key}`}
241
+                            value={form.data.after}
242
+                            onChange={(event) =>
243
+                                form.setData('after', event.target.value)
244
+                            }
245
+                            className={selectClass}
246
+                        >
247
+                            {homeSections.map((section) => (
248
+                                <option key={section.id} value={section.id}>
249
+                                    {section.label}
250
+                                </option>
251
+                            ))}
252
+                        </select>
253
+                    </div>
254
+                )}
255
+            </div>
256
+
257
+            <InputError message={errors.section} />
258
+
259
+            <div className="flex flex-wrap items-center gap-2">
260
+                <Button size="sm" disabled={disabled}>
261
+                    {video ? 'Save video' : 'Add video'}
262
+                </Button>
263
+                {video &&
264
+                    (removing ? (
265
+                        <>
266
+                            <Button
267
+                                type="button"
268
+                                size="sm"
269
+                                variant="destructive"
270
+                                onClick={remove}
271
+                                disabled={disabled}
272
+                            >
273
+                                Yes, remove it
274
+                            </Button>
275
+                            <Button
276
+                                type="button"
277
+                                size="sm"
278
+                                variant="ghost"
279
+                                onClick={() => setRemoving(false)}
280
+                            >
281
+                                Keep it
282
+                            </Button>
283
+                        </>
284
+                    ) : (
285
+                        <Button
286
+                            type="button"
287
+                            size="sm"
288
+                            variant="ghost"
289
+                            onClick={() => setRemoving(true)}
290
+                        >
291
+                            <Trash2 />
292
+                            Remove
293
+                        </Button>
294
+                    ))}
295
+            </div>
296
+        </form>
297
+    );
298
+}

+ 249
- 0
resources/js/pages/stores/collections/form.tsx Zobrazit soubor

@@ -0,0 +1,249 @@
1
+import { Form, Head, Link } from '@inertiajs/react';
2
+import { ImageOff } from 'lucide-react';
3
+import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
4
+import ProductController from '@/actions/App/Http/Controllers/ProductController';
5
+import Heading from '@/components/heading';
6
+import InputError from '@/components/input-error';
7
+import { Button } from '@/components/ui/button';
8
+import { Checkbox } from '@/components/ui/checkbox';
9
+import {
10
+    Dialog,
11
+    DialogClose,
12
+    DialogContent,
13
+    DialogDescription,
14
+    DialogFooter,
15
+    DialogHeader,
16
+    DialogTitle,
17
+    DialogTrigger,
18
+} from '@/components/ui/dialog';
19
+import { Input } from '@/components/ui/input';
20
+import { Label } from '@/components/ui/label';
21
+import { dashboard } from '@/routes';
22
+import type { StoreSummary } from '@/types';
23
+
24
+type CollectionData = {
25
+    id: number;
26
+    name: string;
27
+    slug: string;
28
+    description: string | null;
29
+    product_ids: number[];
30
+};
31
+
32
+/** Add a collection, or edit one when `collection` is given. */
33
+export default function CollectionForm({
34
+    store,
35
+    collection,
36
+    products,
37
+}: {
38
+    store: StoreSummary;
39
+    collection: CollectionData | null;
40
+    products: { id: number; name: string; image: string | null }[];
41
+}) {
42
+    const action = collection
43
+        ? CollectionController.update.form({
44
+              slug: store.slug,
45
+              collection: collection.id,
46
+          })
47
+        : CollectionController.store.form(store.slug);
48
+
49
+    return (
50
+        <>
51
+            <Head
52
+                title={`${collection ? collection.name : 'New collection'} - ${store.name}`}
53
+            />
54
+
55
+            <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
56
+                <Heading
57
+                    title={collection ? 'Edit collection' : 'New collection'}
58
+                    description="A group of products shoppers can browse, such as Sun care or Gifts under RM 50."
59
+                />
60
+
61
+                <Form {...action} className="space-y-6">
62
+                    {({ processing, errors }) => (
63
+                        <>
64
+                            <div className="grid gap-2">
65
+                                <Label htmlFor="name">Name</Label>
66
+                                <Input
67
+                                    id="name"
68
+                                    name="name"
69
+                                    required
70
+                                    maxLength={60}
71
+                                    defaultValue={collection?.name}
72
+                                    placeholder="Sun care"
73
+                                />
74
+                                {collection && (
75
+                                    <p className="text-xs text-muted-foreground">
76
+                                        Its address stays /collections/
77
+                                        {collection.slug}, even if you rename
78
+                                        it.
79
+                                    </p>
80
+                                )}
81
+                                <InputError message={errors.name} />
82
+                            </div>
83
+
84
+                            <div className="grid gap-2">
85
+                                <Label htmlFor="description">
86
+                                    Short description (optional)
87
+                                </Label>
88
+                                <textarea
89
+                                    id="description"
90
+                                    name="description"
91
+                                    rows={2}
92
+                                    maxLength={500}
93
+                                    defaultValue={collection?.description ?? ''}
94
+                                    placeholder="Daily protection made for humid weather."
95
+                                    className="w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-xs outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 md:text-sm"
96
+                                />
97
+                                <InputError message={errors.description} />
98
+                            </div>
99
+
100
+                            <fieldset className="space-y-3">
101
+                                <legend className="text-sm font-medium">
102
+                                    Products in this collection
103
+                                </legend>
104
+                                {products.length === 0 ? (
105
+                                    <p className="text-sm text-muted-foreground">
106
+                                        You have no products yet.{' '}
107
+                                        <Link
108
+                                            href={ProductController.create.url(
109
+                                                store.slug,
110
+                                            )}
111
+                                            className="underline underline-offset-2"
112
+                                        >
113
+                                            Add a product
114
+                                        </Link>{' '}
115
+                                        first.
116
+                                    </p>
117
+                                ) : (
118
+                                    <ul className="grid gap-2 sm:grid-cols-2">
119
+                                        {products.map((product) => (
120
+                                            <li key={product.id}>
121
+                                                <label
122
+                                                    htmlFor={`product-${product.id}`}
123
+                                                    className="flex cursor-pointer items-center gap-3 rounded-md border p-2 text-sm hover:bg-muted/40"
124
+                                                >
125
+                                                    <Checkbox
126
+                                                        id={`product-${product.id}`}
127
+                                                        name="product_ids[]"
128
+                                                        value={String(
129
+                                                            product.id,
130
+                                                        )}
131
+                                                        defaultChecked={
132
+                                                            collection?.product_ids.includes(
133
+                                                                product.id,
134
+                                                            ) ?? false
135
+                                                        }
136
+                                                    />
137
+                                                    {product.image ? (
138
+                                                        <img
139
+                                                            src={product.image}
140
+                                                            alt=""
141
+                                                            className="size-9 rounded object-cover"
142
+                                                        />
143
+                                                    ) : (
144
+                                                        <span className="flex size-9 items-center justify-center rounded bg-muted text-muted-foreground">
145
+                                                            <ImageOff className="size-4" />
146
+                                                        </span>
147
+                                                    )}
148
+                                                    <span className="min-w-0 truncate">
149
+                                                        {product.name}
150
+                                                    </span>
151
+                                                </label>
152
+                                            </li>
153
+                                        ))}
154
+                                    </ul>
155
+                                )}
156
+                                <InputError
157
+                                    message={
158
+                                        errors.product_ids ??
159
+                                        Object.entries(errors).find(([key]) =>
160
+                                            key.startsWith('product_ids.'),
161
+                                        )?.[1]
162
+                                    }
163
+                                />
164
+                            </fieldset>
165
+
166
+                            <div className="flex items-center gap-3">
167
+                                <Button
168
+                                    disabled={processing}
169
+                                    data-test="save-collection-button"
170
+                                >
171
+                                    {collection ? 'Save' : 'Create collection'}
172
+                                </Button>
173
+                                <Button variant="ghost" asChild>
174
+                                    <Link
175
+                                        href={ProductController.index.url(
176
+                                            store.slug,
177
+                                        )}
178
+                                    >
179
+                                        Cancel
180
+                                    </Link>
181
+                                </Button>
182
+                            </div>
183
+                        </>
184
+                    )}
185
+                </Form>
186
+
187
+                {collection && (
188
+                    <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-destructive/30 p-4">
189
+                        <div>
190
+                            <p className="font-medium">
191
+                                Delete this collection
192
+                            </p>
193
+                            <p className="text-sm text-muted-foreground">
194
+                                The products stay. Only the group is removed.
195
+                            </p>
196
+                        </div>
197
+                        <Dialog>
198
+                            <DialogTrigger asChild>
199
+                                <Button variant="destructive" size="sm">
200
+                                    Delete
201
+                                </Button>
202
+                            </DialogTrigger>
203
+                            <DialogContent>
204
+                                <DialogHeader>
205
+                                    <DialogTitle>
206
+                                        Delete {collection.name}?
207
+                                    </DialogTitle>
208
+                                    <DialogDescription>
209
+                                        Links to this collection will stop
210
+                                        working. Your products are not changed.
211
+                                    </DialogDescription>
212
+                                </DialogHeader>
213
+                                <DialogFooter>
214
+                                    <DialogClose asChild>
215
+                                        <Button variant="outline">
216
+                                            Cancel
217
+                                        </Button>
218
+                                    </DialogClose>
219
+                                    <Form
220
+                                        {...CollectionController.destroy.form({
221
+                                            slug: store.slug,
222
+                                            collection: collection.id,
223
+                                        })}
224
+                                    >
225
+                                        {({ processing }) => (
226
+                                            <Button
227
+                                                variant="destructive"
228
+                                                disabled={processing}
229
+                                            >
230
+                                                Delete collection
231
+                                            </Button>
232
+                                        )}
233
+                                    </Form>
234
+                                </DialogFooter>
235
+                            </DialogContent>
236
+                        </Dialog>
237
+                    </div>
238
+                )}
239
+            </div>
240
+        </>
241
+    );
242
+}
243
+
244
+CollectionForm.layout = {
245
+    breadcrumbs: [
246
+        { title: 'Dashboard', href: dashboard() },
247
+        { title: 'Collection', href: '#' },
248
+    ],
249
+};

+ 5
- 3
resources/js/pages/stores/preview.tsx Zobrazit soubor

@@ -47,9 +47,11 @@ export default function PreviewStore({
47 47
     const title =
48 48
         view.type === 'product'
49 49
             ? view.product.name
50
-            : page
51
-              ? `${page.title} - ${storeName}`
52
-              : storeName;
50
+            : view.type === 'collection'
51
+              ? `${view.collection.name} - ${storeName}`
52
+              : page
53
+                ? `${page.title} - ${storeName}`
54
+                : storeName;
53 55
 
54 56
     return (
55 57
         <>

+ 62
- 1
resources/js/pages/stores/products/index.tsx Zobrazit soubor

@@ -1,5 +1,6 @@
1 1
 import { Head, Link } from '@inertiajs/react';
2
-import { ImageOff, Package, Plus } from 'lucide-react';
2
+import { FolderOpen, ImageOff, Package, Plus } from 'lucide-react';
3
+import CollectionController from '@/actions/App/Http/Controllers/CollectionController';
3 4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
4 5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5 6
 import StoreNav from '@/components/stores/store-nav';
@@ -11,9 +12,16 @@ import type { Product, StoreSummary } from '@/types';
11 12
 export default function ProductsIndex({
12 13
     store,
13 14
     products,
15
+    collections,
14 16
 }: {
15 17
     store: StoreSummary;
16 18
     products: Product[];
19
+    collections: {
20
+        id: number;
21
+        name: string;
22
+        slug: string;
23
+        products_count: number;
24
+    }[];
17 25
 }) {
18 26
     const createUrl = ProductController.create.url(store.slug);
19 27
 
@@ -36,6 +44,59 @@ export default function ProductsIndex({
36 44
 
37 45
                 <StoreNav slug={store.slug} current="products" />
38 46
 
47
+                <section
48
+                    className="space-y-3 rounded-xl border p-4"
49
+                    data-test="collections"
50
+                >
51
+                    <div className="flex flex-wrap items-center justify-between gap-3">
52
+                        <div className="flex items-start gap-3">
53
+                            <FolderOpen className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
54
+                            <div>
55
+                                <h2 className="font-medium">
56
+                                    Collections{' '}
57
+                                    <span className="text-muted-foreground">
58
+                                        ({collections.length})
59
+                                    </span>
60
+                                </h2>
61
+                                <p className="text-sm text-muted-foreground">
62
+                                    Groups shoppers can browse, such as Sun
63
+                                    care. Show them with a "Shop by" section.
64
+                                </p>
65
+                            </div>
66
+                        </div>
67
+                        <Button asChild size="sm" variant="outline">
68
+                            <Link
69
+                                href={CollectionController.create.url(
70
+                                    store.slug,
71
+                                )}
72
+                            >
73
+                                <Plus />
74
+                                New collection
75
+                            </Link>
76
+                        </Button>
77
+                    </div>
78
+                    {collections.length > 0 && (
79
+                        <ul className="flex flex-wrap gap-2">
80
+                            {collections.map((collection) => (
81
+                                <li key={collection.id}>
82
+                                    <Link
83
+                                        href={CollectionController.edit.url({
84
+                                            slug: store.slug,
85
+                                            collection: collection.id,
86
+                                        })}
87
+                                        className="inline-flex items-center gap-2 rounded-full border px-3 py-1 text-sm hover:bg-muted"
88
+                                    >
89
+                                        {collection.name}
90
+                                        <span className="text-muted-foreground tabular-nums">
91
+                                            {collection.products_count}
92
+                                        </span>
93
+                                    </Link>
94
+                                </li>
95
+                            ))}
96
+                        </ul>
97
+                    )}
98
+                </section>
99
+
39 100
                 <div className="flex flex-wrap items-center justify-between gap-3">
40 101
                     <h2 className="font-medium">
41 102
                         Products{' '}

+ 33
- 0
resources/js/pages/stores/show.tsx Zobrazit soubor

@@ -13,7 +13,9 @@ import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGener
13 13
 import DesignChat from '@/components/stores/design-chat';
14 14
 import FeaturedPicker from '@/components/stores/featured-picker';
15 15
 import HeroPicker from '@/components/stores/hero-picker';
16
+import BentoBox from '@/components/stores/bento-box';
16 17
 import LayoutPicker from '@/components/stores/layout-picker';
18
+import VideoBox from '@/components/stores/video-box';
17 19
 import StylePicker from '@/components/stores/style-picker';
18 20
 import DesignProgress from '@/components/stores/design-progress';
19 21
 import PublishPanel from '@/components/stores/publish-panel';
@@ -45,8 +47,12 @@ import type {
45 47
     FeaturedSection,
46 48
     HeroChoice,
47 49
     HeroSectionInfo,
50
+    BentoSectionInfo,
51
+    HomeSectionInfo,
48 52
     LayoutSection,
53
+    LinkSuggestion,
49 54
     ProductOption,
55
+    VideoSectionInfo,
50 56
     StoreStyleInfo,
51 57
     StylePreset,
52 58
     Store,
@@ -69,6 +75,10 @@ type Props = {
69 75
     stylePresets: StylePreset[];
70 76
     layoutSections: LayoutSection[];
71 77
     layoutOptions: Record<string, string[]>;
78
+    videoSections: VideoSectionInfo[];
79
+    bentoSections: BentoSectionInfo[];
80
+    homeSections: HomeSectionInfo[];
81
+    linkSuggestions: LinkSuggestion[];
72 82
 };
73 83
 
74 84
 export default function ShowStore({
@@ -84,6 +94,10 @@ export default function ShowStore({
84 94
     stylePresets,
85 95
     layoutSections,
86 96
     layoutOptions,
97
+    videoSections,
98
+    bentoSections,
99
+    homeSections,
100
+    linkSuggestions,
87 101
 }: Props) {
88 102
     const [device, setDevice] = useState<Device>('desktop');
89 103
     const [confirmOpen, setConfirmOpen] = useState(false);
@@ -116,6 +130,9 @@ export default function ShowStore({
116 130
                     'heroSections',
117 131
                     'style',
118 132
                     'layoutSections',
133
+                    'videoSections',
134
+                    'bentoSections',
135
+                    'homeSections',
119 136
                 ],
120 137
             });
121 138
         }, 2000);
@@ -324,6 +341,22 @@ export default function ShowStore({
324 341
                             busy={busy}
325 342
                         />
326 343
 
344
+                        <BentoBox
345
+                            store={store}
346
+                            bentos={bentoSections}
347
+                            homeSections={homeSections}
348
+                            photos={heroChoices}
349
+                            links={linkSuggestions}
350
+                            busy={busy}
351
+                        />
352
+
353
+                        <VideoBox
354
+                            store={store}
355
+                            videos={videoSections}
356
+                            homeSections={homeSections}
357
+                            busy={busy}
358
+                        />
359
+
327 360
                         <FeaturedPicker
328 361
                             store={store}
329 362
                             sections={featuredSections}

+ 1
- 0
resources/js/storefront/context.tsx Zobrazit soubor

@@ -36,6 +36,7 @@ const StorefrontContext = createContext<Storefront>({
36 36
     shop: {
37 37
         whatsapp: null,
38 38
         free_shipping_over: null,
39
+        collections: [],
39 40
         announcements: [],
40 41
         shipping_from: 0,
41 42
         shipping_west: 0,

+ 87
- 2
resources/js/storefront/pages/shop.tsx Zobrazit soubor

@@ -1,25 +1,110 @@
1
+import { cn } from '@/lib/utils';
1 2
 import { useStorefront } from '../context';
2 3
 import { ProductCard } from '../product-card';
3 4
 import { storefrontText } from '../text';
4
-import { Container } from '../ui';
5
+import type { StoreCollection, StoreProduct } from '../types';
6
+import { Container, SfLink } from '../ui';
5 7
 
6 8
 /** The full shop: every product shoppers may see. Built by us, in the store's colours and fonts. */
7 9
 export function ShopPage() {
8 10
     const { products, language } = useStorefront();
9 11
     const t = storefrontText(language);
10 12
 
13
+    return (
14
+        <ProductList
15
+            title={t.allProducts}
16
+            description={null}
17
+            products={products}
18
+            current={null}
19
+        />
20
+    );
21
+}
22
+
23
+/** One collection's page: its products, with links to the other collections. */
24
+export function CollectionPage({
25
+    collection,
26
+    products,
27
+}: {
28
+    collection: StoreCollection;
29
+    products: StoreProduct[];
30
+}) {
31
+    return (
32
+        <ProductList
33
+            title={collection.name}
34
+            description={collection.description}
35
+            products={products}
36
+            current={collection.slug}
37
+        />
38
+    );
39
+}
40
+
41
+function ProductList({
42
+    title,
43
+    description,
44
+    products,
45
+    current,
46
+}: {
47
+    title: string;
48
+    description: string | null;
49
+    products: StoreProduct[];
50
+    current: string | null;
51
+}) {
52
+    const { shop, language } = useStorefront();
53
+    const t = storefrontText(language);
54
+    const chip =
55
+        'inline-flex rounded-full border px-4 py-1.5 text-sm transition-colors';
56
+
11 57
     return (
12 58
         <main className="py-12 md:py-16">
13 59
             <Container>
14 60
                 <h1 className="sf-heading text-4xl font-semibold sm:text-5xl">
15
-                    {t.allProducts}
61
+                    {title}
16 62
                 </h1>
63
+                {description && (
64
+                    <p className="mt-3 max-w-2xl text-(--sf-muted)">
65
+                        {description}
66
+                    </p>
67
+                )}
17 68
                 <p className="mt-3 text-sm text-(--sf-muted)">
18 69
                     {products.length > 0
19 70
                         ? t.productCount(products.length)
20 71
                         : t.noProducts}
21 72
                 </p>
22 73
 
74
+                {shop.collections.length > 0 && (
75
+                    <nav
76
+                        aria-label={t.collections}
77
+                        className="mt-6 flex flex-wrap gap-2"
78
+                        data-test="collection-links"
79
+                    >
80
+                        <SfLink
81
+                            href="/shop"
82
+                            className={cn(
83
+                                chip,
84
+                                current === null
85
+                                    ? 'border-(--sf-fg) bg-(--sf-fg) text-(--sf-bg)'
86
+                                    : 'border-(--sf-border) hover:bg-(--sf-surface)',
87
+                            )}
88
+                        >
89
+                            {t.allProducts}
90
+                        </SfLink>
91
+                        {shop.collections.map((collection) => (
92
+                            <SfLink
93
+                                key={collection.slug}
94
+                                href={`/collections/${collection.slug}`}
95
+                                className={cn(
96
+                                    chip,
97
+                                    current === collection.slug
98
+                                        ? 'border-(--sf-fg) bg-(--sf-fg) text-(--sf-bg)'
99
+                                        : 'border-(--sf-border) hover:bg-(--sf-surface)',
100
+                                )}
101
+                            >
102
+                                {collection.name}
103
+                            </SfLink>
104
+                        ))}
105
+                    </nav>
106
+                )}
107
+
23 108
                 {products.length > 0 && (
24 109
                     <ul className="mt-10 grid grid-cols-2 gap-x-5 gap-y-10 md:grid-cols-3 lg:grid-cols-4">
25 110
                         {products.map((product, index) => (

+ 19
- 1
resources/js/storefront/renderer.tsx Zobrazit soubor

@@ -5,9 +5,10 @@ import { CartPage } from './pages/cart';
5 5
 import { CheckoutPage } from './pages/checkout';
6 6
 import { OrderPage } from './pages/order';
7 7
 import { ProductPage } from './pages/product';
8
-import { ShopPage } from './pages/shop';
8
+import { CollectionPage, ShopPage } from './pages/shop';
9 9
 import { About } from './sections/about';
10 10
 import { AnnouncementBar } from './sections/announcement-bar';
11
+import { Bento } from './sections/bento';
11 12
 import { Contact } from './sections/contact';
12 13
 import { Faq } from './sections/faq';
13 14
 import { FeaturedProduct } from './sections/featured-product';
@@ -16,8 +17,10 @@ import { Header } from './sections/header';
16 17
 import { Hero } from './sections/hero';
17 18
 import { Newsletter } from './sections/newsletter';
18 19
 import { ProductGrid } from './sections/product-grid';
20
+import { ShopBy } from './sections/shop-by';
19 21
 import { Testimonials } from './sections/testimonials';
20 22
 import { TrustBar } from './sections/trust-bar';
23
+import { VideoBlock } from './sections/video';
21 24
 import { styleAttributes, styleOf, themeStyle } from './theme';
22 25
 import { Reveal } from './reveal';
23 26
 import { WhatsAppButton } from './whatsapp';
@@ -42,6 +45,12 @@ function Section({ section }: { section: PlanSection }) {
42 45
             return <Hero section={section} />;
43 46
         case 'trust_bar':
44 47
             return <TrustBar section={section} />;
48
+        case 'shop_by':
49
+            return <ShopBy section={section} />;
50
+        case 'bento':
51
+            return <Bento section={section} />;
52
+        case 'video':
53
+            return <VideoBlock section={section} />;
45 54
         case 'product_grid':
46 55
             return <ProductGrid section={section} />;
47 56
         case 'featured_product':
@@ -67,6 +76,15 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
67 76
         return <ShopPage />;
68 77
     }
69 78
 
79
+    if (view.type === 'collection') {
80
+        return (
81
+            <CollectionPage
82
+                collection={view.collection}
83
+                products={view.collectionProducts}
84
+            />
85
+        );
86
+    }
87
+
70 88
     if (view.type === 'cart') {
71 89
         return <CartPage />;
72 90
     }

+ 118
- 0
resources/js/storefront/sections/bento.tsx Zobrazit soubor

@@ -0,0 +1,118 @@
1
+import { ArrowUpRight } from 'lucide-react';
2
+import { cn } from '@/lib/utils';
3
+import { useStorefront } from '../context';
4
+import type { BentoSection, BentoTile } from '../types';
5
+import { Container, SectionHeading, SfLink } from '../ui';
6
+
7
+/**
8
+ * Tile sizes for the mosaic layout on wide screens (4 columns), by how many tiles there are.
9
+ * The first tile is always the big one. On phones the big and wide tiles take the full width.
10
+ */
11
+const mosaic: Record<number, string[]> = {
12
+    3: ['big', 'wide', 'wide'],
13
+    4: ['big', 'wide', 'small', 'small'],
14
+    5: ['big', 'small', 'small', 'small', 'small'],
15
+    6: ['big', 'small', 'small', 'small', 'small', 'full'],
16
+};
17
+
18
+const sizeClass: Record<string, string> = {
19
+    big: 'col-span-2 row-span-2',
20
+    wide: 'col-span-2',
21
+    small: 'col-span-1',
22
+    full: 'col-span-2 md:col-span-4',
23
+};
24
+
25
+const toneClass: Record<string, string> = {
26
+    primary: 'bg-(--sf-primary) text-(--sf-primary-fg)',
27
+    accent: 'bg-(--sf-accent) text-(--sf-fg)',
28
+    dark: 'bg-(--sf-fg) text-(--sf-bg)',
29
+    surface: 'bg-(--sf-surface) text-(--sf-fg)',
30
+};
31
+
32
+/** Tiles of different sizes for products, collections, offers and stories, like a bento box. */
33
+export function Bento({ section }: { section: BentoSection }) {
34
+    const { heading, tiles } = section.content;
35
+    const even = section.variant === 'even';
36
+    const sizes = mosaic[tiles.length] ?? [];
37
+
38
+    return (
39
+        <section
40
+            id={section.id}
41
+            className="sf-section scroll-mt-20 py-16 md:py-20"
42
+            data-layout={section.variant}
43
+        >
44
+            <Container>
45
+                {heading && <SectionHeading heading={heading} />}
46
+                <ul
47
+                    className={cn(
48
+                        'grid gap-4',
49
+                        heading && 'mt-10',
50
+                        even
51
+                            ? 'grid-cols-1 sm:grid-cols-2 lg:grid-cols-3'
52
+                            : 'auto-rows-[180px] grid-cols-2 md:auto-rows-[220px] md:grid-cols-4',
53
+                    )}
54
+                >
55
+                    {tiles.map((tile, index) => (
56
+                        <li
57
+                            key={tile.title + index}
58
+                            className={cn(
59
+                                !even && sizeClass[sizes[index] ?? 'small'],
60
+                                even && 'aspect-[4/3]',
61
+                            )}
62
+                        >
63
+                            <Tile tile={tile} big={!even && index === 0} />
64
+                        </li>
65
+                    ))}
66
+                </ul>
67
+            </Container>
68
+        </section>
69
+    );
70
+}
71
+
72
+function Tile({ tile, big }: { tile: BentoTile; big: boolean }) {
73
+    const { heroImages } = useStorefront();
74
+    const photo = tile.image ? heroImages.refs[tile.image] : undefined;
75
+
76
+    return (
77
+        <SfLink
78
+            href={tile.href}
79
+            className={cn(
80
+                'sf-card group relative flex h-full flex-col justify-end overflow-hidden rounded-(--sf-radius-card) border border-(--sf-border) p-5',
81
+                photo
82
+                    ? 'text-white'
83
+                    : (toneClass[tile.tone ?? 'surface'] ?? toneClass.surface),
84
+            )}
85
+        >
86
+            {photo && (
87
+                <>
88
+                    <img
89
+                        src={photo}
90
+                        alt=""
91
+                        loading="lazy"
92
+                        className="absolute inset-0 -z-0 h-full w-full object-cover transition-transform duration-500 motion-safe:group-hover:scale-[1.04]"
93
+                    />
94
+                    <span className="absolute inset-0 bg-linear-to-t from-black/70 via-black/20 to-transparent" />
95
+                </>
96
+            )}
97
+            <ArrowUpRight
98
+                className="absolute top-4 right-4 size-5 opacity-70 transition-transform group-hover:translate-x-0.5 group-hover:-translate-y-0.5"
99
+                aria-hidden="true"
100
+            />
101
+            <span className="relative">
102
+                <span
103
+                    className={cn(
104
+                        'sf-heading block font-semibold text-balance',
105
+                        big ? 'text-2xl md:text-3xl' : 'text-lg',
106
+                    )}
107
+                >
108
+                    {tile.title}
109
+                </span>
110
+                {tile.text && (
111
+                    <span className="mt-1 block text-sm opacity-85">
112
+                        {tile.text}
113
+                    </span>
114
+                )}
115
+            </span>
116
+        </SfLink>
117
+    );
118
+}

+ 120
- 0
resources/js/storefront/sections/shop-by.tsx Zobrazit soubor

@@ -0,0 +1,120 @@
1
+import { useStorefront } from '../context';
2
+import type { ShopBySection, StoreCollection } from '../types';
3
+import { Container, ImagePlaceholder, SectionHeading, SfLink } from '../ui';
4
+
5
+/**
6
+ * "Shop by": the store's collections as round photos (circles) or larger photo tiles (tiles).
7
+ * Shows the collections the design names, in that order, or every collection when it names none.
8
+ * Nothing shows until the merchant has a collection with products.
9
+ */
10
+export function ShopBy({ section }: { section: ShopBySection }) {
11
+    const { shop } = useStorefront();
12
+    const { heading, subheading, collections: wanted } = section.content;
13
+
14
+    const shown: StoreCollection[] =
15
+        wanted.length > 0
16
+            ? wanted
17
+                  .map((slug) =>
18
+                      shop.collections.find((item) => item.slug === slug),
19
+                  )
20
+                  .filter((item): item is StoreCollection => Boolean(item))
21
+            : shop.collections;
22
+
23
+    if (shown.length === 0) {
24
+        return null;
25
+    }
26
+
27
+    if (section.variant === 'tiles') {
28
+        return (
29
+            <section
30
+                id={section.id}
31
+                className="sf-section scroll-mt-20 py-16 md:py-20"
32
+                data-layout="tiles"
33
+            >
34
+                <Container>
35
+                    <SectionHeading heading={heading} subheading={subheading} />
36
+                    <ul className="mt-10 grid grid-cols-2 gap-4 md:grid-cols-3">
37
+                        {shown.map((collection, index) => (
38
+                            <li key={collection.slug}>
39
+                                <SfLink
40
+                                    href={`/collections/${collection.slug}`}
41
+                                    className="group relative block overflow-hidden rounded-(--sf-radius-card)"
42
+                                >
43
+                                    {collection.image ? (
44
+                                        <img
45
+                                            src={collection.image}
46
+                                            alt=""
47
+                                            loading="lazy"
48
+                                            className="sf-card aspect-[4/5] w-full rounded-(--sf-radius-card) object-cover transition-transform duration-500 motion-safe:group-hover:scale-[1.04]"
49
+                                        />
50
+                                    ) : (
51
+                                        <ImagePlaceholder
52
+                                            seed={index}
53
+                                            label={collection.name}
54
+                                            className="aspect-[4/5] w-full"
55
+                                        />
56
+                                    )}
57
+                                    <span className="absolute inset-x-0 bottom-0 rounded-b-(--sf-radius-card) bg-linear-to-t from-black/70 to-transparent p-4 pt-12 text-white">
58
+                                        <span className="sf-heading block text-lg font-semibold">
59
+                                            {collection.name}
60
+                                        </span>
61
+                                        <span className="text-sm text-white/80">
62
+                                            {collection.count}
63
+                                        </span>
64
+                                    </span>
65
+                                </SfLink>
66
+                            </li>
67
+                        ))}
68
+                    </ul>
69
+                </Container>
70
+            </section>
71
+        );
72
+    }
73
+
74
+    return (
75
+        <section
76
+            id={section.id}
77
+            className="sf-section scroll-mt-20 py-14 md:py-16"
78
+            data-layout="circles"
79
+        >
80
+            <Container>
81
+                <SectionHeading
82
+                    heading={heading}
83
+                    subheading={subheading}
84
+                    align="center"
85
+                />
86
+                <ul className="-mx-5 mt-8 flex snap-x gap-6 overflow-x-auto px-5 pb-2 sm:mx-0 sm:flex-wrap sm:justify-center sm:overflow-visible sm:px-0">
87
+                    {shown.map((collection, index) => (
88
+                        <li
89
+                            key={collection.slug}
90
+                            className="w-24 shrink-0 snap-start sm:w-32"
91
+                        >
92
+                            <SfLink
93
+                                href={`/collections/${collection.slug}`}
94
+                                className="group flex flex-col items-center gap-3 text-center"
95
+                            >
96
+                                {collection.image ? (
97
+                                    <img
98
+                                        src={collection.image}
99
+                                        alt=""
100
+                                        loading="lazy"
101
+                                        className="aspect-square w-full rounded-full object-cover ring-1 ring-(--sf-border) transition-transform duration-300 motion-safe:group-hover:scale-105"
102
+                                    />
103
+                                ) : (
104
+                                    <ImagePlaceholder
105
+                                        seed={index}
106
+                                        label={collection.name}
107
+                                        className="aspect-square w-full rounded-full!"
108
+                                    />
109
+                                )}
110
+                                <span className="text-sm font-medium group-hover:underline">
111
+                                    {collection.name}
112
+                                </span>
113
+                            </SfLink>
114
+                        </li>
115
+                    ))}
116
+                </ul>
117
+            </Container>
118
+        </section>
119
+    );
120
+}

+ 119
- 0
resources/js/storefront/sections/video.tsx Zobrazit soubor

@@ -0,0 +1,119 @@
1
+import { Play } from 'lucide-react';
2
+import { useState } from 'react';
3
+import { cn } from '@/lib/utils';
4
+import { useStorefront } from '../context';
5
+import { storefrontText } from '../text';
6
+import type { VideoSection } from '../types';
7
+import { Container, SfButton } from '../ui';
8
+
9
+type Video = { provider: 'youtube' | 'vimeo'; id: string };
10
+
11
+/** The video behind a YouTube or Vimeo address, or null for anything else. */
12
+export function parseVideo(url: string): Video | null {
13
+    const youtube = url.match(
14
+        /^https:\/\/(?:(?:www\.|m\.)?youtube\.com\/(?:watch\?v=|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{6,20})/,
15
+    );
16
+
17
+    if (youtube) {
18
+        return { provider: 'youtube', id: youtube[1] };
19
+    }
20
+
21
+    const vimeo = url.match(/^https:\/\/(?:www\.)?vimeo\.com\/([0-9]{5,12})/);
22
+
23
+    return vimeo ? { provider: 'vimeo', id: vimeo[1] } : null;
24
+}
25
+
26
+/**
27
+ * A YouTube or Vimeo video. Until the shopper presses play only a picture shows, so the page stays fast
28
+ * and nothing from the video site loads for shoppers who never watch.
29
+ */
30
+export function VideoBlock({ section }: { section: VideoSection }) {
31
+    const { heading, text, videoUrl, cta } = section.content;
32
+    const split = section.variant === 'split';
33
+    const video = parseVideo(videoUrl);
34
+
35
+    if (!video) {
36
+        return null;
37
+    }
38
+
39
+    const words = (
40
+        <div className={cn(!split && 'mx-auto max-w-2xl text-center')}>
41
+            <h2 className="sf-heading text-3xl leading-tight font-semibold text-balance sm:text-4xl">
42
+                {heading}
43
+            </h2>
44
+            {text && (
45
+                <p className="mt-4 leading-relaxed text-(--sf-muted)">{text}</p>
46
+            )}
47
+            {cta && (
48
+                <SfButton href={cta.href} className="mt-6">
49
+                    {cta.label}
50
+                </SfButton>
51
+            )}
52
+        </div>
53
+    );
54
+
55
+    return (
56
+        <section
57
+            id={section.id}
58
+            className="sf-section scroll-mt-20 py-16 md:py-20"
59
+            data-layout={section.variant}
60
+        >
61
+            <Container
62
+                className={cn(
63
+                    'grid gap-10',
64
+                    split && 'items-center md:grid-cols-[2fr_3fr]',
65
+                )}
66
+            >
67
+                {words}
68
+                <Player video={video} title={heading} />
69
+            </Container>
70
+        </section>
71
+    );
72
+}
73
+
74
+function Player({ video, title }: { video: Video; title: string }) {
75
+    const { language } = useStorefront();
76
+    const t = storefrontText(language);
77
+    const [playing, setPlaying] = useState(false);
78
+
79
+    const src =
80
+        video.provider === 'youtube'
81
+            ? `https://www.youtube-nocookie.com/embed/${video.id}?autoplay=1&rel=0`
82
+            : `https://player.vimeo.com/video/${video.id}?autoplay=1&dnt=1`;
83
+
84
+    return (
85
+        <div className="sf-card relative aspect-video w-full overflow-hidden rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-fg)">
86
+            {playing ? (
87
+                <iframe
88
+                    src={src}
89
+                    title={title}
90
+                    allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
91
+                    allowFullScreen
92
+                    className="absolute inset-0 h-full w-full"
93
+                />
94
+            ) : (
95
+                <button
96
+                    type="button"
97
+                    onClick={() => setPlaying(true)}
98
+                    aria-label={t.playVideo(title)}
99
+                    className="group absolute inset-0 flex items-center justify-center"
100
+                    data-test="video-play"
101
+                >
102
+                    {video.provider === 'youtube' ? (
103
+                        <img
104
+                            src={`https://i.ytimg.com/vi/${video.id}/hqdefault.jpg`}
105
+                            alt=""
106
+                            loading="lazy"
107
+                            className="absolute inset-0 h-full w-full object-cover opacity-90"
108
+                        />
109
+                    ) : (
110
+                        <span className="absolute inset-0 bg-linear-to-br from-(--sf-primary) to-(--sf-fg)" />
111
+                    )}
112
+                    <span className="relative flex size-16 items-center justify-center rounded-full bg-(--sf-primary) text-(--sf-primary-fg) shadow-lg transition-transform group-hover:scale-110">
113
+                        <Play className="ml-1 size-7" aria-hidden="true" />
114
+                    </span>
115
+                </button>
116
+            )}
117
+        </div>
118
+    );
119
+}

+ 4
- 0
resources/js/storefront/text.ts Zobrazit soubor

@@ -23,6 +23,8 @@ const words = {
23 23
         trustWhatsApp: 'Questions? Ask us',
24 24
         trustWhatsAppText: 'Quick replies on WhatsApp',
25 25
         pairsWellWith: 'Pairs well with',
26
+        collections: 'Collections',
27
+        playVideo: (title: string) => `Play video: ${title}`,
26 28
         previousProducts: 'Previous products',
27 29
         nextProducts: 'More products',
28 30
         footerExplore: 'Explore',
@@ -130,6 +132,8 @@ const words = {
130 132
         trustWhatsApp: 'Ada soalan? Tanya kami',
131 133
         trustWhatsAppText: 'Balasan pantas di WhatsApp',
132 134
         pairsWellWith: 'Sesuai digandingkan dengan',
135
+        collections: 'Koleksi',
136
+        playVideo: (title: string) => `Main video: ${title}`,
133 137
         previousProducts: 'Produk sebelum',
134 138
         nextProducts: 'Lagi produk',
135 139
         footerExplore: 'Terokai',

+ 58
- 1
resources/js/storefront/types.ts Zobrazit soubor

@@ -177,8 +177,49 @@ export type TrustBarSection = SectionOf<
177 177
     { items: TrustItem[] }
178 178
 >;
179 179
 
180
+export type ShopBySection = SectionOf<
181
+    'shop_by',
182
+    'circles' | 'tiles',
183
+    {
184
+        heading: string;
185
+        subheading?: string | null;
186
+        /** Web-address names of collections, in order. Empty shows every collection. */
187
+        collections: string[];
188
+    }
189
+>;
190
+
191
+/** One bento tile. "image" is a photo name like a hero's; without one the tile is a colour block. */
192
+export type BentoTile = {
193
+    title: string;
194
+    text?: string | null;
195
+    href: string;
196
+    image?: string | null;
197
+    tone?: 'primary' | 'accent' | 'dark' | 'surface' | null;
198
+};
199
+
200
+export type BentoSection = SectionOf<
201
+    'bento',
202
+    'mosaic' | 'even',
203
+    { heading?: string | null; tiles: BentoTile[] }
204
+>;
205
+
206
+export type VideoSection = SectionOf<
207
+    'video',
208
+    'wide' | 'split',
209
+    {
210
+        heading: string;
211
+        text?: string | null;
212
+        /** A YouTube or Vimeo address. */
213
+        videoUrl: string;
214
+        cta?: PlanLink | null;
215
+    }
216
+>;
217
+
180 218
 export type PlanSection =
181 219
     | HeroSection
220
+    | VideoSection
221
+    | ShopBySection
222
+    | BentoSection
182 223
     | TrustBarSection
183 224
     | ProductGridSection
184 225
     | FeaturedProductSection
@@ -325,6 +366,8 @@ export type ShopInfo = {
325 366
     whatsapp: string | null;
326 367
     /** In ringgit. Orders at or above this ship free. */
327 368
     free_shipping_over: number | null;
369
+    /** Collections with at least one product shoppers can see. */
370
+    collections: StoreCollection[];
328 371
     /** Lines for the slim bar above the header. Empty when switched off. */
329 372
     announcements: string[];
330 373
     /** The cheapest shipping fee, in ringgit. */
@@ -348,4 +391,18 @@ export type StorefrontView =
348 391
           shippingByState: Record<string, number>;
349 392
       }
350 393
     | { type: 'order'; order: StoreOrder }
351
-    | { type: 'product'; product: StoreProduct; related?: StoreProduct[] };
394
+    | { type: 'product'; product: StoreProduct; related?: StoreProduct[] }
395
+    | {
396
+          type: 'collection';
397
+          collection: StoreCollection;
398
+          collectionProducts: StoreProduct[];
399
+      };
400
+
401
+/** A group of products, such as "Sun care". "image" is the first product photo. */
402
+export type StoreCollection = {
403
+    name: string;
404
+    slug: string;
405
+    description: string | null;
406
+    image: string | null;
407
+    count: number;
408
+};

+ 34
- 0
resources/js/types/store.ts Zobrazit soubor

@@ -199,6 +199,40 @@ export type LayoutSection = {
199 199
     label: string;
200 200
 };
201 201
 
202
+/** A video section, for the Design tab's Video box. */
203
+export type VideoSectionInfo = {
204
+    section_id: string;
205
+    page_title: string;
206
+    variant: 'wide' | 'split';
207
+    heading: string;
208
+    text: string | null;
209
+    videoUrl: string;
210
+};
211
+
212
+/** One bento tile as the Design tab edits it. */
213
+export type BentoTileInfo = {
214
+    title: string;
215
+    text: string | null;
216
+    href: string;
217
+    image: string | null;
218
+    tone: 'primary' | 'accent' | 'dark' | 'surface' | null;
219
+};
220
+
221
+/** A bento section, for the Design tab's Bento box. */
222
+export type BentoSectionInfo = {
223
+    section_id: string;
224
+    page_title: string;
225
+    variant: 'mosaic' | 'even';
226
+    heading: string | null;
227
+    tiles: BentoTileInfo[];
228
+};
229
+
230
+/** A home page section a new section can be placed after. */
231
+export type HomeSectionInfo = { id: string; label: string };
232
+
233
+/** A link a tile can point to. */
234
+export type LinkSuggestion = { href: string; label: string };
235
+
202 236
 /** A ready-made look in the Design tab's Style box. */
203 237
 export type StylePreset = {
204 238
     key: string;

+ 17
- 0
routes/web.php Zobrazit soubor

@@ -1,9 +1,11 @@
1 1
 <?php
2 2
 
3 3
 use App\Http\Controllers\AutomaticDiscountController;
4
+use App\Http\Controllers\BentoSectionController;
4 5
 use App\Http\Controllers\BillingController;
5 6
 use App\Http\Controllers\CartController;
6 7
 use App\Http\Controllers\CheckoutController;
8
+use App\Http\Controllers\CollectionController;
7 9
 use App\Http\Controllers\DiscountCodeController;
8 10
 use App\Http\Controllers\FeaturedProductController;
9 11
 use App\Http\Controllers\HeroImageController;
@@ -17,6 +19,7 @@ use App\Http\Controllers\StorePublishController;
17 19
 use App\Http\Controllers\StoreSettingsController;
18 20
 use App\Http\Controllers\StoreStyleController;
19 21
 use App\Http\Controllers\StripeWebhookController;
22
+use App\Http\Controllers\VideoSectionController;
20 23
 use Illuminate\Support\Facades\Route;
21 24
 
22 25
 /*
@@ -36,6 +39,7 @@ Route::domain('{storeSlug}.'.config('storefront.domain'))
36 39
         Route::get('/', [StoreDesignController::class, 'preview'])->name('home');
37 40
         Route::get('shop', [StoreDesignController::class, 'shop'])->name('shop');
38 41
         Route::get('products/{productSlug}', [StoreDesignController::class, 'product'])->name('product');
42
+        Route::get('collections/{collectionSlug}', [StoreDesignController::class, 'collection'])->name('collection');
39 43
 
40 44
         Route::get('cart', [CartController::class, 'show'])->name('cart');
41 45
         Route::post('cart/items', [CartController::class, 'add'])->name('cart.add');
@@ -74,6 +78,13 @@ Route::middleware(['auth', 'verified'])->group(function () {
74 78
     Route::get('stores/{slug}/preview', [StoreDesignController::class, 'preview'])->name('stores.preview');
75 79
     Route::get('stores/{slug}/preview/shop', [StoreDesignController::class, 'shop'])->name('stores.preview.shop');
76 80
     Route::get('stores/{slug}/preview/products/{productSlug}', [StoreDesignController::class, 'product'])->name('stores.preview.product');
81
+    Route::get('stores/{slug}/preview/collections/{collectionSlug}', [StoreDesignController::class, 'collection'])->name('stores.preview.collection');
82
+
83
+    Route::get('stores/{slug}/collections/create', [CollectionController::class, 'create'])->name('stores.collections.create');
84
+    Route::post('stores/{slug}/collections', [CollectionController::class, 'store'])->name('stores.collections.store');
85
+    Route::get('stores/{slug}/collections/{collection}/edit', [CollectionController::class, 'edit'])->name('stores.collections.edit')->whereNumber('collection');
86
+    Route::put('stores/{slug}/collections/{collection}', [CollectionController::class, 'update'])->name('stores.collections.update')->whereNumber('collection');
87
+    Route::delete('stores/{slug}/collections/{collection}', [CollectionController::class, 'destroy'])->name('stores.collections.destroy')->whereNumber('collection');
77 88
 
78 89
     Route::get('stores/{slug}/preview/cart', [CartController::class, 'show'])->name('stores.preview.cart');
79 90
     Route::post('stores/{slug}/preview/cart/items', [CartController::class, 'add'])->name('stores.preview.cart.add');
@@ -117,6 +128,12 @@ Route::middleware(['auth', 'verified'])->group(function () {
117 128
     Route::put('stores/{slug}/hero/{sectionId}', [HeroImageController::class, 'update'])->name('stores.hero.update');
118 129
     Route::put('stores/{slug}/style', [StoreStyleController::class, 'update'])->name('stores.style.update');
119 130
     Route::put('stores/{slug}/layouts/{sectionId}', [SectionLayoutController::class, 'update'])->name('stores.layouts.update');
131
+    Route::post('stores/{slug}/videos', [VideoSectionController::class, 'store'])->name('stores.videos.store');
132
+    Route::put('stores/{slug}/videos/{sectionId}', [VideoSectionController::class, 'update'])->name('stores.videos.update');
133
+    Route::delete('stores/{slug}/videos/{sectionId}', [VideoSectionController::class, 'destroy'])->name('stores.videos.destroy');
134
+    Route::post('stores/{slug}/bento', [BentoSectionController::class, 'store'])->name('stores.bento.store');
135
+    Route::put('stores/{slug}/bento/{sectionId}', [BentoSectionController::class, 'update'])->name('stores.bento.update');
136
+    Route::delete('stores/{slug}/bento/{sectionId}', [BentoSectionController::class, 'destroy'])->name('stores.bento.destroy');
120 137
     Route::post('stores/{slug}/hero/{sectionId}/photo', [HeroImageController::class, 'upload'])->name('stores.hero.upload');
121 138
     Route::get('stores/{slug}/settings', [StoreSettingsController::class, 'edit'])->name('stores.settings');
122 139
     Route::put('stores/{slug}/settings', [StoreSettingsController::class, 'update'])->name('stores.settings.update');

+ 205
- 0
tests/Feature/Stores/CollectionsBentoVideoTest.php Zobrazit soubor

@@ -0,0 +1,205 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Enums\GenerationStatus;
6
+use App\Models\Collection;
7
+use App\Models\Product;
8
+use App\Models\Store;
9
+use App\Models\User;
10
+use App\StorePlan\PlanValidator;
11
+use App\StorePlan\SamplePlan;
12
+use Illuminate\Foundation\Testing\RefreshDatabase;
13
+use Inertia\Testing\AssertableInertia as Assert;
14
+use Tests\Support\ScriptedDriver;
15
+use Tests\TestCase;
16
+
17
+class CollectionsBentoVideoTest extends TestCase
18
+{
19
+    use RefreshDatabase;
20
+
21
+    private User $user;
22
+
23
+    private Store $store;
24
+
25
+    private Product $sunscreen;
26
+
27
+    private Product $cleanser;
28
+
29
+    protected function setUp(): void
30
+    {
31
+        parent::setUp();
32
+
33
+        $this->user = User::factory()->create();
34
+        $this->store = Store::factory()->for($this->user)->create(['description' => 'Gentle skincare.']);
35
+        $this->store->plan = SamplePlan::for($this->store);
36
+        $this->store->save();
37
+        $this->actingAs($this->user);
38
+
39
+        $this->sunscreen = $this->store->products()->create(['name' => 'Sunscreen', 'price' => 4900, 'stock' => 5, 'status' => 'active']);
40
+        $this->sunscreen->images()->create(['store_id' => $this->store->id, 'path' => 'products/1/sun.jpg', 'position' => 1]);
41
+        $this->cleanser = $this->store->products()->create(['name' => 'Cleanser', 'price' => 4200, 'stock' => 5, 'status' => 'active']);
42
+    }
43
+
44
+    private function collection(string $name, array $productIds): Collection
45
+    {
46
+        $this->post(route('stores.collections.store', $this->store->slug), ['name' => $name, 'product_ids' => $productIds])
47
+            ->assertSessionHasNoErrors();
48
+
49
+        return $this->store->collections()->latest('id')->firstOrFail();
50
+    }
51
+
52
+    /**
53
+     * The sample plan with one more section on the home page.
54
+     *
55
+     * @param  array<string, mixed>  $section
56
+     * @return array<string, mixed>
57
+     */
58
+    private function withSection(array $section): array
59
+    {
60
+        $plan = $this->store->plan;
61
+        $plan['pages'][0]['sections'][] = $section;
62
+
63
+        return $plan;
64
+    }
65
+
66
+    public function test_the_merchant_can_manage_collections()
67
+    {
68
+        $sun = $this->collection('Sun care', [$this->sunscreen->id]);
69
+
70
+        $this->assertSame('sun-care', $sun->slug);
71
+        $this->assertSame([$this->sunscreen->id], $sun->products->modelKeys());
72
+
73
+        $this->get(route('stores.products.index', $this->store->slug))
74
+            ->assertInertia(fn (Assert $page) => $page->where('collections.0.name', 'Sun care')->where('collections.0.products_count', 1));
75
+
76
+        // Renaming keeps the address, so links keep working.
77
+        $this->put(route('stores.collections.update', [$this->store->slug, $sun->id]), [
78
+            'name' => 'Sun protection', 'product_ids' => [$this->cleanser->id, $this->sunscreen->id],
79
+        ])->assertSessionHasNoErrors();
80
+
81
+        $sun->refresh();
82
+        $this->assertSame('sun-care', $sun->slug);
83
+        $this->assertSame([$this->cleanser->id, $this->sunscreen->id], $sun->products->modelKeys());
84
+
85
+        // Only this store's products.
86
+        $foreign = Product::factory()->create();
87
+        $this->post(route('stores.collections.store', $this->store->slug), ['name' => 'Bad', 'product_ids' => [$foreign->id]])
88
+            ->assertSessionHasErrors('product_ids.0');
89
+
90
+        $this->delete(route('stores.collections.destroy', [$this->store->slug, $sun->id]));
91
+        $this->assertSame(0, Collection::count());
92
+        $this->assertNotNull($this->sunscreen->fresh());
93
+
94
+        $other = Store::factory()->create();
95
+        $theirs = $other->collections()->create(['name' => 'Theirs']);
96
+        $this->get(route('stores.collections.edit', [$this->store->slug, $theirs->id]))->assertNotFound();
97
+    }
98
+
99
+    public function test_shoppers_can_browse_a_collection()
100
+    {
101
+        $sun = $this->collection('Sun care', [$this->sunscreen->id]);
102
+        // A collection whose products are all hidden is not offered to shoppers.
103
+        $draft = $this->store->products()->create(['name' => 'Hidden', 'price' => 100, 'stock' => 1, 'status' => 'draft']);
104
+        $this->collection('Coming soon', [$draft->id]);
105
+
106
+        $this->get(route('stores.preview.collection', [$this->store->slug, 'sun-care']))
107
+            ->assertInertia(fn (Assert $page) => $page
108
+                ->where('view.type', 'collection')
109
+                ->where('view.collection.name', 'Sun care')
110
+                ->where('view.collectionProducts.0.name', 'Sunscreen')
111
+                ->has('shop.collections', 1)
112
+                ->where('shop.collections.0.image', '/storage/products/1/sun.jpg'));
113
+
114
+        $this->get(route('stores.preview.collection', [$this->store->slug, 'nope']))->assertNotFound();
115
+        $this->assertNotNull($sun);
116
+    }
117
+
118
+    public function test_links_to_collections_are_allowed_and_the_address_is_reserved()
119
+    {
120
+        $validator = app(PlanValidator::class);
121
+        $plan = $this->store->plan;
122
+        $plan['header']['content']['links'][] = ['label' => 'Sun care', 'href' => '/collections/sun-care'];
123
+
124
+        $this->assertTrue($validator->passes($plan));
125
+
126
+        $plan['pages'][] = ['id' => 'collections', 'title' => 'Collections', 'sections' => [$this->store->plan['pages'][0]['sections'][0]]];
127
+        $this->assertFalse($validator->passes($plan));
128
+    }
129
+
130
+    public function test_shop_by_bento_and_video_sections_are_checked()
131
+    {
132
+        $validator = app(PlanValidator::class);
133
+        $tiles = [
134
+            ['title' => 'Bestsellers', 'href' => '/shop', 'image' => 'product:sunscreen'],
135
+            ['title' => 'Gift sets', 'text' => 'Ready to give', 'href' => '/collections/gifts', 'tone' => 'primary'],
136
+            ['title' => 'Our story', 'href' => '#about', 'tone' => 'dark'],
137
+        ];
138
+
139
+        $this->assertTrue($validator->passes($this->withSection(['id' => 'by', 'type' => 'shop_by', 'variant' => 'circles', 'content' => ['heading' => 'Shop by need', 'collections' => []]])));
140
+        $this->assertTrue($validator->passes($this->withSection(['id' => 'tiles', 'type' => 'bento', 'variant' => 'mosaic', 'content' => ['tiles' => $tiles]])));
141
+        $this->assertTrue($validator->passes($this->withSection(['id' => 'film', 'type' => 'video', 'variant' => 'split', 'content' => ['heading' => 'How we make it', 'videoUrl' => 'https://youtu.be/dQw4w9WgXcQ']])));
142
+
143
+        // Too few tiles, a colour that does not exist, a video from another site.
144
+        $this->assertFalse($validator->passes($this->withSection(['id' => 'tiles', 'type' => 'bento', 'variant' => 'mosaic', 'content' => ['tiles' => array_slice($tiles, 0, 2)]])));
145
+        $this->assertFalse($validator->passes($this->withSection(['id' => 'tiles', 'type' => 'bento', 'variant' => 'even', 'content' => ['tiles' => [...array_slice($tiles, 0, 2), ['title' => 'X', 'href' => '/shop', 'tone' => 'neon']]]])));
146
+        $this->assertFalse($validator->passes($this->withSection(['id' => 'film', 'type' => 'video', 'variant' => 'wide', 'content' => ['heading' => 'Film', 'videoUrl' => 'https://evil.example/video.mp4']])));
147
+    }
148
+
149
+    public function test_bento_photos_reach_the_storefront()
150
+    {
151
+        $this->store->plan = app(PlanValidator::class)->validate($this->withSection(['id' => 'tiles', 'type' => 'bento', 'variant' => 'mosaic', 'content' => ['tiles' => [
152
+            ['title' => 'Sunscreen', 'href' => '/products/sunscreen', 'image' => 'product:sunscreen'],
153
+            ['title' => 'Shop', 'href' => '/shop', 'tone' => 'primary'],
154
+            ['title' => 'Story', 'href' => '#about'],
155
+        ]]]));
156
+        $this->store->save();
157
+
158
+        $this->get(route('stores.preview', $this->store->slug))
159
+            ->assertInertia(fn (Assert $page) => $page->where('heroImages.refs.product:sunscreen', '/storage/products/1/sun.jpg'));
160
+    }
161
+
162
+    public function test_the_ai_can_only_use_real_collections_and_videos_the_merchant_gave()
163
+    {
164
+        $this->collection('Sun care', [$this->sunscreen->id]);
165
+        $shopBy = fn (string $slug) => (string) json_encode(['reply' => 'Done.', 'add' => [['page' => 'home', 'after' => 'hero', 'section' => [
166
+            'id' => 'by', 'type' => 'shop_by', 'variant' => 'tiles', 'content' => ['heading' => 'Shop by need', 'collections' => [$slug]],
167
+        ]]]]);
168
+
169
+        ScriptedDriver::use([$shopBy('made-up'), $shopBy('sun-care')]);
170
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Add shop by collection']);
171
+
172
+        $this->assertStringContainsString('- sun-care: Sun care (1 products)', ScriptedDriver::$requests[0]->prompt);
173
+        $this->assertStringContainsString('made-up', ScriptedDriver::$requests[1]->prompt);
174
+        $this->assertSame(GenerationStatus::Completed, $this->store->generations()->latest('id')->firstOrFail()->status);
175
+
176
+        // A video address the merchant never wrote is refused, twice, so nothing changes.
177
+        $video = (string) json_encode(['reply' => 'Done.', 'add' => [['page' => 'home', 'after' => null, 'section' => [
178
+            'id' => 'film', 'type' => 'video', 'variant' => 'wide', 'content' => ['heading' => 'Our story', 'videoUrl' => 'https://youtu.be/dQw4w9WgXcQ'],
179
+        ]]]]);
180
+        ScriptedDriver::use([$video, $video]);
181
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Add a video about us']);
182
+        $this->assertSame(GenerationStatus::Failed, $this->store->generations()->latest('id')->firstOrFail()->status);
183
+
184
+        // With the address in the message, it works.
185
+        ScriptedDriver::use([$video]);
186
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Add this video: https://youtu.be/dQw4w9WgXcQ']);
187
+        $this->assertSame(GenerationStatus::Completed, $this->store->generations()->latest('id')->firstOrFail()->status);
188
+        $this->assertSame('film', collect($this->store->fresh()->plan['pages'][0]['sections'])->last()['id']);
189
+    }
190
+
191
+    public function test_a_collection_can_be_created_by_chat()
192
+    {
193
+        ScriptedDriver::use([(string) json_encode(['reply' => 'Confirm below.', 'actions' => [[
194
+            'type' => 'create_collection', 'name' => 'Daily essentials', 'products' => [$this->cleanser->slug, $this->sunscreen->slug],
195
+        ]]])]);
196
+
197
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Make a daily essentials collection']);
198
+        $edit = $this->store->generations()->firstOrFail();
199
+
200
+        $this->assertSame('Create the collection "Daily essentials" with: Cleanser, Sunscreen', $edit->actions[0]['summary']);
201
+        $this->post(route('stores.edits.confirm', [$this->store->slug, $edit->id]))->assertSessionHasNoErrors();
202
+
203
+        $this->assertSame([$this->cleanser->id, $this->sunscreen->id], Collection::firstOrFail()->products->modelKeys());
204
+    }
205
+}

+ 161
- 0
tests/Feature/Stores/DesignSectionBoxesTest.php Zobrazit soubor

@@ -0,0 +1,161 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Models\Store;
6
+use App\Models\User;
7
+use App\StorePlan\SamplePlan;
8
+use App\StorePlan\SectionEditor;
9
+use Illuminate\Foundation\Testing\RefreshDatabase;
10
+use Inertia\Testing\AssertableInertia as Assert;
11
+use Tests\TestCase;
12
+
13
+class DesignSectionBoxesTest extends TestCase
14
+{
15
+    use RefreshDatabase;
16
+
17
+    private User $user;
18
+
19
+    private Store $store;
20
+
21
+    protected function setUp(): void
22
+    {
23
+        parent::setUp();
24
+
25
+        $this->user = User::factory()->create();
26
+        $this->store = Store::factory()->for($this->user)->create();
27
+        $plan = SamplePlan::for($this->store);
28
+        // Start without the sample's bento, so adding one is clear.
29
+        $this->store->plan = SectionEditor::remove($plan, 'highlights');
30
+        $this->store->save();
31
+        $this->actingAs($this->user);
32
+    }
33
+
34
+    /**
35
+     * @return list<string>
36
+     */
37
+    private function homeIds(): array
38
+    {
39
+        return array_column($this->store->fresh()->plan['pages'][0]['sections'], 'id');
40
+    }
41
+
42
+    /**
43
+     * @return array<string, mixed>
44
+     */
45
+    private function section(string $id): array
46
+    {
47
+        return collect($this->store->fresh()->plan['pages'][0]['sections'])->firstWhere('id', $id);
48
+    }
49
+
50
+    public function test_a_video_can_be_added_after_a_section_changed_and_removed()
51
+    {
52
+        $this->post(route('stores.videos.store', $this->store->slug), [
53
+            'video_url' => 'https://youtu.be/otej7WLdPh0?si=eYqNO3QE14avO4VL',
54
+            'heading' => 'How we make it',
55
+            'text' => '',
56
+            'variant' => 'wide',
57
+            'after' => 'about',
58
+        ])->assertSessionHasNoErrors();
59
+
60
+        $ids = $this->homeIds();
61
+        $this->assertSame('video', $ids[array_search('about', $ids, true) + 1]);
62
+        $this->assertSame('https://youtu.be/otej7WLdPh0?si=eYqNO3QE14avO4VL', $this->section('video')['content']['videoUrl']);
63
+
64
+        $this->get(route('stores.show', $this->store->slug))
65
+            ->assertInertia(fn (Assert $page) => $page
66
+                ->where('videoSections.0.section_id', 'video')
67
+                ->where('videoSections.0.heading', 'How we make it')
68
+                ->where('homeSections.0.id', 'hero'));
69
+
70
+        $this->put(route('stores.videos.update', [$this->store->slug, 'video']), [
71
+            'video_url' => 'https://vimeo.com/76979871', 'heading' => 'Our kitchen', 'text' => 'A day with Nenek.', 'variant' => 'split',
72
+        ])->assertSessionHasNoErrors();
73
+
74
+        $video = $this->section('video');
75
+        $this->assertSame('split', $video['variant']);
76
+        $this->assertSame('A day with Nenek.', $video['content']['text']);
77
+
78
+        // A second video gets its own id.
79
+        $this->post(route('stores.videos.store', $this->store->slug), [
80
+            'video_url' => 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', 'heading' => 'Second', 'variant' => 'wide', 'after' => 'hero',
81
+        ])->assertSessionHasNoErrors();
82
+        $this->assertContains('video-2', $this->homeIds());
83
+
84
+        $this->delete(route('stores.videos.destroy', [$this->store->slug, 'video']))->assertSessionHasNoErrors();
85
+        $this->assertNotContains('video', $this->homeIds());
86
+    }
87
+
88
+    public function test_video_links_and_sections_are_checked()
89
+    {
90
+        $url = route('stores.videos.store', $this->store->slug);
91
+
92
+        $this->post($url, ['video_url' => 'https://evil.example/v.mp4', 'heading' => 'X', 'variant' => 'wide'])->assertSessionHasErrors('video_url');
93
+        $this->post($url, ['video_url' => 'https://youtu.be/otej7WLdPh0', 'heading' => '', 'variant' => 'wide'])->assertSessionHasErrors('heading');
94
+        $this->post($url, ['video_url' => 'https://youtu.be/otej7WLdPh0', 'heading' => 'X', 'variant' => 'wide', 'after' => 'nowhere'])->assertSessionHasErrors('after');
95
+
96
+        // Only video sections can be edited here.
97
+        $this->put(route('stores.videos.update', [$this->store->slug, 'about']), [
98
+            'video_url' => 'https://youtu.be/otej7WLdPh0', 'heading' => 'X', 'variant' => 'wide',
99
+        ])->assertNotFound();
100
+
101
+        $this->actingAs(User::factory()->create())
102
+            ->post($url, ['video_url' => 'https://youtu.be/otej7WLdPh0', 'heading' => 'X', 'variant' => 'wide'])
103
+            ->assertNotFound();
104
+    }
105
+
106
+    public function test_bento_tiles_start_filled_and_can_be_edited()
107
+    {
108
+        $product = $this->store->products()->create(['name' => 'Sambal', 'price' => 1000, 'stock' => 3, 'status' => 'active']);
109
+        $product->images()->create(['store_id' => $this->store->id, 'path' => 'products/1/s.jpg', 'position' => 1]);
110
+        $collection = $this->store->collections()->create(['name' => 'Gift sets']);
111
+
112
+        $this->post(route('stores.bento.store', $this->store->slug), ['after' => 'trust'])->assertSessionHasNoErrors();
113
+
114
+        $ids = $this->homeIds();
115
+        $this->assertSame('highlights', $ids[array_search('trust', $ids, true) + 1]);
116
+        $tiles = $this->section('highlights')['content']['tiles'];
117
+        $this->assertSame(['/shop', '/collections/'.$collection->slug, '#about'], array_column($tiles, 'href'));
118
+        $this->assertSame('product:'.$product->slug, $tiles[0]['image']);
119
+
120
+        $this->get(route('stores.show', $this->store->slug))
121
+            ->assertInertia(fn (Assert $page) => $page
122
+                ->where('bentoSections.0.tiles.1.title', 'Gift sets')
123
+                ->where('linkSuggestions.1.href', '/collections/gift-sets'));
124
+
125
+        $this->put(route('stores.bento.update', [$this->store->slug, 'highlights']), [
126
+            'heading' => 'Start here',
127
+            'variant' => 'even',
128
+            'tiles' => [
129
+                ['title' => 'Everything', 'text' => '', 'href' => '/shop', 'image' => null, 'tone' => 'primary'],
130
+                ['title' => 'Gifts', 'text' => 'Ready to give', 'href' => '/collections/gift-sets', 'image' => 'product:'.$product->slug, 'tone' => 'accent'],
131
+                ['title' => 'Story', 'href' => '#about', 'tone' => 'dark'],
132
+                ['title' => 'FAQ', 'href' => '#faq', 'tone' => 'surface'],
133
+            ],
134
+        ])->assertSessionHasNoErrors();
135
+
136
+        $bento = $this->section('highlights');
137
+        $this->assertSame('even', $bento['variant']);
138
+        $this->assertSame('Start here', $bento['content']['heading']);
139
+        $this->assertCount(4, $bento['content']['tiles']);
140
+        $this->assertNull($bento['content']['tiles'][0]['text']);
141
+
142
+        $this->delete(route('stores.bento.destroy', [$this->store->slug, 'highlights']))->assertSessionHasNoErrors();
143
+        $this->assertNotContains('highlights', $this->homeIds());
144
+    }
145
+
146
+    public function test_bento_tiles_are_checked()
147
+    {
148
+        $this->post(route('stores.bento.store', $this->store->slug), ['after' => 'hero']);
149
+        $url = route('stores.bento.update', [$this->store->slug, 'highlights']);
150
+        $tile = ['title' => 'Shop', 'href' => '/shop', 'tone' => 'primary'];
151
+        $before = $this->section('highlights');
152
+
153
+        $this->put($url, ['variant' => 'mosaic', 'tiles' => [$tile, $tile]])->assertSessionHasErrors('tiles');
154
+        $this->put($url, ['variant' => 'mosaic', 'tiles' => [$tile, $tile, [...$tile, 'href' => 'javascript:alert(1)']]])->assertSessionHasErrors('tiles.2.href');
155
+        $this->put($url, ['variant' => 'mosaic', 'tiles' => [$tile, $tile, [...$tile, 'image' => 'product:not-ours']]])->assertSessionHasErrors('section');
156
+        // A link to a page the store does not have is caught by the plan checker.
157
+        $this->put($url, ['variant' => 'mosaic', 'tiles' => [$tile, $tile, [...$tile, 'href' => '/no-such-page']]])->assertSessionHasErrors('section');
158
+
159
+        $this->assertSame($before, $this->section('highlights'));
160
+    }
161
+}

+ 2
- 1
tests/Feature/Stores/PlanValidatorTest.php Zobrazit soubor

@@ -45,8 +45,9 @@ class PlanValidatorTest extends TestCase
45 45
         $this->assertSame('home', $plan['pages'][0]['id']);
46 46
         $this->assertArrayHasKey('logoText', $plan['header']['content']);
47 47
         $this->assertArrayHasKey('text', $plan['footer']['content']);
48
+        // Video is left out on purpose: the AI must only use a video the merchant gives, so the example has none.
48 49
         $this->assertEqualsCanonicalizing(
49
-            array_keys(PlanSchema::pageSections()),
50
+            array_values(array_diff(array_keys(PlanSchema::pageSections()), ['video'])),
50 51
             array_column($plan['pages'][0]['sections'], 'type'),
51 52
         );
52 53
     }

+ 1
- 1
tests/Feature/Stores/StoreDesignTest.php Zobrazit soubor

@@ -38,7 +38,7 @@ class StoreDesignTest extends TestCase
38 38
             ->assertInertia(fn (Assert $page) => $page
39 39
                 ->component('stores/preview')
40 40
                 ->where('storeName', 'Sambal Nenek')
41
-                ->has('plan.pages.0.sections', 9)
41
+                ->has('plan.pages.0.sections', 11)
42 42
                 ->where('plan.header.content.logoText', 'Sambal Nenek')
43 43
                 ->where('view.type', 'page')
44 44
                 ->where('view.pageId', 'home')

Načítá se…
Zrušit
Uložit