Przeglądaj źródła

Add publishing: live stores on their own address

Step 5:
- Publish, publish changes and take offline, with a panel on the store
  page showing the live address.
- Live stores open at <store name>.<domain> with no login. Shoppers see
  a saved copy of the design (published_plan); products stay live.
- One Storefront class decides live or preview, so the same controllers
  and pages serve both.
- On a store's address only store pages exist; the dashboard and login
  give "not found".
- More reserved store names; STOREFRONT_DOMAIN setting.
feature/publishing
fahmisaad 5 dni temu
rodzic
commit
ce64cdb320

+ 3
- 1
.env Wyświetl plik

@@ -71,7 +71,6 @@ AWS_USE_PATH_STYLE_ENDPOINT=false
71 71
 
72 72
 VITE_APP_NAME="${APP_NAME}"
73 73
 
74
-
75 74
 STRIPE_KEY=
76 75
 STRIPE_SECRET=
77 76
 
@@ -90,3 +89,6 @@ DEEPSEEK_API_KEY=
90 89
 DB_QUEUE_RETRY_AFTER=600
91 90
 # Optional. Lets Stripe tell the app about payments directly. Starts with whsec_.
92 91
 STRIPE_WEBHOOK_SECRET=
92
+
93
+# Published stores open at <store name>.<this domain>. Leave blank on a development machine to use localhost.
94
+STOREFRONT_DOMAIN=

+ 75
- 39
PROGRESS.md Wyświetl plik

@@ -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-14
7
-**Current step:** Step 5 — Publishing (Step 4 Commerce is done and tested with a real Stripe test payment)
8
-**Next action:** Start Step 5 on a new branch: publish a store so real shoppers can open it (local: `storename.localhost`)
7
+**Current step:** Step 6 — Our own subscription billing (Step 5 Publishing is done for local use; custom domains wait for hosting)
8
+**Next action:** Start Step 6: plans table, subscribe, upgrade and cancel through Stripe, 14-day trial, enforce plan limits
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -100,6 +100,16 @@ Changing from Claude to another AI model (or back) must be a settings change, no
100 100
 - Until Step 6 (billing), every user is on the free trial. The plan name is stored in the `plan` column of the `users` table.
101 101
 - The AI is told not to invent facts (awards, halal or other certificates, contact details) that the merchant did not give.
102 102
 
103
+### How publishing works (added in Step 5)
104
+
105
+- A published store opens at `<store name>.<domain>`. The domain is `localhost` on a development machine and is set with `STOREFRONT_DOMAIN` once the app is hosted. The port and http/https come from the address the app itself is opened at.
106
+- The `stores` table has `published_plan` (the copy shoppers see) and `published_at`. `plan` stays the working design. Publishing copies `plan` into `published_plan` after checking it once more.
107
+- Products, prices and stock are always live. Only the design waits for "Publish changes".
108
+- The same controllers and screens serve the live store and the owner's preview. `App\Storefront\Storefront` is the only place that knows the difference: which store, which design, and what the links are built on.
109
+- On a store's address only store pages exist. Everything else, including the dashboard and login, gives "not found".
110
+- Taking a store offline keeps the design, products and orders.
111
+- Some store names cannot be used as addresses (`www`, `admin`, `login` and so on). Such a store gets a number added, for example `login-2`.
112
+
103 113
 ### Plan prices and limits (starting numbers, adjust after real usage)
104 114
 
105 115
 | Plan                 | Price / month | Stores | Full regenerations / month | AI edits / month |
@@ -162,13 +172,18 @@ Changing from Claude to another AI model (or back) must be a settings change, no
162 172
 - [x] Checkout with Stripe Malaysia (test mode): shopper details and address, then Stripe's hosted payment page. Tested with a real Stripe test payment on 2026-11-15
163 173
 - [x] Orders list and order page for the merchant ("Orders" tab)
164 174
 - [x] Order confirmation email, in the store's language, sent once when the order is paid
165
-- [ ] Known gaps, to do later: shipping fee is RM 0 until EasyParcel (Step 7); the merchant cannot mark an order as shipped yet; unpaid orders stay in the list as "Awaiting payment"; the Stripe webhook needs a public address, so it only starts working after hosting (Step 8)
175
+- [ ] Known gaps, to do later: shipping fee is RM 0 until EasyParcel (Step 7); the merchant cannot mark an order as shipped yet; unpaid orders stay in the list as "Awaiting payment"; the Stripe webhook needs a public address, so it only starts working after hosting (Step 9)
166 176
 - [x] Content pages by chat ("add an About page", "remove the About page"): the AI creates the page, and the app itself makes sure the menu links to it. Tested with real DeepSeek on 2026-11-15
167 177
 
168 178
 ### Step 5 — Publishing
169 179
 
170
-- [ ] Publish a store to a subdomain (local: `storename.localhost`)
171
-- [ ] Custom domains (after hosting is chosen)
180
+- [x] Publish a store to its own address (local: `storename.localhost:8000`). Shoppers need no login
181
+- [x] "Publish store", "Publish changes" and "Take offline" buttons on the store page, with the live address shown
182
+- [x] Shoppers see a saved copy of the design, so design changes stay private until the merchant publishes again
183
+- [x] The whole shop works on the live address: home, extra pages, shop, product, cart, checkout, thank-you page
184
+- [x] The dashboard and login pages cannot be opened on a store's address
185
+- [ ] Custom domains (after hosting is chosen, Step 9)
186
+- [ ] Known gaps, to do before launch: pages are drawn in the shopper's browser, so search engines may read them poorly (fix: server-side rendering); no page description or sharing image for search and social media yet; the browser tab shows our app name for a moment while a page loads
172 187
 
173 188
 ### Step 6 — Our own subscription billing
174 189
 
@@ -184,7 +199,23 @@ Changing from Claude to another AI model (or back) must be a settings change, no
184 199
 - [ ] Bahasa Malaysia and English store generation
185 200
 - [ ] WhatsApp order notifications and chat button
186 201
 
187
-### Step 8 — Before launch
202
+### Step 8 — Discounts and product options
203
+
204
+Agreed on 2026-11-15. Build in this order. It comes after Step 7 because automatic discounts such as free shipping need shipping to exist.
205
+
206
+- [ ] Discount codes: a "Discounts" tab for the merchant (code, percent or fixed amount off, optional minimum spend, start and end date, usage limit); a "Discount code" box in the cart; the order records the code and the amount taken off; the final amount is sent to Stripe
207
+- [ ] Product variants: size, colour, flavour and so on, each with its own price and stock
208
+- [ ] Bundles with linked stock: a product made of other products, with one bundle price. The product page shows what is included and the saving. Selling a bundle lowers the stock of each item in it, and a bundle is sold out when any item is sold out
209
+- [ ] Chat commands for products, discounts and bundles ("create a bundle of the cleanser and moisturiser for RM 85", "make a 10% code RAYA10"). The AI turns the sentence into an action, the app shows a confirmation, and nothing changes until the merchant confirms
210
+- [ ] Later: automatic discounts ("buy 2, get 10% off", "free shipping over RM 100")
211
+
212
+Notes:
213
+
214
+- A sale price on one product already works today (the "price before discount" field).
215
+- Every feature gets a normal form first. Chat commands are a shortcut on top of the forms.
216
+- The confirm step is required for chat commands because these actions involve money.
217
+
218
+### Step 9 — Before launch
188 219
 
189 220
 - [ ] Choose hosting and deploy
190 221
 - [ ] Privacy policy and terms of service (name the AI providers)
@@ -233,43 +264,46 @@ Then, from the project folder:
233 264
 
234 265
 ## 4b. Where things are in the code
235 266
 
236
-| Thing                                 | Location                                                                        |
237
-| ------------------------------------- | ------------------------------------------------------------------------------- |
238
-| Store model                           | `app/Models/Store.php`                                                          |
239
-| Store screens logic                   | `app/Http/Controllers/StoreController.php`                                      |
240
-| Store categories, languages, statuses | `app/Enums/`                                                                    |
241
-| Store form rules                      | `app/Http/Requests/Stores/CreateStoreRequest.php`                               |
242
-| Screens                               | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                |
243
-| Store tests                           | `tests/Feature/Stores/`                                                         |
244
-| Store plan format (the rules)         | `app/StorePlan/PlanSchema.php`                                                  |
245
-| Store plan checker                    | `app/StorePlan/PlanValidator.php`                                               |
246
-| Sample plan                           | `app/StorePlan/SamplePlan.php`                                                  |
247
-| Preview logic                         | `app/Http/Controllers/StoreDesignController.php`                                |
248
-| AI settings                           | `config/ai.php` (providers, models per task)                                    |
249
-| AI layer and providers                | `app/Ai/`, `app/Ai/Drivers/`                                                    |
250
-| AI prompts, generation and chat edits | `app/StorePlan/Ai/`                                                             |
251
-| Start an AI job (buttons)             | `app/Http/Controllers/StoreGenerationController.php`                            |
252
-| Background AI job                     | `app/Jobs/RunStoreGeneration.php`                                               |
253
-| Plan limits and usage counting        | `config/plans.php`, `app/Billing/UsageLimits.php`                               |
254
-| Progress screen and chat box          | `resources/js/components/stores/`                                               |
255
-| Product model and photos              | `app/Models/Product.php`, `app/Models/ProductImage.php`                         |
256
-| Product screens logic                 | `app/Http/Controllers/ProductController.php`                                    |
257
-| Product screens                       | `resources/js/pages/stores/products/`                                           |
258
-| Storefront Shop and product pages     | `resources/js/storefront/pages/`                                                |
259
-| Checkout and order logic              | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`      |
260
-| Payment providers                     | `app/Commerce/Payments/` (interface and Stripe)                                 |
261
-| Stripe webhook                        | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`) |
262
-| Orders for the merchant               | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |
263
-| Order email                           | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                |
264
-| Cart logic                            | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`              |
265
-| Storefront words (English, Malay)     | `resources/js/storefront/text.ts`                                               |
266
-| Store plan format (frontend types)    | `resources/js/storefront/types.ts`                                              |
267
-| Storefront renderer and sections      | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`     |
267
+| Thing                                  | Location                                                                        |
268
+| -------------------------------------- | ------------------------------------------------------------------------------- |
269
+| Store model                            | `app/Models/Store.php`                                                          |
270
+| Store screens logic                    | `app/Http/Controllers/StoreController.php`                                      |
271
+| Store categories, languages, statuses  | `app/Enums/`                                                                    |
272
+| Store form rules                       | `app/Http/Requests/Stores/CreateStoreRequest.php`                               |
273
+| Screens                                | `resources/js/pages/dashboard.tsx`, `resources/js/pages/stores/`                |
274
+| Store tests                            | `tests/Feature/Stores/`                                                         |
275
+| Store plan format (the rules)          | `app/StorePlan/PlanSchema.php`                                                  |
276
+| Store plan checker                     | `app/StorePlan/PlanValidator.php`                                               |
277
+| Sample plan                            | `app/StorePlan/SamplePlan.php`                                                  |
278
+| Preview logic                          | `app/Http/Controllers/StoreDesignController.php`                                |
279
+| AI settings                            | `config/ai.php` (providers, models per task)                                    |
280
+| AI layer and providers                 | `app/Ai/`, `app/Ai/Drivers/`                                                    |
281
+| AI prompts, generation and chat edits  | `app/StorePlan/Ai/`                                                             |
282
+| Start an AI job (buttons)              | `app/Http/Controllers/StoreGenerationController.php`                            |
283
+| Background AI job                      | `app/Jobs/RunStoreGeneration.php`                                               |
284
+| Plan limits and usage counting         | `config/plans.php`, `app/Billing/UsageLimits.php`                               |
285
+| Progress screen and chat box           | `resources/js/components/stores/`                                               |
286
+| Product model and photos               | `app/Models/Product.php`, `app/Models/ProductImage.php`                         |
287
+| Product screens logic                  | `app/Http/Controllers/ProductController.php`                                    |
288
+| Product screens                        | `resources/js/pages/stores/products/`                                           |
289
+| Storefront Shop and product pages      | `resources/js/storefront/pages/`                                                |
290
+| Checkout and order logic               | `app/Commerce/Checkout.php`, `app/Http/Controllers/CheckoutController.php`      |
291
+| Payment providers                      | `app/Commerce/Payments/` (interface and Stripe)                                 |
292
+| Stripe webhook                         | `app/Http/Controllers/StripeWebhookController.php` (address: `/stripe/webhook`) |
293
+| Orders for the merchant                | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |
294
+| Order email                            | `app/Mail/OrderConfirmation.php`, `resources/views/mail/orders/`                |
295
+| Live store or preview (the difference) | `app/Storefront/Storefront.php`                                                 |
296
+| Live store addresses                   | top of `routes/web.php`, `config/storefront.php`                                |
297
+| Publish and take offline               | `app/Http/Controllers/StorePublishController.php`                               |
298
+| Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`              |
299
+| Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                               |
300
+| Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                              |
301
+| Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`     |
268 302
 
269 303
 ## 5. Open questions
270 304
 
271 305
 - **Who receives the money?** Today every payment goes to our own Stripe account (the keys in `.env.local`). Before real merchants sell, each merchant must be paid into their own account. The usual way is Stripe Connect. Decide before launch; it changes the checkout a little and adds an onboarding step for merchants.
272
-- Hosting provider (decide at Step 8)
306
+- Hosting provider (decide at Step 9)
273 307
 
274 308
 ## 6. Later improvements
275 309
 
@@ -299,3 +333,5 @@ Add one line per work session: date, what was done, what is next.
299 333
 | 2026-11-15 | Step 4 finished on branch `feature/commerce`: checkout with Stripe (test mode), orders for the merchant, order confirmation email. 133 tests pass. A real Stripe test payment worked end to end: order paid, stock lowered, email written to the log.                                                   | Merge into `main`, then Step 5: publishing                      |
300 334
 | 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                            | Step 5: publishing                                              |
301 335
 | 2026-11-15 | Content pages by chat on branch `feature/content-pages`: add, rename and remove pages, each page at its own address, menu links guaranteed by the app. 139 tests pass; tested with real DeepSeek and in the browser. Step 4 is now complete except the known gaps.                                      | Step 5: publishing                                              |
336
+| 2026-11-15 | Planning only. Added Step 8 (discount codes, product variants, bundles with linked stock, chat commands with a confirm step), placed after Malaysia features. "Before launch" is now Step 9. Cart items redesigned as cards.                                                                            | Step 5: publishing                                              |
337
+| 2026-11-15 | Step 5 on branch `feature/publishing`: publish and take offline, live stores on their own address, design changes private until published again, dashboard blocked on store addresses. 150 tests pass; Luna Skin published and checked in the browser at `luna-skin.localhost:8000`.                    | Step 6: subscription billing                                    |

+ 23
- 11
README.md Wyświetl plik

@@ -10,17 +10,18 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
10 10
 
11 11
 ## Current status
12 12
 
13
-| Step | What                                                    | Status      |
14
-| ---- | ------------------------------------------------------- | ----------- |
15
-| 0    | Prepare the local machine                               | Done        |
16
-| 1    | Project foundation: login, create a store, dashboard    | Done        |
17
-| 2    | Store sections, renderer and preview                    | Done        |
18
-| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done        |
19
-| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done        |
20
-| 5    | Publishing: subdomains, then custom domains             | Next        |
21
-| 6    | Our own subscription billing                            | Not started |
22
-| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Not started |
23
-| 8    | Before launch: hosting, legal pages, backups            | Not started |
13
+| Step | What                                                    | Status                                              |
14
+| ---- | ------------------------------------------------------- | --------------------------------------------------- |
15
+| 0    | Prepare the local machine                               | Done                                                |
16
+| 1    | Project foundation: login, create a store, dashboard    | Done                                                |
17
+| 2    | Store sections, renderer and preview                    | Done                                                |
18
+| 3    | AI generation (Claude Sonnet 5.5, DeepSeek for edits)   | Done                                                |
19
+| 4    | Commerce: products, cart, checkout with Stripe Malaysia | Done                                                |
20
+| 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting |
21
+| 6    | Our own subscription billing                            | Next                                                |
22
+| 7    | Malaysia features: FPX, DuitNow, EasyParcel, WhatsApp   | Not started                                         |
23
+| 8    | Discounts and product options: codes, variants, bundles | Not started                                         |
24
+| 9    | Before launch: hosting, legal pages, backups            | Not started                                         |
24 25
 
25 26
 ## What works today
26 27
 
@@ -42,6 +43,8 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
42 43
 - Cart: add products, change quantities, remove items, see the subtotal. No account needed
43 44
 - Checkout with Stripe (test mode): shopper details, Stripe's hosted payment page, thank-you page
44 45
 - Orders tab for the merchant, and an order confirmation email to the shopper
46
+- Publishing: a store goes live at its own address (`storename.localhost:8000` on a local machine), with no login for shoppers
47
+- Design changes stay private until the merchant clicks "Publish changes"
45 48
 
46 49
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.
47 50
 
@@ -190,6 +193,14 @@ Changing from Claude to another AI model is a settings change, not a code rewrit
190 193
 - AI work runs in the background, so the worker must be running. `composer run dev` starts it.
191 194
 - Settings are in `config/ai.php`. Plan limits are in `config/plans.php`.
192 195
 
196
+## Published stores
197
+
198
+- A published store opens at `<store name>.<domain>`, for example http://luna-skin.localhost:8000.
199
+- On a local machine this works without any setup, because browsers send every `*.localhost` address to your own computer.
200
+- Once hosted, set `STOREFRONT_DOMAIN` in the settings file (for example `mystores.my`), and point `*.mystores.my` at the server.
201
+- Shoppers see a saved copy of the design. The merchant's later changes go live only after "Publish changes". Products, prices and stock are always live.
202
+- The owner's private preview stays at `/stores/<store name>/preview`.
203
+
193 204
 ## Payments
194 205
 
195 206
 - Checkout uses Stripe's hosted payment page, so card details never touch this app.
@@ -252,4 +263,5 @@ Starting numbers, to adjust after real usage.
252 263
 
253 264
 Private. All rights reserved.
254 265
 | Cart, checkout and payments | `app/Commerce/` |
266
+| Live store or preview | `app/Storefront/Storefront.php`, top of `routes/web.php` |
255 267
 | Orders for the merchant | `app/Http/Controllers/OrderController.php`, `resources/js/pages/stores/orders/` |

+ 11
- 11
app/Http/Controllers/CartController.php Wyświetl plik

@@ -12,23 +12,23 @@ use Illuminate\Validation\ValidationException;
12 12
 use Inertia\Response;
13 13
 
14 14
 /**
15
- * The shopper's cart for one store.
15
+ * The shopper's cart for one store. Used for both the live store and the owner's preview.
16 16
  */
17 17
 class CartController extends Controller
18 18
 {
19 19
     use RendersStorefront;
20 20
 
21
-    public function show(Request $request, string $slug): Response
21
+    public function show(Request $request): Response
22 22
     {
23
-        return $this->renderStorefront($request, $this->ownedStore($request, $slug), ['type' => 'cart']);
23
+        return $this->renderStorefront($request, $this->storefront($request), ['type' => 'cart']);
24 24
     }
25 25
 
26 26
     /**
27 27
      * Add a product to the cart.
28 28
      */
29
-    public function add(Request $request, string $slug): RedirectResponse
29
+    public function add(Request $request): RedirectResponse
30 30
     {
31
-        $store = $this->ownedStore($request, $slug);
31
+        $store = $this->storefront($request)->store;
32 32
 
33 33
         $validated = $request->validate([
34 34
             'product_id' => ['required', 'integer'],
@@ -49,24 +49,24 @@ class CartController extends Controller
49 49
     /**
50 50
      * Change how many of a product are in the cart. Zero removes it.
51 51
      */
52
-    public function update(Request $request, string $slug, int $product): RedirectResponse
52
+    public function update(Request $request): RedirectResponse
53 53
     {
54
-        $store = $this->ownedStore($request, $slug);
54
+        $store = $this->storefront($request)->store;
55 55
 
56 56
         $validated = $request->validate([
57 57
             'quantity' => ['required', 'integer', 'min:0', 'max:'.Cart::MAX_QUANTITY],
58 58
         ]);
59 59
 
60
-        $this->cart($request, $store)->set($this->buyableProduct($store, $product), $validated['quantity']);
60
+        $this->cart($request, $store)->set($this->buyableProduct($store, (int) $request->route('product')), $validated['quantity']);
61 61
 
62 62
         return back();
63 63
     }
64 64
 
65
-    public function remove(Request $request, string $slug, int $product): RedirectResponse
65
+    public function remove(Request $request): RedirectResponse
66 66
     {
67
-        $store = $this->ownedStore($request, $slug);
67
+        $store = $this->storefront($request)->store;
68 68
 
69
-        $this->cart($request, $store)->remove($product);
69
+        $this->cart($request, $store)->remove((int) $request->route('product'));
70 70
 
71 71
         return back();
72 72
     }

+ 15
- 13
app/Http/Controllers/CheckoutController.php Wyświetl plik

@@ -26,15 +26,15 @@ class CheckoutController extends Controller
26 26
     /**
27 27
      * The form for the shopper's contact details and delivery address.
28 28
      */
29
-    public function show(Request $request, string $slug): Response|RedirectResponse
29
+    public function show(Request $request): Response|RedirectResponse
30 30
     {
31
-        $store = $this->ownedStore($request, $slug);
31
+        $storefront = $this->storefront($request);
32 32
 
33
-        if ($this->cart($request, $store)->lines()->isEmpty()) {
34
-            return to_route('stores.preview.cart', $store->slug);
33
+        if ($this->cart($request, $storefront->store)->lines()->isEmpty()) {
34
+            return redirect($storefront->path('/cart'));
35 35
         }
36 36
 
37
-        return $this->renderStorefront($request, $store, [
37
+        return $this->renderStorefront($request, $storefront, [
38 38
             'type' => 'checkout',
39 39
             'states' => MalaysianStates::ALL,
40 40
         ]);
@@ -43,9 +43,10 @@ class CheckoutController extends Controller
43 43
     /**
44 44
      * Save the order, then send the shopper to the payment page.
45 45
      */
46
-    public function store(Request $request, Checkout $checkout, PaymentGateway $gateway, string $slug): HttpResponse
46
+    public function store(Request $request, Checkout $checkout, PaymentGateway $gateway): HttpResponse
47 47
     {
48
-        $store = $this->ownedStore($request, $slug);
48
+        $storefront = $this->storefront($request);
49
+        $store = $storefront->store;
49 50
 
50 51
         $details = $request->validate([
51 52
             'name' => ['required', 'string', 'min:2', 'max:120'],
@@ -66,8 +67,8 @@ class CheckoutController extends Controller
66 67
         try {
67 68
             $link = $gateway->startCheckout(
68 69
                 $order,
69
-                successUrl: route('stores.preview.order', [$store->slug, $order->public_id]),
70
-                cancelUrl: route('stores.preview.cart', $store->slug),
70
+                successUrl: $storefront->url('/orders/'.$order->public_id),
71
+                cancelUrl: $storefront->url('/cart'),
71 72
             );
72 73
         } catch (PaymentException $e) {
73 74
             report($e);
@@ -89,12 +90,13 @@ class CheckoutController extends Controller
89 90
     /**
90 91
      * Where the shopper lands after paying. The long random id in the address is what protects the page.
91 92
      */
92
-    public function order(Request $request, Checkout $checkout, PaymentGateway $gateway, string $slug, string $publicId): Response
93
+    public function order(Request $request, Checkout $checkout, PaymentGateway $gateway): Response
93 94
     {
94
-        $store = $this->ownedStore($request, $slug);
95
+        $storefront = $this->storefront($request);
96
+        $store = $storefront->store;
95 97
 
96 98
         /** @var Order $order */
97
-        $order = $store->orders()->with('items')->where('public_id', $publicId)->firstOrFail();
99
+        $order = $store->orders()->with('items')->where('public_id', (string) $request->route('publicId'))->firstOrFail();
98 100
 
99 101
         // Ask the payment provider directly. Nothing in the web address is trusted.
100 102
         if (! $order->isPaid() && $order->payment_checkout_id !== null) {
@@ -109,7 +111,7 @@ class CheckoutController extends Controller
109 111
             $this->cart($request, $store)->clear();
110 112
         }
111 113
 
112
-        return $this->renderStorefront($request, $store, [
114
+        return $this->renderStorefront($request, $storefront, [
113 115
             'type' => 'order',
114 116
             'order' => $order->toDisplay(),
115 117
         ]);

+ 11
- 10
app/Http/Controllers/Concerns/RendersStorefront.php Wyświetl plik

@@ -5,20 +5,20 @@ namespace App\Http\Controllers\Concerns;
5 5
 use App\Commerce\Cart;
6 6
 use App\Models\Product;
7 7
 use App\Models\Store;
8
+use App\Storefront\Storefront;
8 9
 use App\StorePlan\PlanSchema;
9 10
 use Illuminate\Http\Request;
10 11
 use Inertia\Inertia;
11 12
 use Inertia\Response;
12 13
 
13 14
 /**
14
- * Shared by the controllers that show storefront pages.
15
- * For now the storefront is a preview that only the store's owner can open. Step 5 makes it public.
15
+ * Shared by the controllers that show store pages, both live and in the owner's preview.
16 16
  */
17 17
 trait RendersStorefront
18 18
 {
19
-    private function ownedStore(Request $request, string $slug): Store
19
+    private function storefront(Request $request): Storefront
20 20
     {
21
-        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
21
+        return Storefront::fromRequest($request);
22 22
     }
23 23
 
24 24
     private function cart(Request $request, Store $store): Cart
@@ -27,21 +27,22 @@ trait RendersStorefront
27 27
     }
28 28
 
29 29
     /**
30
-     * Every storefront page gets the same basics: the plan, the fonts, the product list and the cart.
30
+     * Every store page gets the same basics: the design, the fonts, the product list and the cart.
31 31
      *
32 32
      * @param  array<string, mixed>  $view  Which page to show.
33 33
      */
34
-    private function renderStorefront(Request $request, Store $store, array $view): Response
34
+    private function renderStorefront(Request $request, Storefront $storefront, array $view): Response
35 35
     {
36
-        abort_if($store->plan === null, 404);
36
+        $store = $storefront->store;
37 37
 
38 38
         return Inertia::render('stores/preview', [
39 39
             'storeName' => $store->name,
40 40
             'language' => $store->language->value,
41
-            'plan' => $store->plan,
41
+            'plan' => $storefront->plan,
42 42
             'fonts' => PlanSchema::FONTS,
43
-            // Links inside the storefront are built on top of this address.
44
-            'baseUrl' => route('stores.preview', $store->slug, false),
43
+            // Links inside the store are built on top of this address. It is empty for a live store.
44
+            'baseUrl' => $storefront->baseUrl,
45
+            'preview' => $storefront->preview,
45 46
             'view' => $view,
46 47
             'products' => $store->products()
47 48
                 ->active()

+ 6
- 0
app/Http/Controllers/StoreController.php Wyświetl plik

@@ -9,6 +9,7 @@ use App\Enums\StoreLanguage;
9 9
 use App\Http\Requests\Stores\CreateStoreRequest;
10 10
 use App\Models\Store;
11 11
 use App\Models\StoreGeneration;
12
+use App\Storefront\Storefront;
12 13
 use Illuminate\Http\RedirectResponse;
13 14
 use Illuminate\Http\Request;
14 15
 use Inertia\Inertia;
@@ -96,6 +97,11 @@ class StoreController extends Controller
96 97
             'status' => $store->status->value,
97 98
             'status_label' => $store->status->label(),
98 99
             'has_design' => $store->plan !== null,
100
+            'is_published' => $store->isPublished(),
101
+            'has_unpublished_changes' => $store->hasUnpublishedChanges(),
102
+            'published_at' => $store->published_at?->toIso8601String(),
103
+            // Where shoppers open the store once it is published.
104
+            'live_url' => Storefront::liveUrl($store, request()),
99 105
             // Changes whenever the design is saved, so the preview knows to reload.
100 106
             'design_version' => $store->updated_at?->getTimestamp(),
101 107
             'created_at' => $store->created_at?->toIso8601String(),

+ 22
- 16
app/Http/Controllers/StoreDesignController.php Wyświetl plik

@@ -9,56 +9,62 @@ use Illuminate\Http\Request;
9 9
 use Inertia\Response;
10 10
 
11 11
 /**
12
- * The storefront pages: home, shop and product.
12
+ * The store pages that come from the design: home, extra pages, shop and product.
13
+ * Used for both the live store and the owner's preview (see App\Storefront\Storefront).
13 14
  */
14 15
 class StoreDesignController extends Controller
15 16
 {
16 17
     use RendersStorefront;
17 18
 
18 19
     /**
19
-     * The home page of the storefront, drawn from the store's saved plan.
20
+     * The home page.
20 21
      */
21
-    public function preview(Request $request, string $slug): Response
22
+    public function preview(Request $request): Response
22 23
     {
23
-        return $this->renderStorefront($request, $this->ownedStore($request, $slug), [
24
+        return $this->renderStorefront($request, $this->storefront($request), [
24 25
             'type' => 'page',
25 26
             'pageId' => PlanSchema::HOME_PAGE,
26 27
         ]);
27 28
     }
28 29
 
29 30
     /**
30
-     * Any other page of the plan, such as "about". Its id is its address.
31
+     * Any other page of the design, such as "about". Its id is its address.
31 32
      */
32
-    public function page(Request $request, string $slug, string $pageId): Response|RedirectResponse
33
+    public function page(Request $request): Response|RedirectResponse
33 34
     {
34
-        $store = $this->ownedStore($request, $slug);
35
+        $storefront = $this->storefront($request);
36
+        $pageId = (string) $request->route('pageId');
35 37
 
36 38
         if ($pageId === PlanSchema::HOME_PAGE) {
37
-            return to_route('stores.preview', $store->slug);
39
+            return redirect($storefront->path());
38 40
         }
39 41
 
40
-        abort_unless(in_array($pageId, array_column($store->plan['pages'] ?? [], 'id'), true), 404);
42
+        abort_unless(in_array($pageId, array_column($storefront->plan['pages'] ?? [], 'id'), true), 404);
41 43
 
42
-        return $this->renderStorefront($request, $store, ['type' => 'page', 'pageId' => $pageId]);
44
+        return $this->renderStorefront($request, $storefront, ['type' => 'page', 'pageId' => $pageId]);
43 45
     }
44 46
 
45 47
     /**
46 48
      * The shop page: every product shoppers may see.
47 49
      */
48
-    public function shop(Request $request, string $slug): Response
50
+    public function shop(Request $request): Response
49 51
     {
50
-        return $this->renderStorefront($request, $this->ownedStore($request, $slug), ['type' => 'shop']);
52
+        return $this->renderStorefront($request, $this->storefront($request), ['type' => 'shop']);
51 53
     }
52 54
 
53 55
     /**
54 56
      * One product's own page.
55 57
      */
56
-    public function product(Request $request, string $slug, string $productSlug): Response
58
+    public function product(Request $request): Response
57 59
     {
58
-        $store = $this->ownedStore($request, $slug);
60
+        $storefront = $this->storefront($request);
59 61
 
60
-        $product = $store->products()->active()->with('images')->where('slug', $productSlug)->firstOrFail();
62
+        $product = $storefront->store->products()
63
+            ->active()
64
+            ->with('images')
65
+            ->where('slug', (string) $request->route('productSlug'))
66
+            ->firstOrFail();
61 67
 
62
-        return $this->renderStorefront($request, $store, ['type' => 'product', 'product' => $product->toStorefront()]);
68
+        return $this->renderStorefront($request, $storefront, ['type' => 'product', 'product' => $product->toStorefront()]);
63 69
     }
64 70
 }

+ 71
- 0
app/Http/Controllers/StorePublishController.php Wyświetl plik

@@ -0,0 +1,71 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Enums\StoreStatus;
6
+use App\Models\Store;
7
+use App\StorePlan\PlanValidator;
8
+use Illuminate\Http\RedirectResponse;
9
+use Illuminate\Http\Request;
10
+use Illuminate\Validation\ValidationException;
11
+use Inertia\Inertia;
12
+
13
+/**
14
+ * Puts a store live for shoppers, updates the live copy, or takes the store offline.
15
+ */
16
+class StorePublishController extends Controller
17
+{
18
+    /**
19
+     * Publish the store, or publish the latest design changes of a store that is already live.
20
+     * Shoppers see a saved copy of the design, taken at this moment.
21
+     */
22
+    public function publish(Request $request, PlanValidator $validator, string $slug): RedirectResponse
23
+    {
24
+        $store = $this->ownedStore($request, $slug);
25
+
26
+        abort_if($store->plan === null, 404);
27
+
28
+        try {
29
+            // Checked once more, so nothing broken can ever go live.
30
+            $plan = $validator->validate($store->plan);
31
+        } catch (ValidationException) {
32
+            return $this->flash($store, 'error', __('This design has a problem and cannot be published. Please regenerate it.'));
33
+        }
34
+
35
+        $wasLive = $store->isPublished();
36
+
37
+        $store->published_plan = $plan;
38
+        $store->published_at = now();
39
+        $store->status = StoreStatus::Published;
40
+        $store->save();
41
+
42
+        return $this->flash($store, 'success', $wasLive ? __('Your changes are live.') : __('Your store is live.'));
43
+    }
44
+
45
+    /**
46
+     * Take the store offline. The design, products and orders are all kept.
47
+     */
48
+    public function unpublish(Request $request, string $slug): RedirectResponse
49
+    {
50
+        $store = $this->ownedStore($request, $slug);
51
+
52
+        $store->status = StoreStatus::Draft;
53
+        $store->published_plan = null;
54
+        $store->published_at = null;
55
+        $store->save();
56
+
57
+        return $this->flash($store, 'success', __('Your store is offline.'));
58
+    }
59
+
60
+    private function flash(Store $store, string $type, string $message): RedirectResponse
61
+    {
62
+        Inertia::flash('toast', ['type' => $type, 'message' => $message]);
63
+
64
+        return to_route('stores.show', $store->slug);
65
+    }
66
+
67
+    private function ownedStore(Request $request, string $slug): Store
68
+    {
69
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
70
+    }
71
+}

+ 33
- 1
app/Models/Store.php Wyświetl plik

@@ -5,8 +5,10 @@ namespace App\Models;
5 5
 use App\Enums\StoreCategory;
6 6
 use App\Enums\StoreLanguage;
7 7
 use App\Enums\StoreStatus;
8
+use Carbon\CarbonInterface;
8 9
 use Database\Factories\StoreFactory;
9 10
 use Illuminate\Database\Eloquent\Attributes\Fillable;
11
+use Illuminate\Database\Eloquent\Builder;
10 12
 use Illuminate\Database\Eloquent\Factories\HasFactory;
11 13
 use Illuminate\Database\Eloquent\Model;
12 14
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
@@ -26,6 +28,8 @@ use Illuminate\Support\Str;
26 28
  * @property StoreLanguage $language
27 29
  * @property StoreStatus $status
28 30
  * @property array<string, mixed>|null $plan
31
+ * @property array<string, mixed>|null $published_plan
32
+ * @property CarbonInterface|null $published_at
29 33
  * @property Carbon|null $created_at
30 34
  * @property Carbon|null $updated_at
31 35
  */
@@ -40,7 +44,10 @@ class Store extends Model
40 44
      *
41 45
      * @var list<string>
42 46
      */
43
-    public const array RESERVED_SLUGS = ['www', 'app', 'api', 'admin', 'dashboard', 'mail', 'store', 'stores', 'create'];
47
+    public const array RESERVED_SLUGS = [
48
+        'www', 'app', 'api', 'admin', 'dashboard', 'mail', 'store', 'stores', 'create',
49
+        'localhost', 'static', 'assets', 'cdn', 'help', 'support', 'status', 'blog', 'billing', 'login', 'register',
50
+    ];
44 51
 
45 52
     /**
46 53
      * Default values for new stores.
@@ -90,6 +97,29 @@ class Store extends Model
90 97
         return $this->belongsTo(User::class);
91 98
     }
92 99
 
100
+    /**
101
+     * Stores that shoppers can open.
102
+     *
103
+     * @param  Builder<Store>  $query
104
+     */
105
+    public function scopePublished(Builder $query): void
106
+    {
107
+        $query->where('status', StoreStatus::Published)->whereNotNull('published_plan');
108
+    }
109
+
110
+    public function isPublished(): bool
111
+    {
112
+        return $this->status === StoreStatus::Published && $this->published_plan !== null;
113
+    }
114
+
115
+    /**
116
+     * True when the working design differs from the copy shoppers see.
117
+     */
118
+    public function hasUnpublishedChanges(): bool
119
+    {
120
+        return $this->isPublished() && $this->plan != $this->published_plan;
121
+    }
122
+
93 123
     /**
94 124
      * @return HasMany<Product, $this>
95 125
      */
@@ -128,6 +158,8 @@ class Store extends Model
128 158
             'language' => StoreLanguage::class,
129 159
             'status' => StoreStatus::class,
130 160
             'plan' => 'array',
161
+            'published_plan' => 'array',
162
+            'published_at' => 'datetime',
131 163
         ];
132 164
     }
133 165
 }

+ 78
- 0
app/Storefront/Storefront.php Wyświetl plik

@@ -0,0 +1,78 @@
1
+<?php
2
+
3
+namespace App\Storefront;
4
+
5
+use App\Models\Store;
6
+use Illuminate\Http\Request;
7
+
8
+/**
9
+ * One visit to a store's pages, in one of two ways:
10
+ *
11
+ * - Live: a shopper on the store's own address (such as sambal-nenek.localhost). No login.
12
+ *   Shows the published copy of the design. Only published stores can be opened.
13
+ * - Preview: the owner, logged in, inside the dashboard address. Shows the working design.
14
+ *
15
+ * The same controllers and pages serve both. This class is the only place that knows the difference.
16
+ */
17
+final readonly class Storefront
18
+{
19
+    /**
20
+     * @param  array<string, mixed>  $plan  The design to draw.
21
+     * @param  string  $baseUrl  Path of the store's home page. Every other store address is built on it.
22
+     */
23
+    public function __construct(
24
+        public Store $store,
25
+        public array $plan,
26
+        public string $baseUrl,
27
+        public bool $preview,
28
+        private string $origin,
29
+    ) {}
30
+
31
+    /**
32
+     * Work out which store this request is for. Gives "not found" when the visitor may not see it.
33
+     */
34
+    public static function fromRequest(Request $request): self
35
+    {
36
+        $liveSlug = $request->route('storeSlug');
37
+
38
+        if (is_string($liveSlug)) {
39
+            $store = Store::query()->published()->where('slug', $liveSlug)->firstOrFail();
40
+
41
+            return new self($store, $store->published_plan ?? [], '', false, $request->getSchemeAndHttpHost());
42
+        }
43
+
44
+        $store = $request->user()?->stores()->where('slug', (string) $request->route('slug'))->first();
45
+
46
+        abort_if($store === null || $store->plan === null, 404);
47
+
48
+        return new self($store, $store->plan, route('stores.preview', $store->slug, false), true, $request->getSchemeAndHttpHost());
49
+    }
50
+
51
+    /**
52
+     * A path inside this store, such as "/cart".
53
+     */
54
+    public function path(string $path = ''): string
55
+    {
56
+        return $this->baseUrl.$path ?: '/';
57
+    }
58
+
59
+    /**
60
+     * A full web address inside this store, for places outside our pages (the payment provider, emails).
61
+     */
62
+    public function url(string $path = ''): string
63
+    {
64
+        return $this->origin.$this->path($path);
65
+    }
66
+
67
+    /**
68
+     * The address shoppers open a published store at, built from the address the app itself is on.
69
+     * "http://localhost:8000" and store "luna-skin" give "http://luna-skin.localhost:8000".
70
+     */
71
+    public static function liveUrl(Store $store, Request $request): string
72
+    {
73
+        $port = $request->getPort();
74
+        $standard = ($request->getScheme() === 'https' && $port === 443) || ($request->getScheme() === 'http' && $port === 80);
75
+
76
+        return $request->getScheme().'://'.$store->slug.'.'.config('storefront.domain').($standard || $port === null ? '' : ':'.$port);
77
+    }
78
+}

+ 18
- 0
config/storefront.php Wyświetl plik

@@ -0,0 +1,18 @@
1
+<?php
2
+
3
+/*
4
+|--------------------------------------------------------------------------
5
+| Published stores
6
+|--------------------------------------------------------------------------
7
+|
8
+| A published store is opened at "<store name>.<domain>", for example
9
+| "sambal-nenek.localhost" on a development machine. The port and http/https
10
+| are taken from the address the app itself is opened at.
11
+|
12
+*/
13
+
14
+return [
15
+
16
+    'domain' => env('STOREFRONT_DOMAIN') ?: 'localhost',
17
+
18
+];

+ 27
- 0
database/migrations/2026_11_15_000000_add_publishing_to_stores_table.php Wyświetl plik

@@ -0,0 +1,27 @@
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
+    /**
10
+     * A published store shows shoppers a saved copy of the design ("published_plan"),
11
+     * so the merchant can keep editing the working design without shoppers seeing half-finished changes.
12
+     */
13
+    public function up(): void
14
+    {
15
+        Schema::table('stores', function (Blueprint $table) {
16
+            $table->json('published_plan')->nullable()->after('plan');
17
+            $table->timestamp('published_at')->nullable()->after('published_plan');
18
+        });
19
+    }
20
+
21
+    public function down(): void
22
+    {
23
+        Schema::table('stores', function (Blueprint $table) {
24
+            $table->dropColumn(['published_plan', 'published_at']);
25
+        });
26
+    }
27
+};

+ 9
- 1
resources/js/app.tsx Wyświetl plik

@@ -5,11 +5,19 @@ import { initializeTheme } from '@/hooks/use-appearance';
5 5
 import AppLayout from '@/layouts/app-layout';
6 6
 import AuthLayout from '@/layouts/auth-layout';
7 7
 import SettingsLayout from '@/layouts/settings/layout';
8
+import { storefrontTitlePrefix } from '@/storefront/theme';
8 9
 
9 10
 const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
10 11
 
11 12
 void createInertiaApp({
12
-    title: (title) => (title ? `${title} - ${appName}` : appName),
13
+    title: (title) => {
14
+        // A store's own pages show the store's name only, never ours.
15
+        if (title.startsWith(storefrontTitlePrefix)) {
16
+            return title.slice(storefrontTitlePrefix.length);
17
+        }
18
+
19
+        return title ? `${title} - ${appName}` : appName;
20
+    },
13 21
     layout: (name) => {
14 22
         switch (true) {
15 23
             case name === 'welcome':

+ 154
- 0
resources/js/components/stores/publish-panel.tsx Wyświetl plik

@@ -0,0 +1,154 @@
1
+import { Form } from '@inertiajs/react';
2
+import { ExternalLink, Globe, GlobeLock } from 'lucide-react';
3
+import StorePublishController from '@/actions/App/Http/Controllers/StorePublishController';
4
+import { Button } from '@/components/ui/button';
5
+import {
6
+    Dialog,
7
+    DialogClose,
8
+    DialogContent,
9
+    DialogDescription,
10
+    DialogFooter,
11
+    DialogHeader,
12
+    DialogTitle,
13
+    DialogTrigger,
14
+} from '@/components/ui/dialog';
15
+import { formatDateTime } from '@/lib/money';
16
+import type { Store } from '@/types';
17
+
18
+/**
19
+ * Shows whether the store is live, where shoppers open it, and the buttons to publish or take it offline.
20
+ */
21
+export default function PublishPanel({
22
+    store,
23
+    busy,
24
+}: {
25
+    store: Store;
26
+    busy: boolean;
27
+}) {
28
+    const address = store.live_url.replace(/^https?:\/\//, '');
29
+
30
+    if (!store.is_published) {
31
+        return (
32
+            <div className="flex flex-wrap items-center justify-between gap-4 rounded-xl border p-4">
33
+                <div className="flex items-start gap-3">
34
+                    <GlobeLock className="mt-0.5 size-5 shrink-0 text-muted-foreground" />
35
+                    <div>
36
+                        <p className="font-medium">Your store is not live</p>
37
+                        <p className="mt-0.5 text-sm text-muted-foreground">
38
+                            Only you can see it. When you publish, shoppers can
39
+                            open it at{' '}
40
+                            <span className="font-medium text-foreground">
41
+                                {address}
42
+                            </span>
43
+                            .
44
+                        </p>
45
+                    </div>
46
+                </div>
47
+
48
+                <Form {...StorePublishController.publish.form(store.slug)}>
49
+                    {({ processing }) => (
50
+                        <Button
51
+                            disabled={processing || busy}
52
+                            data-test="publish-store-button"
53
+                        >
54
+                            <Globe />
55
+                            Publish store
56
+                        </Button>
57
+                    )}
58
+                </Form>
59
+            </div>
60
+        );
61
+    }
62
+
63
+    return (
64
+        <div
65
+            className="space-y-3 rounded-xl border p-4"
66
+            data-test="publish-panel-live"
67
+        >
68
+            <div className="flex flex-wrap items-center justify-between gap-4">
69
+                <div className="flex items-start gap-3">
70
+                    <Globe className="mt-0.5 size-5 shrink-0 text-green-600 dark:text-green-400" />
71
+                    <div className="min-w-0">
72
+                        <p className="font-medium">Your store is live</p>
73
+                        <p className="mt-0.5 text-sm break-all">
74
+                            <a
75
+                                href={store.live_url}
76
+                                target="_blank"
77
+                                rel="noreferrer"
78
+                                className="inline-flex items-center gap-1 underline underline-offset-2"
79
+                            >
80
+                                {address}
81
+                                <ExternalLink className="size-3.5" />
82
+                            </a>
83
+                        </p>
84
+                        <p className="mt-0.5 text-xs text-muted-foreground">
85
+                            Last published {formatDateTime(store.published_at)}
86
+                        </p>
87
+                    </div>
88
+                </div>
89
+
90
+                <Dialog>
91
+                    <DialogTrigger asChild>
92
+                        <Button
93
+                            variant="outline"
94
+                            size="sm"
95
+                            data-test="unpublish-store-button"
96
+                        >
97
+                            Take offline
98
+                        </Button>
99
+                    </DialogTrigger>
100
+                    <DialogContent>
101
+                        <DialogHeader>
102
+                            <DialogTitle>Take your store offline?</DialogTitle>
103
+                            <DialogDescription>
104
+                                Shoppers will no longer be able to open{' '}
105
+                                {address}. Your design, products and orders are
106
+                                kept, and you can publish again any time.
107
+                            </DialogDescription>
108
+                        </DialogHeader>
109
+                        <DialogFooter>
110
+                            <DialogClose asChild>
111
+                                <Button variant="outline">Cancel</Button>
112
+                            </DialogClose>
113
+                            <Form
114
+                                {...StorePublishController.unpublish.form(
115
+                                    store.slug,
116
+                                )}
117
+                            >
118
+                                {({ processing }) => (
119
+                                    <Button
120
+                                        variant="destructive"
121
+                                        disabled={processing}
122
+                                        data-test="confirm-unpublish-button"
123
+                                    >
124
+                                        Take offline
125
+                                    </Button>
126
+                                )}
127
+                            </Form>
128
+                        </DialogFooter>
129
+                    </DialogContent>
130
+                </Dialog>
131
+            </div>
132
+
133
+            {store.has_unpublished_changes && (
134
+                <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg bg-amber-50 p-3 text-sm text-amber-900 dark:bg-amber-950/40 dark:text-amber-200">
135
+                    <p>
136
+                        You changed the design since you last published.
137
+                        Shoppers still see the older version.
138
+                    </p>
139
+                    <Form {...StorePublishController.publish.form(store.slug)}>
140
+                        {({ processing }) => (
141
+                            <Button
142
+                                size="sm"
143
+                                disabled={processing || busy}
144
+                                data-test="publish-changes-button"
145
+                            >
146
+                                Publish changes
147
+                            </Button>
148
+                        )}
149
+                    </Form>
150
+                </div>
151
+            )}
152
+        </div>
153
+    );
154
+}

+ 11
- 2
resources/js/pages/stores/preview.tsx Wyświetl plik

@@ -1,6 +1,6 @@
1 1
 import { Head } from '@inertiajs/react';
2 2
 import { StorefrontRenderer } from '@/storefront/renderer';
3
-import { fontStylesheetUrl } from '@/storefront/theme';
3
+import { fontStylesheetUrl, storefrontTitlePrefix } from '@/storefront/theme';
4 4
 import type {
5 5
     FontMap,
6 6
     StoreCart,
@@ -15,6 +15,7 @@ export default function PreviewStore({
15 15
     plan,
16 16
     fonts,
17 17
     baseUrl,
18
+    preview,
18 19
     view,
19 20
     products,
20 21
     cart,
@@ -24,6 +25,8 @@ export default function PreviewStore({
24 25
     plan: StorePlan;
25 26
     fonts: FontMap;
26 27
     baseUrl: string;
28
+    /** True in the owner's preview, false on the live store. */
29
+    preview: boolean;
27 30
     view: StorefrontView;
28 31
     products: StoreProduct[];
29 32
     cart: StoreCart;
@@ -42,7 +45,13 @@ export default function PreviewStore({
42 45
 
43 46
     return (
44 47
         <>
45
-            <Head title={`${title} (preview)`}>
48
+            <Head
49
+                title={
50
+                    preview
51
+                        ? `${title} (preview)`
52
+                        : storefrontTitlePrefix + title
53
+                }
54
+            >
46 55
                 {fontUrl && <link rel="stylesheet" href={fontUrl} />}
47 56
             </Head>
48 57
 

+ 16
- 2
resources/js/pages/stores/show.tsx Wyświetl plik

@@ -12,6 +12,7 @@ import StoreDesignController from '@/actions/App/Http/Controllers/StoreDesignCon
12 12
 import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGenerationController';
13 13
 import DesignChat from '@/components/stores/design-chat';
14 14
 import DesignProgress from '@/components/stores/design-progress';
15
+import PublishPanel from '@/components/stores/publish-panel';
15 16
 import StoreNav from '@/components/stores/store-nav';
16 17
 import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
17 18
 import { Badge } from '@/components/ui/badge';
@@ -50,7 +51,9 @@ type Props = {
50 51
 export default function ShowStore({ store, generation, edits, usage }: Props) {
51 52
     const [device, setDevice] = useState<Device>('desktop');
52 53
     const [confirmOpen, setConfirmOpen] = useState(false);
53
-    const previewUrl = StoreDesignController.preview.url(store.slug);
54
+    const previewUrl = StoreDesignController.preview[
55
+        '/stores/{slug}/preview'
56
+    ].url(store.slug);
54 57
 
55 58
     const busy =
56 59
         generation?.status === 'queued' || generation?.status === 'running';
@@ -98,6 +101,8 @@ export default function ShowStore({ store, generation, edits, usage }: Props) {
98 101
 
99 102
                 <StoreNav slug={store.slug} current="design" />
100 103
 
104
+                {store.has_design && <PublishPanel store={store} busy={busy} />}
105
+
101 106
                 <Card>
102 107
                     <CardHeader>
103 108
                         <CardTitle>Brand description</CardTitle>
@@ -115,7 +120,16 @@ export default function ShowStore({ store, generation, edits, usage }: Props) {
115 120
                 {store.has_design ? (
116 121
                     <section className="space-y-3">
117 122
                         <div className="flex flex-wrap items-center justify-between gap-3">
118
-                            <h2 className="font-medium">Store design</h2>
123
+                            <div>
124
+                                <h2 className="font-medium">Store design</h2>
125
+                                {store.is_published && (
126
+                                    <p className="text-xs text-muted-foreground">
127
+                                        This preview shows your working design,
128
+                                        including changes that are not published
129
+                                        yet.
130
+                                    </p>
131
+                                )}
132
+                            </div>
119 133
 
120 134
                             <div className="flex items-center gap-2">
121 135
                                 <ToggleGroup

+ 6
- 0
resources/js/storefront/theme.ts Wyświetl plik

@@ -66,3 +66,9 @@ const ringgit = new Intl.NumberFormat('en-MY', {
66 66
 export function formatPrice(amount: number): string {
67 67
     return ringgit.format(amount);
68 68
 }
69
+
70
+/**
71
+ * Put in front of a page title to say "this is a store's own page".
72
+ * app.tsx removes it and leaves out our app name.
73
+ */
74
+export const storefrontTitlePrefix = 'storefront::';

+ 4
- 0
resources/js/types/store.ts Wyświetl plik

@@ -10,6 +10,10 @@ export type Store = {
10 10
     status: 'draft' | 'published';
11 11
     status_label: string;
12 12
     has_design: boolean;
13
+    is_published: boolean;
14
+    has_unpublished_changes: boolean;
15
+    published_at: string | null;
16
+    live_url: string;
13 17
     design_version: number | null;
14 18
     created_at: string | null;
15 19
 };

+ 37
- 0
routes/web.php Wyświetl plik

@@ -7,9 +7,44 @@ use App\Http\Controllers\ProductController;
7 7
 use App\Http\Controllers\StoreController;
8 8
 use App\Http\Controllers\StoreDesignController;
9 9
 use App\Http\Controllers\StoreGenerationController;
10
+use App\Http\Controllers\StorePublishController;
10 11
 use App\Http\Controllers\StripeWebhookController;
11 12
 use Illuminate\Support\Facades\Route;
12 13
 
14
+/*
15
+|--------------------------------------------------------------------------
16
+| Live stores
17
+|--------------------------------------------------------------------------
18
+|
19
+| A published store has its own address: "<store name>.<domain>", such as
20
+| sambal-nenek.localhost. Shoppers need no login. These routes are listed
21
+| first so that on a store's address nothing else of the app can be opened.
22
+|
23
+*/
24
+Route::domain('{storeSlug}.'.config('storefront.domain'))
25
+    ->middleware('throttle:240,1')
26
+    ->name('storefront.')
27
+    ->group(function () {
28
+        Route::get('/', [StoreDesignController::class, 'preview'])->name('home');
29
+        Route::get('shop', [StoreDesignController::class, 'shop'])->name('shop');
30
+        Route::get('products/{productSlug}', [StoreDesignController::class, 'product'])->name('product');
31
+
32
+        Route::get('cart', [CartController::class, 'show'])->name('cart');
33
+        Route::post('cart/items', [CartController::class, 'add'])->name('cart.add');
34
+        Route::patch('cart/items/{product}', [CartController::class, 'update'])->name('cart.update')->whereNumber('product');
35
+        Route::delete('cart/items/{product}', [CartController::class, 'remove'])->name('cart.remove')->whereNumber('product');
36
+
37
+        Route::get('checkout', [CheckoutController::class, 'show'])->name('checkout');
38
+        Route::post('checkout', [CheckoutController::class, 'store'])->middleware('throttle:20,1')->name('checkout.store');
39
+        Route::get('orders/{publicId}', [CheckoutController::class, 'order'])->name('order');
40
+
41
+        // Pages the merchant added, such as /about.
42
+        Route::get('{pageId}', [StoreDesignController::class, 'page'])->name('page')->where('pageId', '[a-z][a-z0-9-]*');
43
+
44
+        // Anything else on a store's address does not exist. This hides the dashboard and login pages there.
45
+        Route::any('{any}', fn () => abort(404))->where('any', '.*')->name('missing');
46
+    });
47
+
13 48
 Route::inertia('/', 'welcome')->name('home');
14 49
 
15 50
 // Called by Stripe, not by a browser, so it has no login. Each message is checked with a signing secret.
@@ -48,6 +83,8 @@ Route::middleware(['auth', 'verified'])->group(function () {
48 83
     Route::post('stores/{slug}/products/{product}', [ProductController::class, 'update'])->name('stores.products.update')->whereNumber('product');
49 84
     Route::delete('stores/{slug}/products/{product}', [ProductController::class, 'destroy'])->name('stores.products.destroy')->whereNumber('product');
50 85
     Route::delete('stores/{slug}/products/{product}/images/{image}', [ProductController::class, 'destroyImage'])->name('stores.products.images.destroy')->whereNumber(['product', 'image']);
86
+    Route::post('stores/{slug}/publish', [StorePublishController::class, 'publish'])->name('stores.publish');
87
+    Route::post('stores/{slug}/unpublish', [StorePublishController::class, 'unpublish'])->name('stores.unpublish');
51 88
     Route::post('stores/{slug}/generate', [StoreGenerationController::class, 'generate'])->name('stores.generate');
52 89
     Route::post('stores/{slug}/edits', [StoreGenerationController::class, 'edit'])->name('stores.edits');
53 90
 });

+ 288
- 0
tests/Feature/Stores/PublishingTest.php Wyświetl plik

@@ -0,0 +1,288 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Enums\StoreStatus;
7
+use App\Mail\OrderConfirmation;
8
+use App\Models\Order;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use App\Models\User;
12
+use App\StorePlan\SamplePlan;
13
+use Illuminate\Foundation\Testing\RefreshDatabase;
14
+use Illuminate\Support\Facades\Mail;
15
+use Inertia\Testing\AssertableInertia as Assert;
16
+use Tests\Support\FakeGateway;
17
+use Tests\TestCase;
18
+
19
+class PublishingTest extends TestCase
20
+{
21
+    use RefreshDatabase;
22
+
23
+    private User $user;
24
+
25
+    private Store $store;
26
+
27
+    protected function setUp(): void
28
+    {
29
+        parent::setUp();
30
+
31
+        $this->user = User::factory()->create();
32
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
33
+        $this->store->plan = SamplePlan::for($this->store);
34
+        $this->store->save();
35
+    }
36
+
37
+    /** The address shoppers use for a page of the live store. */
38
+    private function live(string $path = '/', ?Store $store = null): string
39
+    {
40
+        return 'http://'.($store ?? $this->store)->slug.'.localhost'.$path;
41
+    }
42
+
43
+    /** A dashboard address. Always on the app's own host, whichever host the last request went to. */
44
+    private function app(string $name, mixed $parameters = []): string
45
+    {
46
+        return 'http://localhost'.route($name, $parameters, false);
47
+    }
48
+
49
+    private function publish(): void
50
+    {
51
+        $this->actingAs($this->user)->post($this->app('stores.publish', $this->store->slug))
52
+            ->assertRedirect($this->app('stores.show', $this->store->slug));
53
+
54
+        auth()->logout();
55
+    }
56
+
57
+    public function test_a_store_is_private_until_it_is_published()
58
+    {
59
+        $this->get($this->live())->assertNotFound();
60
+        $this->get($this->live('/shop'))->assertNotFound();
61
+        $this->get('http://no-such-store.localhost/')->assertNotFound();
62
+
63
+        $this->actingAs($this->user)
64
+            ->get($this->app('stores.show', $this->store->slug))
65
+            ->assertInertia(fn (Assert $page) => $page
66
+                ->where('store.is_published', false)
67
+                ->where('store.status', 'draft')
68
+                ->where('store.live_url', 'http://kedai-ali.localhost'));
69
+    }
70
+
71
+    public function test_the_owner_can_publish_and_anyone_can_then_open_the_store()
72
+    {
73
+        $this->publish();
74
+
75
+        $this->store->refresh();
76
+
77
+        $this->assertSame(StoreStatus::Published, $this->store->status);
78
+        $this->assertEquals($this->store->plan, $this->store->published_plan);
79
+        $this->assertNotNull($this->store->published_at);
80
+
81
+        // No login.
82
+        $this->get($this->live())
83
+            ->assertOk()
84
+            ->assertInertia(fn (Assert $page) => $page
85
+                ->component('stores/preview')
86
+                ->where('storeName', 'Kedai Ali')
87
+                ->where('preview', false)
88
+                // Links are built from the root of the store's own address.
89
+                ->where('baseUrl', '')
90
+                ->where('view.pageId', 'home')
91
+                ->where('auth.user', null));
92
+
93
+        $this->actingAs($this->user)
94
+            ->get($this->app('stores.show', $this->store->slug))
95
+            ->assertInertia(fn (Assert $page) => $page
96
+                ->where('store.is_published', true)
97
+                ->where('store.has_unpublished_changes', false)
98
+                ->where('store.status', 'published'));
99
+    }
100
+
101
+    public function test_design_changes_stay_private_until_published_again()
102
+    {
103
+        $this->publish();
104
+
105
+        $plan = $this->store->fresh()->plan;
106
+        $plan['header']['content']['logoText'] = 'New Name';
107
+        $this->store->plan = $plan;
108
+        $this->store->save();
109
+
110
+        $this->get($this->live())
111
+            ->assertInertia(fn (Assert $page) => $page->where('plan.header.content.logoText', 'Kedai Ali'));
112
+
113
+        // The owner's preview shows the working design.
114
+        $this->actingAs($this->user)
115
+            ->get($this->app('stores.preview', $this->store->slug))
116
+            ->assertInertia(fn (Assert $page) => $page
117
+                ->where('plan.header.content.logoText', 'New Name')
118
+                ->where('preview', true));
119
+
120
+        $this->get($this->app('stores.show', $this->store->slug))
121
+            ->assertInertia(fn (Assert $page) => $page->where('store.has_unpublished_changes', true));
122
+
123
+        $this->publish();
124
+
125
+        $this->get($this->live())
126
+            ->assertInertia(fn (Assert $page) => $page->where('plan.header.content.logoText', 'New Name'));
127
+    }
128
+
129
+    public function test_taking_a_store_offline_hides_it_again()
130
+    {
131
+        $this->publish();
132
+
133
+        $this->actingAs($this->user)->post($this->app('stores.unpublish', $this->store->slug))
134
+            ->assertRedirect($this->app('stores.show', $this->store->slug));
135
+        auth()->logout();
136
+
137
+        $this->store->refresh();
138
+
139
+        $this->assertSame(StoreStatus::Draft, $this->store->status);
140
+        $this->assertNull($this->store->published_plan);
141
+        $this->assertNotNull($this->store->plan);
142
+        $this->get($this->live())->assertNotFound();
143
+    }
144
+
145
+    public function test_a_store_needs_a_design_and_its_owner_to_be_published()
146
+    {
147
+        $empty = Store::factory()->for($this->user)->create();
148
+        $stranger = User::factory()->create();
149
+
150
+        $this->actingAs($this->user)->post($this->app('stores.publish', $empty->slug))->assertNotFound();
151
+        $this->actingAs($stranger)->post($this->app('stores.publish', $this->store->slug))->assertNotFound();
152
+        $this->actingAs($stranger)->post($this->app('stores.unpublish', $this->store->slug))->assertNotFound();
153
+        auth()->logout();
154
+        $this->post($this->app('stores.publish', $this->store->slug))->assertRedirect($this->app('login'));
155
+
156
+        $this->assertFalse($this->store->fresh()->isPublished());
157
+    }
158
+
159
+    public function test_a_broken_design_cannot_go_live()
160
+    {
161
+        $plan = $this->store->plan;
162
+        $plan['theme']['colors']['primary'] = 'not-a-colour';
163
+        $this->store->plan = $plan;
164
+        $this->store->save();
165
+
166
+        $this->actingAs($this->user)->post($this->app('stores.publish', $this->store->slug));
167
+
168
+        $this->assertFalse($this->store->fresh()->isPublished());
169
+    }
170
+
171
+    public function test_the_live_store_has_shop_product_and_extra_pages()
172
+    {
173
+        $plan = $this->store->plan;
174
+        $plan['pages'][] = [
175
+            'id' => 'about',
176
+            'title' => 'About us',
177
+            'sections' => [[
178
+                'id' => 'about-main',
179
+                'type' => 'about',
180
+                'variant' => 'simple',
181
+                'content' => ['heading' => 'Our story', 'body' => 'We started small.', 'stats' => []],
182
+            ]],
183
+        ];
184
+        $this->store->plan = $plan;
185
+        $this->store->save();
186
+
187
+        $visible = Product::factory()->for($this->store)->create(['name' => 'Sambal']);
188
+        $hidden = Product::factory()->for($this->store)->draft()->create();
189
+        $this->publish();
190
+
191
+        $this->get($this->live('/shop'))->assertOk()->assertInertia(fn (Assert $page) => $page
192
+            ->where('view.type', 'shop')
193
+            ->has('products', 1)
194
+            ->where('products.0.name', 'Sambal'));
195
+
196
+        $this->get($this->live('/products/'.$visible->slug))->assertOk()
197
+            ->assertInertia(fn (Assert $page) => $page->where('view.product.name', 'Sambal'));
198
+        $this->get($this->live('/products/'.$hidden->slug))->assertNotFound();
199
+
200
+        $this->get($this->live('/about'))->assertOk()
201
+            ->assertInertia(fn (Assert $page) => $page->where('view.pageId', 'about'));
202
+        $this->get($this->live('/home'))->assertRedirect('http://kedai-ali.localhost');
203
+        $this->get($this->live('/no-such-page'))->assertNotFound();
204
+    }
205
+
206
+    public function test_the_dashboard_and_login_cannot_be_opened_on_a_stores_address()
207
+    {
208
+        $this->publish();
209
+
210
+        foreach (['/dashboard', '/login', '/register', '/stores/create', '/settings/profile', '/stores/kedai-ali/preview', '/stripe/webhook'] as $path) {
211
+            $this->get($this->live($path))->assertNotFound();
212
+        }
213
+
214
+        $this->post($this->live('/login'), ['email' => 'x@example.com', 'password' => 'x'])->assertNotFound();
215
+        $this->actingAs($this->user)->get($this->live('/dashboard'))->assertNotFound();
216
+    }
217
+
218
+    public function test_a_shopper_can_buy_from_a_live_store_without_an_account()
219
+    {
220
+        Mail::fake();
221
+        $gateway = new FakeGateway;
222
+        $this->app->instance(PaymentGateway::class, $gateway);
223
+
224
+        $product = Product::factory()->for($this->store)->create(['name' => 'Sambal', 'price' => 1290, 'stock' => 5]);
225
+        $this->publish();
226
+
227
+        $this->post($this->live('/cart/items'), ['product_id' => $product->id, 'quantity' => 2])->assertRedirect();
228
+
229
+        $this->get($this->live('/cart'))->assertOk()->assertInertia(fn (Assert $page) => $page
230
+            ->where('view.type', 'cart')
231
+            ->where('cart.count', 2)
232
+            ->where('cart.subtotal', 25.8));
233
+
234
+        $this->get($this->live('/checkout'))->assertOk()
235
+            ->assertInertia(fn (Assert $page) => $page->where('view.type', 'checkout'));
236
+
237
+        $this->post($this->live('/checkout'), [
238
+            'name' => 'Aminah binti Ali',
239
+            'email' => 'aminah@example.com',
240
+            'phone' => '0123456789',
241
+            'line1' => '12 Jalan Mawar',
242
+            'city' => 'Shah Alam',
243
+            'postcode' => '40000',
244
+            'state' => 'Selangor',
245
+        ])->assertRedirect('https://pay.test/cs_fake_1');
246
+
247
+        $order = Order::firstOrFail();
248
+
249
+        // The payment page sends the shopper back to the store's own address, not to the dashboard.
250
+        $this->assertSame($this->live('/orders/'.$order->public_id), $gateway->successUrl);
251
+        $this->assertSame($this->live('/cart'), $gateway->cancelUrl);
252
+
253
+        $gateway->pay($order);
254
+
255
+        $this->get($this->live('/orders/'.$order->public_id))->assertOk()->assertInertia(fn (Assert $page) => $page
256
+            ->where('view.order.status', 'paid')
257
+            ->where('cart.count', 0));
258
+
259
+        $this->assertSame(3, $product->fresh()->stock);
260
+        Mail::assertSent(OrderConfirmation::class, 1);
261
+
262
+        // An order page only opens on the address of the store it belongs to.
263
+        $other = Store::factory()->for($this->user)->create(['name' => 'Other']);
264
+        $other->plan = SamplePlan::for($other);
265
+        $other->save();
266
+        $this->actingAs($this->user)->post($this->app('stores.publish', $other->slug));
267
+        auth()->logout();
268
+
269
+        $this->get($this->live('/orders/'.$order->public_id, $other))->assertNotFound();
270
+        $this->get($this->live('/orders/01ARZ3NDEKTSV4RRFFQ69G5FAV'))->assertNotFound();
271
+    }
272
+
273
+    public function test_an_empty_live_cart_sends_checkout_back_to_the_cart()
274
+    {
275
+        $this->publish();
276
+
277
+        $this->get($this->live('/checkout'))->assertRedirect($this->live('/cart'));
278
+    }
279
+
280
+    public function test_store_names_that_clash_with_app_addresses_get_a_different_address()
281
+    {
282
+        $login = Store::factory()->for($this->user)->create(['name' => 'Login']);
283
+        $www = Store::factory()->for($this->user)->create(['name' => 'WWW']);
284
+
285
+        $this->assertSame('login-2', $login->slug);
286
+        $this->assertSame('www-2', $www->slug);
287
+    }
288
+}

+ 6
- 0
tests/Support/FakeGateway.php Wyświetl plik

@@ -22,6 +22,10 @@ final class FakeGateway implements PaymentGateway
22 22
 
23 23
     public bool $failToStart = false;
24 24
 
25
+    public ?string $successUrl = null;
26
+
27
+    public ?string $cancelUrl = null;
28
+
25 29
     public function name(): string
26 30
     {
27 31
         return 'fake';
@@ -35,6 +39,8 @@ final class FakeGateway implements PaymentGateway
35 39
 
36 40
         $id = 'cs_fake_'.$order->id;
37 41
         $this->started[] = $order;
42
+        $this->successUrl = $successUrl;
43
+        $this->cancelUrl = $cancelUrl;
38 44
         $this->payments[$id] = new PaymentStatus($id, paid: false);
39 45
 
40 46
         return new CheckoutLink($id, 'https://pay.test/'.$id);

Ładowanie…
Anuluj
Zapisz