Procházet zdrojové kódy

Upgrade product page and add phone menu

- Folding sections: product's own (form or chat) plus shipping from real fees
- Trust points and WhatsApp question link under the button
- Sticky add-to-cart bar on phones; photos stay in view on wide screens
- Pairs well with: bundle partners first, then other products
- Phone menu for the store header
redesign/part-3-product-page
fahmisaad před 1 dnem
rodič
revize
c55c044c73

+ 66
- 54
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-18
7
-**Current step:** Step 9 — Modern store design (parts 1 and 2 done; next: part 3, product page upgrade)
8
-**Next action:** Commit part 2 on `redesign/part-2-announcement-bar` (do not merge into `main` yet). Then create `redesign/part-3-product-page` from it and build the product page upgrade. Step 7 part 2 still waits for an EasyParcel API key
7
+**Current step:** Step 9 — Modern store design (parts 1–3 done; next: part 4, style options and motion)
8
+**Next action:** Commit part 3 on `redesign/part-3-product-page` (do not merge into `main` yet). Then create `redesign/part-4-style-options` from it and build style options and motion. 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
 
@@ -209,6 +209,16 @@ Changing from Claude to another AI model (or back) must be a settings change, no
209 209
 - **Trust row:** a new section type, `trust_bar`, with layouts `row` (a band of icons) and `boxed` (small cards), 2 to 4 items. Items of kind `shipping`, `payment` and `whatsapp` are written by the store from its real settings, so they stay true when settings change (the WhatsApp item hides when there is no number). A `custom` item has a title, optional text and an icon from a fixed list, and the AI may only state what the merchant said. The AI adds a trust row after the hero in new designs, and can add one by chat.
210 210
 - "Secure checkout, pay safely through Stripe" is used instead of listing payment methods, because FPX and e-wallets depend on what the merchant switches on in Stripe.
211 211
 
212
+### How the product page works (upgraded in Step 9 part 3)
213
+
214
+- **Folding sections:** each product can have up to 5 sections (`products.details`, title and text), edited under "More information" in the product form. A "Shipping" section is always added by the store from its real fees (Peninsular, Sabah/Sarawak/Labuan, free shipping), so it is never out of date.
215
+- **Chat:** `create_product`, `update_product` and `create_bundle` accept `details`. In `update_product` they merge by title (same title rewritten, new title added) and `remove_details` takes sections out, because the AI only sees section titles, not their text, and must not wipe them. The confirm card shows the full new text. The AI must not write ingredients or materials unless the merchant gives them.
216
+- **Trust points** under the button: shipping, secure checkout, and "Ask about this product on WhatsApp" (opens WhatsApp with the product name), all from real settings.
217
+- **Sticky add-to-cart bar on phones:** appears once the main button has scrolled up under the header; shows the name, choice and price. It is hidden for sold-out products. The WhatsApp button moves up while it shows. (A scroll check is used, because some embedded browsers ignore the "intersection" margin.)
218
+- **Pairs well with:** up to 4 products: those sold in a bundle with this one first, then the bundles containing it, then other in-stock products, newest first (`App\Storefront\RelatedProducts`).
219
+- **Phone menu:** below tablet width both header layouts show a menu button that opens all links and the header button; Escape or a link closes it.
220
+- On wide screens the photos stay in view while the shopper scrolls the details.
221
+
212 222
 ### Category guides for the AI (agreed 2026-11-17)
213 223
 
214 224
 - 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.
@@ -349,7 +359,7 @@ Agreed on 2026-11-17 after comparing our stores with 2026 design trends (researc
349 359
 
350 360
 - [x] Part 1 — Photos first (done 2026-11-18): hero layouts with a big photo (full width, and split photo and text), a hero photo the merchant uploads in the Design tab or one of their product photos, second product photo on hover, nicer placeholders when there is no photo
351 361
 - [x] Part 2 — Announcement bar and trust row (done 2026-11-18): a slim bar above the header and a row of trust points, filled in by themselves from free shipping, automatic discounts, secure payment and WhatsApp
352
-- [ ] Part 3 — Product page upgrade: trust points under the button, folding sections (how to use, what's inside, shipping) written by the AI, sticky add-to-cart bar on phones, "pairs well with", and a proper phone menu for the header
362
+- [x] Part 3 — Product page upgrade (done 2026-11-18): trust points under the button, folding sections (the product's own, such as "How to use", plus shipping from real fees), sticky add-to-cart bar on phones, "pairs well with", photos that stay in view on wide screens, and a phone menu for the header
353 363
 - [ ] Part 4 — Style options and motion: style presets the AI picks (minimal, bold, dark and elegant, soft, playful), buttons (solid, outline, pill), borders and shadows, spacing (compact or airy), section backgrounds, more fonts, more layouts per section, and gentle motion (always off for visitors who ask their device for less motion)
354 364
 - [ ] Part 5 — Category guides for the AI (see section 2)
355 365
 - [ ] Part 6 — Collections ("shop by need" tiles and menu links), bento grid section, video section, real reviews from buyers after delivery
@@ -414,57 +424,58 @@ Then, from the project folder:
414 424
 
415 425
 ## 4b. Where things are in the code
416 426
 
417
-| Thing                                  | Location                                                                                                                                      |
418
-| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
419
-| Store model                            | `app/Models/Store.php`                                                                                                                        |
420
-| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                                                                    |
421
-| Store categories, languages, statuses  | `app/Enums/`                                                                                                                                  |
422
-| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                                                                             |
423
-| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                                                                              |
424
-| Store tests                            | `tests/Feature/Stores/`                                                                                                                       |
425
-| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                                                                |
426
-| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                                                                             |
427
-| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                                                                |
428
-| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                                                                              |
429
-| AI settings                            | `config/ai.php` (providers, models per task)                                                                                                  |
430
-| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                                                                  |
431
-| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                                                                           |
432
-| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                                                                          |
433
-| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                                                                             |
434
-| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                                                                             |
435
-| Progress screen and chat box           | `resources/js/components/stores/`                                                                                                             |
436
-| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                                                                       |
437
-| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                                                                  |
438
-| Product screens                        | `resources/js/pages/stores/products/`                                                                                                         |
439
-| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                                                                              |
440
-| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                                                                    |
441
-| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                                                               |
442
-| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                                                               |
443
-| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                                                               |
444
-| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                                                                              |
445
-| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                                                               |
446
-| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                                                                              |
447
-| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                                                                             |
448
-| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`                                                   |
449
-| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                                                                |
450
-| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                                                                   |
451
-| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php`                                                |
452
-| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                                                                      |
453
-| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                                                                          |
454
-| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                                                                      |
455
-| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                                                                        |
456
-| Discount codes                         | `app/Models/DiscountCode.php`, `app/Http/Controllers/DiscountCodeController.php`, `resources/js/pages/stores/discounts/`                      |
457
-| Discount in the cart and checkout      | `Cart::applyCode` and `Cart::discount`, `Checkout::placeOrder`                                                                                |
458
-| Product variants                       | `app/Models/ProductVariant.php`, `SaveProductRequest`, `ProductController::syncVariants`, `resources/js/components/stores/variant-editor.tsx` |
459
-| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                                            |
460
-| Bundles                                | `app/Models/BundleItem.php`, `app/Commerce/BundleStock.php`, `resources/js/components/stores/bundle-editor.tsx`                               |
461
-| Chat commands                          | `app/Commerce/ChatActions.php`, `StoreGenerationController::confirm`, `resources/js/components/stores/design-chat.tsx`                        |
462
-| Automatic discounts                    | `app/Models/AutomaticDiscount.php`, `app/Commerce/AutomaticDiscountRules.php`, `Cart::applied`, `AutomaticDiscountController`                 |
463
-| Hero photos                            | `app/StorePlan/HeroImages.php`, `HeroImageController`, `resources/js/storefront/sections/hero.tsx`, `components/stores/hero-picker.tsx`       |
464
-| Announcement bar and trust row         | `app/Storefront/Announcements.php`, `storefront/sections/announcement-bar.tsx`, `storefront/sections/trust-bar.tsx`                           |
465
-| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                             |
466
-| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                            |
467
-| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                   |
427
+| Thing                                  | Location                                                                                                                                       |
428
+| -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
429
+| Store model                            | `app/Models/Store.php`                                                                                                                         |
430
+| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                                                                                     |
431
+| Store categories, languages, statuses  | `app/Enums/`                                                                                                                                   |
432
+| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                                                                                              |
433
+| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                                                                               |
434
+| Store tests                            | `tests/Feature/Stores/`                                                                                                                        |
435
+| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                                                                                 |
436
+| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                                                                                              |
437
+| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                                                                                 |
438
+| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                                                                               |
439
+| AI settings                            | `config/ai.php` (providers, models per task)                                                                                                   |
440
+| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                                                                                   |
441
+| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                                                                                            |
442
+| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                                                                                           |
443
+| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                                                                                              |
444
+| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                                                                                              |
445
+| Progress screen and chat box           | `resources/js/components/stores/`                                                                                                              |
446
+| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                                                                                        |
447
+| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                                                                                   |
448
+| Product screens                        | `resources/js/pages/stores/products/`                                                                                                          |
449
+| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                                                                               |
450
+| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`                                                                     |
451
+| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                                                                                |
452
+| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`)                                                                |
453
+| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/`                                                                |
454
+| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                                                                               |
455
+| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                                                                                |
456
+| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                                                                               |
457
+| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                                                                                              |
458
+| Plans, trial and limits                | `app/Models/Plan.php`, `app/Models/User.php` (`currentPlan`), `app/Billing/UsageLimits.php`                                                    |
459
+| Subscriptions with Stripe              | `app/Billing/` (`Billing`, `SubscriptionGateway`, `StripeSubscriptionGateway`)                                                                 |
460
+| Billing page                           | `app/Http/Controllers/BillingController.php`, `resources/js/pages/billing/`                                                                    |
461
+| Shipping fees                          | `app/Commerce/Shipping/`, store settings in `app/Http/Controllers/StoreSettingsController.php`                                                 |
462
+| Store settings page                    | `resources/js/pages/stores/settings.tsx`                                                                                                       |
463
+| Mark as shipped and its email          | `OrderController::ship`, `app/Mail/OrderShipped.php`                                                                                           |
464
+| WhatsApp links and phone cleaning      | `app/Support/MalaysianPhone.php`, `resources/js/storefront/whatsapp.tsx`                                                                       |
465
+| Shopper messages in English and Malay  | `app/Storefront/StorefrontText.php`, `resources/js/storefront/text.ts`                                                                         |
466
+| Discount codes                         | `app/Models/DiscountCode.php`, `app/Http/Controllers/DiscountCodeController.php`, `resources/js/pages/stores/discounts/`                       |
467
+| Discount in the cart and checkout      | `Cart::applyCode` and `Cart::discount`, `Checkout::placeOrder`                                                                                 |
468
+| Product variants                       | `app/Models/ProductVariant.php`, `SaveProductRequest`, `ProductController::syncVariants`, `resources/js/components/stores/variant-editor.tsx`  |
469
+| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                                             |
470
+| Bundles                                | `app/Models/BundleItem.php`, `app/Commerce/BundleStock.php`, `resources/js/components/stores/bundle-editor.tsx`                                |
471
+| Chat commands                          | `app/Commerce/ChatActions.php`, `StoreGenerationController::confirm`, `resources/js/components/stores/design-chat.tsx`                         |
472
+| Automatic discounts                    | `app/Models/AutomaticDiscount.php`, `app/Commerce/AutomaticDiscountRules.php`, `Cart::applied`, `AutomaticDiscountController`                  |
473
+| Hero photos                            | `app/StorePlan/HeroImages.php`, `HeroImageController`, `resources/js/storefront/sections/hero.tsx`, `components/stores/hero-picker.tsx`        |
474
+| Announcement bar and trust row         | `app/Storefront/Announcements.php`, `storefront/sections/announcement-bar.tsx`, `storefront/sections/trust-bar.tsx`                            |
475
+| Product page, phone menu               | `storefront/pages/product.tsx`, `app/Storefront/RelatedProducts.php`, `components/stores/details-editor.tsx`, `storefront/sections/header.tsx` |
476
+| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                              |
477
+| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                             |
478
+| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                    |
468 479
 
469 480
 ## 5. Open questions
470 481
 
@@ -521,3 +532,4 @@ Add one line per work session: date, what was done, what is next.
521 532
 | 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                                     |
522 533
 | 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                                              |
523 534
 | 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                             |
535
+| 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                             |

+ 4
- 2
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–2 done; part 3 next                       |
24
+| 9    | Modern store design: photos, styles, category guides    | In progress: parts 1–3 done; part 4 next                       |
25 25
 | 10   | Before launch: hosting, legal pages, backups            | Not started                                                    |
26 26
 
27 27
 ## What works today
@@ -38,6 +38,8 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
38 38
 - Product cards show a second photo on hover
39 39
 - Announcement bar above the header: free shipping and running automatic discounts appear by themselves, plus up to 3 of the merchant's own lines (Settings tab)
40 40
 - Trust row under the hero: shipping, secure payment and WhatsApp, always taken from the store's real settings
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
+- Phone menu for the store header
41 43
 - 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
42 44
 - Add or remove whole pages by chat, for example "add an About page". The menu link is added automatically
43 45
 - "Regenerate" for a completely new design, limited by the plan
@@ -59,7 +61,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
59 61
 - Automatic discounts with no code, such as "buy 2, get 10% off", on all or chosen products. Only one discount applies per order: the shopper gets whichever saves more
60 62
 - Billing: 14-day free trial, then Starter, Growth or Pro through Stripe. Merchants can switch or cancel on the Billing page, and plan limits are enforced
61 63
 
62
-Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.
64
+Known gaps: images are placeholders until the merchant adds photos, and the newsletter form does not save sign-ups.
63 65
 
64 66
 ## Tech stack
65 67
 

+ 102
- 5
app/Commerce/ChatActions.php Zobrazit soubor

@@ -131,6 +131,9 @@ final class ChatActions
131 131
         $data = self::validate($input, [
132 132
             'name' => ['required', 'string', 'min:2', 'max:120'],
133 133
             'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
134
+            'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
135
+            'details.*.title' => ['required', 'string', 'max:60'],
136
+            'details.*.body' => ['required', 'string', 'max:2000'],
134 137
             'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
135 138
             'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
136 139
             'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
@@ -142,7 +145,8 @@ final class ChatActions
142 145
             .self::wasPrice($data['compare_at_price'] ?? null)
143 146
             .", {$data['stock']} in stock, "
144 147
             .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
145
-            .self::descriptionNote($data['description'] ?? null);
148
+            .self::descriptionNote($data['description'] ?? null)
149
+            .(self::cleanDetails($data['details'] ?? null) !== null ? '. Sections '.self::detailsNote((array) self::cleanDetails($data['details'] ?? null)) : '');
146 150
 
147 151
         return [
148 152
             'input' => $data,
@@ -151,6 +155,7 @@ final class ChatActions
151 155
                 $store->products()->create([
152 156
                     'name' => $data['name'],
153 157
                     'description' => self::cleanText($data['description'] ?? null),
158
+                    'details' => self::cleanDetails($data['details'] ?? null),
154 159
                     'price' => self::sen($data['price']),
155 160
                     'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
156 161
                     'stock' => (int) $data['stock'],
@@ -171,6 +176,11 @@ final class ChatActions
171 176
             'variant' => ['nullable', 'string', 'max:90'],
172 177
             'name' => ['sometimes', 'string', 'min:2', 'max:120'],
173 178
             'description' => ['sometimes', 'nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
179
+            'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
180
+            'details.*.title' => ['required', 'string', 'max:60'],
181
+            'details.*.body' => ['required', 'string', 'max:2000'],
182
+            'remove_details' => ['sometimes', 'array', 'list', 'max:'.Product::MAX_DETAILS],
183
+            'remove_details.*' => ['string', 'max:60'],
174 184
             'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
175 185
             'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
176 186
             'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'],
@@ -179,10 +189,10 @@ final class ChatActions
179 189
 
180 190
         $product = self::findProduct($store, $data['product'], 'product');
181 191
         $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data));
182
-        $productFields = array_intersect(['name', 'description', 'status'], array_keys($data));
192
+        $productFields = array_intersect(['name', 'description', 'details', 'remove_details', 'status'], array_keys($data));
183 193
 
184 194
         if ($priceFields === [] && $productFields === []) {
185
-            self::fail('product', 'Say what to change: name, description, price, compare_at_price, stock or status.');
195
+            self::fail('product', 'Say what to change: name, description, details, price, compare_at_price, stock or status.');
186 196
         }
187 197
 
188 198
         $variant = null;
@@ -243,6 +253,27 @@ final class ChatActions
243 253
             $changes[] = $description === null ? 'remove the description' : "description: \"{$description}\"";
244 254
         }
245 255
 
256
+        // Sections merge by title: a known title is rewritten, a new one is added, "remove_details" takes some out.
257
+        // The AI never sees the full text of the others, so it must not wipe them.
258
+        $details = self::mergeDetails($product->details, self::cleanDetails($data['details'] ?? null), $data['remove_details'] ?? []);
259
+
260
+        if ($details !== null && count($details) > Product::MAX_DETAILS) {
261
+            self::fail('details', 'A product can have at most '.Product::MAX_DETAILS.' sections. Remove one first with "remove_details".');
262
+        }
263
+
264
+        // Only the sections that change are spelled out, in full.
265
+        if ($details !== $product->details) {
266
+            $written = self::cleanDetails($data['details'] ?? null);
267
+
268
+            if ($written !== null) {
269
+                $changes[] = 'sections '.self::detailsNote($written);
270
+            }
271
+
272
+            foreach ($data['remove_details'] ?? [] as $title) {
273
+                $changes[] = "remove the section \"{$title}\"";
274
+            }
275
+        }
276
+
246 277
         if ($changes === []) {
247 278
             self::fail('product', 'These values are already set. Nothing would change.');
248 279
         }
@@ -252,7 +283,7 @@ final class ChatActions
252 283
         return [
253 284
             'input' => $data,
254 285
             'summary' => "Change \"{$label}\": ".implode(', ', $changes),
255
-            'run' => function () use ($product, $variant, $data, $newPrice, $newCompare): void {
286
+            'run' => function () use ($product, $variant, $data, $newPrice, $newCompare, $details): void {
256 287
                 $owner = $variant ?? $product;
257 288
                 $owner->price = $newPrice;
258 289
                 $owner->compare_at_price = $newCompare;
@@ -271,6 +302,8 @@ final class ChatActions
271 302
                     $product->description = self::cleanText($data['description']);
272 303
                 }
273 304
 
305
+                $product->details = $details;
306
+
274 307
                 if (array_key_exists('status', $data)) {
275 308
                     $product->status = ProductStatus::from($data['status']);
276 309
                 }
@@ -413,6 +446,9 @@ final class ChatActions
413 446
         $data = self::validate($input, [
414 447
             'name' => ['required', 'string', 'min:2', 'max:120'],
415 448
             'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
449
+            'details' => ['sometimes', 'nullable', 'array', 'list', 'max:'.Product::MAX_DETAILS],
450
+            'details.*.title' => ['required', 'string', 'max:60'],
451
+            'details.*.body' => ['required', 'string', 'max:2000'],
416 452
             'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
417 453
             'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
418 454
             'status' => ['nullable', 'in:active,draft'],
@@ -462,7 +498,8 @@ final class ChatActions
462 498
             .': '.implode(', ', $labels)
463 499
             .". Enough stock for {$stock} now, "
464 500
             .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
465
-            .self::descriptionNote($data['description'] ?? null);
501
+            .self::descriptionNote($data['description'] ?? null)
502
+            .(self::cleanDetails($data['details'] ?? null) !== null ? '. Sections '.self::detailsNote((array) self::cleanDetails($data['details'] ?? null)) : '');
466 503
 
467 504
         return [
468 505
             'input' => $data,
@@ -471,6 +508,7 @@ final class ChatActions
471 508
                 $bundle = $store->products()->make([
472 509
                     'name' => $data['name'],
473 510
                     'description' => self::cleanText($data['description'] ?? null),
511
+                    'details' => self::cleanDetails($data['details'] ?? null),
474 512
                     'price' => self::sen($data['price']),
475 513
                     'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
476 514
                     'stock' => 0,
@@ -595,6 +633,65 @@ final class ChatActions
595 633
         return $variant;
596 634
     }
597 635
 
636
+    /**
637
+     * Trimmed sections without empty ones, or null when none are left.
638
+     *
639
+     * @return list<array{title: string, body: string}>|null
640
+     */
641
+    private static function cleanDetails(mixed $details): ?array
642
+    {
643
+        $clean = [];
644
+
645
+        foreach (is_array($details) ? $details : [] as $row) {
646
+            $title = trim((string) ($row['title'] ?? ''));
647
+            $body = trim((string) ($row['body'] ?? ''));
648
+
649
+            if ($title !== '' && $body !== '') {
650
+                $clean[] = ['title' => $title, 'body' => $body];
651
+            }
652
+        }
653
+
654
+        return $clean === [] ? null : $clean;
655
+    }
656
+
657
+    /**
658
+     * The product's sections after a chat change: same title (letter case ignored) replaces, new titles are added
659
+     * at the end, and titles in $remove are taken out.
660
+     *
661
+     * @param  list<array{title: string, body: string}>|null  $current
662
+     * @param  list<array{title: string, body: string}>|null  $changes
663
+     * @param  list<string>  $remove
664
+     * @return list<array{title: string, body: string}>|null
665
+     */
666
+    private static function mergeDetails(?array $current, ?array $changes, array $remove): ?array
667
+    {
668
+        $key = fn (string $title) => mb_strtolower(trim($title));
669
+        $removed = array_map($key, $remove);
670
+        $merged = [];
671
+
672
+        foreach ($current ?? [] as $row) {
673
+            if (! in_array($key($row['title']), $removed, true)) {
674
+                $merged[$key($row['title'])] = $row;
675
+            }
676
+        }
677
+
678
+        foreach ($changes ?? [] as $row) {
679
+            $merged[$key($row['title'])] = $row;
680
+        }
681
+
682
+        return $merged === [] ? null : array_values($merged);
683
+    }
684
+
685
+    /**
686
+     * Each section in full: "How to use": "Apply ...", so the merchant reads what will be saved.
687
+     *
688
+     * @param  list<array{title: string, body: string}>  $details
689
+     */
690
+    private static function detailsNote(array $details): string
691
+    {
692
+        return implode('; ', array_map(fn (array $row) => "\"{$row['title']}\": \"{$row['body']}\"", $details));
693
+    }
694
+
598 695
     private static function descriptionNote(mixed $description): string
599 696
     {
600 697
         $text = self::cleanText($description);

+ 3
- 1
app/Http/Controllers/Concerns/RendersStorefront.php Zobrazit soubor

@@ -75,8 +75,10 @@ trait RendersStorefront
75 75
                 'free_shipping_over' => $store->free_shipping_over !== null ? $store->free_shipping_over / 100 : null,
76 76
                 // Lines for the slim bar above the header. Empty when the merchant switched it off.
77 77
                 'announcements' => Announcements::for($store, $cart->liveOffers()),
78
-                // The cheapest shipping fee in ringgit, for the trust row.
78
+                // Shipping fees in ringgit, for the trust row and the product page.
79 79
                 'shipping_from' => min($store->shipping_west, $store->shipping_east) / 100,
80
+                'shipping_west' => $store->shipping_west / 100,
81
+                'shipping_east' => $store->shipping_east / 100,
80 82
                 // Automatic discounts running now, so product pages can mention them.
81 83
                 'offers' => $cart->liveOffers()->map(fn (AutomaticDiscount $offer) => [
82 84
                     'name' => $offer->name,

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

@@ -258,6 +258,7 @@ class ProductController extends Controller
258 258
             'name' => $product->name,
259 259
             'slug' => $product->slug,
260 260
             'description' => $product->description,
261
+            'details' => $product->details ?? [],
261 262
             'price' => number_format($product->price / 100, 2, '.', ''),
262 263
             'compare_at_price' => $product->compare_at_price !== null
263 264
                 ? number_format($product->compare_at_price / 100, 2, '.', '')

+ 6
- 1
app/Http/Controllers/StoreDesignController.php Zobrazit soubor

@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
4 4
 
5 5
 use App\Http\Controllers\Concerns\RendersStorefront;
6 6
 use App\Models\Product;
7
+use App\Storefront\RelatedProducts;
7 8
 use App\StorePlan\PlanSchema;
8 9
 use Illuminate\Http\RedirectResponse;
9 10
 use Illuminate\Http\Request;
@@ -66,6 +67,10 @@ class StoreDesignController extends Controller
66 67
             ->where('slug', (string) $request->route('productSlug'))
67 68
             ->firstOrFail();
68 69
 
69
-        return $this->renderStorefront($request, $storefront, ['type' => 'product', 'product' => $product->toStorefront()]);
70
+        return $this->renderStorefront($request, $storefront, [
71
+            'type' => 'product',
72
+            'product' => $product->toStorefront(),
73
+            'related' => RelatedProducts::for($product)->map(fn (Product $item) => $item->toStorefront())->values()->all(),
74
+        ]);
70 75
     }
71 76
 }

+ 30
- 1
app/Http/Requests/Products/SaveProductRequest.php Zobrazit soubor

@@ -65,6 +65,11 @@ class SaveProductRequest extends FormRequest
65 65
             'variants.*.compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
66 66
             'variants.*.stock' => ['required', 'integer', 'min:0', 'max:1000000'],
67 67
 
68
+            // Folding sections on the product page, such as "How to use". Empty rows are dropped.
69
+            'details' => ['nullable', 'array', 'max:'.Product::MAX_DETAILS],
70
+            'details.*.title' => ['nullable', 'string', 'max:60', 'required_with:details.*.body'],
71
+            'details.*.body' => ['nullable', 'string', 'max:2000', 'required_with:details.*.title'],
72
+
68 73
             'is_bundle' => ['nullable', 'boolean'],
69 74
             ...($bundle ? [
70 75
                 'bundle_items' => ['required', 'array', 'min:1', 'max:'.self::MAX_BUNDLE_ITEMS],
@@ -90,6 +95,9 @@ class SaveProductRequest extends FormRequest
90 95
             'options.*.values.required' => 'List the choices for each option, separated by commas.',
91 96
             'variants.*.price.required' => 'Every combination needs a price.',
92 97
             'variants.*.stock.required' => 'Every combination needs a stock number.',
98
+            'details.max' => 'A product can have at most '.Product::MAX_DETAILS.' extra sections.',
99
+            'details.*.title.required_with' => 'Give this section a title, such as "How to use".',
100
+            'details.*.body.required_with' => 'Write the text for this section.',
93 101
             'bundle_items.required' => 'Add at least one product to the bundle.',
94 102
             'bundle_items.min' => 'Add at least one product to the bundle.',
95 103
             'bundle_items.max' => 'A bundle can hold at most '.self::MAX_BUNDLE_ITEMS.' different products.',
@@ -163,6 +171,27 @@ class SaveProductRequest extends FormRequest
163 171
         });
164 172
     }
165 173
 
174
+    /**
175
+     * The folding sections, trimmed, without empty rows. Null when there are none.
176
+     *
177
+     * @return list<array{title: string, body: string}>|null
178
+     */
179
+    public function detailsData(): ?array
180
+    {
181
+        $details = [];
182
+
183
+        foreach (array_values((array) $this->input('details', [])) as $row) {
184
+            $title = trim((string) ($row['title'] ?? ''));
185
+            $body = trim((string) ($row['body'] ?? ''));
186
+
187
+            if ($title !== '' && $body !== '') {
188
+                $details[] = ['title' => $title, 'body' => $body];
189
+            }
190
+        }
191
+
192
+        return $details === [] ? null : $details;
193
+    }
194
+
166 195
     /**
167 196
      * A bundle never has options of its own; its items may.
168 197
      */
@@ -364,7 +393,7 @@ class SaveProductRequest extends FormRequest
364 393
      */
365 394
     public function productData(): array
366 395
     {
367
-        $data = $this->safe()->only(['name', 'description', 'status']);
396
+        $data = [...$this->safe()->only(['name', 'description', 'status']), 'details' => $this->detailsData()];
368 397
 
369 398
         if ($this->isBundle()) {
370 399
             $compare = $this->validated('compare_at_price');

+ 7
- 1
app/Models/Product.php Zobrazit soubor

@@ -22,6 +22,7 @@ use Illuminate\Support\Str;
22 22
  * @property string $name
23 23
  * @property string $slug
24 24
  * @property string|null $description
25
+ * @property list<array{title: string, body: string}>|null $details Folding sections on the product page, such as "How to use"
25 26
  * @property list<array{name: string, values: list<string>}>|null $options Up to 2 options. Null for a simple product.
26 27
  * @property bool $is_bundle True for a bundle: its stock comes from the products inside it.
27 28
  * @property int $price
@@ -35,12 +36,15 @@ use Illuminate\Support\Str;
35 36
  * @property-read Collection<int, ProductVariant> $variants
36 37
  * @property-read Collection<int, BundleItem> $bundleItems
37 38
  */
38
-#[Fillable(['name', 'description', 'price', 'compare_at_price', 'stock', 'status'])]
39
+#[Fillable(['name', 'description', 'details', 'price', 'compare_at_price', 'stock', 'status'])]
39 40
 class Product extends Model
40 41
 {
41 42
     /** @use HasFactory<ProductFactory> */
42 43
     use HasFactory;
43 44
 
45
+    /** The most folding sections one product may have. */
46
+    public const int MAX_DETAILS = 5;
47
+
44 48
     /** What the storefront needs loaded to show a product. */
45 49
     public const array STOREFRONT_RELATIONS = ['images', 'variants', 'bundleItems.product', 'bundleItems.variant'];
46 50
 
@@ -173,6 +177,7 @@ class Product extends Model
173 177
             'name' => $this->name,
174 178
             'slug' => $this->slug,
175 179
             'description' => $this->description,
180
+            'details' => $this->details ?? [],
176 181
             'price' => $this->price / 100,
177 182
             'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
178 183
             'in_stock' => $this->stock > 0,
@@ -208,6 +213,7 @@ class Product extends Model
208 213
             'compare_at_price' => 'integer',
209 214
             'stock' => 'integer',
210 215
             'options' => 'array',
216
+            'details' => 'array',
211 217
             'is_bundle' => 'boolean',
212 218
         ];
213 219
     }

+ 8
- 2
app/StorePlan/Ai/PlanPrompt.php Zobrazit soubor

@@ -141,7 +141,8 @@ final class PlanPrompt
141 141
 
142 142
         $productLines = $products->map(function (Product $product) use ($money): string {
143 143
             // Whether it has a description, so "write descriptions for products without one" works.
144
-            $line = "- {$product->slug}: {$product->name}, {$product->status->value}, ".(filled($product->description) ? 'has a description' : 'no description');
144
+            $line = "- {$product->slug}: {$product->name}, {$product->status->value}, ".(filled($product->description) ? 'has a description' : 'no description')
145
+                .(! empty($product->details) ? ', sections: '.implode(', ', array_column($product->details, 'title')) : '');
145 146
 
146 147
             if ($product->isBundle()) {
147 148
                 return $line.', bundle, '.$money($product->price).', enough stock for '.$product->stock
@@ -232,7 +233,7 @@ final class PlanPrompt
232 233
         Besides the design, the merchant may ask to change products, discount codes or bundles. Do not change the design for these. Put them in "actions" instead. They are not done yet: the merchant sees each one and confirms it first, so in "reply" say what you prepared and ask them to confirm, for example "I've prepared the RAYA10 code. Please confirm below." Use these, with prices in ringgit as plain numbers:
233 234
 
234 235
         {"type": "create_product", "name": "...", "price": 12.9, "stock": 20, "compare_at_price": null or a higher "was" price, "description": "..." or null, "status": "active" or "draft"}
235
-        {"type": "update_product", "product": "web-address name", "variant": "the choice, such as \"100ml\", only for products with choices", then only the fields to change: "name", "description", "price", "compare_at_price" (null removes it), "stock", "status"}
236
+        {"type": "update_product", "product": "web-address name", "variant": "the choice, such as \"100ml\", only for products with choices", then only the fields to change: "name", "description", "details", "remove_details", "price", "compare_at_price" (null removes it), "stock", "status"}
236 237
         {"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}
237 238
         {"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}
238 239
         {"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"}
@@ -253,6 +254,11 @@ final class PlanPrompt
253 254
         - Never invent facts that the name or the merchant did not give: no ingredients, materials, sizes, origins, certifications (including halal), awards, health or medical claims, or numbers. Describe what the name tells you and how the customer may use or enjoy it.
254 255
         - The confirm card shows the full text, so in "reply" just say which products you wrote descriptions for.
255 256
 
257
+        # Product sections
258
+
259
+        A product can also have up to 5 extra sections that fold open on its page, such as "How to use" or "Care": "details": [{"title": "How to use", "body": "..."}]. In "update_product" they merge by title: a title the product already has is rewritten, a new title is added, and "remove_details": ["Care"] takes sections out. Shipping is shown by the store itself, so never write a shipping section.
260
+        - Write sections only when asked, or when adding a new product. Same rules as descriptions: plain text, 1 to 4 sentences, no invented facts. Never write an ingredients or materials section unless the merchant gives you the list.
261
+
256 262
         Never say in "reply" that you changed something unless your answer contains that change.
257 263
 
258 264
         If the request is not about this store's design, text, products, discount codes or bundles, or you cannot do it within the format below, change nothing and explain briefly in "reply".

+ 60
- 0
app/Storefront/RelatedProducts.php Zobrazit soubor

@@ -0,0 +1,60 @@
1
+<?php
2
+
3
+namespace App\Storefront;
4
+
5
+use App\Models\BundleItem;
6
+use App\Models\Product;
7
+use Illuminate\Database\Eloquent\Builder;
8
+use Illuminate\Database\Eloquent\Collection;
9
+
10
+/**
11
+ * "Pairs well with" on a product page.
12
+ *
13
+ * Products that are sold together in a bundle come first (they really do go together), then the bundles
14
+ * this product is part of, then other products shoppers can buy now, newest first.
15
+ */
16
+final class RelatedProducts
17
+{
18
+    public const int LIMIT = 4;
19
+
20
+    /**
21
+     * @return Collection<int, Product>
22
+     */
23
+    public static function for(Product $product): Collection
24
+    {
25
+        $bundleIds = BundleItem::query()->where('product_id', $product->id)->pluck('bundle_id')->all();
26
+
27
+        // Other products inside the same bundles, then the bundles themselves.
28
+        $partners = BundleItem::query()->whereIn('bundle_id', $bundleIds)->pluck('product_id')->all();
29
+        $wanted = array_values(array_unique(array_merge($partners, $bundleIds)));
30
+
31
+        $picked = self::query($product)->whereKey($wanted)->get()
32
+            ->sortBy(fn (Product $candidate) => array_search($candidate->id, $wanted, true))
33
+            ->values();
34
+
35
+        if ($picked->count() < self::LIMIT) {
36
+            $more = self::query($product)
37
+                ->whereKeyNot($picked->modelKeys())
38
+                ->where('stock', '>', 0)
39
+                ->latest('id')
40
+                ->limit(self::LIMIT - $picked->count())
41
+                ->get();
42
+
43
+            $picked = $picked->concat($more);
44
+        }
45
+
46
+        return $picked->take(self::LIMIT)->values();
47
+    }
48
+
49
+    /**
50
+     * @return Builder<Product>
51
+     */
52
+    private static function query(Product $product): Builder
53
+    {
54
+        return Product::query()
55
+            ->where('store_id', $product->store_id)
56
+            ->active()
57
+            ->whereKeyNot($product->id)
58
+            ->with(Product::STOREFRONT_RELATIONS);
59
+    }
60
+}

+ 23
- 0
database/migrations/2026_11_18_000003_add_details_to_products_table.php Zobrazit soubor

@@ -0,0 +1,23 @@
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
+        Schema::table('products', function (Blueprint $table) {
12
+            // Folding sections on the product page, such as [{"title": "How to use", "body": "..."}]. Up to 5.
13
+            $table->json('details')->nullable()->after('description');
14
+        });
15
+    }
16
+
17
+    public function down(): void
18
+    {
19
+        Schema::table('products', function (Blueprint $table) {
20
+            $table->dropColumn('details');
21
+        });
22
+    }
23
+};

+ 7
- 0
resources/css/app.css Zobrazit soubor

@@ -197,3 +197,10 @@
197 197
         transform: translateY(2px);
198 198
     }
199 199
 }
200
+
201
+/* On phones, the product page's add-to-cart bar sits at the bottom; the WhatsApp button moves above it. */
202
+@media (max-width: 767px) {
203
+    .sf-sticky-cart .sf-whatsapp {
204
+        bottom: 5.5rem;
205
+    }
206
+}

+ 121
- 0
resources/js/components/stores/details-editor.tsx Zobrazit soubor

@@ -0,0 +1,121 @@
1
+import { Plus, X } from 'lucide-react';
2
+import { useState } from 'react';
3
+import InputError from '@/components/input-error';
4
+import { Button } from '@/components/ui/button';
5
+import { Input } from '@/components/ui/input';
6
+import { Label } from '@/components/ui/label';
7
+
8
+type Row = { title: string; body: string };
9
+
10
+const MAX_ROWS = 5;
11
+
12
+const fieldClass =
13
+    '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';
14
+
15
+/**
16
+ * Extra sections that fold open on the product page, such as "How to use" or "Care".
17
+ * The inputs carry the names the server reads: details[i][title] and details[i][body].
18
+ */
19
+export default function DetailsEditor({
20
+    initial,
21
+    errors,
22
+}: {
23
+    initial: Row[];
24
+    errors: Record<string, string>;
25
+}) {
26
+    const [rows, setRows] = useState<Row[]>(initial);
27
+
28
+    function update(index: number, field: keyof Row, value: string) {
29
+        setRows((current) =>
30
+            current.map((row, i) =>
31
+                i === index ? { ...row, [field]: value } : row,
32
+            ),
33
+        );
34
+    }
35
+
36
+    const listError =
37
+        errors.details ??
38
+        Object.entries(errors).find(([key]) => key.startsWith('details.'))?.[1];
39
+
40
+    return (
41
+        <div className="space-y-3" data-test="details-editor">
42
+            <div>
43
+                <p className="text-sm font-medium">More information</p>
44
+                <p className="text-xs text-muted-foreground">
45
+                    Sections shoppers can open on the product page, such as "How
46
+                    to use" or "Care". Shipping is added by itself.
47
+                </p>
48
+            </div>
49
+
50
+            {rows.map((row, index) => (
51
+                <div key={index} className="grid gap-2 rounded-md border p-3">
52
+                    <div className="flex items-center gap-2">
53
+                        <Label
54
+                            htmlFor={`detail-title-${index}`}
55
+                            className="sr-only"
56
+                        >
57
+                            Section {index + 1} title
58
+                        </Label>
59
+                        <Input
60
+                            id={`detail-title-${index}`}
61
+                            name={`details[${index}][title]`}
62
+                            maxLength={60}
63
+                            value={row.title}
64
+                            onChange={(event) =>
65
+                                update(index, 'title', event.target.value)
66
+                            }
67
+                            placeholder="How to use"
68
+                        />
69
+                        <Button
70
+                            type="button"
71
+                            variant="ghost"
72
+                            size="icon"
73
+                            aria-label={`Remove section ${index + 1}`}
74
+                            onClick={() =>
75
+                                setRows((current) =>
76
+                                    current.filter((_, i) => i !== index),
77
+                                )
78
+                            }
79
+                        >
80
+                            <X />
81
+                        </Button>
82
+                    </div>
83
+                    <Label htmlFor={`detail-body-${index}`} className="sr-only">
84
+                        Section {index + 1} text
85
+                    </Label>
86
+                    <textarea
87
+                        id={`detail-body-${index}`}
88
+                        name={`details[${index}][body]`}
89
+                        rows={3}
90
+                        maxLength={2000}
91
+                        value={row.body}
92
+                        onChange={(event) =>
93
+                            update(index, 'body', event.target.value)
94
+                        }
95
+                        className={fieldClass}
96
+                        placeholder="Apply a small amount to clean skin, morning and night."
97
+                    />
98
+                </div>
99
+            ))}
100
+
101
+            {rows.length < MAX_ROWS && (
102
+                <Button
103
+                    type="button"
104
+                    variant="outline"
105
+                    size="sm"
106
+                    onClick={() =>
107
+                        setRows((current) => [
108
+                            ...current,
109
+                            { title: '', body: '' },
110
+                        ])
111
+                    }
112
+                >
113
+                    <Plus />
114
+                    Add a section
115
+                </Button>
116
+            )}
117
+
118
+            <InputError message={listError} />
119
+        </div>
120
+    );
121
+}

+ 6
- 0
resources/js/components/stores/product-form.tsx Zobrazit soubor

@@ -4,6 +4,7 @@ import { useState } from 'react';
4 4
 import ProductController from '@/actions/App/Http/Controllers/ProductController';
5 5
 import InputError from '@/components/input-error';
6 6
 import BundleEditor from '@/components/stores/bundle-editor';
7
+import DetailsEditor from '@/components/stores/details-editor';
7 8
 import VariantEditor from '@/components/stores/variant-editor';
8 9
 import { Button } from '@/components/ui/button';
9 10
 import { Input } from '@/components/ui/input';
@@ -90,6 +91,11 @@ export default function ProductForm({
90 91
                         <InputError message={errors.description} />
91 92
                     </div>
92 93
 
94
+                    <DetailsEditor
95
+                        initial={product?.details ?? []}
96
+                        errors={errors}
97
+                    />
98
+
93 99
                     <div className="grid gap-6 sm:grid-cols-2">
94 100
                         {!hasOptions && (
95 101
                             <>

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

@@ -38,6 +38,8 @@ const StorefrontContext = createContext<Storefront>({
38 38
         free_shipping_over: null,
39 39
         announcements: [],
40 40
         shipping_from: 0,
41
+        shipping_west: 0,
42
+        shipping_east: 0,
41 43
         offers: [],
42 44
     },
43 45
     featuredProducts: {},

+ 245
- 10
resources/js/storefront/pages/product.tsx Zobrazit soubor

@@ -1,16 +1,29 @@
1 1
 import { router } from '@inertiajs/react';
2
-import { Tag } from 'lucide-react';
3
-import { useState } from 'react';
2
+import {
3
+    ChevronDown,
4
+    MessageCircle,
5
+    ShieldCheck,
6
+    Tag,
7
+    Truck,
8
+} from 'lucide-react';
9
+import { useEffect, useRef, useState } from 'react';
4 10
 import { useStorefront } from '../context';
5
-import { ProductImage } from '../product-card';
11
+import { ProductCard, ProductImage } from '../product-card';
6 12
 import { storefrontText } from '../text';
7 13
 import { formatPrice } from '../theme';
8 14
 import { cn } from '@/lib/utils';
9 15
 import type { StoreProduct, StoreVariant } from '../types';
10 16
 import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
17
+import { whatsappLink } from '../whatsapp';
11 18
 
12 19
 /** One product's own page. Built by us, in the store's colours and fonts. */
13
-export function ProductPage({ product }: { product: StoreProduct }) {
20
+export function ProductPage({
21
+    product,
22
+    related,
23
+}: {
24
+    product: StoreProduct;
25
+    related: StoreProduct[];
26
+}) {
14 27
     const { language, shop } = useStorefront();
15 28
     const t = storefrontText(language);
16 29
     const [selected, setSelected] = useState(0);
@@ -67,7 +80,8 @@ export function ProductPage({ product }: { product: StoreProduct }) {
67 80
                 </SfLink>
68 81
 
69 82
                 <div className="mt-6 grid gap-10 md:grid-cols-2 md:gap-14">
70
-                    <div>
83
+                    {/* On wide screens the photos stay in view while the shopper reads. */}
84
+                    <div className="md:sticky md:top-24 md:self-start">
71 85
                         <ProductImage
72 86
                             src={shown}
73 87
                             alt={product.name}
@@ -227,21 +241,158 @@ export function ProductPage({ product }: { product: StoreProduct }) {
227 241
                         <AddToCart
228 242
                             product={product}
229 243
                             variant={variant}
244
+                            price={price}
230 245
                             key={variant?.id ?? 'simple'}
231 246
                         />
247
+
248
+                        <TrustPoints product={product} />
249
+
250
+                        <Sections product={product} />
232 251
                     </div>
233 252
                 </div>
253
+
254
+                {related.length > 0 && (
255
+                    <section className="mt-20" data-test="related-products">
256
+                        <h2 className="sf-heading text-2xl font-semibold sm:text-3xl">
257
+                            {t.pairsWellWith}
258
+                        </h2>
259
+                        <ul className="mt-6 grid grid-cols-2 gap-x-4 gap-y-8 md:grid-cols-4 md:gap-x-6">
260
+                            {related.map((item, index) => (
261
+                                <li key={item.id}>
262
+                                    <ProductCard product={item} seed={index} />
263
+                                </li>
264
+                            ))}
265
+                        </ul>
266
+                    </section>
267
+                )}
234 268
             </Container>
235 269
         </main>
236 270
     );
237 271
 }
238 272
 
273
+/** Short reassurances under the button, from the store's real settings. */
274
+function TrustPoints({ product }: { product: StoreProduct }) {
275
+    const { shop, language, storeName } = useStorefront();
276
+    const t = storefrontText(language);
277
+    const free = shop.free_shipping_over;
278
+
279
+    return (
280
+        <ul
281
+            className="mt-6 space-y-2.5 border-t border-(--sf-border) pt-6 text-sm"
282
+            data-test="trust-points"
283
+        >
284
+            <li className="flex items-center gap-3">
285
+                <Truck
286
+                    className="size-4 shrink-0 text-(--sf-primary)"
287
+                    aria-hidden="true"
288
+                />
289
+                <span>
290
+                    {free === 0
291
+                        ? t.trustFreeShipping
292
+                        : free !== null
293
+                          ? t.trustFreeShippingOver(formatPrice(free))
294
+                          : t.trustShippingFrom(
295
+                                formatPrice(shop.shipping_from),
296
+                            )}
297
+                    <span className="text-(--sf-muted)">
298
+                        {' '}
299
+                        · {t.trustShippingText}
300
+                    </span>
301
+                </span>
302
+            </li>
303
+            <li className="flex items-center gap-3">
304
+                <ShieldCheck
305
+                    className="size-4 shrink-0 text-(--sf-primary)"
306
+                    aria-hidden="true"
307
+                />
308
+                <span>
309
+                    {t.trustPayment}
310
+                    <span className="text-(--sf-muted)">
311
+                        {' '}
312
+                        · {t.trustPaymentText}
313
+                    </span>
314
+                </span>
315
+            </li>
316
+            {shop.whatsapp && (
317
+                <li className="flex items-center gap-3">
318
+                    <MessageCircle
319
+                        className="size-4 shrink-0 text-(--sf-primary)"
320
+                        aria-hidden="true"
321
+                    />
322
+                    <a
323
+                        href={whatsappLink(
324
+                            shop.whatsapp,
325
+                            t.askAboutProduct(product.name, storeName),
326
+                        )}
327
+                        target="_blank"
328
+                        rel="noreferrer"
329
+                        className="underline underline-offset-4 hover:text-(--sf-primary)"
330
+                    >
331
+                        {t.askOnWhatsApp}
332
+                    </a>
333
+                </li>
334
+            )}
335
+        </ul>
336
+    );
337
+}
338
+
339
+/**
340
+ * Folding sections: the product's own (such as "How to use") and a shipping section the store writes
341
+ * from its real fees, so it is always right.
342
+ */
343
+function Sections({ product }: { product: StoreProduct }) {
344
+    const { shop, language } = useStorefront();
345
+    const t = storefrontText(language);
346
+    const free = shop.free_shipping_over;
347
+
348
+    const shipping = [
349
+        t.shippingWest(formatPrice(shop.shipping_west)),
350
+        t.shippingEast(formatPrice(shop.shipping_east)),
351
+        free === 0
352
+            ? t.shippingFreeAll
353
+            : free !== null
354
+              ? t.shippingFreeOver(formatPrice(free))
355
+              : null,
356
+    ]
357
+        .filter(Boolean)
358
+        .join('\n');
359
+
360
+    const sections = [
361
+        ...product.details,
362
+        { title: t.shipping, body: shipping },
363
+    ];
364
+
365
+    return (
366
+        <div
367
+            className="mt-6 divide-y divide-(--sf-border) border-y border-(--sf-border)"
368
+            data-test="product-sections"
369
+        >
370
+            {sections.map((section) => (
371
+                <details key={section.title} className="group">
372
+                    <summary className="flex cursor-pointer list-none items-center justify-between gap-4 py-4 font-medium [&::-webkit-details-marker]:hidden">
373
+                        {section.title}
374
+                        <ChevronDown
375
+                            className="size-4 shrink-0 text-(--sf-muted) transition-transform group-open:rotate-180"
376
+                            aria-hidden="true"
377
+                        />
378
+                    </summary>
379
+                    <p className="pb-4 text-sm leading-relaxed whitespace-pre-line text-(--sf-muted)">
380
+                        {section.body}
381
+                    </p>
382
+                </details>
383
+            ))}
384
+        </div>
385
+    );
386
+}
387
+
239 388
 function AddToCart({
240 389
     product,
241 390
     variant,
391
+    price,
242 392
 }: {
243 393
     product: StoreProduct;
244 394
     variant: StoreVariant | null;
395
+    price: number;
245 396
 }) {
246 397
     const { baseUrl, language, cart } = useStorefront();
247 398
     const t = storefrontText(language);
@@ -261,6 +412,54 @@ function AddToCart({
261 412
     const max = Math.max(0, Math.min(stockLeft, 99) - inCart);
262 413
     const canAdd = !needsChoice && inStock && max > 0;
263 414
 
415
+    // On phones, once the main button scrolls out of view, a bar with the price and the button
416
+    // stays at the bottom of the screen.
417
+    const buttonRef = useRef<HTMLButtonElement>(null);
418
+    const [showBar, setShowBar] = useState(false);
419
+
420
+    useEffect(() => {
421
+        let frame = 0;
422
+
423
+        // Shown once the button has gone up under the sticky header, not before the shopper reaches it.
424
+        const check = () => {
425
+            cancelAnimationFrame(frame);
426
+            frame = requestAnimationFrame(() => {
427
+                const button = buttonRef.current;
428
+
429
+                if (button) {
430
+                    setShowBar(button.getBoundingClientRect().bottom < 96);
431
+                }
432
+            });
433
+        };
434
+
435
+        check();
436
+        window.addEventListener('scroll', check, { passive: true });
437
+        window.addEventListener('resize', check);
438
+
439
+        return () => {
440
+            cancelAnimationFrame(frame);
441
+            window.removeEventListener('scroll', check);
442
+            window.removeEventListener('resize', check);
443
+        };
444
+    }, []);
445
+
446
+    // Nothing to offer for a sold-out product, so no bar then.
447
+    const barVisible = showBar && (canAdd || needsChoice);
448
+
449
+    // Lets the WhatsApp button move up so the bar never covers it.
450
+    useEffect(() => {
451
+        document.documentElement.classList.toggle('sf-sticky-cart', barVisible);
452
+
453
+        return () =>
454
+            document.documentElement.classList.remove('sf-sticky-cart');
455
+    }, [barVisible]);
456
+
457
+    const label = needsChoice
458
+        ? t.unavailable
459
+        : inStock
460
+          ? t.addToCart
461
+          : t.soldOut;
462
+
264 463
     function add() {
265 464
         setError(null);
266 465
         router.post(
@@ -312,18 +511,54 @@ function AddToCart({
312 511
             )}
313 512
 
314 513
             <button
514
+                ref={buttonRef}
315 515
                 type="button"
316 516
                 onClick={add}
317 517
                 disabled={!canAdd || busy}
318 518
                 className="inline-flex w-full items-center justify-center rounded-(--sf-radius) bg-(--sf-primary) px-6 py-3 text-sm font-semibold text-(--sf-primary-fg) transition-opacity hover:opacity-85 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-(--sf-primary) disabled:cursor-not-allowed disabled:opacity-50 sm:w-auto"
319 519
             >
320
-                {needsChoice
321
-                    ? t.unavailable
322
-                    : inStock
323
-                      ? t.addToCart
324
-                      : t.soldOut}
520
+                {label}
325 521
             </button>
326 522
 
523
+            {barVisible && (
524
+                <div
525
+                    className="sf-fade-in fixed inset-x-0 bottom-0 z-40 border-t border-(--sf-border) bg-(--sf-bg) px-4 pt-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] shadow-[0_-6px_20px_rgba(0,0,0,0.08)] md:hidden"
526
+                    data-test="sticky-cart-bar"
527
+                >
528
+                    <div className="flex items-center gap-3">
529
+                        <div className="min-w-0 flex-1">
530
+                            <p className="truncate text-sm font-medium">
531
+                                {product.name}
532
+                                {variant && (
533
+                                    <span className="text-(--sf-muted)">
534
+                                        {' '}
535
+                                        · {variant.name}
536
+                                    </span>
537
+                                )}
538
+                            </p>
539
+                            <p className="text-sm font-semibold tabular-nums">
540
+                                {formatPrice(price)}
541
+                            </p>
542
+                        </div>
543
+                        <button
544
+                            type="button"
545
+                            onClick={() =>
546
+                                canAdd
547
+                                    ? add()
548
+                                    : buttonRef.current?.scrollIntoView({
549
+                                          behavior: 'smooth',
550
+                                          block: 'center',
551
+                                      })
552
+                            }
553
+                            disabled={busy || (!canAdd && !needsChoice)}
554
+                            className="shrink-0 rounded-(--sf-radius) bg-(--sf-primary) px-5 py-2.5 text-sm font-semibold text-(--sf-primary-fg) disabled:opacity-50"
555
+                        >
556
+                            {needsChoice ? t.chooseShort : label}
557
+                        </button>
558
+                    </div>
559
+                </div>
560
+            )}
561
+
327 562
             <div aria-live="polite" className="mt-3 min-h-6 text-sm">
328 563
                 {error && <p className="text-red-700">{error}</p>}
329 564
                 {added && !error && (

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

@@ -83,7 +83,9 @@ function PageBody({ plan, view }: { plan: StorePlan; view: StorefrontView }) {
83 83
     }
84 84
 
85 85
     if (view.type === 'product') {
86
-        return <ProductPage product={view.product} />;
86
+        return (
87
+            <ProductPage product={view.product} related={view.related ?? []} />
88
+        );
87 89
     }
88 90
 
89 91
     const page =

+ 80
- 9
resources/js/storefront/sections/header.tsx Zobrazit soubor

@@ -1,4 +1,5 @@
1
-import { ShoppingBag } from 'lucide-react';
1
+import { Menu, ShoppingBag, X } from 'lucide-react';
2
+import { useEffect, useState } from 'react';
2 3
 import { cn } from '@/lib/utils';
3 4
 import { useStorefront } from '../context';
4 5
 import { storefrontText } from '../text';
@@ -14,6 +15,24 @@ export function Header({
14 15
     const centered = section.variant === 'centered';
15 16
     const { cart, language } = useStorefront();
16 17
     const t = storefrontText(language);
18
+    const [open, setOpen] = useState(false);
19
+
20
+    // Escape closes the phone menu.
21
+    useEffect(() => {
22
+        if (!open) {
23
+            return;
24
+        }
25
+
26
+        const close = (event: KeyboardEvent) => {
27
+            if (event.key === 'Escape') {
28
+                setOpen(false);
29
+            }
30
+        };
31
+
32
+        window.addEventListener('keydown', close);
33
+
34
+        return () => window.removeEventListener('keydown', close);
35
+    }, [open]);
17 36
 
18 37
     const cartLink = (
19 38
         <SfLink
@@ -33,14 +52,40 @@ export function Header({
33 52
         </SfLink>
34 53
     );
35 54
 
55
+    // Only on phones: opens the list of links.
56
+    const menuButton =
57
+        links.length > 0 || cta ? (
58
+            <button
59
+                type="button"
60
+                onClick={() => setOpen((value) => !value)}
61
+                aria-expanded={open}
62
+                aria-controls="sf-phone-menu"
63
+                aria-label={open ? t.closeMenu : t.openMenu}
64
+                className="inline-flex size-10 items-center justify-center rounded-(--sf-radius) text-(--sf-fg) transition-colors hover:bg-(--sf-surface) md:hidden"
65
+                data-test="phone-menu-button"
66
+            >
67
+                {open ? (
68
+                    <X className="size-5" aria-hidden="true" />
69
+                ) : (
70
+                    <Menu className="size-5" aria-hidden="true" />
71
+                )}
72
+            </button>
73
+        ) : (
74
+            <span className="size-10 md:hidden" aria-hidden="true" />
75
+        );
76
+
36 77
     return (
37 78
         <header className="sticky top-0 z-20 border-b border-(--sf-border) bg-(--sf-bg)/90 backdrop-blur">
38 79
             <Container
39 80
                 className={cn(
40 81
                     'relative flex items-center gap-6 py-4',
41
-                    centered ? 'flex-col sm:gap-3' : 'justify-between',
82
+                    centered
83
+                        ? 'justify-between md:flex-col md:justify-center md:gap-3'
84
+                        : 'justify-between',
42 85
                 )}
43 86
             >
87
+                {centered && <div className="md:hidden">{menuButton}</div>}
88
+
44 89
                 <SfLink href="#" className="sf-heading text-xl font-semibold">
45 90
                     {logoText}
46 91
                 </SfLink>
@@ -48,10 +93,8 @@ export function Header({
48 93
                 <nav
49 94
                     aria-label="Main"
50 95
                     className={cn(
51
-                        'items-center gap-7 text-sm',
52
-                        centered
53
-                            ? 'flex flex-wrap justify-center'
54
-                            : 'hidden md:flex',
96
+                        'hidden items-center gap-7 text-sm md:flex',
97
+                        centered && 'flex-wrap justify-center',
55 98
                     )}
56 99
                 >
57 100
                     {links.map((link) => (
@@ -66,23 +109,51 @@ export function Header({
66 109
                 </nav>
67 110
 
68 111
                 {centered ? (
69
-                    <div className="absolute top-3 right-5 sm:right-8">
112
+                    <div className="md:absolute md:top-3 md:right-8">
70 113
                         {cartLink}
71 114
                     </div>
72 115
                 ) : (
73
-                    <div className="flex items-center gap-2">
116
+                    <div className="flex items-center gap-1 sm:gap-2">
74 117
                         {cartLink}
75 118
                         {cta && (
76 119
                             <SfButton
77 120
                                 href={cta.href}
78
-                                className="hidden px-4 py-2 sm:inline-flex"
121
+                                className="hidden px-4 py-2 md:inline-flex"
79 122
                             >
80 123
                                 {cta.label}
81 124
                             </SfButton>
82 125
                         )}
126
+                        {menuButton}
83 127
                     </div>
84 128
                 )}
85 129
             </Container>
130
+
131
+            {open && (
132
+                <nav
133
+                    id="sf-phone-menu"
134
+                    aria-label="Main"
135
+                    className="sf-fade-in border-t border-(--sf-border) bg-(--sf-bg) md:hidden"
136
+                    data-test="phone-menu"
137
+                >
138
+                    <Container className="flex flex-col py-2">
139
+                        {links.map((link) => (
140
+                            <SfLink
141
+                                key={link.label + link.href}
142
+                                href={link.href}
143
+                                onClick={() => setOpen(false)}
144
+                                className="border-b border-(--sf-border) py-3.5 text-base last:border-b-0"
145
+                            >
146
+                                {link.label}
147
+                            </SfLink>
148
+                        ))}
149
+                        {cta && (
150
+                            <SfButton href={cta.href} className="my-3 w-full">
151
+                                {cta.label}
152
+                            </SfButton>
153
+                        )}
154
+                    </Container>
155
+                </nav>
156
+            )}
86 157
         </header>
87 158
     );
88 159
 }

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

@@ -22,6 +22,18 @@ const words = {
22 22
         trustPaymentText: 'Pay safely through Stripe',
23 23
         trustWhatsApp: 'Questions? Ask us',
24 24
         trustWhatsAppText: 'Quick replies on WhatsApp',
25
+        pairsWellWith: 'Pairs well with',
26
+        openMenu: 'Open menu',
27
+        closeMenu: 'Close menu',
28
+        chooseShort: 'Choose an option',
29
+        askOnWhatsApp: 'Ask about this product on WhatsApp',
30
+        askAboutProduct: (product: string, store: string) =>
31
+            `Hi ${store}, I have a question about ${product}.`,
32
+        shippingWest: (fee: string) => `Peninsular Malaysia: ${fee}`,
33
+        shippingEast: (fee: string) => `Sabah, Sarawak and Labuan: ${fee}`,
34
+        shippingFreeOver: (amount: string) =>
35
+            `Free shipping on orders over ${amount}.`,
36
+        shippingFreeAll: 'Free shipping on every order.',
25 37
         previousMessage: 'Previous message',
26 38
         nextMessage: 'Next message',
27 39
         inStock: 'In stock',
@@ -113,6 +125,18 @@ const words = {
113 125
         trustPaymentText: 'Bayar dengan selamat melalui Stripe',
114 126
         trustWhatsApp: 'Ada soalan? Tanya kami',
115 127
         trustWhatsAppText: 'Balasan pantas di WhatsApp',
128
+        pairsWellWith: 'Sesuai digandingkan dengan',
129
+        openMenu: 'Buka menu',
130
+        closeMenu: 'Tutup menu',
131
+        chooseShort: 'Pilih pilihan',
132
+        askOnWhatsApp: 'Tanya tentang produk ini di WhatsApp',
133
+        askAboutProduct: (product: string, store: string) =>
134
+            `Hai ${store}, saya ada soalan tentang ${product}.`,
135
+        shippingWest: (fee: string) => `Semenanjung Malaysia: ${fee}`,
136
+        shippingEast: (fee: string) => `Sabah, Sarawak dan Labuan: ${fee}`,
137
+        shippingFreeOver: (amount: string) =>
138
+            `Penghantaran percuma untuk pesanan melebihi ${amount}.`,
139
+        shippingFreeAll: 'Penghantaran percuma untuk semua pesanan.',
116 140
         previousMessage: 'Mesej sebelum',
117 141
         nextMessage: 'Mesej seterusnya',
118 142
         inStock: 'Ada stok',

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

@@ -201,6 +201,8 @@ export type StoreProduct = {
201 201
     name: string;
202 202
     slug: string;
203 203
     description: string | null;
204
+    /** Folding sections, such as "How to use". */
205
+    details: { title: string; body: string }[];
204 206
     price: number;
205 207
     compare_at_price: number | null;
206 208
     in_stock: boolean;
@@ -316,6 +318,9 @@ export type ShopInfo = {
316 318
     announcements: string[];
317 319
     /** The cheapest shipping fee, in ringgit. */
318 320
     shipping_from: number;
321
+    /** Peninsular Malaysia, and Sabah, Sarawak and Labuan, in ringgit. */
322
+    shipping_west: number;
323
+    shipping_east: number;
319 324
     /** Automatic discounts running now. "product_ids" null means every product. */
320 325
     offers: { name: string; text: string; product_ids: number[] | null }[];
321 326
 };
@@ -332,4 +337,4 @@ export type StorefrontView =
332 337
           shippingByState: Record<string, number>;
333 338
       }
334 339
     | { type: 'order'; order: StoreOrder }
335
-    | { type: 'product'; product: StoreProduct };
340
+    | { type: 'product'; product: StoreProduct; related?: StoreProduct[] };

+ 3
- 1
resources/js/storefront/ui.tsx Zobrazit soubor

@@ -50,14 +50,16 @@ export function SfButton({
50 50
 export function SfLink({
51 51
     href,
52 52
     className,
53
+    onClick,
53 54
     children,
54 55
 }: {
55 56
     href: string;
56 57
     className?: string;
58
+    onClick?: () => void;
57 59
     children: ReactNode;
58 60
 }) {
59 61
     return (
60
-        <a href={useHref(href)} className={className}>
62
+        <a href={useHref(href)} className={className} onClick={onClick}>
61 63
             {children}
62 64
         </a>
63 65
     );

+ 1
- 1
resources/js/storefront/whatsapp.tsx Zobrazit soubor

@@ -23,7 +23,7 @@ export function WhatsAppButton() {
23 23
             href={whatsappLink(shop.whatsapp, t.whatsAppHello(storeName))}
24 24
             target="_blank"
25 25
             rel="noreferrer"
26
-            className="fixed right-4 bottom-4 z-30 inline-flex items-center gap-2 rounded-full bg-[#25D366] px-4 py-3 text-sm font-semibold text-[#073B1C] shadow-lg transition-transform hover:scale-105 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#25D366] sm:right-6 sm:bottom-6"
26
+            className="sf-whatsapp fixed right-4 bottom-4 z-30 inline-flex items-center gap-2 rounded-full bg-[#25D366] px-4 py-3 text-sm font-semibold text-[#073B1C] shadow-lg transition-transform hover:scale-105 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[#25D366] sm:right-6 sm:bottom-6"
27 27
             data-test="whatsapp-button"
28 28
         >
29 29
             <MessageCircle className="size-5" aria-hidden="true" />

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

@@ -63,6 +63,8 @@ export type Product = {
63 63
     name: string;
64 64
     slug: string;
65 65
     description: string | null;
66
+    /** Folding sections on the product page, such as "How to use". */
67
+    details: { title: string; body: string }[];
66 68
     price: string;
67 69
     compare_at_price: string | null;
68 70
     stock: number;

+ 152
- 0
tests/Feature/Stores/ProductPageTest.php Zobrazit soubor

@@ -0,0 +1,152 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Models\Product;
6
+use App\Models\Store;
7
+use App\Models\User;
8
+use App\StorePlan\SamplePlan;
9
+use Illuminate\Foundation\Testing\RefreshDatabase;
10
+use Inertia\Testing\AssertableInertia as Assert;
11
+use Tests\Support\ScriptedDriver;
12
+use Tests\TestCase;
13
+
14
+class ProductPageTest extends TestCase
15
+{
16
+    use RefreshDatabase;
17
+
18
+    private User $user;
19
+
20
+    private Store $store;
21
+
22
+    protected function setUp(): void
23
+    {
24
+        parent::setUp();
25
+
26
+        $this->user = User::factory()->create();
27
+        $this->store = Store::factory()->for($this->user)->create(['shipping_west' => 800, 'shipping_east' => 1500]);
28
+        $this->store->plan = SamplePlan::for($this->store);
29
+        $this->store->save();
30
+        $this->actingAs($this->user);
31
+    }
32
+
33
+    private function product(string $name, array $attributes = []): Product
34
+    {
35
+        return $this->store->products()->create(['name' => $name, 'price' => 1000, 'stock' => 5, 'status' => 'active', ...$attributes]);
36
+    }
37
+
38
+    private function page(Product $product, callable $assert): void
39
+    {
40
+        $this->get(route('stores.preview.product', [$this->store->slug, $product->slug]))
41
+            ->assertInertia(fn (Assert $page) => $assert($page));
42
+    }
43
+
44
+    public function test_the_product_form_saves_folding_sections()
45
+    {
46
+        $this->post(route('stores.products.store', $this->store->slug), [
47
+            'name' => 'Sunscreen', 'status' => 'active', 'price' => '49', 'stock' => 10,
48
+            'details' => [
49
+                ['title' => ' How to use ', 'body' => 'Apply as the last step of your morning routine.'],
50
+                ['title' => '', 'body' => ''],
51
+                ['title' => 'Care', 'body' => 'Keep out of direct sun.'],
52
+            ],
53
+        ])->assertSessionHasNoErrors();
54
+
55
+        $product = $this->store->products()->firstOrFail();
56
+        $this->assertSame([
57
+            ['title' => 'How to use', 'body' => 'Apply as the last step of your morning routine.'],
58
+            ['title' => 'Care', 'body' => 'Keep out of direct sun.'],
59
+        ], $product->details);
60
+
61
+        $this->get(route('stores.products.edit', [$this->store->slug, $product->id]))
62
+            ->assertInertia(fn (Assert $page) => $page->where('product.details.1.title', 'Care'));
63
+
64
+        $this->page($product, fn (Assert $page) => $page
65
+            ->where('view.product.details.0.title', 'How to use')
66
+            ->where('shop.shipping_west', 8)
67
+            ->where('shop.shipping_east', 15));
68
+
69
+        // A title needs text and the other way round; at most 5.
70
+        $url = route('stores.products.update', [$this->store->slug, $product->id]);
71
+        $base = ['name' => 'Sunscreen', 'status' => 'active', 'price' => '49', 'stock' => 10];
72
+        $this->post($url, [...$base, 'details' => [['title' => 'How to use', 'body' => '']]])->assertSessionHasErrors('details.0.body');
73
+        $this->post($url, [...$base, 'details' => array_fill(0, 6, ['title' => 'A', 'body' => 'B'])])->assertSessionHasErrors('details');
74
+
75
+        // Saving with no sections removes them.
76
+        $this->post($url, $base)->assertSessionHasNoErrors();
77
+        $this->assertNull($product->fresh()->details);
78
+    }
79
+
80
+    public function test_pairs_well_with_puts_bundle_partners_first()
81
+    {
82
+        $cleanser = $this->product('Cleanser');
83
+        $moisturiser = $this->product('Moisturiser');
84
+        $this->product('Lip balm', ['stock' => 0]);
85
+        $draft = $this->product('Hidden', ['status' => 'draft']);
86
+        $toner = $this->product('Toner');
87
+
88
+        $this->post(route('stores.products.store', $this->store->slug), [
89
+            'name' => 'Duo', 'status' => 'active', 'price' => '70', 'is_bundle' => '1',
90
+            'bundle_items' => [['item' => (string) $cleanser->id, 'quantity' => 1], ['item' => (string) $moisturiser->id, 'quantity' => 1]],
91
+        ])->assertSessionHasNoErrors();
92
+        $duo = $this->store->products()->where('name', 'Duo')->firstOrFail();
93
+
94
+        // The moisturiser shares a bundle with the cleanser, then the bundle itself, then others in stock.
95
+        $this->page($cleanser, fn (Assert $page) => $page
96
+            ->where('view.related.0.id', $moisturiser->id)
97
+            ->where('view.related.1.id', $duo->id)
98
+            ->where('view.related.2.id', $toner->id)
99
+            ->has('view.related', 3));
100
+
101
+        $this->assertNotContains($draft->id, [$moisturiser->id, $duo->id, $toner->id]);
102
+    }
103
+
104
+    public function test_the_ai_merges_sections_by_title()
105
+    {
106
+        $product = $this->product('Sunscreen', ['details' => [
107
+            ['title' => 'How to use', 'body' => 'Old text.'],
108
+            ['title' => 'Care', 'body' => 'Keep cool.'],
109
+        ]]);
110
+
111
+        ScriptedDriver::use([(string) json_encode(['reply' => 'Confirm below.', 'actions' => [[
112
+            'type' => 'update_product', 'product' => $product->slug,
113
+            'details' => [
114
+                ['title' => 'how to use', 'body' => 'Apply generously 15 minutes before going out.'],
115
+                ['title' => 'Good to know', 'body' => 'Reapply after swimming.'],
116
+            ],
117
+            'remove_details' => ['Care'],
118
+        ]]])]);
119
+
120
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Rewrite how to use, add good to know, drop care']);
121
+        $edit = $this->store->generations()->firstOrFail();
122
+
123
+        $this->assertSame(
124
+            'Change "Sunscreen": sections "how to use": "Apply generously 15 minutes before going out."; "Good to know": "Reapply after swimming.", remove the section "Care"',
125
+            $edit->actions[0]['summary'],
126
+        );
127
+        $this->assertStringContainsString($product->slug.': Sunscreen, active, no description, sections: How to use, Care', ScriptedDriver::$requests[0]->prompt);
128
+
129
+        $this->post(route('stores.edits.confirm', [$this->store->slug, $edit->id]))->assertSessionHasNoErrors();
130
+
131
+        $this->assertSame([
132
+            ['title' => 'how to use', 'body' => 'Apply generously 15 minutes before going out.'],
133
+            ['title' => 'Good to know', 'body' => 'Reapply after swimming.'],
134
+        ], $product->fresh()->details);
135
+    }
136
+
137
+    public function test_a_new_product_from_chat_can_have_sections()
138
+    {
139
+        ScriptedDriver::use([(string) json_encode(['reply' => 'Confirm below.', 'actions' => [[
140
+            'type' => 'create_product', 'name' => 'Lip Balm', 'price' => 15, 'stock' => 10,
141
+            'details' => [['title' => 'How to use', 'body' => 'Apply whenever lips feel dry.']],
142
+        ]]])]);
143
+
144
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Add a lip balm']);
145
+        $edit = $this->store->generations()->firstOrFail();
146
+
147
+        $this->assertStringEndsWith('. Sections "How to use": "Apply whenever lips feel dry."', $edit->actions[0]['summary']);
148
+
149
+        $this->post(route('stores.edits.confirm', [$this->store->slug, $edit->id]));
150
+        $this->assertSame('How to use', $this->store->products()->firstOrFail()->details[0]['title']);
151
+    }
152
+}

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