Explorar el Código

Add automatic discounts and AI product descriptions

- Discounts with no code: min items or spend, all or chosen products, dates
- One discount per order: the better of code and automatic discount
- Cart nudge, product page note, name on order, Stripe and email
- Chat commands can create automatic discounts and write product descriptions
feature/automatic-discounts
fahmisaad hace 2 días
padre
commit
4173f33abd
Se han modificado 33 ficheros con 1719 adiciones y 82 borrados
  1. 43
    28
      PROGRESS.md
  2. 3
    2
      README.md
  3. 72
    0
      app/Commerce/AutomaticDiscountRules.php
  4. 102
    6
      app/Commerce/Cart.php
  5. 28
    0
      app/Commerce/CartDiscount.php
  6. 116
    10
      app/Commerce/ChatActions.php
  7. 7
    6
      app/Commerce/Checkout.php
  8. 2
    1
      app/Commerce/Payments/StripeGateway.php
  9. 138
    0
      app/Http/Controllers/AutomaticDiscountController.php
  10. 1
    1
      app/Http/Controllers/CheckoutController.php
  11. 9
    1
      app/Http/Controllers/Concerns/RendersStorefront.php
  12. 2
    0
      app/Http/Controllers/DiscountCodeController.php
  13. 170
    0
      app/Models/AutomaticDiscount.php
  14. 2
    0
      app/Models/Order.php
  15. 8
    0
      app/Models/Store.php
  16. 31
    4
      app/StorePlan/Ai/PlanPrompt.php
  17. 6
    0
      app/Storefront/StorefrontText.php
  18. 46
    0
      database/migrations/2026_11_17_000003_create_automatic_discounts_table.php
  19. 388
    0
      resources/js/pages/stores/discounts/automatic-form.tsx
  20. 115
    3
      resources/js/pages/stores/discounts/index.tsx
  21. 3
    2
      resources/js/pages/stores/orders/show.tsx
  22. 3
    1
      resources/js/storefront/context.tsx
  23. 12
    6
      resources/js/storefront/pages/cart.tsx
  24. 3
    3
      resources/js/storefront/pages/checkout.tsx
  25. 3
    2
      resources/js/storefront/pages/order.tsx
  26. 29
    1
      resources/js/storefront/pages/product.tsx
  27. 9
    1
      resources/js/storefront/types.ts
  28. 19
    0
      resources/js/types/store.ts
  29. 1
    1
      resources/views/mail/orders/confirmation.blade.php
  30. 6
    0
      routes/web.php
  31. 302
    0
      tests/Feature/Stores/AutomaticDiscountTest.php
  32. 39
    2
      tests/Feature/Stores/ChatActionsTest.php
  33. 1
    1
      tests/Feature/Stores/FeaturedProductTest.php

+ 43
- 28
PROGRESS.md Ver fichero

@@ -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-17
7
-**Current step:** Step 8 — Discounts and product options (all done except automatic discounts, which are marked "later")
8
-**Next action:** Merge `feature/chat-commands` into `main`. Then choose: automatic discounts (Step 8, later item), Step 7 part 2 (waits for an EasyParcel API key and FPX in the Stripe dashboard), or Step 9 (before launch)
7
+**Current step:** Step 8 — Discounts and product options (done)
8
+**Next action:** Merge `feature/automatic-discounts` into `main`. Then choose: Step 7 part 2 (waits for an EasyParcel API key and FPX in the Stripe dashboard) or Step 9 (before launch)
9 9
 
10 10
 Status marks: `[ ]` not started · `[~]` in progress · `[x]` done
11 11
 
@@ -163,14 +163,26 @@ Changing from Claude to another AI model (or back) must be a settings change, no
163 163
 - Each order line for a bundle keeps `bundle_contents` (what was inside at the time). Paying lowers the stock of those items. The merchant's order page shows "Each has: 1 × Cleanser, 1 × Moisturiser (50ml)" for packing.
164 164
 - The product form shows "Bought one by one: RM X" and how many bundles can be sold, to help set the price. The storefront product page shows "What's inside" with links to the items.
165 165
 
166
+### How automatic discounts work (added in Step 8)
167
+
168
+- An automatic discount needs no code. It applies by itself when the cart qualifies: a name shown to shoppers ("Raya Sale"), percent or fixed amount off, an optional minimum number of items and/or minimum spend, all products or only chosen ones, optional dates, on or off. They are listed on the Discounts tab under the codes.
169
+- With chosen products, only those count towards the minimum and only those get cheaper. A fixed amount comes off once per order, never more than the eligible products cost.
170
+- **Only one discount applies per order.** The cart compares the code (if any) with every running automatic discount and uses whichever saves the most. If the code loses, the cart says "Raya Sale already saves you more, so this code is not used". A code only counts as used when it was the one applied.
171
+- The cart nudges shoppers who are close: "Add 1 more to get 10% off (Raya Sale)" or "Spend RM 10.00 more to get …".
172
+- Product pages show the running automatic discounts that cover that product.
173
+- The order keeps the name in `discount_name` (codes stay in `discount_code`). Stripe's page, the thank-you page, the email and the merchant's order page all show it.
174
+- Free shipping over an amount was already built in Step 7 (store Settings), so it is not an automatic discount type.
175
+- Chat: `create_automatic_discount` ("buy 2 sambal, get 15% off until end of January"), with the same confirm step as other chat commands.
176
+
166 177
 ### How chat commands work (added in Step 8)
167 178
 
168 179
 - The same "Ask the AI" box in the Design tab handles design changes and store changes. Each message counts as one AI edit.
169
-- Besides design changes, the AI may answer with `actions`: `create_product`, `update_product` (name, price, "was" price, stock, status, per variant for products with options), `create_discount`, `update_discount` (on/off, last day, number of uses) and `create_bundle`. At most 5 per message.
180
+- Besides design changes, the AI may answer with `actions`: `create_product`, `update_product` (name, price, "was" price, stock, status, per variant for products with options), `create_discount`, `update_discount` (on/off, last day, number of uses) and `create_bundle`. At most 10 per message.
170 181
 - The AI gets the full product list (drafts, stock, choices), the discount codes and today's Malaysian date, so "until the end of the month" works.
171 182
 - `App\Commerce\ChatActions` checks each action with the same rules as the Products and Discounts forms (discount rules are shared through `DiscountCodeRules`). A wrong product, choice or code goes back to the AI once to fix, like a bad design answer.
172 183
 - Actions are saved on the chat message (`store_generations.actions`, `actions_status`) and shown as plain sentences, such as "Change "Moisturiser (100ml)": price RM 55.00 → RM 52.00". Nothing changes until the merchant clicks Confirm. Cancel changes nothing.
173 184
 - On Confirm everything is checked again (the store may have changed), and either all actions happen or none. If one fails, the merchant sees why and the card stays waiting.
185
+- Product descriptions (added 2026-11-17): "write descriptions for my products without one" or "rewrite the sunscreen description". The AI writes 2 to 4 sentences from the product name, its choices, what is inside a bundle and the store's category, in the store's language, and must not invent facts (ingredients, halal, awards, health claims, numbers). The confirm card shows the full text before anything is saved. The AI is told which products have no description and what each bundle contains. Up to 10 actions per message, so a small store fits in one message.
174 186
 - The AI cannot add photos, delete products or codes, or change options; it tells the merchant to use the Products or Discounts tab.
175 187
 
176 188
 ### How the featured product section works (fixed in Step 7)
@@ -301,7 +313,7 @@ Agreed on 2026-11-15. Build in this order. It comes after Step 7 because automat
301 313
 - [x] Product variants (done 2026-11-16): up to 2 options per product (such as Size and Flavour), with a price, "price before discount" and stock for every combination. Shoppers pick with buttons on the product page; sold-out choices are crossed out. Each choice is its own cart line, order line and stock count. Tested with a real Stripe test payment
302 314
 - [x] Bundles with linked stock (done 2026-11-16): a product made of other products, with one bundle price. The product page shows what is included and the saving ("price before discount" crossed out). Selling a bundle lowers the stock of each item in it, and a bundle is sold out when any item is sold out. Tested with a real Stripe test payment
303 315
 - [x] Chat commands for products, discounts and bundles (done 2026-11-17): "create a bundle of the cleanser and moisturiser for RM 85", "make a 10% code RAYA10". The AI turns the sentence into actions, the chat shows them in plain words with Confirm and Cancel, and nothing changes until the merchant confirms. Tested with real DeepSeek
304
-- [ ] Later: automatic discounts ("buy 2, get 10% off", "free shipping over RM 100")
316
+- [x] Automatic discounts (done 2026-11-17): "buy 2, get 10% off" or "spend RM 100, get RM 15 off", on all or chosen products, with dates. Only one discount per order: the shopper gets whichever of the code and the automatic discounts saves more. "Free shipping over RM 100" already exists in store Settings. Tested with a real Stripe test payment and real DeepSeek
305 317
 
306 318
 Notes:
307 319
 
@@ -403,6 +415,7 @@ Then, from the project folder:
403 415
 | Cart logic                             | `app/Commerce/Cart.php`, `app/Http/Controllers/CartController.php`                                                                            |
404 416
 | Bundles                                | `app/Models/BundleItem.php`, `app/Commerce/BundleStock.php`, `resources/js/components/stores/bundle-editor.tsx`                               |
405 417
 | Chat commands                          | `app/Commerce/ChatActions.php`, `StoreGenerationController::confirm`, `resources/js/components/stores/design-chat.tsx`                        |
418
+| Automatic discounts                    | `app/Models/AutomaticDiscount.php`, `app/Commerce/AutomaticDiscountRules.php`, `Cart::applied`, `AutomaticDiscountController`                 |
406 419
 | Storefront words (English, Malay)      | `resources/js/storefront/text.ts`                                                                                                             |
407 420
 | Store plan format (frontend types)     | `resources/js/storefront/types.ts`                                                                                                            |
408 421
 | Storefront renderer and sections       | `resources/js/storefront/renderer.tsx`, `resources/js/storefront/sections/`                                                                   |
@@ -450,27 +463,29 @@ Notes:
450 463
 
451 464
 Add one line per work session: date, what was done, what is next.
452 465
 
453
-| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                         | Next                                                            |
454
-| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------- |
455
-| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                          | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
456
-| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                     | Step 2: store plan format, sections, renderer                   |
457
-| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                              | Step 3: swappable AI layer and store generation                 |
458
-| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                        | Step 3: swappable AI layer and store generation                 |
459
-| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                      | Add API keys, run the real test, then Step 4                    |
460
-| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                           | Real AI test, then Step 4                                       |
461
-| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                            | Merge into `main`, then Step 4: products                        |
462
-| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                  | Step 4 part 2: cart, Stripe checkout, orders, email             |
463
-| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                        | Stripe checkout (needs test keys), orders, email                |
464
-| 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                      |
465
-| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                 | Step 5: publishing                                              |
466
-| 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                                              |
467
-| 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                                              |
468
-| 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                                    |
469
-| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                 | Merge into `main`, then Step 7                                  |
470
-| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                  | Merge, then Step 7 part 2 or Step 8                             |
471
-| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                          | Merge both branches, then Step 7 part 2 or Step 8               |
472
-| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                   | Merge branches, then Step 7 part 2 or Step 8                    |
473
-| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                               | Merge, then product variants                                    |
474
-| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                    | Merge both branches, then bundles                               |
475
-| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                     | Merge, then chat commands                                       |
476
-| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled. | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
466
+| Date       | Done                                                                                                                                                                                                                                                                                                                                                                                                                               | Next                                                            |
467
+| ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
468
+| 2026-11-14 | Planning. Chose stack, market, payments, AI models, plan prices. Checked local tools. Created this file. All proposed decisions confirmed. Added the rule that the AI model must be easy to change.                                                                                                                                                                                                                                | Install PHP 8.4, create the Laravel project (Step 0 and Step 1) |
469
+| 2026-11-14 | Installed PHP 8.4. Created the Laravel 13 + React project, MySQL database and git repo. Built create-a-store flow and dashboard. 51 tests pass; login and store creation checked in the browser. Step 0 and Step 1 done.                                                                                                                                                                                                           | Step 2: store plan format, sections, renderer                   |
470
+| 2026-11-14 | Step 2 done on branch `feature/store-sections-renderer`: store plan format and validator, 10 sections with 2 variants each, renderer, dashboard preview, sample design. 69 tests pass; storefront checked in the browser on desktop and mobile.                                                                                                                                                                                    | Step 3: swappable AI layer and store generation                 |
471
+| 2026-11-14 | First commit made and pushed to the private repository on git.mirfalah.my (branch `feature/store-sections-renderer`).                                                                                                                                                                                                                                                                                                              | Step 3: swappable AI layer and store generation                 |
472
+| 2026-11-14 | Step 3 built on branch `feature/ai-generation`: swappable AI layer (Claude, DeepSeek, fake), full store generation, chat edits, background job with progress screen, plan limits. 92 tests pass; whole flow checked in the browser with the fake provider. Not yet run against real Claude or DeepSeek.                                                                                                                            | Add API keys, run the real test, then Step 4                    |
473
+| 2026-11-14 | Split settings into `.env` (uploaded, no secrets, AI settings blank) and `.env.local` (private, complete). Removed `.env.example`.                                                                                                                                                                                                                                                                                                 | Real AI test, then Step 4                                       |
474
+| 2026-11-14 | Real AI test passed: Claude Sonnet 5.5 generated two stores, DeepSeek made two chat edits. Tuned the prompt for more varied layouts. Step 3 done.                                                                                                                                                                                                                                                                                  | Merge into `main`, then Step 4: products                        |
475
+| 2026-11-14 | Step 4 part 1 on branch `feature/commerce`: store plan version 2 with pages, products with photos, Shop page, product page, real products on the home page. 108 tests pass; checked in the browser; real Claude and DeepSeek re-tested with the new format.                                                                                                                                                                        | Step 4 part 2: cart, Stripe checkout, orders, email             |
476
+| 2026-11-14 | Cart built on branch `feature/commerce`: add to cart, quantity, remove, subtotal, header count, stock limits. 118 tests pass; checked in the browser.                                                                                                                                                                                                                                                                              | Stripe checkout (needs test keys), orders, email                |
477
+| 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                      |
478
+| 2026-11-15 | Merged Steps 3 and 4 into `main` and pushed.                                                                                                                                                                                                                                                                                                                                                                                       | Step 5: publishing                                              |
479
+| 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                                              |
480
+| 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                                              |
481
+| 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                                    |
482
+| 2026-11-16 | Step 6 on branch `feature/billing`: plans table, 14-day trial, Stripe subscriptions (subscribe, switch, cancel, undo), Billing page, limits enforced, live stores offline when there is no plan. 164 tests pass; real Stripe test subscription to Growth, cancel and undo all worked. Switched the session model from Fable 5.2 to Opus 5.5.                                                                                       | Merge into `main`, then Step 7                                  |
483
+| 2026-11-16 | Step 7 part 1 on branch `feature/malaysia-shipping`: store settings, flat shipping fees (west, east, free over), mark as shipped with tracking and email, WhatsApp buttons, Malay checkout messages, Malaysian phone check. Fixed live-store menu links on pages other than home (bug from Step 5). 178 tests pass; real Stripe test payment with shipping to Sabah worked.                                                        | Merge, then Step 7 part 2 or Step 8                             |
484
+| 2026-11-16 | Featured product fix on branch `feature/featured-product-link` (built on `feature/malaysia-shipping`): the section links to a real product (Design tab picker or chat), shows its real name, price, photo and page, and hides the made-up price otherwise. Added a check that marks chat edits that changed nothing. 191 tests pass; checked in the browser and with real DeepSeek.                                                | Merge both branches, then Step 7 part 2 or Step 8               |
485
+| 2026-11-16 | Planning only. Added "more design styles" to later improvements: style options (effects, backgrounds, buttons, spacing, motion), more fonts, more layouts per section, more section types.                                                                                                                                                                                                                                         | Merge branches, then Step 7 part 2 or Step 8                    |
486
+| 2026-11-16 | Step 8 part 1 on branch `feature/discount-codes`: discount codes (merchant Discounts tab, cart code box, order record, Stripe coupon, use counted when paid). 207 tests pass; real Stripe test payment with a 20% code worked.                                                                                                                                                                                                     | Merge, then product variants                                    |
487
+| 2026-11-16 | Step 8 part 2 on branch `feature/product-variants` (built on `feature/discount-codes`): product options and variants, option buttons on the product page, variant cart lines, orders and stock. 217 tests pass; real Stripe test payment for a 100ml variant with a discount code worked.                                                                                                                                          | Merge both branches, then bundles                               |
488
+| 2026-11-16 | Step 8 part 3 on branch `feature/bundles`: bundles with linked stock (bundle editor in the product form, "What's inside" on the product page, shared stock check at checkout, order shows what to pack). 223 tests pass; real Stripe test payment for "Glow Starter Set" (cleanser + 50ml moisturiser, RM 69 + RM 8 shipping) lowered both items' stock.                                                                           | Merge, then chat commands                                       |
489
+| 2026-11-17 | Step 8 part 4 on branch `feature/chat-commands`: chat commands for products, discount codes and bundles, with Confirm and Cancel in the chat. Shared discount rules. Fixed a test that failed by chance (random stock). 233 tests pass; with real DeepSeek, "GLOW15 until end of month + 100ml to RM 52" was proposed, confirmed and saved; a product + bundle request was proposed correctly and cancelled.                       | Merge; then automatic discounts, Step 7 part 2 or Step 9        |
490
+| 2026-11-17 | Step 8 part 5 on branch `feature/automatic-discounts`: automatic discounts (Discounts tab form, best-of-one rule with codes, cart nudge, product page note, order/Stripe/email name, chat command). Step 8 is done. 243 tests pass; real Stripe test payment with "Glow Week" (2 cleansers, −RM 8.40, total RM 83.60) worked, GLOW15 correctly won when typed; real DeepSeek proposed a sunscreen-only sale correctly (cancelled). | Merge; then Step 7 part 2 or Step 9                             |
491
+| 2026-11-17 | Chat commands can write product descriptions from the product name (same branch, `feature/automatic-discounts`). Real DeepSeek test found the AI guessing bundle contents, so bundle contents are now listed for it; second try was accurate. 244 tests pass.                                                                                                                                                                      | Merge; then Step 7 part 2 or Step 9                             |

+ 3
- 2
README.md Ver fichero

@@ -20,7 +20,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
20 20
 | 5    | Publishing: subdomains, then custom domains             | Done for local use; custom domains wait for hosting            |
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
-| 8    | Discounts and product options: codes, variants, bundles | Done (automatic discounts later)                               |
23
+| 8    | Discounts and product options: codes, variants, bundles | Done                                                           |
24 24
 | 9    | Before launch: hosting, legal pages, backups            | Not started                                                    |
25 25
 
26 26
 ## What works today
@@ -33,7 +33,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
33 33
 - A live preview of the storefront inside the dashboard, at desktop and mobile size
34 34
 - "Generate my store": the AI designs the whole store in the background, with a progress screen
35 35
 - Change the design by chat, for example "make the main colour dark green"
36
-- 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". The AI shows what it will do, and nothing changes until you press Confirm
36
+- 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
37 37
 - Add or remove whole pages by chat, for example "add an About page". The menu link is added automatically
38 38
 - "Regenerate" for a completely new design, limited by the plan
39 39
 - Usage counting and limits for regenerations and AI edits
@@ -51,6 +51,7 @@ An AI store generator for ecommerce. A customer describes their brand, and the A
51 51
 - Shipping fees for Peninsular and East Malaysia, with optional free shipping, and "mark as shipped" with a tracking number
52 52
 - WhatsApp chat button on the store, and WhatsApp links on order pages
53 53
 - Discount codes: percent or fixed amount off, with optional minimum spend, dates and number of uses
54
+- 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
54 55
 - 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
55 56
 
56 57
 Known gaps: no phone menu for header links yet, images are placeholders, and the newsletter form does not save sign-ups.

+ 72
- 0
app/Commerce/AutomaticDiscountRules.php Ver fichero

@@ -0,0 +1,72 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Models\AutomaticDiscount;
6
+use App\Models\DiscountCode;
7
+use App\Models\Store;
8
+use Illuminate\Support\Carbon;
9
+use Illuminate\Validation\Rule;
10
+
11
+/**
12
+ * The rules for an automatic discount, shared by its form and chat commands.
13
+ * Amounts arrive in ringgit as typed; dates are Malaysian days (Y-m-d).
14
+ */
15
+final class AutomaticDiscountRules
16
+{
17
+    /**
18
+     * @return array<string, list<mixed>>
19
+     */
20
+    public static function rules(Store $store, bool $percent): array
21
+    {
22
+        return [
23
+            'name' => ['required', 'string', 'min:2', 'max:40'],
24
+            'type' => ['required', Rule::in([DiscountCode::PERCENT, DiscountCode::FIXED])],
25
+            'value' => $percent
26
+                ? ['required', 'integer', 'min:1', 'max:100']
27
+                : ['required', 'numeric', 'decimal:0,2', 'min:0.01', 'max:999999.99'],
28
+            'minimum_quantity' => ['nullable', 'integer', 'min:1', 'max:999'],
29
+            'minimum_subtotal' => ['nullable', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
30
+            'applies_to' => ['required', Rule::in(['all', 'chosen'])],
31
+            'product_ids' => ['exclude_unless:applies_to,chosen', 'required', 'array', 'min:1', 'max:200'],
32
+            'product_ids.*' => ['integer', Rule::exists('products', 'id')->where('store_id', $store->id)],
33
+            'starts_on' => ['nullable', 'date_format:Y-m-d'],
34
+            'ends_on' => ['nullable', 'date_format:Y-m-d', 'after_or_equal:starts_on'],
35
+            'active' => ['boolean'],
36
+        ];
37
+    }
38
+
39
+    /**
40
+     * @return array<string, string>
41
+     */
42
+    public static function messages(bool $percent): array
43
+    {
44
+        return [
45
+            'value.max' => $percent ? __('A percentage cannot be more than 100.') : __('The amount is too large.'),
46
+            'product_ids.required' => __('Choose at least one product.'),
47
+            'product_ids.*.exists' => __('Choose products from this store.'),
48
+            'ends_on.after_or_equal' => __('The last day cannot be before the first day.'),
49
+        ];
50
+    }
51
+
52
+    /**
53
+     * @param  array<string, mixed>  $data
54
+     */
55
+    public static function fill(AutomaticDiscount $offer, array $data): void
56
+    {
57
+        $percent = $data['type'] === DiscountCode::PERCENT;
58
+        $timezone = DiscountCodeRules::TIMEZONE;
59
+
60
+        $offer->name = trim($data['name']);
61
+        $offer->type = $data['type'];
62
+        $offer->value = $percent ? (int) $data['value'] : (int) round(((float) $data['value']) * 100);
63
+        $offer->minimum_quantity = filled($data['minimum_quantity'] ?? null) ? (int) $data['minimum_quantity'] : null;
64
+        $offer->minimum_subtotal = filled($data['minimum_subtotal'] ?? null) ? (int) round(((float) $data['minimum_subtotal']) * 100) : null;
65
+        $offer->product_ids = ($data['applies_to'] ?? 'all') === 'chosen'
66
+            ? array_values(array_unique(array_map('intval', $data['product_ids'] ?? [])))
67
+            : null;
68
+        $offer->starts_at = filled($data['starts_on'] ?? null) ? Carbon::parse($data['starts_on'], $timezone)->startOfDay()->utc() : null;
69
+        $offer->ends_at = filled($data['ends_on'] ?? null) ? Carbon::parse($data['ends_on'], $timezone)->endOfDay()->utc() : null;
70
+        $offer->active = (bool) ($data['active'] ?? false);
71
+    }
72
+}

+ 102
- 6
app/Commerce/Cart.php Ver fichero

@@ -2,6 +2,7 @@
2 2
 
3 3
 namespace App\Commerce;
4 4
 
5
+use App\Models\AutomaticDiscount;
5 6
 use App\Models\DiscountCode;
6 7
 use App\Models\Product;
7 8
 use App\Models\ProductVariant;
@@ -16,6 +17,8 @@ use Illuminate\Support\Collection;
16 17
  * It is kept in the browser session, so shoppers do not need an account, and each store
17 18
  * has its own cart. Only product and variant ids and quantities are saved. Names, prices and stock are
18 19
  * always read fresh from the database, so the cart can never show an old price.
20
+ *
21
+ * @phpstan-type CartLine array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}
19 22
  */
20 23
 class Cart
21 24
 {
@@ -28,6 +31,9 @@ class Cart
28 31
     /** True when the discount code was taken out because it can no longer be used. */
29 32
     private bool $discountRemoved = false;
30 33
 
34
+    /** @var Collection<int, AutomaticDiscount>|null Loaded once per request. */
35
+    private ?Collection $offers = null;
36
+
31 37
     public function __construct(
32 38
         private readonly Session $session,
33 39
         private readonly Store $store,
@@ -205,6 +211,82 @@ class Cart
205 211
         return new AppliedDiscount($discount, $problem === null ? $discount->amountFor($subtotal) : 0, $problem);
206 212
     }
207 213
 
214
+    /**
215
+     * Automatic discounts that are on and within their dates, biggest first.
216
+     *
217
+     * @return Collection<int, AutomaticDiscount>
218
+     */
219
+    public function liveOffers(): Collection
220
+    {
221
+        return $this->offers ??= $this->store->automaticDiscounts()
222
+            ->where('active', true)
223
+            ->orderByDesc('value')
224
+            ->get()
225
+            ->filter(fn (AutomaticDiscount $offer) => $offer->isLive())
226
+            ->values()
227
+            ->toBase();
228
+    }
229
+
230
+    /**
231
+     * The one discount these lines get: the code or the best automatic discount, whichever saves more.
232
+     * Only one applies, so a code and a sale never add up to more than the merchant planned.
233
+     *
234
+     * @param  Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}>  $lines
235
+     */
236
+    public function applied(Collection $lines): ?CartDiscount
237
+    {
238
+        if ($lines->isEmpty()) {
239
+            return null;
240
+        }
241
+
242
+        $code = $this->discount((int) $lines->sum('line_total'));
243
+        $codeAmount = $code !== null && $code->problem === null ? $code->amount : 0;
244
+
245
+        $best = null;
246
+        $bestAmount = 0;
247
+
248
+        foreach ($this->liveOffers() as $offer) {
249
+            $amount = $offer->amountFor($lines);
250
+
251
+            if ($amount > $bestAmount) {
252
+                [$best, $bestAmount] = [$offer, $amount];
253
+            }
254
+        }
255
+
256
+        if ($best !== null && $bestAmount > $codeAmount) {
257
+            return new CartDiscount($bestAmount, offer: $best);
258
+        }
259
+
260
+        return $code !== null && $codeAmount > 0 ? new CartDiscount($codeAmount, code: $code->code) : null;
261
+    }
262
+
263
+    /**
264
+     * A nudge such as "Add 1 more to get 10% off (Raya Sale)", for an automatic discount the cart
265
+     * has started on but does not reach yet. Null when there is nothing worth saying.
266
+     *
267
+     * @param  Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}>  $lines
268
+     */
269
+    private function offerHint(Collection $lines, ?CartDiscount $applied): ?string
270
+    {
271
+        $language = $this->store->language->value;
272
+
273
+        foreach ($this->liveOffers() as $offer) {
274
+            $shortfall = $offer->shortfall($lines);
275
+
276
+            if ($shortfall === null || $offer->eligible($lines)->isEmpty() || $applied?->offer?->is($offer)) {
277
+                continue;
278
+            }
279
+
280
+            $replace = [':label' => $offer->label($language), ':name' => $offer->name];
281
+
282
+            return isset($shortfall['items'])
283
+                ? StorefrontText::line($language, 'offer_add_items', [...$replace, ':count' => (string) $shortfall['items']])
284
+                : StorefrontText::line($language, 'offer_spend_more', [...$replace, ':amount' => 'RM '.number_format(($shortfall['amount'] ?? 0) / 100, 2)]);
285
+        }
286
+
287
+        return null;
288
+    }
289
+
208 290
     /**
209 291
      * The cart lines, with fresh product details.
210 292
      * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
@@ -272,14 +354,17 @@ class Cart
272 354
     /**
273 355
      * What the storefront is allowed to see. Money is in ringgit here.
274 356
      *
275
-     * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
357
+     * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, applied: array<string, mixed>|null, offer_hint: string|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
276 358
      */
277 359
     public function toStorefront(): array
278 360
     {
279 361
         $lines = $this->lines();
280 362
         $subtotal = (int) $lines->sum('line_total');
363
+        $applied = $this->applied($lines);
281 364
         $discount = $lines->isEmpty() ? null : $this->discount($subtotal);
282 365
         $language = $this->store->language->value;
366
+        // The code works, but an automatic discount saves more, so the code is not used.
367
+        $codeBeaten = $discount !== null && $discount->problem === null && $applied?->offer !== null;
283 368
 
284 369
         return [
285 370
             'count' => (int) $lines->sum('quantity'),
@@ -288,13 +373,24 @@ class Cart
288 373
                 'code' => $discount->code->code,
289 374
                 'label' => $discount->code->label($language),
290 375
                 'amount' => $discount->amount / 100,
291
-                // Why it does not count yet, for example "Spend at least RM 50.00 ...".
292
-                'message' => $discount->problem === null ? null : StorefrontText::line($language, $discount->problem, [
293
-                    ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
294
-                ]),
376
+                // Why it does not count, for example "Spend at least RM 50.00 ..." or "Raya Sale saves you more".
377
+                'message' => match (true) {
378
+                    $codeBeaten => StorefrontText::line($language, 'discount_offer_better', [':name' => $applied->name()]),
379
+                    $discount->problem === null => null,
380
+                    default => StorefrontText::line($language, $discount->problem, [
381
+                        ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
382
+                    ]),
383
+                },
384
+            ],
385
+            // The discount actually taken off: the code, or an automatic discount.
386
+            'applied' => $applied === null ? null : [
387
+                'name' => $applied->name(),
388
+                'amount' => $applied->amount / 100,
389
+                'automatic' => $applied->offer !== null,
295 390
             ],
391
+            'offer_hint' => $this->offerHint($lines, $applied),
296 392
             // Products after the discount, before shipping.
297
-            'total' => ($subtotal - ($discount !== null ? $discount->amount : 0)) / 100,
393
+            'total' => ($subtotal - ($applied !== null ? $applied->amount : 0)) / 100,
298 394
             'adjusted' => $this->adjusted || $this->discountRemoved,
299 395
             'lines' => $lines->map(fn (array $line) => [
300 396
                 'key' => $line['key'],

+ 28
- 0
app/Commerce/CartDiscount.php Ver fichero

@@ -0,0 +1,28 @@
1
+<?php
2
+
3
+namespace App\Commerce;
4
+
5
+use App\Models\AutomaticDiscount;
6
+use App\Models\DiscountCode;
7
+
8
+/**
9
+ * The one discount a cart gets: the shopper's code, or an automatic discount, whichever saves more.
10
+ * Amounts are in sen.
11
+ */
12
+final readonly class CartDiscount
13
+{
14
+    public function __construct(
15
+        /** What comes off the products. */
16
+        public int $amount,
17
+        public ?DiscountCode $code = null,
18
+        public ?AutomaticDiscount $offer = null,
19
+    ) {}
20
+
21
+    /**
22
+     * "RAYA10" for a code, "Raya Sale" for an automatic discount.
23
+     */
24
+    public function name(): string
25
+    {
26
+        return $this->code !== null ? $this->code->code : (string) $this->offer?->name;
27
+    }
28
+}

+ 116
- 10
app/Commerce/ChatActions.php Ver fichero

@@ -4,6 +4,7 @@ namespace App\Commerce;
4 4
 
5 5
 use App\Enums\ProductStatus;
6 6
 use App\Http\Requests\Products\SaveProductRequest;
7
+use App\Models\AutomaticDiscount;
7 8
 use App\Models\BundleItem;
8 9
 use App\Models\DiscountCode;
9 10
 use App\Models\Product;
@@ -25,9 +26,13 @@ use Illuminate\Validation\ValidationException;
25 26
  */
26 27
 final class ChatActions
27 28
 {
28
-    public const int MAX_ACTIONS = 5;
29
+    /** Ten, so "write descriptions for all my products" fits in one message for a small store. */
30
+    public const int MAX_ACTIONS = 10;
29 31
 
30
-    public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle'];
32
+    /** Product descriptions written in the chat stay short enough to read on the confirm card. */
33
+    public const int MAX_DESCRIPTION = 1500;
34
+
35
+    public const array TYPES = ['create_product', 'update_product', 'create_discount', 'update_discount', 'create_bundle', 'create_automatic_discount'];
31 36
 
32 37
     /**
33 38
      * Check the actions in an AI answer. Returns each with its cleaned input and a sentence for the merchant.
@@ -101,6 +106,7 @@ final class ChatActions
101 106
                 'create_discount' => self::createDiscount($store, $action),
102 107
                 'update_discount' => self::updateDiscount($store, $action),
103 108
                 'create_bundle' => self::createBundle($store, $action),
109
+                'create_automatic_discount' => self::createAutomaticDiscount($store, $action),
104 110
             };
105 111
         } catch (ValidationException $e) {
106 112
             // "price" becomes "actions.2.price", so it is clear which action has the problem.
@@ -124,7 +130,7 @@ final class ChatActions
124 130
     {
125 131
         $data = self::validate($input, [
126 132
             'name' => ['required', 'string', 'min:2', 'max:120'],
127
-            'description' => ['nullable', 'string', 'max:5000'],
133
+            'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
128 134
             'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
129 135
             'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
130 136
             'stock' => ['required', 'integer', 'min:0', 'max:1000000'],
@@ -135,7 +141,8 @@ final class ChatActions
135 141
         $summary = "Add the product \"{$data['name']}\" at ".self::money(self::sen($data['price']))
136 142
             .self::wasPrice($data['compare_at_price'] ?? null)
137 143
             .", {$data['stock']} in stock, "
138
-            .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft');
144
+            .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
145
+            .self::descriptionNote($data['description'] ?? null);
139 146
 
140 147
         return [
141 148
             'input' => $data,
@@ -143,7 +150,7 @@ final class ChatActions
143 150
             'run' => function () use ($store, $data): void {
144 151
                 $store->products()->create([
145 152
                     'name' => $data['name'],
146
-                    'description' => $data['description'] ?? null,
153
+                    'description' => self::cleanText($data['description'] ?? null),
147 154
                     'price' => self::sen($data['price']),
148 155
                     'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
149 156
                     'stock' => (int) $data['stock'],
@@ -163,6 +170,7 @@ final class ChatActions
163 170
             'product' => ['required', 'string'],
164 171
             'variant' => ['nullable', 'string', 'max:90'],
165 172
             'name' => ['sometimes', 'string', 'min:2', 'max:120'],
173
+            'description' => ['sometimes', 'nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
166 174
             'price' => ['sometimes', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
167 175
             'compare_at_price' => ['sometimes', 'nullable', 'numeric', 'decimal:0,2', 'max:999999.99'],
168 176
             'stock' => ['sometimes', 'integer', 'min:0', 'max:1000000'],
@@ -171,10 +179,10 @@ final class ChatActions
171 179
 
172 180
         $product = self::findProduct($store, $data['product'], 'product');
173 181
         $priceFields = array_intersect(['price', 'compare_at_price', 'stock'], array_keys($data));
174
-        $productFields = array_intersect(['name', 'status'], array_keys($data));
182
+        $productFields = array_intersect(['name', 'description', 'status'], array_keys($data));
175 183
 
176 184
         if ($priceFields === [] && $productFields === []) {
177
-            self::fail('product', 'Say what to change: name, price, compare_at_price, stock or status.');
185
+            self::fail('product', 'Say what to change: name, description, price, compare_at_price, stock or status.');
178 186
         }
179 187
 
180 188
         $variant = null;
@@ -228,6 +236,13 @@ final class ChatActions
228 236
             $changes[] = $data['status'] === 'active' ? 'show it in the store' : 'hide it (draft)';
229 237
         }
230 238
 
239
+        $description = array_key_exists('description', $data) ? self::cleanText($data['description']) : $product->description;
240
+
241
+        // The full new text goes in the sentence, so the merchant reads exactly what will be saved.
242
+        if ($description !== $product->description) {
243
+            $changes[] = $description === null ? 'remove the description' : "description: \"{$description}\"";
244
+        }
245
+
231 246
         if ($changes === []) {
232 247
             self::fail('product', 'These values are already set. Nothing would change.');
233 248
         }
@@ -252,6 +267,10 @@ final class ChatActions
252 267
                     $product->name = $data['name'];
253 268
                 }
254 269
 
270
+                if (array_key_exists('description', $data)) {
271
+                    $product->description = self::cleanText($data['description']);
272
+                }
273
+
255 274
                 if (array_key_exists('status', $data)) {
256 275
                     $product->status = ProductStatus::from($data['status']);
257 276
                 }
@@ -393,7 +412,7 @@ final class ChatActions
393 412
     {
394 413
         $data = self::validate($input, [
395 414
             'name' => ['required', 'string', 'min:2', 'max:120'],
396
-            'description' => ['nullable', 'string', 'max:5000'],
415
+            'description' => ['nullable', 'string', 'max:'.self::MAX_DESCRIPTION],
397 416
             'price' => ['required', 'numeric', 'decimal:0,2', 'min:0', 'max:999999.99'],
398 417
             'compare_at_price' => ['nullable', 'numeric', 'decimal:0,2', 'max:999999.99', 'gt:price'],
399 418
             'status' => ['nullable', 'in:active,draft'],
@@ -442,7 +461,8 @@ final class ChatActions
442 461
             .self::wasPrice($data['compare_at_price'] ?? null)
443 462
             .': '.implode(', ', $labels)
444 463
             .". Enough stock for {$stock} now, "
445
-            .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft');
464
+            .($data['status'] === 'active' ? 'shown in the store' : 'saved as a draft')
465
+            .self::descriptionNote($data['description'] ?? null);
446 466
 
447 467
         return [
448 468
             'input' => $data,
@@ -450,7 +470,7 @@ final class ChatActions
450 470
             'run' => function () use ($store, $data, $items): void {
451 471
                 $bundle = $store->products()->make([
452 472
                     'name' => $data['name'],
453
-                    'description' => $data['description'] ?? null,
473
+                    'description' => self::cleanText($data['description'] ?? null),
454 474
                     'price' => self::sen($data['price']),
455 475
                     'compare_at_price' => filled($data['compare_at_price'] ?? null) ? self::sen($data['compare_at_price']) : null,
456 476
                     'stock' => 0,
@@ -464,6 +484,75 @@ final class ChatActions
464 484
         ];
465 485
     }
466 486
 
487
+    /**
488
+     * A discount with no code, such as "Raya Sale: buy 2 or more, get 10% off", for all or some products.
489
+     *
490
+     * @param  array<string, mixed>  $input
491
+     * @return array{input: array<string, mixed>, summary: string, run: Closure(): void}
492
+     */
493
+    private static function createAutomaticDiscount(Store $store, array $input): array
494
+    {
495
+        $slugs = $input['products'] ?? null;
496
+
497
+        if ($slugs !== null && (! is_array($slugs) || ! array_is_list($slugs) || $slugs === [])) {
498
+            self::fail('products', 'Give a list of web-address names, or null for every product.');
499
+        }
500
+
501
+        $products = [];
502
+
503
+        foreach ($slugs ?? [] as $index => $slug) {
504
+            $products[] = self::findProduct($store, (string) $slug, "products.$index");
505
+        }
506
+
507
+        $percent = ($input['discount_type'] ?? null) === DiscountCode::PERCENT;
508
+        $form = [
509
+            'name' => $input['name'] ?? null,
510
+            'type' => $input['discount_type'] ?? null,
511
+            'value' => $input['value'] ?? null,
512
+            'minimum_quantity' => $input['minimum_quantity'] ?? null,
513
+            'minimum_subtotal' => $input['minimum_spend'] ?? null,
514
+            'applies_to' => $slugs === null ? 'all' : 'chosen',
515
+            'product_ids' => array_map(fn (Product $product) => $product->id, $products),
516
+            'starts_on' => $input['starts_on'] ?? null,
517
+            'ends_on' => $input['ends_on'] ?? null,
518
+            'active' => true,
519
+        ];
520
+
521
+        $validator = Validator::make($form, AutomaticDiscountRules::rules($store, $percent), AutomaticDiscountRules::messages($percent));
522
+
523
+        if ($validator->fails()) {
524
+            $renamed = ['type' => 'discount_type', 'minimum_subtotal' => 'minimum_spend', 'product_ids' => 'products'];
525
+            $messages = [];
526
+
527
+            foreach ($validator->errors()->toArray() as $field => $errors) {
528
+                $messages[$renamed[$field] ?? $field] = $errors;
529
+            }
530
+
531
+            throw ValidationException::withMessages($messages);
532
+        }
533
+
534
+        $data = $validator->validated();
535
+        $preview = new AutomaticDiscount;
536
+        AutomaticDiscountRules::fill($preview, $data);
537
+
538
+        $details = array_filter([
539
+            $products !== [] ? 'only on '.implode(', ', array_map(fn (Product $product) => $product->name, $products)) : 'on every product',
540
+            filled($data['starts_on'] ?? null) ? "from {$data['starts_on']}" : null,
541
+            filled($data['ends_on'] ?? null) ? "until {$data['ends_on']}" : null,
542
+        ]);
543
+
544
+        return [
545
+            'input' => array_intersect_key($input, array_flip(['name', 'discount_type', 'value', 'minimum_quantity', 'minimum_spend', 'products', 'starts_on', 'ends_on'])),
546
+            'summary' => "Start the automatic discount \"{$preview->name}\": {$preview->describe()}, ".implode(', ', $details).'. No code needed',
547
+            'run' => function () use ($store, $data): void {
548
+                $offer = new AutomaticDiscount;
549
+                $offer->store_id = $store->id;
550
+                AutomaticDiscountRules::fill($offer, $data);
551
+                $offer->save();
552
+            },
553
+        ];
554
+    }
555
+
467 556
     /**
468 557
      * @param  array<string, mixed>  $input
469 558
      * @param  array<string, list<mixed>>  $rules
@@ -506,6 +595,23 @@ final class ChatActions
506 595
         return $variant;
507 596
     }
508 597
 
598
+    private static function descriptionNote(mixed $description): string
599
+    {
600
+        $text = self::cleanText($description);
601
+
602
+        return $text === null ? '' : ". Description: \"{$text}\"";
603
+    }
604
+
605
+    /**
606
+     * Trimmed text, or null when empty.
607
+     */
608
+    private static function cleanText(mixed $text): ?string
609
+    {
610
+        $text = trim((string) $text);
611
+
612
+        return $text === '' ? null : $text;
613
+    }
614
+
509 615
     private static function plain(string $text): string
510 616
     {
511 617
         return mb_strtolower((string) preg_replace('/\s+/', '', $text));

+ 7
- 6
app/Commerce/Checkout.php Ver fichero

@@ -59,17 +59,17 @@ class Checkout
59 59
             throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'not_enough_stock')]);
60 60
         }
61 61
 
62
-        $applied = $cart->discount($subtotal);
62
+        // The code, or an automatic discount, whichever saves more. Only one applies.
63
+        $applied = $cart->applied($lines);
63 64
 
64 65
         // The code stopped working since the shopper last saw the cart: stop, so the total never surprises them.
65 66
         if ($cart->discountWasRemoved()) {
66 67
             throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_changed')]);
67 68
         }
68 69
 
69
-        // A code that still needs a bigger cart is worth nothing; the cart already showed that.
70
-        $usable = $applied !== null && $applied->problem === null ? $applied : null;
71
-        $discount = $usable !== null ? $usable->amount : 0;
72
-        $discountCode = $usable !== null && $discount > 0 ? $usable->code->code : null;
70
+        $discount = $applied !== null ? $applied->amount : 0;
71
+        $discountCode = $applied?->code?->code;
72
+        $discountName = $applied?->offer?->name;
73 73
 
74 74
         // Free shipping is decided on what the shopper pays for the products, after the discount.
75 75
         $shipping = $this->shipping->quote($store, $subtotal - $discount, $details['state']);
@@ -78,7 +78,7 @@ class Checkout
78 78
             throw ValidationException::withMessages(['cart' => StorefrontText::line($language, 'discount_total_too_low')]);
79 79
         }
80 80
 
81
-        return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $shipping, $details): Order {
81
+        return DB::transaction(function () use ($store, $lines, $subtotal, $discount, $discountCode, $discountName, $shipping, $details): Order {
82 82
             // Lock the store row so two orders placed at the same moment cannot get the same number.
83 83
             Store::query()->whereKey($store->id)->lockForUpdate()->first();
84 84
 
@@ -100,6 +100,7 @@ class Checkout
100 100
             ];
101 101
             $order->subtotal = $subtotal;
102 102
             $order->discount_code = $discountCode;
103
+            $order->discount_name = $discountName;
103 104
             $order->discount_total = $discount;
104 105
             $order->shipping_total = $shipping;
105 106
             $order->total = $subtotal - $discount + $shipping;

+ 2
- 1
app/Commerce/Payments/StripeGateway.php Ver fichero

@@ -78,7 +78,8 @@ final class StripeGateway implements PaymentGateway
78 78
             'currency' => strtolower($order->currency),
79 79
             'duration' => 'once',
80 80
             'max_redemptions' => 1,
81
-            'name' => (string) $order->discount_code,
81
+            // The code, or the automatic discount's name, such as "Raya Sale".
82
+            'name' => $order->discount_code ?? $order->discount_name ?? 'Discount',
82 83
             'metadata' => ['order_id' => (string) $order->id],
83 84
         ])->id;
84 85
     }

+ 138
- 0
app/Http/Controllers/AutomaticDiscountController.php Ver fichero

@@ -0,0 +1,138 @@
1
+<?php
2
+
3
+namespace App\Http\Controllers;
4
+
5
+use App\Commerce\AutomaticDiscountRules;
6
+use App\Commerce\DiscountCodeRules;
7
+use App\Models\AutomaticDiscount;
8
+use App\Models\DiscountCode;
9
+use App\Models\Product;
10
+use App\Models\Store;
11
+use Illuminate\Http\RedirectResponse;
12
+use Illuminate\Http\Request;
13
+use Inertia\Inertia;
14
+use Inertia\Response;
15
+
16
+/**
17
+ * The merchant's automatic discounts for one store, listed on the Discounts tab next to the codes.
18
+ */
19
+class AutomaticDiscountController extends Controller
20
+{
21
+    public function create(Request $request, string $slug): Response
22
+    {
23
+        $store = $this->ownedStore($request, $slug);
24
+
25
+        return Inertia::render('stores/discounts/automatic-form', [
26
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
27
+            'offer' => null,
28
+            'products' => $this->productChoices($store),
29
+        ]);
30
+    }
31
+
32
+    public function store(Request $request, string $slug): RedirectResponse
33
+    {
34
+        $store = $this->ownedStore($request, $slug);
35
+
36
+        $offer = new AutomaticDiscount;
37
+        $offer->store_id = $store->id;
38
+        AutomaticDiscountRules::fill($offer, $this->validated($request, $store));
39
+        $offer->save();
40
+
41
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Automatic discount ":name" created.', ['name' => $offer->name])]);
42
+
43
+        return to_route('stores.discounts.index', $store->slug);
44
+    }
45
+
46
+    public function edit(Request $request, string $slug, int $offer): Response
47
+    {
48
+        $store = $this->ownedStore($request, $slug);
49
+
50
+        return Inertia::render('stores/discounts/automatic-form', [
51
+            'store' => ['name' => $store->name, 'slug' => $store->slug],
52
+            'offer' => self::present($this->ownedOffer($store, $offer)),
53
+            'products' => $this->productChoices($store),
54
+        ]);
55
+    }
56
+
57
+    public function update(Request $request, string $slug, int $offer): RedirectResponse
58
+    {
59
+        $store = $this->ownedStore($request, $slug);
60
+        $model = $this->ownedOffer($store, $offer);
61
+
62
+        AutomaticDiscountRules::fill($model, $this->validated($request, $store));
63
+        $model->save();
64
+
65
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Automatic discount saved.')]);
66
+
67
+        return to_route('stores.discounts.index', $store->slug);
68
+    }
69
+
70
+    public function destroy(Request $request, string $slug, int $offer): RedirectResponse
71
+    {
72
+        $store = $this->ownedStore($request, $slug);
73
+
74
+        // Orders keep their own copy of the name and the amount.
75
+        $this->ownedOffer($store, $offer)->delete();
76
+
77
+        Inertia::flash('toast', ['type' => 'success', 'message' => __('Automatic discount deleted.')]);
78
+
79
+        return to_route('stores.discounts.index', $store->slug);
80
+    }
81
+
82
+    /**
83
+     * What the dashboard is allowed to see. Amounts are text in ringgit; dates are Malaysian days.
84
+     *
85
+     * @return array<string, mixed>
86
+     */
87
+    public static function present(AutomaticDiscount $offer): array
88
+    {
89
+        $timezone = DiscountCodeRules::TIMEZONE;
90
+
91
+        return [
92
+            'id' => $offer->id,
93
+            'name' => $offer->name,
94
+            'type' => $offer->type,
95
+            'value' => $offer->type === DiscountCode::PERCENT ? (string) $offer->value : number_format($offer->value / 100, 2, '.', ''),
96
+            'description' => $offer->describe(),
97
+            'minimum_quantity' => $offer->minimum_quantity,
98
+            'minimum_subtotal' => $offer->minimum_subtotal !== null ? number_format($offer->minimum_subtotal / 100, 2, '.', '') : null,
99
+            'product_ids' => $offer->product_ids,
100
+            'starts_on' => $offer->starts_at?->setTimezone($timezone)->format('Y-m-d'),
101
+            'ends_on' => $offer->ends_at?->setTimezone($timezone)->format('Y-m-d'),
102
+            'active' => $offer->active,
103
+            'status' => $offer->status(),
104
+        ];
105
+    }
106
+
107
+    /**
108
+     * @return array<string, mixed>
109
+     */
110
+    private function validated(Request $request, Store $store): array
111
+    {
112
+        $percent = $request->input('type') === DiscountCode::PERCENT;
113
+
114
+        return $request->validate(AutomaticDiscountRules::rules($store, $percent), AutomaticDiscountRules::messages($percent));
115
+    }
116
+
117
+    /**
118
+     * @return list<array{id: int, name: string}>
119
+     */
120
+    private function productChoices(Store $store): array
121
+    {
122
+        return array_values($store->products()
123
+            ->orderBy('name')
124
+            ->get(['id', 'name'])
125
+            ->map(fn (Product $product) => ['id' => $product->id, 'name' => $product->name])
126
+            ->all());
127
+    }
128
+
129
+    private function ownedStore(Request $request, string $slug): Store
130
+    {
131
+        return $request->user()->stores()->where('slug', $slug)->firstOrFail();
132
+    }
133
+
134
+    private function ownedOffer(Store $store, int $id): AutomaticDiscount
135
+    {
136
+        return $store->automaticDiscounts()->whereKey($id)->firstOrFail();
137
+    }
138
+}

+ 1
- 1
app/Http/Controllers/CheckoutController.php Ver fichero

@@ -39,7 +39,7 @@ class CheckoutController extends Controller
39 39
 
40 40
         $cart = $this->cart($request, $storefront->store);
41 41
         $subtotal = (int) $lines->sum('line_total');
42
-        $applied = $cart->discount($subtotal);
42
+        $applied = $cart->applied($lines);
43 43
         // Shipping is worked out on what the shopper pays for the products, after any discount.
44 44
         $afterDiscount = $subtotal - ($applied !== null ? $applied->amount : 0);
45 45
 

+ 9
- 1
app/Http/Controllers/Concerns/RendersStorefront.php Ver fichero

@@ -3,6 +3,7 @@
3 3
 namespace App\Http\Controllers\Concerns;
4 4
 
5 5
 use App\Commerce\Cart;
6
+use App\Models\AutomaticDiscount;
6 7
 use App\Models\Product;
7 8
 use App\Models\Store;
8 9
 use App\Storefront\Storefront;
@@ -35,6 +36,7 @@ trait RendersStorefront
35 36
     private function renderStorefront(Request $request, Storefront $storefront, array $view): Response
36 37
     {
37 38
         $store = $storefront->store;
39
+        $cart = $this->cart($request, $store);
38 40
 
39 41
         return Inertia::render('stores/preview', [
40 42
             'storeName' => $store->name,
@@ -61,12 +63,18 @@ trait RendersStorefront
61 63
                 ->get()
62 64
                 ->mapWithKeys(fn (Product $product) => [$product->slug => $product->toStorefront()])
63 65
                 ->all(),
64
-            'cart' => $this->cart($request, $store)->toStorefront(),
66
+            'cart' => $cart->toStorefront(),
65 67
             'shop' => [
66 68
                 // Digits only, such as 60123456789, or null when the merchant has not set one.
67 69
                 'whatsapp' => $store->whatsapp_number,
68 70
                 // In ringgit, or null when shipping is never free.
69 71
                 'free_shipping_over' => $store->free_shipping_over !== null ? $store->free_shipping_over / 100 : null,
72
+                // Automatic discounts running now, so product pages can mention them.
73
+                'offers' => $cart->liveOffers()->map(fn (AutomaticDiscount $offer) => [
74
+                    'name' => $offer->name,
75
+                    'text' => $offer->describe($store->language->value),
76
+                    'product_ids' => $offer->product_ids,
77
+                ])->values()->all(),
70 78
             ],
71 79
         ]);
72 80
     }

+ 2
- 0
app/Http/Controllers/DiscountCodeController.php Ver fichero

@@ -3,6 +3,7 @@
3 3
 namespace App\Http\Controllers;
4 4
 
5 5
 use App\Commerce\DiscountCodeRules;
6
+use App\Models\AutomaticDiscount;
6 7
 use App\Models\DiscountCode;
7 8
 use App\Models\Store;
8 9
 use Illuminate\Http\RedirectResponse;
@@ -25,6 +26,7 @@ class DiscountCodeController extends Controller
25 26
         return Inertia::render('stores/discounts/index', [
26 27
             'store' => ['name' => $store->name, 'slug' => $store->slug],
27 28
             'codes' => $store->discountCodes()->latest('id')->get()->map(fn (DiscountCode $code) => $this->present($code)),
29
+            'offers' => $store->automaticDiscounts()->latest('id')->get()->map(fn (AutomaticDiscount $offer) => AutomaticDiscountController::present($offer)),
28 30
         ]);
29 31
     }
30 32
 

+ 170
- 0
app/Models/AutomaticDiscount.php Ver fichero

@@ -0,0 +1,170 @@
1
+<?php
2
+
3
+namespace App\Models;
4
+
5
+use App\Commerce\Cart;
6
+use Carbon\CarbonInterface;
7
+use Illuminate\Database\Eloquent\Model;
8
+use Illuminate\Database\Eloquent\Relations\BelongsTo;
9
+use Illuminate\Support\Collection;
10
+
11
+/**
12
+ * A discount that applies by itself when the cart qualifies, with no code to type.
13
+ * For example "Raya Sale: buy 2 or more, get 10% off" or "spend RM 100, get RM 15 off".
14
+ * It can cover every product or only chosen ones; then only those count and only those get cheaper.
15
+ * Amounts are in sen.
16
+ *
17
+ * @property int $id
18
+ * @property int $store_id
19
+ * @property string $name Shown to shoppers
20
+ * @property string $type "percent" or "fixed"
21
+ * @property int $value A whole percentage, or an amount in sen
22
+ * @property int|null $minimum_quantity
23
+ * @property int|null $minimum_subtotal
24
+ * @property list<int>|null $product_ids Null means every product
25
+ * @property CarbonInterface|null $starts_at
26
+ * @property CarbonInterface|null $ends_at
27
+ * @property bool $active
28
+ * @property-read Store $store
29
+ *
30
+ * @phpstan-import-type CartLine from Cart
31
+ */
32
+class AutomaticDiscount extends Model
33
+{
34
+    /**
35
+     * @return BelongsTo<Store, $this>
36
+     */
37
+    public function store(): BelongsTo
38
+    {
39
+        return $this->belongsTo(Store::class);
40
+    }
41
+
42
+    /**
43
+     * Switched on, and today is within its dates.
44
+     */
45
+    public function isLive(): bool
46
+    {
47
+        return $this->status() === 'active';
48
+    }
49
+
50
+    public function status(): string
51
+    {
52
+        return match (true) {
53
+            ! $this->active => 'off',
54
+            $this->starts_at !== null && $this->starts_at->isFuture() => 'scheduled',
55
+            $this->ends_at !== null && $this->ends_at->isPast() => 'expired',
56
+            default => 'active',
57
+        };
58
+    }
59
+
60
+    public function appliesTo(Product $product): bool
61
+    {
62
+        return $this->product_ids === null || in_array($product->id, $this->product_ids, true);
63
+    }
64
+
65
+    /**
66
+     * The cart lines this discount covers.
67
+     *
68
+     * @param  Collection<int, CartLine>  $lines
69
+     * @return Collection<int, CartLine>
70
+     */
71
+    public function eligible(Collection $lines): Collection
72
+    {
73
+        return $lines->filter(fn (array $line) => $this->appliesTo($line['product']))->values();
74
+    }
75
+
76
+    /**
77
+     * How much comes off these cart lines, in sen. Zero when the cart does not qualify.
78
+     *
79
+     * @param  Collection<int, CartLine>  $lines
80
+     */
81
+    public function amountFor(Collection $lines): int
82
+    {
83
+        $eligible = $this->eligible($lines);
84
+        $subtotal = (int) $eligible->sum('line_total');
85
+
86
+        if ($subtotal === 0 || $this->shortfall($lines) !== null) {
87
+            return 0;
88
+        }
89
+
90
+        $amount = $this->type === DiscountCode::PERCENT
91
+            ? intdiv($subtotal * min(100, $this->value), 100)
92
+            : $this->value;
93
+
94
+        return max(0, min($amount, $subtotal));
95
+    }
96
+
97
+    /**
98
+     * What the cart still needs to qualify: ["items" => 1] or ["amount" => 1200 sen]. Null when it qualifies.
99
+     *
100
+     * @param  Collection<int, CartLine>  $lines
101
+     * @return array{items?: int, amount?: int}|null
102
+     */
103
+    public function shortfall(Collection $lines): ?array
104
+    {
105
+        $eligible = $this->eligible($lines);
106
+        $quantity = (int) $eligible->sum('quantity');
107
+        $subtotal = (int) $eligible->sum('line_total');
108
+
109
+        if ($this->minimum_quantity !== null && $quantity < $this->minimum_quantity) {
110
+            return ['items' => $this->minimum_quantity - $quantity];
111
+        }
112
+
113
+        if ($this->minimum_subtotal !== null && $subtotal < $this->minimum_subtotal) {
114
+            return ['amount' => $this->minimum_subtotal - $subtotal];
115
+        }
116
+
117
+        return null;
118
+    }
119
+
120
+    /**
121
+     * "10% off" or "RM 5.00 off", in the store's language.
122
+     */
123
+    public function label(string $language = 'en'): string
124
+    {
125
+        $amount = $this->type === DiscountCode::PERCENT
126
+            ? $this->value.'%'
127
+            : 'RM '.number_format($this->value / 100, 2);
128
+
129
+        return $language === 'ms' ? 'diskaun '.$amount : $amount.' off';
130
+    }
131
+
132
+    /**
133
+     * The whole offer in one line for shoppers: "Buy 2 or more, get 10% off".
134
+     */
135
+    public function describe(string $language = 'en'): string
136
+    {
137
+        $malay = $language === 'ms';
138
+        $condition = match (true) {
139
+            $this->minimum_quantity !== null && $this->minimum_quantity > 1 => $malay
140
+                ? "Beli {$this->minimum_quantity} atau lebih"
141
+                : "Buy {$this->minimum_quantity} or more",
142
+            $this->minimum_subtotal !== null => $malay
143
+                ? 'Belanja RM '.number_format($this->minimum_subtotal / 100, 2).' atau lebih'
144
+                : 'Spend RM '.number_format($this->minimum_subtotal / 100, 2).' or more',
145
+            default => null,
146
+        };
147
+
148
+        if ($condition === null) {
149
+            return ucfirst($this->label($language));
150
+        }
151
+
152
+        return $condition.($malay ? ', dapat ' : ', get ').$this->label($language);
153
+    }
154
+
155
+    /**
156
+     * @return array<string, string>
157
+     */
158
+    protected function casts(): array
159
+    {
160
+        return [
161
+            'value' => 'integer',
162
+            'minimum_quantity' => 'integer',
163
+            'minimum_subtotal' => 'integer',
164
+            'product_ids' => 'array',
165
+            'starts_at' => 'datetime',
166
+            'ends_at' => 'datetime',
167
+            'active' => 'boolean',
168
+        ];
169
+    }
170
+}

+ 2
- 0
app/Models/Order.php Ver fichero

@@ -28,6 +28,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
28 28
  * @property array{line1: string, line2: string|null, city: string, postcode: string, state: string, country: string} $shipping_address
29 29
  * @property int $subtotal
30 30
  * @property string|null $discount_code
31
+ * @property string|null $discount_name The automatic discount used, when there was no code
31 32
  * @property int $discount_total
32 33
  * @property int $shipping_total
33 34
  * @property int $total
@@ -89,6 +90,7 @@ class Order extends Model
89 90
             'shipping_address' => $this->shipping_address,
90 91
             'subtotal' => $this->subtotal / 100,
91 92
             'discount_code' => $this->discount_code,
93
+            'discount_name' => $this->discount_name,
92 94
             'discount_total' => $this->discount_total / 100,
93 95
             'shipping_total' => $this->shipping_total / 100,
94 96
             'total' => $this->total / 100,

+ 8
- 0
app/Models/Store.php Ver fichero

@@ -143,6 +143,14 @@ class Store extends Model
143 143
         return $this->hasMany(DiscountCode::class);
144 144
     }
145 145
 
146
+    /**
147
+     * @return HasMany<AutomaticDiscount, $this>
148
+     */
149
+    public function automaticDiscounts(): HasMany
150
+    {
151
+        return $this->hasMany(AutomaticDiscount::class);
152
+    }
153
+
146 154
     /**
147 155
      * @return HasMany<Order, $this>
148 156
      */

+ 31
- 4
app/StorePlan/Ai/PlanPrompt.php Ver fichero

@@ -4,6 +4,8 @@ namespace App\StorePlan\Ai;
4 4
 
5 5
 use App\Commerce\ChatActions;
6 6
 use App\Commerce\DiscountCodeRules;
7
+use App\Models\AutomaticDiscount;
8
+use App\Models\BundleItem;
7 9
 use App\Models\DiscountCode;
8 10
 use App\Models\Product;
9 11
 use App\Models\ProductVariant;
@@ -86,6 +88,10 @@ final class PlanPrompt
86 88
             ->map(fn (Product $product) => '- '.$product->slug.': '.$product->name.' (RM '.number_format($product->price / 100, 2).')')
87 89
             ->implode("\n");
88 90
 
91
+        $offerLines = $store->automaticDiscounts()->orderBy('name')->limit(20)->get()
92
+            ->map(fn (AutomaticDiscount $offer) => "- {$offer->name}: {$offer->describe()}, ".$offer->status())
93
+            ->implode("\n");
94
+
89 95
         return <<<TEXT
90 96
 
91 97
         The store's real products (web-address name: product name and price):
@@ -101,16 +107,19 @@ final class PlanPrompt
101 107
      */
102 108
     public static function catalogue(Store $store): string
103 109
     {
104
-        $products = $store->products()->with('variants')->orderBy('name')->limit(60)->get();
110
+        $products = $store->products()->with(['variants', 'bundleItems.product', 'bundleItems.variant'])->orderBy('name')->limit(60)->get();
105 111
         $codes = $store->discountCodes()->orderBy('code')->limit(30)->get();
106 112
         $today = now(DiscountCodeRules::TIMEZONE)->format('Y-m-d (l)');
113
+        $language = $store->language->value === 'ms' ? 'Bahasa Malaysia' : 'English';
107 114
         $money = fn (int $sen) => 'RM '.number_format($sen / 100, 2, '.', '');
108 115
 
109 116
         $productLines = $products->map(function (Product $product) use ($money): string {
110
-            $line = "- {$product->slug}: {$product->name}, {$product->status->value}";
117
+            // Whether it has a description, so "write descriptions for products without one" works.
118
+            $line = "- {$product->slug}: {$product->name}, {$product->status->value}, ".(filled($product->description) ? 'has a description' : 'no description');
111 119
 
112 120
             if ($product->isBundle()) {
113
-                return $line.', bundle, '.$money($product->price).', enough stock for '.$product->stock;
121
+                return $line.', bundle, '.$money($product->price).', enough stock for '.$product->stock
122
+                    .', contains: '.$product->bundleItems->map(fn (BundleItem $item) => $item->label())->implode(', ');
114 123
             }
115 124
 
116 125
             if ($product->hasVariants()) {
@@ -128,9 +137,14 @@ final class PlanPrompt
128 137
             .($code->ends_at !== null ? ', last day '.$code->ends_at->setTimezone(DiscountCodeRules::TIMEZONE)->format('Y-m-d') : ''))
129 138
             ->implode("\n");
130 139
 
140
+        $offerLines = $store->automaticDiscounts()->orderBy('name')->limit(20)->get()
141
+            ->map(fn (AutomaticDiscount $offer) => "- {$offer->name}: {$offer->describe()}, ".$offer->status())
142
+            ->implode("\n");
143
+
131 144
         return <<<TEXT
132 145
 
133 146
         Today in Malaysia: {$today}
147
+        Store: {$store->name} ({$store->category->label()}). Write product descriptions in: {$language}
134 148
 
135 149
         The store's products (web-address name: name, status, price and stock):
136 150
         {$productLines}
@@ -139,6 +153,9 @@ final class PlanPrompt
139 153
 
140 154
         The store's discount codes:
141 155
         {$codeLines}
156
+
157
+        The store's automatic discounts (no code needed):
158
+        {$offerLines}
142 159
         TEXT;
143 160
     }
144 161
 
@@ -183,17 +200,27 @@ final class PlanPrompt
183 200
         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:
184 201
 
185 202
         {"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"}
186
-        {"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", "price", "compare_at_price" (null removes it), "stock", "status"}
203
+        {"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"}
187 204
         {"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}
188 205
         {"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}
206
+        {"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"}
189 207
         {"type": "create_bundle", "name": "...", "price": 85, "compare_at_price": null or a higher "was" price, "description": "..." or null, "status": "active" or "draft", "items": [{"product": "web-address name", "variant": "the choice, only for products with choices", "quantity": 1}]}
190 208
 
191 209
         - Use only web-address names, choices and codes from the lists you are given. A product with choices needs "variant" for price and stock changes, and inside a bundle.
192 210
         - A bundle's stock comes from its items, so never set "stock" on a bundle.
211
+        - A discount code is typed by shoppers. An automatic discount needs no code and applies by itself, such as "buy 2, get 10% off" or a sale. Use "create_automatic_discount" when the merchant does not mention a code. A "fixed" value comes off the order once, not off each item; describe it that way in "reply". Only one discount applies per order: shoppers get whichever of their code and the automatic discounts saves more.
193 212
         - Work out dates from today's date, such as "until the end of the month".
194 213
         - At most [[MAX_ACTIONS]] actions. If something is missing that you cannot sensibly choose (such as a price for a new product), propose nothing and ask for it in "reply".
195 214
         - You cannot add photos, delete products or codes, or change options; tell the merchant to use the Products or Discounts tab for those.
196 215
 
216
+        # Product descriptions
217
+
218
+        The merchant may ask you to write or rewrite descriptions, for one product, several, or "all products without one". Use "update_product" with "description" for each (one action per product), or "description" in "create_product" and "create_bundle". If the merchant adds a new product without a description, write one too.
219
+        - Base the description on the product name, its choices (such as sizes), what is inside a bundle, and the store's category. Use details the merchant gives in the request as well.
220
+        - 2 to 4 short sentences, plain text, no headings, no emoji, no prices (prices are shown separately). Warm and concrete, in the store's language.
221
+        - 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.
222
+        - The confirm card shows the full text, so in "reply" just say which products you wrote descriptions for.
223
+
197 224
         Never say in "reply" that you changed something unless your answer contains that change.
198 225
 
199 226
         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".

+ 6
- 0
app/Storefront/StorefrontText.php Ver fichero

@@ -23,6 +23,9 @@ final class StorefrontText
23 23
             'discount_minimum' => 'Spend at least :amount on products to use this code.',
24 24
             'discount_total_too_low' => 'After the discount, the order total must be at least RM 2.00.',
25 25
             'discount_changed' => 'Your discount code can no longer be used, so it was removed. Please check your total.',
26
+            'discount_offer_better' => ':name already saves you more, so this code is not used. Only one discount applies per order.',
27
+            'offer_add_items' => 'Add :count more to get :label (:name).',
28
+            'offer_spend_more' => 'Spend :amount more to get :label (:name).',
26 29
         ],
27 30
         'ms' => [
28 31
             'cart_empty' => 'Troli anda kosong.',
@@ -38,6 +41,9 @@ final class StorefrontText
38 41
             'discount_minimum' => 'Belanja sekurang-kurangnya :amount untuk produk bagi menggunakan kod ini.',
39 42
             'discount_total_too_low' => 'Selepas diskaun, jumlah pesanan mestilah sekurang-kurangnya RM 2.00.',
40 43
             'discount_changed' => 'Kod diskaun anda tidak lagi boleh digunakan, jadi ia telah dibuang. Sila semak jumlah anda.',
44
+            'discount_offer_better' => ':name sudah memberi anda jimat lebih, jadi kod ini tidak digunakan. Hanya satu diskaun bagi setiap pesanan.',
45
+            'offer_add_items' => 'Tambah :count lagi untuk dapat :label (:name).',
46
+            'offer_spend_more' => 'Belanja :amount lagi untuk dapat :label (:name).',
41 47
         ],
42 48
     ];
43 49
 

+ 46
- 0
database/migrations/2026_11_17_000003_create_automatic_discounts_table.php Ver fichero

@@ -0,0 +1,46 @@
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
+        // Discounts that apply by themselves when the cart qualifies, such as "buy 2, get 10% off".
12
+        Schema::create('automatic_discounts', function (Blueprint $table) {
13
+            $table->id();
14
+            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
15
+            // Shown to shoppers, such as "Raya Sale".
16
+            $table->string('name', 40);
17
+            $table->string('type', 10);
18
+            // A whole percentage, or an amount in sen.
19
+            $table->unsignedInteger('value');
20
+            $table->unsignedSmallInteger('minimum_quantity')->nullable();
21
+            $table->unsignedInteger('minimum_subtotal')->nullable();
22
+            // Null means every product; otherwise a list of product ids.
23
+            $table->json('product_ids')->nullable();
24
+            $table->timestamp('starts_at')->nullable();
25
+            $table->timestamp('ends_at')->nullable();
26
+            $table->boolean('active')->default(true);
27
+            $table->timestamps();
28
+
29
+            $table->index(['store_id', 'active']);
30
+        });
31
+
32
+        Schema::table('orders', function (Blueprint $table) {
33
+            // The automatic discount's name, when one was used instead of a code.
34
+            $table->string('discount_name', 40)->nullable()->after('discount_code');
35
+        });
36
+    }
37
+
38
+    public function down(): void
39
+    {
40
+        Schema::table('orders', function (Blueprint $table) {
41
+            $table->dropColumn('discount_name');
42
+        });
43
+
44
+        Schema::dropIfExists('automatic_discounts');
45
+    }
46
+};

+ 388
- 0
resources/js/pages/stores/discounts/automatic-form.tsx Ver fichero

@@ -0,0 +1,388 @@
1
+import { Form, Head, Link } from '@inertiajs/react';
2
+import { useState } from 'react';
3
+import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
4
+import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
5
+import Heading from '@/components/heading';
6
+import InputError from '@/components/input-error';
7
+import { Button } from '@/components/ui/button';
8
+import { Checkbox } from '@/components/ui/checkbox';
9
+import {
10
+    Dialog,
11
+    DialogClose,
12
+    DialogContent,
13
+    DialogDescription,
14
+    DialogFooter,
15
+    DialogHeader,
16
+    DialogTitle,
17
+    DialogTrigger,
18
+} from '@/components/ui/dialog';
19
+import { Input } from '@/components/ui/input';
20
+import { Label } from '@/components/ui/label';
21
+import { dashboard } from '@/routes';
22
+import type { AutomaticDiscount, StoreSummary } from '@/types';
23
+
24
+/** Add an automatic discount, or edit one when `offer` is given. */
25
+export default function AutomaticDiscountForm({
26
+    store,
27
+    offer,
28
+    products,
29
+}: {
30
+    store: StoreSummary;
31
+    offer: AutomaticDiscount | null;
32
+    products: { id: number; name: string }[];
33
+}) {
34
+    const [type, setType] = useState<'percent' | 'fixed'>(
35
+        offer?.type ?? 'percent',
36
+    );
37
+    const [appliesTo, setAppliesTo] = useState<'all' | 'chosen'>(
38
+        offer?.product_ids ? 'chosen' : 'all',
39
+    );
40
+    const action = offer
41
+        ? AutomaticDiscountController.update.form({
42
+              slug: store.slug,
43
+              offer: offer.id,
44
+          })
45
+        : AutomaticDiscountController.store.form(store.slug);
46
+
47
+    return (
48
+        <>
49
+            <Head
50
+                title={`${offer ? offer.name : 'New automatic discount'} - ${store.name}`}
51
+            />
52
+
53
+            <div className="mx-auto w-full max-w-2xl space-y-8 p-4">
54
+                <Heading
55
+                    title={
56
+                        offer
57
+                            ? 'Edit automatic discount'
58
+                            : 'New automatic discount'
59
+                    }
60
+                    description="No code needed. It applies by itself when a cart qualifies."
61
+                />
62
+
63
+                <Form {...action} className="space-y-6">
64
+                    {({ processing, errors }) => (
65
+                        <>
66
+                            <div className="grid gap-2">
67
+                                <Label htmlFor="name">Name</Label>
68
+                                <Input
69
+                                    id="name"
70
+                                    name="name"
71
+                                    required
72
+                                    maxLength={40}
73
+                                    defaultValue={offer?.name}
74
+                                    placeholder="Raya Sale"
75
+                                    aria-describedby="name-help"
76
+                                />
77
+                                <p
78
+                                    id="name-help"
79
+                                    className="text-xs text-muted-foreground"
80
+                                >
81
+                                    Shoppers see it on product pages, in the
82
+                                    cart and on their order.
83
+                                </p>
84
+                                <InputError message={errors.name} />
85
+                            </div>
86
+
87
+                            <fieldset className="grid gap-3">
88
+                                <legend className="mb-1 text-sm font-medium">
89
+                                    Discount
90
+                                </legend>
91
+                                <div className="flex flex-wrap gap-4 text-sm">
92
+                                    <label className="flex items-center gap-2">
93
+                                        <input
94
+                                            type="radio"
95
+                                            name="type"
96
+                                            value="percent"
97
+                                            checked={type === 'percent'}
98
+                                            onChange={() => setType('percent')}
99
+                                        />
100
+                                        Percentage off
101
+                                    </label>
102
+                                    <label className="flex items-center gap-2">
103
+                                        <input
104
+                                            type="radio"
105
+                                            name="type"
106
+                                            value="fixed"
107
+                                            checked={type === 'fixed'}
108
+                                            onChange={() => setType('fixed')}
109
+                                        />
110
+                                        Fixed amount off
111
+                                    </label>
112
+                                </div>
113
+                                <div className="grid gap-2 sm:max-w-xs">
114
+                                    <Label htmlFor="value">
115
+                                        {type === 'percent'
116
+                                            ? 'Percentage (%)'
117
+                                            : 'Amount (RM)'}
118
+                                    </Label>
119
+                                    <Input
120
+                                        id="value"
121
+                                        name="value"
122
+                                        required
123
+                                        inputMode={
124
+                                            type === 'percent'
125
+                                                ? 'numeric'
126
+                                                : 'decimal'
127
+                                        }
128
+                                        defaultValue={offer?.value}
129
+                                        placeholder={
130
+                                            type === 'percent' ? '10' : '5.00'
131
+                                        }
132
+                                    />
133
+                                    <InputError message={errors.value} />
134
+                                </div>
135
+                                <InputError message={errors.type} />
136
+                            </fieldset>
137
+
138
+                            <fieldset className="grid gap-3">
139
+                                <legend className="mb-1 text-sm font-medium">
140
+                                    When it applies (leave both empty for a sale
141
+                                    on every cart)
142
+                                </legend>
143
+                                <div className="grid gap-6 sm:grid-cols-2">
144
+                                    <div className="grid gap-2">
145
+                                        <Label htmlFor="minimum_quantity">
146
+                                            Buy at least (items)
147
+                                        </Label>
148
+                                        <Input
149
+                                            id="minimum_quantity"
150
+                                            name="minimum_quantity"
151
+                                            type="number"
152
+                                            min={1}
153
+                                            step={1}
154
+                                            defaultValue={
155
+                                                offer?.minimum_quantity ?? ''
156
+                                            }
157
+                                            placeholder="2"
158
+                                        />
159
+                                        <InputError
160
+                                            message={errors.minimum_quantity}
161
+                                        />
162
+                                    </div>
163
+                                    <div className="grid gap-2">
164
+                                        <Label htmlFor="minimum_subtotal">
165
+                                            Spend at least (RM)
166
+                                        </Label>
167
+                                        <Input
168
+                                            id="minimum_subtotal"
169
+                                            name="minimum_subtotal"
170
+                                            inputMode="decimal"
171
+                                            defaultValue={
172
+                                                offer?.minimum_subtotal ?? ''
173
+                                            }
174
+                                            placeholder="100.00"
175
+                                        />
176
+                                        <InputError
177
+                                            message={errors.minimum_subtotal}
178
+                                        />
179
+                                    </div>
180
+                                </div>
181
+                            </fieldset>
182
+
183
+                            <fieldset className="grid gap-3">
184
+                                <legend className="mb-1 text-sm font-medium">
185
+                                    Products
186
+                                </legend>
187
+                                <div className="flex flex-wrap gap-4 text-sm">
188
+                                    <label className="flex items-center gap-2">
189
+                                        <input
190
+                                            type="radio"
191
+                                            name="applies_to"
192
+                                            value="all"
193
+                                            checked={appliesTo === 'all'}
194
+                                            onChange={() => setAppliesTo('all')}
195
+                                        />
196
+                                        All products
197
+                                    </label>
198
+                                    <label className="flex items-center gap-2">
199
+                                        <input
200
+                                            type="radio"
201
+                                            name="applies_to"
202
+                                            value="chosen"
203
+                                            checked={appliesTo === 'chosen'}
204
+                                            onChange={() =>
205
+                                                setAppliesTo('chosen')
206
+                                            }
207
+                                        />
208
+                                        Only some products
209
+                                    </label>
210
+                                </div>
211
+                                {appliesTo === 'chosen' && (
212
+                                    <div className="space-y-2 rounded-md border p-3">
213
+                                        <p className="text-xs text-muted-foreground">
214
+                                            Only these count towards the
215
+                                            minimum, and only these get cheaper.
216
+                                        </p>
217
+                                        <ul className="grid gap-2 sm:grid-cols-2">
218
+                                            {products.map((product) => (
219
+                                                <li
220
+                                                    key={product.id}
221
+                                                    className="flex items-center gap-2 text-sm"
222
+                                                >
223
+                                                    <Checkbox
224
+                                                        id={`product-${product.id}`}
225
+                                                        name="product_ids[]"
226
+                                                        value={String(
227
+                                                            product.id,
228
+                                                        )}
229
+                                                        defaultChecked={
230
+                                                            offer?.product_ids?.includes(
231
+                                                                product.id,
232
+                                                            ) ?? false
233
+                                                        }
234
+                                                    />
235
+                                                    <Label
236
+                                                        htmlFor={`product-${product.id}`}
237
+                                                        className="font-normal"
238
+                                                    >
239
+                                                        {product.name}
240
+                                                    </Label>
241
+                                                </li>
242
+                                            ))}
243
+                                        </ul>
244
+                                    </div>
245
+                                )}
246
+                                <InputError
247
+                                    message={
248
+                                        errors.product_ids ??
249
+                                        Object.entries(errors).find(([key]) =>
250
+                                            key.startsWith('product_ids.'),
251
+                                        )?.[1]
252
+                                    }
253
+                                />
254
+                            </fieldset>
255
+
256
+                            <div className="grid gap-6 sm:grid-cols-2">
257
+                                <div className="grid gap-2">
258
+                                    <Label htmlFor="starts_on">
259
+                                        First day (optional)
260
+                                    </Label>
261
+                                    <Input
262
+                                        id="starts_on"
263
+                                        name="starts_on"
264
+                                        type="date"
265
+                                        defaultValue={offer?.starts_on ?? ''}
266
+                                    />
267
+                                    <InputError message={errors.starts_on} />
268
+                                </div>
269
+                                <div className="grid gap-2">
270
+                                    <Label htmlFor="ends_on">
271
+                                        Last day (optional)
272
+                                    </Label>
273
+                                    <Input
274
+                                        id="ends_on"
275
+                                        name="ends_on"
276
+                                        type="date"
277
+                                        defaultValue={offer?.ends_on ?? ''}
278
+                                    />
279
+                                    <InputError message={errors.ends_on} />
280
+                                </div>
281
+                            </div>
282
+
283
+                            <div className="flex items-center gap-3">
284
+                                <input type="hidden" name="active" value="0" />
285
+                                <Checkbox
286
+                                    id="active"
287
+                                    name="active"
288
+                                    value="1"
289
+                                    defaultChecked={offer?.active ?? true}
290
+                                />
291
+                                <Label htmlFor="active">
292
+                                    Active (applies to carts now)
293
+                                </Label>
294
+                            </div>
295
+
296
+                            <p className="text-sm text-muted-foreground">
297
+                                Only one discount applies per order. If a
298
+                                shopper also types a code, they get whichever
299
+                                saves more.
300
+                            </p>
301
+
302
+                            <div className="flex items-center gap-3">
303
+                                <Button
304
+                                    disabled={processing}
305
+                                    data-test="save-automatic-discount-button"
306
+                                >
307
+                                    {offer ? 'Save' : 'Create'}
308
+                                </Button>
309
+                                <Button variant="ghost" asChild>
310
+                                    <Link
311
+                                        href={DiscountCodeController.index.url(
312
+                                            store.slug,
313
+                                        )}
314
+                                    >
315
+                                        Cancel
316
+                                    </Link>
317
+                                </Button>
318
+                            </div>
319
+                        </>
320
+                    )}
321
+                </Form>
322
+
323
+                {offer && (
324
+                    <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-destructive/30 p-4">
325
+                        <div>
326
+                            <p className="font-medium">
327
+                                Delete this automatic discount
328
+                            </p>
329
+                            <p className="text-sm text-muted-foreground">
330
+                                Carts stop getting it. Past orders keep their
331
+                                discount.
332
+                            </p>
333
+                        </div>
334
+                        <Dialog>
335
+                            <DialogTrigger asChild>
336
+                                <Button variant="destructive" size="sm">
337
+                                    Delete
338
+                                </Button>
339
+                            </DialogTrigger>
340
+                            <DialogContent>
341
+                                <DialogHeader>
342
+                                    <DialogTitle>
343
+                                        Delete {offer.name}?
344
+                                    </DialogTitle>
345
+                                    <DialogDescription>
346
+                                        This cannot be undone. Past orders are
347
+                                        not changed.
348
+                                    </DialogDescription>
349
+                                </DialogHeader>
350
+                                <DialogFooter>
351
+                                    <DialogClose asChild>
352
+                                        <Button variant="outline">
353
+                                            Cancel
354
+                                        </Button>
355
+                                    </DialogClose>
356
+                                    <Form
357
+                                        {...AutomaticDiscountController.destroy.form(
358
+                                            {
359
+                                                slug: store.slug,
360
+                                                offer: offer.id,
361
+                                            },
362
+                                        )}
363
+                                    >
364
+                                        {({ processing }) => (
365
+                                            <Button
366
+                                                variant="destructive"
367
+                                                disabled={processing}
368
+                                            >
369
+                                                Delete
370
+                                            </Button>
371
+                                        )}
372
+                                    </Form>
373
+                                </DialogFooter>
374
+                            </DialogContent>
375
+                        </Dialog>
376
+                    </div>
377
+                )}
378
+            </div>
379
+        </>
380
+    );
381
+}
382
+
383
+AutomaticDiscountForm.layout = {
384
+    breadcrumbs: [
385
+        { title: 'Dashboard', href: dashboard() },
386
+        { title: 'Automatic discount', href: '#' },
387
+    ],
388
+};

+ 115
- 3
resources/js/pages/stores/discounts/index.tsx Ver fichero

@@ -1,12 +1,13 @@
1 1
 import { Head, Link } from '@inertiajs/react';
2
-import { Plus, TicketPercent } from 'lucide-react';
2
+import { Plus, Tag, TicketPercent } from 'lucide-react';
3
+import AutomaticDiscountController from '@/actions/App/Http/Controllers/AutomaticDiscountController';
3 4
 import DiscountCodeController from '@/actions/App/Http/Controllers/DiscountCodeController';
4 5
 import StoreController from '@/actions/App/Http/Controllers/StoreController';
5 6
 import StoreNav from '@/components/stores/store-nav';
6 7
 import { Badge } from '@/components/ui/badge';
7 8
 import { Button } from '@/components/ui/button';
8 9
 import { dashboard } from '@/routes';
9
-import type { DiscountCode, StoreSummary } from '@/types';
10
+import type { AutomaticDiscount, DiscountCode, StoreSummary } from '@/types';
10 11
 
11 12
 const statusLabel: Record<DiscountCode['status'], string> = {
12 13
     active: 'Active',
@@ -23,7 +24,10 @@ function day(value: string): string {
23 24
 }
24 25
 
25 26
 /** "From 1 Apr 2027 to 30 Apr 2027", "Until 30 Apr 2027" and so on. */
26
-function dates(code: DiscountCode): string | null {
27
+function dates(code: {
28
+    starts_on: string | null;
29
+    ends_on: string | null;
30
+}): string | null {
27 31
     if (code.starts_on && code.ends_on) {
28 32
         return `${day(code.starts_on)} to ${day(code.ends_on)}`;
29 33
     }
@@ -42,9 +46,11 @@ function dates(code: DiscountCode): string | null {
42 46
 export default function DiscountsIndex({
43 47
     store,
44 48
     codes,
49
+    offers,
45 50
 }: {
46 51
     store: StoreSummary;
47 52
     codes: DiscountCode[];
53
+    offers: AutomaticDiscount[];
48 54
 }) {
49 55
     const createUrl = DiscountCodeController.create.url(store.slug);
50 56
 
@@ -156,11 +162,117 @@ export default function DiscountsIndex({
156 162
                     A code takes money off the products only, never off
157 163
                     shipping. It counts as used when an order with it is paid.
158 164
                 </p>
165
+
166
+                <AutomaticDiscounts store={store} offers={offers} />
159 167
             </div>
160 168
         </>
161 169
     );
162 170
 }
163 171
 
172
+/** Discounts that apply by themselves when the cart qualifies. */
173
+function AutomaticDiscounts({
174
+    store,
175
+    offers,
176
+}: {
177
+    store: StoreSummary;
178
+    offers: AutomaticDiscount[];
179
+}) {
180
+    const createUrl = AutomaticDiscountController.create.url(store.slug);
181
+
182
+    return (
183
+        <section className="space-y-4 border-t pt-6">
184
+            <div className="flex flex-wrap items-center justify-between gap-3">
185
+                <div>
186
+                    <h2 className="font-medium">
187
+                        Automatic discounts{' '}
188
+                        <span className="text-muted-foreground">
189
+                            ({offers.length})
190
+                        </span>
191
+                    </h2>
192
+                    <p className="text-sm text-muted-foreground">
193
+                        No code needed. They apply by themselves when the cart
194
+                        qualifies, such as "buy 2, get 10% off".
195
+                    </p>
196
+                </div>
197
+                <Button
198
+                    asChild
199
+                    size="sm"
200
+                    variant="outline"
201
+                    data-test="add-automatic-discount-button"
202
+                >
203
+                    <Link href={createUrl}>
204
+                        <Plus />
205
+                        New automatic discount
206
+                    </Link>
207
+                </Button>
208
+            </div>
209
+
210
+            {offers.length === 0 ? (
211
+                <div className="flex flex-col items-center gap-2 rounded-xl border border-dashed p-8 text-center">
212
+                    <Tag className="size-6 text-muted-foreground" />
213
+                    <p className="max-w-sm text-sm text-muted-foreground">
214
+                        No automatic discounts yet. Try "Buy 2 or more, get 10%
215
+                        off" for a sale.
216
+                    </p>
217
+                </div>
218
+            ) : (
219
+                <ul className="divide-y rounded-xl border">
220
+                    {offers.map((offer) => {
221
+                        const when = dates(offer);
222
+
223
+                        return (
224
+                            <li
225
+                                key={offer.id}
226
+                                className="flex flex-wrap items-center gap-x-4 gap-y-2 p-4"
227
+                            >
228
+                                <div className="min-w-0 flex-1">
229
+                                    <p className="font-semibold">
230
+                                        {offer.name}
231
+                                    </p>
232
+                                    <p className="text-sm text-muted-foreground">
233
+                                        {offer.description}
234
+                                        {offer.product_ids !== null &&
235
+                                            ` · ${offer.product_ids.length} chosen ${offer.product_ids.length === 1 ? 'product' : 'products'}`}
236
+                                        {when && ` · ${when}`}
237
+                                    </p>
238
+                                </div>
239
+
240
+                                <Badge
241
+                                    variant={
242
+                                        offer.status === 'active'
243
+                                            ? 'default'
244
+                                            : 'secondary'
245
+                                    }
246
+                                >
247
+                                    {statusLabel[offer.status]}
248
+                                </Badge>
249
+
250
+                                <Button variant="outline" size="sm" asChild>
251
+                                    <Link
252
+                                        href={AutomaticDiscountController.edit.url(
253
+                                            {
254
+                                                slug: store.slug,
255
+                                                offer: offer.id,
256
+                                            },
257
+                                        )}
258
+                                    >
259
+                                        Edit
260
+                                    </Link>
261
+                                </Button>
262
+                            </li>
263
+                        );
264
+                    })}
265
+                </ul>
266
+            )}
267
+
268
+            <p className="text-xs text-muted-foreground">
269
+                Only one discount applies per order. When a shopper also has a
270
+                code, they get whichever saves more.
271
+            </p>
272
+        </section>
273
+    );
274
+}
275
+
164 276
 DiscountsIndex.layout = {
165 277
     breadcrumbs: [
166 278
         { title: 'Dashboard', href: dashboard() },

+ 3
- 2
resources/js/pages/stores/orders/show.tsx Ver fichero

@@ -108,8 +108,9 @@ export default function ShowOrder({
108 108
                                 <div className="flex justify-between gap-4">
109 109
                                     <span>
110 110
                                         Discount
111
-                                        {order.discount_code &&
112
-                                            ` (${order.discount_code})`}
111
+                                        {(order.discount_code ??
112
+                                            order.discount_name) &&
113
+                                            ` (${order.discount_code ?? order.discount_name})`}
113 114
                                     </span>
114 115
                                     <span className="tabular-nums">
115 116
                                         −{formatRinggit(order.discount_total)}

+ 3
- 1
resources/js/storefront/context.tsx Ver fichero

@@ -25,12 +25,14 @@ const StorefrontContext = createContext<Storefront>({
25 25
         count: 0,
26 26
         subtotal: 0,
27 27
         discount: null,
28
+        applied: null,
29
+        offer_hint: null,
28 30
         total: 0,
29 31
         adjusted: false,
30 32
         lines: [],
31 33
     },
32 34
     storeName: '',
33
-    shop: { whatsapp: null, free_shipping_over: null },
35
+    shop: { whatsapp: null, free_shipping_over: null, offers: [] },
34 36
     featuredProducts: {},
35 37
 });
36 38
 

+ 12
- 6
resources/js/storefront/pages/cart.tsx Ver fichero

@@ -145,7 +145,7 @@ export function CartPage() {
145 145
                         <aside className="h-fit rounded-(--sf-radius-card) border border-(--sf-border) bg-(--sf-surface) p-6">
146 146
                             <DiscountBox />
147 147
 
148
-                            {cart.discount && cart.discount.amount > 0 && (
148
+                            {cart.applied && (
149 149
                                 <div className="mb-3 space-y-1.5 text-sm">
150 150
                                     <div className="flex justify-between gap-4">
151 151
                                         <span>{t.subtotal}</span>
@@ -158,10 +158,10 @@ export function CartPage() {
158 158
                                         data-test="cart-discount-line"
159 159
                                     >
160 160
                                         <span>
161
-                                            {t.discount} ({cart.discount.code})
161
+                                            {t.discount} ({cart.applied.name})
162 162
                                         </span>
163 163
                                         <span className="tabular-nums">
164
-                                            −{formatPrice(cart.discount.amount)}
164
+                                            −{formatPrice(cart.applied.amount)}
165 165
                                         </span>
166 166
                                     </div>
167 167
                                 </div>
@@ -169,9 +169,7 @@ export function CartPage() {
169 169
 
170 170
                             <div className="flex items-baseline justify-between gap-4">
171 171
                                 <span className="font-medium">
172
-                                    {cart.discount && cart.discount.amount > 0
173
-                                        ? t.total
174
-                                        : t.subtotal}
172
+                                    {cart.applied ? t.total : t.subtotal}
175 173
                                 </span>
176 174
                                 <span className="text-xl font-semibold tabular-nums">
177 175
                                     {formatPrice(cart.total)}
@@ -180,6 +178,14 @@ export function CartPage() {
180 178
                             <p className="mt-2 text-sm text-(--sf-muted)">
181 179
                                 {t.shippingNote}
182 180
                             </p>
181
+                            {cart.offer_hint && (
182
+                                <p
183
+                                    className="mt-2 text-sm font-medium"
184
+                                    data-test="offer-hint"
185
+                                >
186
+                                    {cart.offer_hint}
187
+                                </p>
188
+                            )}
183 189
                             {freeShippingNote && (
184 190
                                 <p
185 191
                                     className="mt-2 text-sm font-medium"

+ 3
- 3
resources/js/storefront/pages/checkout.tsx Ver fichero

@@ -236,13 +236,13 @@ export function CheckoutPage({
236 236
                                     {formatPrice(cart.subtotal)}
237 237
                                 </span>
238 238
                             </div>
239
-                            {cart.discount && cart.discount.amount > 0 && (
239
+                            {cart.applied && (
240 240
                                 <div className="flex justify-between gap-4">
241 241
                                     <span>
242
-                                        {t.discount} ({cart.discount.code})
242
+                                        {t.discount} ({cart.applied.name})
243 243
                                     </span>
244 244
                                     <span className="tabular-nums">
245
-                                        −{formatPrice(cart.discount.amount)}
245
+                                        −{formatPrice(cart.applied.amount)}
246 246
                                     </span>
247 247
                                 </div>
248 248
                             )}

+ 3
- 2
resources/js/storefront/pages/order.tsx Ver fichero

@@ -55,8 +55,9 @@ export function OrderPage({ order }: { order: StoreOrder }) {
55 55
                             <div className="flex justify-between gap-4">
56 56
                                 <span>
57 57
                                     {t.discount}
58
-                                    {order.discount_code &&
59
-                                        ` (${order.discount_code})`}
58
+                                    {(order.discount_code ??
59
+                                        order.discount_name) &&
60
+                                        ` (${order.discount_code ?? order.discount_name})`}
60 61
                                 </span>
61 62
                                 <span className="tabular-nums">
62 63
                                     −{formatPrice(order.discount_total)}

+ 29
- 1
resources/js/storefront/pages/product.tsx Ver fichero

@@ -1,4 +1,5 @@
1 1
 import { router } from '@inertiajs/react';
2
+import { Tag } from 'lucide-react';
2 3
 import { useState } from 'react';
3 4
 import { useStorefront } from '../context';
4 5
 import { ProductImage } from '../product-card';
@@ -10,9 +11,14 @@ import { Container, QuantityStepper, SfButton, SfLink } from '../ui';
10 11
 
11 12
 /** One product's own page. Built by us, in the store's colours and fonts. */
12 13
 export function ProductPage({ product }: { product: StoreProduct }) {
13
-    const { language } = useStorefront();
14
+    const { language, shop } = useStorefront();
14 15
     const t = storefrontText(language);
15 16
     const [selected, setSelected] = useState(0);
17
+    const offers = shop.offers.filter(
18
+        (offer) =>
19
+            offer.product_ids === null ||
20
+            offer.product_ids.includes(product.id),
21
+    );
16 22
     const shown = product.images[selected] ?? product.image;
17 23
 
18 24
     // Start on the first combination that is in stock, so the page opens ready to buy.
@@ -109,6 +115,28 @@ export function ProductPage({ product }: { product: StoreProduct }) {
109 115
                             {inStock ? t.inStock : t.soldOut}
110 116
                         </p>
111 117
 
118
+                        {offers.length > 0 && (
119
+                            <ul className="mt-4 space-y-2" data-test="offers">
120
+                                {offers.map((offer) => (
121
+                                    <li
122
+                                        key={offer.name}
123
+                                        className="flex items-center gap-2 rounded-(--sf-radius) bg-(--sf-surface) px-3 py-2 text-sm"
124
+                                    >
125
+                                        <Tag
126
+                                            className="size-4 shrink-0 text-(--sf-primary)"
127
+                                            aria-hidden="true"
128
+                                        />
129
+                                        <span>
130
+                                            <span className="font-semibold">
131
+                                                {offer.name}:
132
+                                            </span>{' '}
133
+                                            {offer.text}
134
+                                        </span>
135
+                                    </li>
136
+                                ))}
137
+                            </ul>
138
+                        )}
139
+
112 140
                         {product.options.length > 0 && (
113 141
                             <div className="mt-6 space-y-5">
114 142
                                 {product.options.map((option, index) => (

+ 9
- 1
resources/js/storefront/types.ts Ver fichero

@@ -214,9 +214,13 @@ export type StoreCart = {
214 214
         label: string;
215 215
         /** Money off the products, in ringgit. Zero while the code does not count yet. */
216 216
         amount: number;
217
-        /** Why the code does not count yet, such as a minimum spend. */
217
+        /** Why the code does not count, such as a minimum spend, or a better automatic discount. */
218 218
         message: string | null;
219 219
     } | null;
220
+    /** The one discount taken off: the code, or an automatic discount, whichever saves more. */
221
+    applied: { name: string; amount: number; automatic: boolean } | null;
222
+    /** A nudge such as "Add 1 more to get 10% off (Raya Sale)". */
223
+    offer_hint: string | null;
220 224
     /** Products after the discount, before shipping. */
221 225
     total: number;
222 226
     /** True when stock changed and the cart was corrected. */
@@ -246,6 +250,8 @@ export type StoreOrder = {
246 250
     shipping_address: OrderAddress;
247 251
     subtotal: number;
248 252
     discount_code: string | null;
253
+    /** The automatic discount used, when there was no code. */
254
+    discount_name: string | null;
249 255
     discount_total: number;
250 256
     shipping_total: number;
251 257
     total: number;
@@ -269,6 +275,8 @@ export type ShopInfo = {
269 275
     whatsapp: string | null;
270 276
     /** In ringgit. Orders at or above this ship free. */
271 277
     free_shipping_over: number | null;
278
+    /** Automatic discounts running now. "product_ids" null means every product. */
279
+    offers: { name: string; text: string; product_ids: number[] | null }[];
272 280
 };
273 281
 
274 282
 /** Which storefront page to show. */

+ 19
- 0
resources/js/types/store.ts Ver fichero

@@ -119,6 +119,7 @@ export type Order = {
119 119
     };
120 120
     subtotal: number;
121 121
     discount_code: string | null;
122
+    discount_name: string | null;
122 123
     discount_total: number;
123 124
     shipping_total: number;
124 125
     total: number;
@@ -176,6 +177,24 @@ export type ProductOption = {
176 177
 };
177 178
 
178 179
 /** A discount code as the dashboard sees it. Amounts are text in ringgit; dates are Malaysian days (YYYY-MM-DD). */
180
+/** A discount that applies by itself, such as "buy 2, get 10% off". Money is text in ringgit. */
181
+export type AutomaticDiscount = {
182
+    id: number;
183
+    name: string;
184
+    type: 'percent' | 'fixed';
185
+    value: string;
186
+    /** "Buy 2 or more, get 10% off". */
187
+    description: string;
188
+    minimum_quantity: number | null;
189
+    minimum_subtotal: string | null;
190
+    /** Null means every product. */
191
+    product_ids: number[] | null;
192
+    starts_on: string | null;
193
+    ends_on: string | null;
194
+    active: boolean;
195
+    status: 'active' | 'off' | 'scheduled' | 'expired';
196
+};
197
+
179 198
 export type DiscountCode = {
180 199
     id: number;
181 200
     code: string;

+ 1
- 1
resources/views/mail/orders/confirmation.blade.php Ver fichero

@@ -14,7 +14,7 @@
14 14
 | {{ $item->name }} | {{ $item->quantity }} | {{ $money($item->line_total) }} |
15 15
 @endforeach
16 16
 @if ($order->discount_total > 0)
17
-| {{ $malay ? 'Diskaun' : 'Discount' }}{{ $order->discount_code ? ' ('.$order->discount_code.')' : '' }} | | -{{ $money($order->discount_total) }} |
17
+| {{ $malay ? 'Diskaun' : 'Discount' }}{{ ($order->discount_code ?? $order->discount_name) ? ' ('.($order->discount_code ?? $order->discount_name).')' : '' }} | | -{{ $money($order->discount_total) }} |
18 18
 @endif
19 19
 | {{ $malay ? 'Penghantaran' : 'Shipping' }} | | {{ $order->shipping_total === 0 ? ($malay ? 'Percuma' : 'Free') : $money($order->shipping_total) }} |
20 20
 | **{{ $malay ? 'Jumlah dibayar' : 'Total paid' }}** | | **{{ $money($order->total) }}** |

+ 6
- 0
routes/web.php Ver fichero

@@ -1,5 +1,6 @@
1 1
 <?php
2 2
 
3
+use App\Http\Controllers\AutomaticDiscountController;
3 4
 use App\Http\Controllers\BillingController;
4 5
 use App\Http\Controllers\CartController;
5 6
 use App\Http\Controllers\CheckoutController;
@@ -91,6 +92,11 @@ Route::middleware(['auth', 'verified'])->group(function () {
91 92
     Route::get('stores/{slug}/discounts/{discount}/edit', [DiscountCodeController::class, 'edit'])->name('stores.discounts.edit')->whereNumber('discount');
92 93
     Route::put('stores/{slug}/discounts/{discount}', [DiscountCodeController::class, 'update'])->name('stores.discounts.update')->whereNumber('discount');
93 94
     Route::delete('stores/{slug}/discounts/{discount}', [DiscountCodeController::class, 'destroy'])->name('stores.discounts.destroy')->whereNumber('discount');
95
+    Route::get('stores/{slug}/automatic-discounts/create', [AutomaticDiscountController::class, 'create'])->name('stores.automatic-discounts.create');
96
+    Route::post('stores/{slug}/automatic-discounts', [AutomaticDiscountController::class, 'store'])->name('stores.automatic-discounts.store');
97
+    Route::get('stores/{slug}/automatic-discounts/{offer}/edit', [AutomaticDiscountController::class, 'edit'])->name('stores.automatic-discounts.edit')->whereNumber('offer');
98
+    Route::put('stores/{slug}/automatic-discounts/{offer}', [AutomaticDiscountController::class, 'update'])->name('stores.automatic-discounts.update')->whereNumber('offer');
99
+    Route::delete('stores/{slug}/automatic-discounts/{offer}', [AutomaticDiscountController::class, 'destroy'])->name('stores.automatic-discounts.destroy')->whereNumber('offer');
94 100
 
95 101
     Route::get('stores/{slug}/orders', [OrderController::class, 'index'])->name('stores.orders.index');
96 102
     Route::get('stores/{slug}/orders/{order}', [OrderController::class, 'show'])->name('stores.orders.show')->whereNumber('order');

+ 302
- 0
tests/Feature/Stores/AutomaticDiscountTest.php Ver fichero

@@ -0,0 +1,302 @@
1
+<?php
2
+
3
+namespace Tests\Feature\Stores;
4
+
5
+use App\Commerce\Payments\PaymentGateway;
6
+use App\Models\AutomaticDiscount;
7
+use App\Models\DiscountCode;
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\Support\ScriptedDriver;
18
+use Tests\TestCase;
19
+
20
+class AutomaticDiscountTest extends TestCase
21
+{
22
+    use RefreshDatabase;
23
+
24
+    private User $user;
25
+
26
+    private Store $store;
27
+
28
+    private FakeGateway $gateway;
29
+
30
+    private Product $sambal;
31
+
32
+    private Product $kerepek;
33
+
34
+    protected function setUp(): void
35
+    {
36
+        parent::setUp();
37
+
38
+        Mail::fake();
39
+        $this->gateway = new FakeGateway;
40
+        $this->app->instance(PaymentGateway::class, $this->gateway);
41
+
42
+        $this->user = User::factory()->create();
43
+        $this->store = Store::factory()->for($this->user)->create(['name' => 'Kedai Ali']);
44
+        $this->store->plan = SamplePlan::for($this->store);
45
+        $this->store->save();
46
+        $this->actingAs($this->user);
47
+
48
+        $this->sambal = $this->store->products()->create(['name' => 'Sambal', 'price' => 2000, 'stock' => 50, 'status' => 'active']);
49
+        $this->kerepek = $this->store->products()->create(['name' => 'Kerepek', 'price' => 1000, 'stock' => 50, 'status' => 'active']);
50
+    }
51
+
52
+    /**
53
+     * "Raya Sale: buy 2 or more, get 10% off", on every product unless changed.
54
+     *
55
+     * @return array<string, mixed>
56
+     */
57
+    private function form(array $overrides = []): array
58
+    {
59
+        return [
60
+            'name' => 'Raya Sale',
61
+            'type' => 'percent',
62
+            'value' => '10',
63
+            'minimum_quantity' => 2,
64
+            'minimum_subtotal' => '',
65
+            'applies_to' => 'all',
66
+            'starts_on' => '',
67
+            'ends_on' => '',
68
+            'active' => '1',
69
+            ...$overrides,
70
+        ];
71
+    }
72
+
73
+    private function createOffer(array $overrides = []): AutomaticDiscount
74
+    {
75
+        $this->post(route('stores.automatic-discounts.store', $this->store->slug), $this->form($overrides))
76
+            ->assertSessionHasNoErrors();
77
+
78
+        return $this->store->automaticDiscounts()->latest('id')->firstOrFail();
79
+    }
80
+
81
+    private function add(Product $product, int $quantity = 1): void
82
+    {
83
+        $this->post(route('stores.preview.cart.add', $this->store->slug), ['product_id' => $product->id, 'quantity' => $quantity])
84
+            ->assertSessionHasNoErrors();
85
+    }
86
+
87
+    private function cart(callable $assert): void
88
+    {
89
+        $this->get(route('stores.preview.cart', $this->store->slug))->assertInertia(fn (Assert $page) => $assert($page));
90
+    }
91
+
92
+    private function placeOrder(): Order
93
+    {
94
+        $this->post(route('stores.preview.checkout.store', $this->store->slug), [
95
+            'name' => 'Aminah', 'email' => 'a@example.com', 'phone' => '0123456789',
96
+            'line1' => '12 Jalan Mawar', 'city' => 'Shah Alam', 'postcode' => '40000', 'state' => 'Selangor',
97
+        ])->assertRedirect();
98
+
99
+        return Order::latest('id')->firstOrFail();
100
+    }
101
+
102
+    public function test_the_merchant_can_create_edit_and_delete_one()
103
+    {
104
+        $offer = $this->createOffer();
105
+
106
+        $this->assertSame(10, $offer->value);
107
+        $this->assertSame(2, $offer->minimum_quantity);
108
+        $this->assertNull($offer->product_ids);
109
+
110
+        $this->get(route('stores.discounts.index', $this->store->slug))
111
+            ->assertInertia(fn (Assert $page) => $page
112
+                ->where('offers.0.name', 'Raya Sale')
113
+                ->where('offers.0.description', 'Buy 2 or more, get 10% off')
114
+                ->where('offers.0.status', 'active'));
115
+
116
+        $this->put(route('stores.automatic-discounts.update', [$this->store->slug, $offer->id]), $this->form([
117
+            'type' => 'fixed', 'value' => '5.50', 'minimum_quantity' => '', 'minimum_subtotal' => '50',
118
+            'applies_to' => 'chosen', 'product_ids' => [$this->sambal->id],
119
+        ]))->assertSessionHasNoErrors();
120
+
121
+        $offer->refresh();
122
+        $this->assertSame(550, $offer->value);
123
+        $this->assertSame(5000, $offer->minimum_subtotal);
124
+        $this->assertSame([$this->sambal->id], $offer->product_ids);
125
+        $this->assertSame('Spend RM 50.00 or more, get RM 5.50 off', $offer->describe());
126
+
127
+        $this->delete(route('stores.automatic-discounts.destroy', [$this->store->slug, $offer->id]));
128
+        $this->assertSame(0, AutomaticDiscount::count());
129
+    }
130
+
131
+    public function test_the_form_checks_its_values()
132
+    {
133
+        $other = Product::factory()->create();
134
+        $url = route('stores.automatic-discounts.store', $this->store->slug);
135
+
136
+        $this->post($url, $this->form(['value' => '150']))->assertSessionHasErrors('value');
137
+        $this->post($url, $this->form(['name' => '']))->assertSessionHasErrors('name');
138
+        $this->post($url, $this->form(['applies_to' => 'chosen']))->assertSessionHasErrors('product_ids');
139
+        $this->post($url, $this->form(['applies_to' => 'chosen', 'product_ids' => [$other->id]]))->assertSessionHasErrors('product_ids.0');
140
+        $this->post($url, $this->form(['starts_on' => '2030-05-10', 'ends_on' => '2030-05-01']))->assertSessionHasErrors('ends_on');
141
+
142
+        $this->assertSame(0, AutomaticDiscount::count());
143
+
144
+        // Another merchant cannot open it.
145
+        $offer = $this->createOffer();
146
+        $this->actingAs(User::factory()->create())
147
+            ->get(route('stores.automatic-discounts.edit', [$this->store->slug, $offer->id]))
148
+            ->assertNotFound();
149
+    }
150
+
151
+    public function test_it_applies_by_itself_once_the_cart_qualifies()
152
+    {
153
+        $this->createOffer();
154
+
155
+        $this->add($this->sambal);
156
+
157
+        // One item: not yet, but the cart says how close the shopper is.
158
+        $this->cart(fn (Assert $page) => $page
159
+            ->where('cart.applied', null)
160
+            ->where('cart.total', 20)
161
+            ->where('cart.offer_hint', 'Add 1 more to get 10% off (Raya Sale).'));
162
+
163
+        $this->add($this->kerepek);
164
+
165
+        $this->cart(fn (Assert $page) => $page
166
+            ->where('cart.applied.name', 'Raya Sale')
167
+            ->where('cart.applied.amount', 3)
168
+            ->where('cart.applied.automatic', true)
169
+            ->where('cart.offer_hint', null)
170
+            ->where('cart.total', 27));
171
+
172
+        $order = $this->placeOrder();
173
+
174
+        $this->assertNull($order->discount_code);
175
+        $this->assertSame('Raya Sale', $order->discount_name);
176
+        $this->assertSame(300, $order->discount_total);
177
+        $this->assertSame(2700 + 800, $order->total);
178
+    }
179
+
180
+    public function test_only_chosen_products_count_and_get_cheaper()
181
+    {
182
+        $this->createOffer(['applies_to' => 'chosen', 'product_ids' => [$this->sambal->id]]);
183
+
184
+        // A sambal and a kerepek make 2 items, but only the sambal counts.
185
+        $this->add($this->sambal);
186
+        $this->add($this->kerepek);
187
+        $this->cart(fn (Assert $page) => $page->where('cart.applied', null));
188
+
189
+        $this->add($this->sambal);
190
+
191
+        // 10% of the two sambal (RM 40), not of the kerepek.
192
+        $this->cart(fn (Assert $page) => $page->where('cart.applied.amount', 4)->where('cart.total', 46));
193
+    }
194
+
195
+    public function test_a_spend_minimum_works_and_the_cart_says_how_much_more()
196
+    {
197
+        $this->createOffer(['type' => 'fixed', 'value' => '5', 'minimum_quantity' => '', 'minimum_subtotal' => '50']);
198
+
199
+        $this->add($this->sambal, 2);
200
+        $this->cart(fn (Assert $page) => $page->where('cart.offer_hint', 'Spend RM 10.00 more to get RM 5.00 off (Raya Sale).'));
201
+
202
+        $this->add($this->kerepek);
203
+        $this->cart(fn (Assert $page) => $page->where('cart.applied.amount', 5)->where('cart.total', 45));
204
+    }
205
+
206
+    public function test_only_the_bigger_of_a_code_and_an_automatic_discount_applies()
207
+    {
208
+        $this->createOffer();
209
+        $this->post(route('stores.discounts.store', $this->store->slug), ['code' => 'BIG20', 'type' => 'percent', 'value' => 20, 'active' => true]);
210
+        $this->post(route('stores.discounts.store', $this->store->slug), ['code' => 'SMALL', 'type' => 'fixed', 'value' => '1', 'active' => true]);
211
+
212
+        $this->add($this->sambal, 2);
213
+
214
+        // RM 1 off is less than 10% (RM 4), so the sale wins and the code is not used.
215
+        $this->post(route('stores.preview.cart.discount', $this->store->slug), ['code' => 'SMALL']);
216
+        $this->cart(fn (Assert $page) => $page
217
+            ->where('cart.applied.name', 'Raya Sale')
218
+            ->where('cart.applied.amount', 4)
219
+            ->where('cart.discount.code', 'SMALL')
220
+            ->where('cart.discount.message', 'Raya Sale already saves you more, so this code is not used. Only one discount applies per order.'));
221
+
222
+        // 20% (RM 8) beats the sale.
223
+        $this->delete(route('stores.preview.cart.discount.remove', $this->store->slug));
224
+        $this->post(route('stores.preview.cart.discount', $this->store->slug), ['code' => 'BIG20']);
225
+        $this->cart(fn (Assert $page) => $page
226
+            ->where('cart.applied.name', 'BIG20')
227
+            ->where('cart.applied.amount', 8)
228
+            ->where('cart.discount.message', null)
229
+            ->where('cart.total', 32));
230
+
231
+        $order = $this->placeOrder();
232
+        $this->assertSame('BIG20', $order->discount_code);
233
+        $this->assertNull($order->discount_name);
234
+        $this->assertSame(800, $order->discount_total);
235
+    }
236
+
237
+    public function test_a_code_is_not_counted_as_used_when_the_sale_won()
238
+    {
239
+        $this->createOffer();
240
+        $this->post(route('stores.discounts.store', $this->store->slug), ['code' => 'SMALL', 'type' => 'fixed', 'value' => '1', 'active' => true]);
241
+
242
+        $this->add($this->sambal, 2);
243
+        $this->post(route('stores.preview.cart.discount', $this->store->slug), ['code' => 'SMALL']);
244
+
245
+        $order = $this->placeOrder();
246
+        $this->gateway->pay($order);
247
+        $this->get(route('stores.preview.order', [$this->store->slug, $order->public_id]))
248
+            ->assertInertia(fn (Assert $page) => $page->where('view.order.discount_name', 'Raya Sale'));
249
+
250
+        $this->assertTrue($order->fresh()->isPaid());
251
+        $this->assertSame(0, DiscountCode::where('code', 'SMALL')->firstOrFail()->times_used);
252
+    }
253
+
254
+    public function test_switched_off_scheduled_and_ended_ones_do_not_apply()
255
+    {
256
+        $this->createOffer(['active' => '0']);
257
+        $this->createOffer(['name' => 'Later', 'starts_on' => now('Asia/Kuala_Lumpur')->addDays(3)->format('Y-m-d')]);
258
+        $this->createOffer(['name' => 'Over', 'starts_on' => '2020-01-01', 'ends_on' => '2020-01-31']);
259
+
260
+        $this->add($this->sambal, 3);
261
+
262
+        $this->cart(fn (Assert $page) => $page->where('cart.applied', null)->where('cart.total', 60));
263
+        $this->assertSame(['off', 'scheduled', 'expired'], AutomaticDiscount::orderBy('id')->get()->map->status()->all());
264
+    }
265
+
266
+    public function test_product_pages_mention_the_offers_that_apply()
267
+    {
268
+        $this->createOffer(['applies_to' => 'chosen', 'product_ids' => [$this->sambal->id]]);
269
+
270
+        $this->get(route('stores.preview.product', [$this->store->slug, $this->sambal->slug]))
271
+            ->assertInertia(fn (Assert $page) => $page
272
+                ->where('shop.offers.0.name', 'Raya Sale')
273
+                ->where('shop.offers.0.text', 'Buy 2 or more, get 10% off')
274
+                ->where('shop.offers.0.product_ids', [$this->sambal->id]));
275
+    }
276
+
277
+    public function test_the_ai_can_propose_one_from_chat()
278
+    {
279
+        ScriptedDriver::use([(string) json_encode([
280
+            'reply' => 'Please confirm below.',
281
+            'actions' => [[
282
+                'type' => 'create_automatic_discount', 'name' => 'Sambal Week', 'discount_type' => 'percent', 'value' => 15,
283
+                'minimum_quantity' => 3, 'products' => [$this->sambal->slug], 'ends_on' => '2030-01-31',
284
+            ]],
285
+        ])]);
286
+
287
+        $this->post(route('stores.edits', $this->store->slug), ['instruction' => 'Buy 3 sambal get 15% off until end of January']);
288
+        $edit = $this->store->generations()->firstOrFail();
289
+
290
+        $this->assertSame(
291
+            'Start the automatic discount "Sambal Week": Buy 3 or more, get 15% off, only on Sambal, until 2030-01-31. No code needed',
292
+            $edit->actions[0]['summary'],
293
+        );
294
+        $this->assertSame(0, AutomaticDiscount::count());
295
+
296
+        $this->post(route('stores.edits.confirm', [$this->store->slug, $edit->id]))->assertSessionHasNoErrors();
297
+
298
+        $offer = AutomaticDiscount::firstOrFail();
299
+        $this->assertSame([$this->sambal->id], $offer->product_ids);
300
+        $this->assertSame(3, $offer->minimum_quantity);
301
+    }
302
+}

+ 39
- 2
tests/Feature/Stores/ChatActionsTest.php Ver fichero

@@ -190,7 +190,7 @@ class ChatActionsTest extends TestCase
190 190
             [['type' => 'create_discount', 'code' => 'x', 'discount_type' => 'percent', 'value' => 10]],
191 191
             [['type' => 'create_discount', 'code' => 'BIG', 'discount_type' => 'percent', 'value' => 150]],
192 192
             [['type' => 'create_bundle', 'name' => 'Set', 'price' => 10, 'items' => [['product' => $this->moisturiser->slug]]]],
193
-            array_fill(0, 6, ['type' => 'update_product', 'product' => $this->cleanser->slug, 'stock' => 1]),
193
+            array_fill(0, 11, ['type' => 'update_product', 'product' => $this->cleanser->slug, 'stock' => 1]),
194 194
         ];
195 195
 
196 196
         foreach ($wrong as $actions) {
@@ -246,10 +246,47 @@ class ChatActionsTest extends TestCase
246 246
         $prompt = ScriptedDriver::$requests[0]->prompt;
247 247
 
248 248
         $this->assertStringContainsString('Today in Malaysia: ', $prompt);
249
-        $this->assertStringContainsString($this->moisturiser->slug.': Moisturiser, active, choices: "50ml" RM 39.00 stock 8; "100ml" RM 55.00 stock 4', $prompt);
249
+        $this->assertStringContainsString($this->moisturiser->slug.': Moisturiser, active, no description, choices: "50ml" RM 39.00 stock 8; "100ml" RM 55.00 stock 4', $prompt);
250 250
         $this->assertStringContainsString('"create_bundle"', ScriptedDriver::$requests[0]->system);
251 251
     }
252 252
 
253
+    public function test_the_ai_can_write_product_descriptions()
254
+    {
255
+        $text = 'A gentle gel cleanser for everyday use. It rinses off easily and leaves skin feeling fresh, morning and night.';
256
+
257
+        $edit = $this->ask([
258
+            ['type' => 'update_product', 'product' => $this->cleanser->slug, 'description' => "  {$text}  "],
259
+            ['type' => 'create_product', 'name' => 'Lip Balm', 'price' => 15, 'stock' => 10, 'description' => 'A soft lip balm for dry days.'],
260
+        ]);
261
+
262
+        // The merchant reads the whole text before it is saved.
263
+        $this->assertSame("Change \"Gel Cleanser\": description: \"{$text}\"", $edit->actions[0]['summary']);
264
+        $this->assertStringEndsWith('. Description: "A soft lip balm for dry days."', $edit->actions[1]['summary']);
265
+        $this->assertNull($this->cleanser->fresh()->description);
266
+
267
+        $this->confirm($edit)->assertSessionHasNoErrors();
268
+
269
+        $this->assertSame($text, $this->cleanser->fresh()->description);
270
+        $this->assertSame('A soft lip balm for dry days.', $this->store->products()->where('name', 'Lip Balm')->firstOrFail()->description);
271
+
272
+        // The AI is told which products still need one, and in which language to write.
273
+        $this->ask([]);
274
+        $prompt = ScriptedDriver::$requests[0]->prompt;
275
+        $this->assertStringContainsString($this->cleanser->slug.': Gel Cleanser, active, has a description', $prompt);
276
+        $this->assertStringContainsString($this->moisturiser->slug.': Moisturiser, active, no description', $prompt);
277
+        $this->assertStringContainsString('Write product descriptions in: English', $prompt);
278
+
279
+        // A bundle's contents are listed, so its description never claims what is not inside.
280
+        $this->ask([['type' => 'create_bundle', 'name' => 'Duo', 'price' => 70, 'items' => [
281
+            ['product' => $this->cleanser->slug],
282
+            ['product' => $this->moisturiser->slug, 'variant' => '50ml'],
283
+        ]]]);
284
+        $this->confirm($this->store->generations()->latest('id')->firstOrFail());
285
+        $this->ask([]);
286
+        $this->assertStringContainsString('contains: 1 × Gel Cleanser, 1 × Moisturiser (50ml)', ScriptedDriver::$requests[0]->prompt);
287
+        $this->assertStringContainsString('Never invent facts', ScriptedDriver::$requests[0]->system);
288
+    }
289
+
253 290
     public function test_only_the_owner_can_confirm()
254 291
     {
255 292
         $edit = $this->ask([['type' => 'update_product', 'product' => $this->cleanser->slug, 'price' => 30]]);

+ 1
- 1
tests/Feature/Stores/FeaturedProductTest.php Ver fichero

@@ -173,7 +173,7 @@ class FeaturedProductTest extends TestCase
173 173
 
174 174
         $this->assertSame(GenerationStatus::Completed, $this->store->generations()->firstOrFail()->status);
175 175
         $this->assertSame([$product->slug], FeaturedProducts::slugs($this->store->fresh()->plan));
176
-        $this->assertStringContainsString($product->slug.': Sambal Hijau, active, RM 12.90', ScriptedDriver::$requests[0]->prompt);
176
+        $this->assertStringContainsString($product->slug.': Sambal Hijau, active, has a description, RM 12.90', ScriptedDriver::$requests[0]->prompt);
177 177
     }
178 178
 
179 179
     public function test_a_made_up_product_from_the_ai_is_sent_back_to_be_fixed()

Loading…
Cancelar
Guardar