# Backend API Changes — Vital Kitchen Ordering, Unified Cart/Checkout, Search, Delivery Scheduling

**Audience:** mobile (Flutter) developer implementing parity with the website.
**Scope:** this document describes only the *backend contract* — endpoints, payloads,
validation, and behavior. It does not prescribe Flutter architecture, since that
requires seeing the existing mobile codebase.

---

## 1. Overview

Two customer-facing product lines now exist side by side and share **one cart** and
**one checkout/payment**:

- **Groceries** — the existing `Product`/`ProductPricing`/`Cart`/`Order` system. Unchanged
  except for one breaking behavior change: **delivery is now schedule-only** (see §4).
- **Vital Kitchen** — salad/bowl products (`SaladBowl`). Previously had **no real ordering
  flow at all** (Add-to-cart on web was cosmetic-only, no API call). It now has a full,
  real cart → checkout → order pipeline, requires login (no guest ordering), and supports
  a flexible **"now" or "scheduled" delivery**.

A single checkout call can place a grocery order, a Vital Kitchen order, or both at once,
under **one combined payment** (one Razorpay transaction, or one COD order confirmation).

---

## 2. Browsing / Catalog API — product listings now interleave Vital Kitchen bowls

### 2.1 Home Sections — `GET /api/home/sections` and `GET /api/home/sections/{sectionId}`

**BREAKING CHANGE:** each section's `products[]` array now contains **both** grocery
products and Vital Kitchen bowls, interleaved in their real display position (the same
position an admin sets by dragging in the backend product/section editor), each item
tagged with a new `product_type` field (`"grocery"` or `"vital_kitchen"`). There is **no
separate `vital_kitchen_products` key** on this endpoint — unlike Search (§5), which keeps
them in a separate array.

Example — `products[]` mixing both types in one section:
```json
{
  "id": 34,
  "name": "Limited Time Offers",
  "section_type": "individual",
  "products": [
    {
      "id": 1, "product_type": "vital_kitchen", "name": "Test FWO Daily",
      "image": null, "short_description": "...", "bowl_type": "veg",
      "min_order_qty": 1, "max_order_qty": 5,
      "mrp": 299.0, "selling_price": 249.0, "discount_percent": 17,
      "category_name": "Salad",
      "is_in_cart": false, "cart_quantity": 0, "cart_item_id": null,
      "is_wishlisted": false
    },
    {
      "id": 33, "product_type": "grocery", "name": "Aashirvaad Whole Wheat",
      "image": null, "short_description": null,
      "min_order_qty": 0, "max_order_qty": 0,
      "is_preorder": false, "is_wishlisted": false,
      "pricing": [
        {
          "id": 255, "label": "1g", "mrp": 100, "selling_price": 100,
          "discount_type": "none", "discount_value": 0, "discount_percent": 0,
          "is_default": true, "is_in_cart": false, "cart_quantity": 0, "cart_item_id": null,
          "stock_qty": 99, "stock_status": "in_stock", "stock_label": "In Stock", "is_available": true
        }
      ]
    }
  ]
}
```
The two shapes are **not unified** — a `"grocery"` item carries a `pricing[]` array (it can
have multiple variants/sizes), a `"vital_kitchen"` item carries flat `mrp`/`selling_price`/
`is_in_cart`/`cart_quantity`/`cart_item_id` fields directly (a bowl has one fixed price, no
variants). Always branch on `product_type` before reading price/cart-state fields — do not
assume every entry in `products[]` has a `pricing[]` array.

`is_in_cart`/`cart_quantity`/`cart_item_id` on Vital Kitchen entries populate for a
logged-in user **or** a guest with a valid `X-Guest-Token`/`guest_token` (consistent with
the guest cart support in §3.2) — they read `false`/`0`/`null` only when neither is present,
same as an empty cart. `is_wishlisted` (new field, see §2.4) follows the same rule.

### 2.2 Product Details

**Grocery** — `GET /api/home/products/{productId}` (existing, unchanged): returns a
`ProductDetailResource` — its `pricing[]` array's entries each have an `id`, which is the
**`product_pricing_id`** needed for add-to-cart (§3.1). A product can have multiple pricing
rows (size/variant), so the client typically lets the user pick one before adding.

**Vital Kitchen** — `GET /api/vital-kitchen/bowls/{id}` (public route, no auth required, but
now reads Bearer token / `X-Guest-Token` / `guest_token` **if present** — see below):
```json
{
  "status": true,
  "message": "Bowl details fetched successfully.",
  "data": {
    "id": 1, "product_type": "vital_kitchen", "name": "Test FWO Daily",
    "description": "...", "image": "https://.../image.jpg", "bowl_type": "veg",
    "pack_size": "500g", "mrp": 299.0, "selling_price": 249.0, "discount_percent": 17,
    "min_order_qty": 1, "max_order_qty": 5, "category_name": "Signature Bowls",
    "is_in_cart": true, "cart_quantity": 2, "cart_item_id": 7,
    "selected_addon_ids": [3],
    "is_wishlisted": true,
    "health_benefits": [{ "id": 1, "name": "High Protein" }],
    "addons": [{ "id": 1, "name": "Avocado", "price": 50.0, "max_qty": 2 }],
    "related_bowls": [
      {
        "id": 5, "product_type": "vital_kitchen", "name": "Protein Power Bowl",
        "image": null, "short_description": "...", "bowl_type": "non_veg",
        "min_order_qty": 1, "max_order_qty": 5,
        "mrp": 320.0, "selling_price": 280.0, "discount_percent": 13,
        "category_name": "Signature Bowls",
        "is_in_cart": false, "cart_quantity": 0, "cart_item_id": null,
        "is_wishlisted": false
      }
    ]
  }
}
```
`404` with `"This item is not available."` if inactive/missing. A bowl has **fixed pricing**
(`selling_price`/`offer_price`), **not** a `ProductPricing`-style variant/size system like
regular products — there is no "select size" step for Vital Kitchen bowls.

**NEW: `is_in_cart` / `cart_quantity` / `cart_item_id` / `selected_addon_ids` /
`is_wishlisted`** — previously missing from this endpoint (it returned static bowl info
only, unlike grocery product details which always had `is_wishlisted` and cart-state via
`pricing[]`). Now populated the same way as the Home Sections bowl card (§2.1): pass a
Bearer token, or `X-Guest-Token` header / `guest_token` query param for a guest — same
resolution as the cart/wishlist endpoints. With neither, these read `false`/`0`/`null`/`[]`
(unauthenticated browsing still works, just without personalized state).
`selected_addon_ids` reflects the addons already on this bowl's existing cart line (if
any) — use it to pre-check the matching addon toggles when rendering the customization UI,
same as the website's `salad-details.blade.php` does.

**NEW: `related_bowls`** — up to 4 other active bowls (random order, excludes the one being
viewed), same shape as a Home Sections bowl card (§2.1) including live `is_in_cart`/
`is_wishlisted` state for the requesting user/guest. This powers an "Explore More Salads"
section on this screen — mirrors what the website's `salad-details.blade.php` page already
shows below the bowl detail. Each entry's `id` is a bowl id — re-fetch
`GET /api/vital-kitchen/bowls/{id}` when the user taps one, same as any other bowl card.

### 2.3 Client branching — details + add-to-cart pairing
Use `product_type` (present on every product-shaped item — search results, cart items,
and now Home Sections listings) to decide which pair of endpoints to call:
```js
if (item.product_type === 'vital_kitchen') {
  // GET  /api/vital-kitchen/bowls/{item.id}
  // POST /api/cart/vital-kitchen/add   { salad_bowl_id: item.id, quantity }
} else {
  // GET  /api/home/products/{item.id}
  // POST /api/cart/add   { product_pricing_id: chosenPricing.id, quantity }
}
```

### 2.4 Wishlist — `/api/wishlist/*` now supports Vital Kitchen bowls too

**BREAKING/NEW:** the wishlist endpoints previously only accepted `product_id` (grocery).
They now branch on a `type` field — send `type: "vital_kitchen"` to target a bowl instead
of a product. Same guest support as before (Bearer token, or `X-Guest-Token`/`guest_token`
— no login required for wishlist, same as cart).

- **`POST /api/wishlist/toggle`**
  - Grocery (unchanged): `{ "product_id": 25, "guest_token": "..." }`
  - Vital Kitchen (new): `{ "type": "vital_kitchen", "salad_bowl_id": 1, "guest_token": "..." }`
  - Response now also carries `salad_bowl_id` and `product_type`:
    ```json
    { "status": true, "message": "Item added to wishlist.",
      "data": { "in_wishlist": true, "product_id": null, "salad_bowl_id": 1, "product_type": "vital_kitchen" } }
    ```
    For a grocery toggle, `salad_bowl_id` is `null` and `product_type` is `"grocery"` —
    both fields are always present now, regardless of which type you toggled.
- **`DELETE /api/wishlist/{id}`** — pass the **bowl's id** as `{id}` and add
  `?type=vital_kitchen` to remove a Vital Kitchen wishlist entry: `DELETE
  /api/wishlist/1?type=vital_kitchen`. Omit `type` (or any other value) for grocery,
  unchanged.
- **`GET /api/wishlist`** — the list now returns **both** types merged, each entry tagged
  `product_type`. The nested object is always called `product` for both types (not
  `salad_bowl`), but its shape differs — branch on the parent's `product_type` before
  reading fields, same rule as §2.1:
  ```json
  {
    "data": [
      {
        "id": 12, "product_type": "vital_kitchen", "product_id": null, "salad_bowl_id": 1,
        "product": {
          "id": 1, "name": "Test FWO Daily", "image": null, "short_description": "...",
          "bowl_type": "veg", "min_order_qty": 1, "max_order_qty": 5,
          "mrp": 299.0, "selling_price": 249.0,
          "is_in_cart": true, "cart_quantity": 2, "cart_item_id": 7
        }
      },
      {
        "id": 13, "product_type": "grocery", "product_id": 25, "salad_bowl_id": null,
        "product": {
          "id": 25, "name": "Coconut Oil", "image": null, "short_description": null,
          "min_order_qty": 0, "max_order_qty": 0,
          "is_in_cart": false, "cart_quantity": 0, "cart_item_id": null,
          "pricing": { "...": "existing ProductPricingResource shape" }
        }
      }
    ]
  }
  ```
  A Vital Kitchen `product` entry never has a `pricing` object (bowls have flat
  `mrp`/`selling_price`, same as everywhere else in this doc) — only grocery entries do.

---

## 3. Cart API — now returns TWO sections in one response

### `GET /api/cart`
Auth: Bearer token (logged in) OR `X-Guest-Token` header / `guest_token` query param —
**both sections now support guest carts identically** (this changed — Vital Kitchen
previously required login for cart access; see §3.2).

**Response (success, 200):**
```json
{
  "status": true,
  "message": "Cart fetched successfully.",
  "data": {
    "overall_grand_total": 349.0,
    "groceries": {
      "cart_id": 13,
      "subtotal": 100.0,
      "product_discount": 0.0,
      "mrp_total": 100.0,
      "discount_total": 0.0,
      "coupon_discount_total": 0.0,
      "tax_total": 0.0,
      "delivery_fee": 0.0,
      "delivery_tip": 0.0,
      "grand_total": 100.0,
      "coupon": null,
      "items_count": 1,
      "serviceability": { "selected_pincode": "641001", "serviceable": true, "message": "..." },
      "frequently_bought_together": [ /* ProductCardResource[] */ ],
      "items": [
        {
          "id": 135, "product_id": 25, "product_pricing_id": 55,
          "name": "Coconut Oil", "image": null, "price": 100.0, "quantity": 1, "total": 100.0,
          "group_name": "Oil", "mrp": 100.0, "line_discount": 0.0,
          "stock_qty": 10, "stock_status": "low_stock", "stock_label": "Low Stock",
          "is_available": true
        }
      ],
      "wallet": { "wallet_type": "points", "balance": 0, "applicable": 0, "...": "..." }
    },
    "vital_kitchen": {
      "cart_id": 2,
      "subtotal": 249.0,
      "delivery_fee": 0.0,
      "delivery_tip": 0.0,
      "grand_total": 249.0,
      "items_count": 1,
      "items": [
        {
          "id": 2, "salad_bowl_id": 1, "product_type": "vital_kitchen",
          "name": "Test FWO Daily", "image": null, "bowl_type": "veg",
          "price": 249.0, "quantity": 1, "total": 249.0,
          "extra_quantities": [], "addons": []
        }
      ]
    }
  }
}
```

**BREAKING CHANGE:** previously `GET /api/cart`'s `data` object *was* the flat grocery
cart summary directly (`data.items`, `data.subtotal`, etc.). It is now nested under
`data.groceries`. Any existing mobile code reading `data.items`/`data.subtotal`/etc.
directly **must** be updated to read `data.groceries.items`/`data.groceries.subtotal`.
`data.vital_kitchen` is new — always present, empty (`items: []`, all totals `0`) when
there's nothing in it (for a guest, resolved from `X-Guest-Token`/`guest_token`, same as
groceries — no login required to have items in this section).

When the whole request fails (network/500), treat both sections as empty — same shape as
above with `items: []` and zero totals (no `cart_id`).

### 2.x `min_order` — minimum order amount (added 2026-07-24)
`GET /api/cart` now also returns a `data.min_order` block:

```json
"min_order": {
  "amount": 100.0,
  "items_value": 36.0,
  "shortfall": 64.0,
  "eligible": false,
  "remarks": "Minimum order amount is ₹100.00. Add items worth ₹64.00 more to place your order."
}
```

- `amount` — the admin-configured minimum (Settings → App & Web → "Minimum Order
  Amount"). `0` means no minimum is in force.
- `items_value` — combined items value across BOTH sections (groceries subtotal +
  vital_kitchen subtotal; after product discounts, before delivery fees/tips).
- `eligible` — `false` when the cart is non-empty and `items_value < amount`. Show
  `remarks` in the cart and disable checkout while `eligible` is false (`remarks` is
  `null` when eligible, and an empty cart is always `eligible: true` — the empty-cart
  state has its own messaging).
- **Server-enforced regardless:** `POST /api/orders/from-cart` rejects a
  below-minimum checkout with a 422 carrying the same message, so the client check is
  UX, not the safety net.

### 2.z Vital Kitchen products in group/subcategory listings (added 2026-07-24)
`GET /api/home/products?group_id=…` (and `…&subgroup_id=…`, plus the
`/api/web/catalog/products` variant) can now include Vital Kitchen products the
admin has assigned to that product group/subcategory. They arrive in the SAME
`data.products` array as the grocery cards, appended after them, using the exact
`SaladBowlCardResource` shape sections already send — discriminate on
`product_type`:

- `"product_type": "grocery"` → grocery card (unchanged)
- `"product_type": "vital_kitchen"` → bowl card (`bowl_type`, `mrp`,
  `selling_price`, `discount_percent`, `is_in_cart`/`cart_quantity`/
  `cart_item_id`, `is_wishlisted`) — route taps to the bowl detail/cart flows,
  same as VK cards in sections.

`price_filter=under_500` and `sort_by=price_*` apply to the VK cards too
(sorted within the appended VK block). Nothing changes for group/subgroup
requests where no VK product is assigned.

### 2.y Delivery tip on Vital-Kitchen-only carts (added 2026-07-24)
`POST /api/tip/apply` / `DELETE /api/tip/remove` previously worked only on the grocery
cart — a VK-only cart got a 422 ("Add items to cart before adding a delivery tip.").
Now, when the grocery cart is empty, the tip is stored on the Vital Kitchen cart
instead (its `grand_total` includes the tip), and the response on that path is:

```json
{ "data": { "applied_to": "vital_kitchen", "vital_kitchen": { ...salad cart summary... } } }
```

The grocery-cart path keeps its existing response shape unchanged. The tip lives in
exactly ONE cart at a time (server-enforced) — read it as
`groceries.delivery_tip + vital_kitchen.delivery_tip` from `GET /api/cart`.
At checkout, a VK-only order records the tip on the checkout's anchor `SaladOrder`
row (`delivery_tip` column, counted once per batch), and order list/detail
(`delivery_tip` in the VK group payload) and invoices include it.

### 3.0 `overall_grand_total` — and how to actually pay via Razorpay (read this)
`data.overall_grand_total` is `groceries.grand_total + vital_kitchen.grand_total`,
computed server-side, so the app never has to add the two totals itself. **Use it only
to display "amount to pay" in the UI before checkout.** It's a preview — it assumes no
delivery-tip override and no wallet redemption at checkout (both are checkout-time-only
adjustments layered on top by `OrderController::storeFromCart`), so it can differ slightly
from the real payable amount in those cases.

**For the actual Razorpay charge, never compute or hardcode an amount on the client at
all** — not `overall_grand_total`, not your own sum of the two totals. The flow is:
1. Call `POST /api/orders/from-cart` with `payment_method: "online"` (§4.6, step 1). The
   server computes the real payable amount (grocery total − its own tip + your requested
   tip + Vital Kitchen total − wallet if used) and creates the Razorpay order **for that
   exact amount**.
2. Pass `razorpay_order.order_id`, `razorpay_order.amount` (already in paise — do not
   multiply by 100 again), and `razorpay_order.key_id` from that response **directly**
   into the Razorpay Checkout SDK's options. The SDK reads the amount from the order,
   not from anything you set — there is no amount field to fill in yourself.
3. After payment, re-call the same endpoint with `payment_reference_no` set (step 2). The
   server independently re-verifies the captured Razorpay amount against a freshly
   recomputed payable total and **rejects the order** (`422`) on any mismatch — so even a
   wrong client-side display amount can never result in being charged the wrong total for
   an order that actually gets created.

Verified server-side: for a cart with no tip override and no wallet, `overall_grand_total`
from `GET /api/cart` exactly equals `payable_amount` from the checkout create-order step.

---

### 3.1 Groceries endpoints (unchanged)
- `POST /api/cart/add` — body `{ product_pricing_id, quantity?, action?: 'add'|'subtract', guest_token? }` → returns the **flat grocery cart summary** directly in `data` (same shape as `data.groceries` above, NOT nested — this endpoint's response shape did not change).
- `PUT /api/cart/items/{id}` — body `{ quantity, guest_token? }` (quantity `0` deletes).
- `DELETE /api/cart/items/{id}`
- `DELETE /api/cart/clear`

### 3.2 Vital Kitchen cart endpoints (guest cart now supported — this changed)
**Login is no longer required to add Vital Kitchen items to cart** — these endpoints now
accept the same `X-Guest-Token` header / `guest_token` body param as groceries, and a
guest's Vital Kitchen cart is automatically merged into their account on login (same
merge that already happens for the grocery cart on `POST /api/auth/verify-otp`).
Checkout (§4) still requires login — only the cart step is guest-accessible, matching
how groceries already work.

- `POST /api/cart/vital-kitchen/add` — body:
  ```json
  { "salad_bowl_id": 1, "quantity": 1, "guest_token": "...", "extra_quantities": [{"salad_ingredient_id": 3, "qty": 1}], "addons": [{"salad_addon_id": 2, "qty": 1}] }
  ```
  `quantity`/`guest_token`/`extra_quantities`/`addons` are optional (`quantity` defaults to
  the bowl's `min_order_qty`; `guest_token` only needed when not logged in — send it the
  same way as `cart/add`). Returns the `vital_kitchen` section shape shown above directly
  in `data` (not nested — same reasoning as `cart/add`).
  - **401** only if neither a Bearer token nor a guest token is present at all:
    `{"status": false, "message": "Authentication or a valid guest_token is required."}`
  - **422** if bowl inactive, or `quantity` exceeds `max_order_qty`.
  - Adding the same bowl with **identical** `extra_quantities`/`addons` merges into the
    existing line (increments quantity) instead of creating a duplicate row; a different
    customization creates a new line.
- `PUT /api/cart/vital-kitchen/items/{id}` — body `{ quantity }` — **absolute** quantity, not
  a delta (unlike groceries' `action: add/subtract` pattern). `quantity: 0` deletes the line.
- `DELETE /api/cart/vital-kitchen/items/{id}`
- `DELETE /api/cart/vital-kitchen/clear`

---

## 4. Checkout — `POST /api/orders/from-cart` (one endpoint, one payment, for both)

Auth: Bearer token required (always — even grocery-only checkout requires login now,
unchanged from before).

### 4.1 What it does
Reads the user's grocery `Cart` **and** `SaladCart` simultaneously. Whichever has items
gets an order created; if both have items, **both** get created in the same DB transaction
under **one combined payment**. If neither has items → `422 "Cart is empty."`

### 4.2 Request body
```json
{
  "address_id": 54,
  "payment_method": "cod",
  "payment_reference_no": null,

  "scheduled_delivery_at": "2026-07-22 07:30:00",
  "scheduled_slot_key": "slot_1",
  "scheduled_slot_label": "07:00 AM - 09:00 AM",

  "vital_kitchen_delivery_type": "now",
  "vital_kitchen_scheduled_delivery_at": null,
  "vital_kitchen_scheduled_slot_key": null,
  "vital_kitchen_scheduled_slot_label": null,

  "delivery_tip": 0,
  "is_bag": false,
  "delivery_instructions": null,
  "use_wallet": false,
  "currency": "INR",
  "receipt": ""
}
```

**BREAKING CHANGE — grocery delivery is now mandatory-scheduled:**
- `delivery_type` field is **removed from the request** (there is no more `"now"` option for
  groceries). Every checkout that includes grocery items **must** send
  `scheduled_delivery_at` (a real future timestamp). If `scheduled_delivery_at` is
  missing/blank while the grocery cart has items → `422`:
  `"Please choose a delivery date and time slot for your grocery items."`
  If present but the resolved time doesn't fall inside a valid configured slot, or is in
  the past → `422` with a slot-specific message (see §4.4).
- If the grocery cart is **empty** (Vital-Kitchen-only checkout), the schedule fields are
  simply ignored — no grocery scheduling error is raised.

**Vital Kitchen delivery timing (independent from groceries):**
- `vital_kitchen_delivery_type`: `"now"` (default if omitted) or `"scheduled"`.
- If `"scheduled"`, `vital_kitchen_scheduled_delivery_at` is **required**, and can be
  **today or tomorrow** only in practice (the UI should only offer those two dates — the
  backend doesn't hard-block a further date, it just resolves it against the same slot
  windows below).
- If the Vital Kitchen cart is empty, these fields are ignored.
- Uses the exact same slot-window configuration as groceries (see §4.4) — fetch via
  `GET /api/settings/scheduled-delivery` (existing endpoint, unchanged) to build the
  date/slot picker for both sections.

### 4.3 Payment amount
The payable amount sent to Razorpay (or charged as COD) is **grocery grand_total + Vital
Kitchen grand_total** combined — always one number, one transaction. Vital Kitchen's own
total has no coupon/wallet/zone-based-fee (flat delivery charge from a settings value only).

### 4.4 Slot validation errors (422, same for grocery and Vital Kitchen scheduling)
- `"Scheduled delivery is currently not available."` — feature disabled in settings.
- `"Scheduled delivery slots are not configured."`
- `"Selected scheduled delivery slot is invalid."` — bad `scheduled_slot_key`.
- `"Scheduled delivery time must be after the current time."`
- `"Scheduled delivery time must be between {slot windows}."` — when no `slot_key` given
  and the raw `scheduled_delivery_at` doesn't fall inside any configured window.

### 4.5 Address / payment / stock validation (422)
- `"Please add or select a delivery address before placing the order."` — no `address_id`
  resolves to a real `UserAddress` owned by the user.
- `"Please select a delivery pincode before placing the order."` / `"Delivery is not
  available for the selected pincode."` — **grocery items only** (zone/pincode
  serviceability doesn't apply to Vital Kitchen).
- `"Cash on Delivery is currently unavailable."` / `"Online payment is currently
  unavailable."` — payment method disabled in settings.
- Per-item stock errors for groceries (existing, unchanged), and for Vital Kitchen:
  ingredient-availability messages like `"Only 3 unit(s) available for {ingredient}; 5
  required."` (from `SaladInventoryService::availabilityErrors()` — checked but **not
  deducted** at checkout; deduction happens later when an admin confirms the order).

### 4.6 Online payment (Razorpay) — two-step flow, unchanged shape
**Step 1** — `payment_method: "online"`, no `payment_reference_no`:
```json
{
  "status": true,
  "message": "Razorpay order created successfully.",
  "data": {
    "payment_method": "online",
    "requires_payment": true,
    "cart_total": 100.0,
    "vital_kitchen_total": 249.0,
    "delivery_tip": 0,
    "payable_amount": 349.0,
    "razorpay_order": { "order_id": "order_xxx", "amount": 34900, "currency": "INR", "key_id": "rzp_xxx" }
  }
}
```
Open Razorpay checkout with this `razorpay_order`. On success, **re-call this same
endpoint** with the identical body **plus** `payment_reference_no` = the Razorpay
`payment_id` returned by the SDK.

**Step 2** — same body + `payment_reference_no` set → proceeds to §4.7 (capture is
verified server-side; amount must exactly match `payable_amount` from step 1 or you get
`422 "Payment amount does not match the cart total."` / `"Paid amount does not match the
payable amount."`).

### 4.7 Success response (COD, or online after capture)
```json
{
  "status": true,
  "message": "Order placed successfully.",
  "data": {
    "order": { /* full OrderResource, or null if the grocery cart was empty */ },
    "salad_orders": [
      { "order_id": 9, "order_no": "CK-SO-000008", "status": "pending", "total_amount": 249.0 }
      /* one entry per distinct bowl in the Vital Kitchen cart; [] if it was empty */
    ]
  }
}
```
- `order` is `null` when checkout was Vital-Kitchen-only.
- `salad_orders` is `[]` when checkout was grocery-only.
- Order numbers: groceries `CK-ORD-000107` (unchanged format), Vital Kitchen `CK-SO-000008`
  (new format/prefix, distinct from the old seeded-data format `SO-2025-...` you may see in
  historical test rows).
- Both carts are cleared atomically in the same transaction.

---

## 5. Search — `GET /api/home/search?q=...` now includes Vital Kitchen results

**New response key**, alongside the existing `products` array:
```json
{
  "data": {
    "query": "salad",
    "total": 5,
    "products": [ /* SearchProductResource[], each now has "product_type": "grocery" */ ],
    "vital_kitchen_products": [
      {
        "id": 1, "product_type": "vital_kitchen", "name": "Test FWO Daily",
        "image": null, "bowl_type": "veg", "min_order_qty": 1, "max_order_qty": 5,
        "mrp": 299.0, "selling_price": 249.0, "category_name": "Signature Bowls"
      }
    ]
  }
}
```
- `products[].product_type` is a **new field**, always `"grocery"`.
- `vital_kitchen_products` is a **new, separate array** — not merged/interleaved into
  `products` (different shape, no `ProductPricing`-style pricing array). Render as a
  distinct section/carousel if you want parity with "products matched" being comprehensive.
- `total` now counts both arrays combined.
- **Note the difference from Home Sections (§2.1):** Search keeps the two types in
  separate arrays; Home Sections merges them into one `products[]` array sorted by
  position. Don't assume the two endpoints share one convention — always check which
  endpoint you're parsing.

---

## 6. `product_type` field — added wherever a product-shaped item appears
A consistent discriminator, `"grocery"` or `"vital_kitchen"`, was added to:
- Home Sections listings (`products[]`, merged) — §2.1.
- Product/bowl detail responses — §2.2.
- Search results (`products[]`, `vital_kitchen_products[]`) — §5.
- Cart items (`groceries.items[]` → always `"grocery"`; `vital_kitchen.items[]` → always
  `"vital_kitchen"`) — §3.
- Order line items (`order.items[]` in the checkout/order responses → always `"grocery"`;
  Vital Kitchen orders are represented as separate `salad_orders[]` entries, not line items,
  since a Vital Kitchen order is always single-bowl).

If your Flutter models don't already have a type discriminator, this is the field to key
UI branching on (icon, route to product-details vs bowl-details, etc.) instead of
inferring type from which array a JSON blob came from.

---

## 7. Order history, detail, invoice & reorder — `GET /api/orders` now includes Vital Kitchen

**BREAKING CHANGE:** `GET /api/orders` now returns **grocery and Vital Kitchen orders
merged into one chronological list**, each entry tagged `order_type: "grocery"` or
`"vital_kitchen"`. This replaces the old grocery-only behavior described in earlier
drafts of this doc — if your app already built a "my orders" screen against this
endpoint expecting only grocery `Order` rows, it now needs to branch on `order_type`.

### 7.1 One checkout with multiple bowls = ONE order entry, not several

A `SaladOrder` row is architecturally **single-bowl** — if a checkout's Vital Kitchen
cart has 3 different bowls, the server internally creates 3 `SaladOrder` rows. **They
are grouped server-side** (via an internal `checkout_batch_id` shared by every row
created in the same checkout) so the customer always sees **one order card** for that
checkout, with all 3 bowls listed as its `items[]` — never 3 separate cards for one
checkout. This grouping applies everywhere a Vital Kitchen order appears: the list
below, the detail endpoint (§7.3), the invoice (§7.4), and reorder (§7.5).

Legacy `SaladOrder` rows created before this grouping existed (no batch id) simply
group as a batch-of-one — same shape, `items_count: 1`.

### 7.2 `GET /api/orders` — order list

Auth: Bearer token required. No pagination — returns the full list as a flat array,
newest first (sorted by `placed_at`, falling back to `created_at`).

**Response (200):**
```json
{
  "status": true,
  "message": "Orders fetched successfully.",
  "data": [
    {
      "id": 9,
      "order_type": "vital_kitchen",
      "order_no": "CK-SO-000008",
      "order_nos": ["CK-SO-000008", "CK-SO-000009", "CK-SO-000010"],
      "status": "pending",
      "status_label": "Pending",
      "payment_method": "cod",
      "payment_status": "pending",
      "delivery_type": "now",
      "scheduled_delivery_at": null,
      "scheduled_slot_label": null,
      "coupon_id": null,
      "coupon_code": null,
      "subtotal": 748.0,
      "product_discount": 0.0,
      "mrp_total": 748.0,
      "discount_total": 0.0,
      "coupon_discount_total": 0.0,
      "tax_total": 0.0,
      "delivery_fee": 30.0,
      "delivery_tip": 0.0,
      "is_bag": false,
      "grand_total": 778.0,
      "selected_pincode": "641001",
      "delivery_zone": null,
      "address_snapshot": {
        "name": "Manikandan S", "mobile": "9999999999",
        "address_line_1": "Test St", "city": "Coimbatore", "pincode": "641001"
      },
      "delivery_instructions": null,
      "items_count": 3,
      "receipt_url": "https://.../invoices/receipt-CK-SO-000008.pdf",
      "placed_at": "2026-07-22 10:15:00",
      "created_at": "2026-07-22 10:15:00",
      "items": [
        {
          "id": 9, "order_no": "CK-SO-000008", "product_type": "vital_kitchen",
          "salad_bowl_id": 1, "product_name": "Test FWO Daily", "bowl_type": "veg",
          "image": null, "quantity": 2, "price": 249.0, "total": 498.0,
          "extra_quantities": [], "addons": []
        },
        {
          "id": 10, "order_no": "CK-SO-000009", "product_type": "vital_kitchen",
          "salad_bowl_id": 4, "product_name": "Protein Power Bowl", "bowl_type": "non_veg",
          "image": null, "quantity": 1, "price": 250.0, "total": 250.0,
          "extra_quantities": [], "addons": []
        }
      ]
    },
    {
      "id": 107,
      "order_type": "grocery",
      "order_no": "CK-ORD-000107",
      "status": "confirmed",
      "status_label": "Confirmed",
      "payment_method": "online",
      "delivery_type": "scheduled",
      "scheduled_delivery_at": "2026-07-23 07:30:00",
      "scheduled_slot_label": "07:00 AM - 09:00 AM",
      "coupon_id": null, "coupon_code": null,
      "subtotal": 100.0, "product_discount": 0.0, "mrp_total": 100.0,
      "discount_total": 0.0, "coupon_discount_total": 0.0, "tax_total": 0.0,
      "delivery_fee": 0.0, "delivery_tip": 0.0, "is_bag": false, "grand_total": 100.0,
      "selected_pincode": "641001", "delivery_zone": null,
      "address_snapshot": { "...": "..." }, "delivery_instructions": null,
      "items_count": 1,
      "receipt_url": "https://.../invoices/receipt-CK-ORD-000107.pdf",
      "placed_at": "2026-07-21 18:02:00", "created_at": "2026-07-21 18:02:00",
      "items": [
        {
          "id": 210, "product_type": "grocery", "product_id": 25, "product_pricing_id": 55,
          "product_name": "Coconut Oil", "product_image": null, "product": { "...": "..." },
          "pricing_label": null, "pricing": { "...": "..." },
          "price": 100.0, "quantity": 1, "total": 100.0
        }
      ]
    }
  ]
}
```

**Field notes — Vital Kitchen entries only:**
- `order_no` is the **first** bowl-row's order number — use this as "the" order number
  for display (e.g. in a title: `Order #CK-SO-000008`).
- `order_nos` is the **full list** of every underlying `SaladOrder` number in the
  checkout — mostly useful for support/debugging; most UIs won't need to render it, but
  if you want to show "+2 more" next to the primary order number, this is the array to
  count. Grocery entries don't have this field (always exactly one `Order` row).
- `items_count` = number of distinct bowls in the checkout (not total quantity).
- `id` is the **first** underlying `SaladOrder`'s numeric id — pass this as `{orderId}`
  to the detail/receipt/reorder endpoints below; the server resolves the whole batch
  from it (§7.1).
- `status`/`payment_status`/`delivery_type`/`scheduled_delivery_at` reflect the first
  row — in practice identical across every row in the same checkout (they're set once,
  together, at checkout time), so this is safe to treat as "the order's" status.

**Field notes — grocery entries:** unchanged shape from before, `items[]` is
`OrderItemResource[]` as already documented; only the new `order_type: "grocery"` field
and `status_label` were added.

### 7.3 `GET /api/orders/{orderId}` — order detail

Auth: Bearer token required. `{orderId}` is the `id` field from the list above.

- **Grocery**: `GET /api/orders/{orderId}` (no query param, or omit `type`) — returns
  the same shape as a grocery entry in §7.2, but with the full `items[]` always loaded
  (never a summary/truncated list) and an extra populated `delivery_zone` object when
  applicable.
- **Vital Kitchen**: `GET /api/orders/{orderId}?type=vital_kitchen` — **`type` is
  required** for a Vital Kitchen order; `orderId` and grocery `Order` ids are separate
  auto-increment spaces, so the same numeric id could otherwise mean two different
  orders. Always pass back the `order_type` you got from §7.2 as this query param.
  Returns the same grouped shape as the Vital Kitchen entry in §7.2 (all bowls in the
  batch, in `items[]`).
- `404` if the id doesn't belong to the logged-in user, or doesn't exist.

```
GET /api/orders/9?type=vital_kitchen
GET /api/orders/107
```

### 7.4 Invoice / receipt PDF

Both order types already expose `receipt_url` directly in §7.2/§7.3 responses — that's
the simplest way to get the PDF link (no extra call needed). The endpoints that
generate it, if you need to call them directly (e.g. to force a fresh generation or
build a "download invoice" button from just the id):

- **Grocery**: `GET /api/orders/{orderId}/receipt`
- **Vital Kitchen**: `GET /api/orders/{orderId}/salad-receipt` — **or**
  `GET /api/orders/{orderId}/receipt?type=vital_kitchen` (both route to the same place).
  `{orderId}` is any `SaladOrder` id in the batch (typically the `id` from §7.2/§7.3) —
  the server resolves and renders the **whole batch as one PDF** (one invoice listing
  every bowl in the checkout, one combined grand total), not one PDF per bowl.

**Response (200), both types:**
```json
{
  "status": true,
  "message": "Invoice download link fetched successfully.",
  "data": {
    "invoice_url": "https://.../invoices/receipt-CK-SO-000008.pdf",
    "file_name": "receipt-CK-SO-000008.pdf"
  }
}
```
The PDF is generated once and cached on disk under `public/invoices/` — repeat calls
return the same file instantly rather than regenerating it.

### 7.5 Reorder — `POST /api/orders/{orderId}/reorder`

Auth: Bearer token required. Adds the order's items back into the user's cart (does
**not** place a new order — just repopulates the cart for the user to review/checkout
again).

- **Grocery**: `POST /api/orders/{orderId}/reorder` — unchanged.
- **Vital Kitchen**: `POST /api/orders/{orderId}/reorder?type=vital_kitchen` — adds
  **every bowl in the checkout batch** back into the Vital Kitchen cart (respecting
  each bowl's current `min_order_qty`/`max_order_qty` and skipping any bowl that's gone
  inactive since — same per-item availability handling as grocery reorder).

**Response (200)** — same `ReorderResource` shape for both types:
```json
{
  "status": true,
  "message": "Reorder processed successfully.",
  "data": {
    "added_items": [
      { "product_name": "Test FWO Daily", "quantity": 2 },
      { "product_name": "Protein Power Bowl", "quantity": 1 }
    ],
    "unavailable_items": [
      { "product_name": "Discontinued Bowl", "reason": "Item is no longer available." }
    ],
    "price_changed_items": [],
    "cart": {
      "cart_id": 2, "subtotal": 748.0, "discount_total": 0.0,
      "delivery_fee": 30.0, "grand_total": 778.0, "items_count": 2
    }
  }
}
```
`price_changed_items` is always `[]` for Vital Kitchen (bowls don't carry a historical
price-changed comparison the way grocery `ProductPricing` does — only grocery reorder
populates it). `cart` reflects whichever cart (grocery or Vital Kitchen) the reorder
targeted, `null` if nothing could be added.

---

## 7.7 Orders — action gates + customer cancel endpoint (2026-07-23)

Every order shape (grocery, VK single, VK grouped) now carries three booleans —
drive the buttons from these, they match exactly what the server will allow:

```json
{ "can_cancel": true, "can_reorder": false, "can_download_invoice": false, ... }
```

- `can_cancel` — true only while status is `pending`. Once the store confirms an
  order it can no longer be cancelled by the customer.
- `can_reorder` / `can_download_invoice` — true only once `delivered`.

**NEW: `POST /api/orders/{orderId}/cancel`** (auth) — cancels the customer's own
pending order. `?type=vital_kitchen` cancels the WHOLE checkout batch (same
discriminator as receipt/reorder). Grocery cancels restore stock server-side.
Non-pending orders → `422` "This order can no longer be cancelled — it has
already been {status}." Fires the usual order_cancelled / salad_order_cancelled
notification.

---

## 7.6 Orders — `invoice_no` field (2026-07-23)

Every order shape (grocery `OrderResource`, Vital Kitchen single + grouped orders in
`GET /api/orders` / order detail) now includes:

```json
{ "order_no": "CK-ORD-000059", "invoice_no": "INV-000123", ... }
```

- `invoice_no` is **null until the order is delivered** — invoice numbers are minted
  sequentially at the moment of delivery, from one shared gap-free sequence across
  grocery and Vital Kitchen. Cancelled/pending orders never consume a number.
- A Vital Kitchen checkout (several bowls, one `checkout_batch_id`) carries ONE
  invoice number for the whole checkout.
- Receipt PDFs downloaded before delivery show "-" in the Invoice No cell; after
  delivery they show the real number. Render "Invoice: {invoice_no}" in the app only
  when the field is non-null.

---

## 7.5 Login — `POST /api/auth/verify-otp` now accepts `name` (2026-07-23)

New optional body field on OTP verification:

```json
{ "mobile": "9876543210", "otp": "1234", "name": "Ravi Kumar", "platform": "android", ... }
```

- `name` (nullable, string, max 100) — the customer's name, collected on the login screen.
- Applied **only** when the account has no profile name yet (i.e. first registration, or an
  old account that never set one). An existing profile name is authoritative and is NEVER
  overwritten by this field, so it is always safe to send.
- Purpose: the `new_customer_registered` welcome notification (WhatsApp) previously greeted
  every new customer as the generic "Customer" because OTP signup captured no name. With
  this field the welcome message greets them by name.
- **App change requested:** add a "Your Name" input to the login screen (the website's
  login popup now requires it before sending the OTP) and pass it in the verify-otp body.
  Older app builds that don't send it keep working — the field is optional server-side.

---

## 8. Not in scope / unchanged
- No coupon, no wallet, no zone-based delivery fee for Vital Kitchen orders (flat fee from
  a settings value). These remain grocery-only features.
- Guest **cart** is now supported for Vital Kitchen (see §3.2), but **checkout** (§4) still
  requires login for both product lines, unchanged.
- Admin-side changes (Manage Orders merge, Vital Kitchen order management page) are
  backend/admin-only and have no mobile API surface.

---

## 9. Testing checklist
- [ ] `GET /api/home/sections` and `GET /api/home/sections/{id}` — each section's `products[]`
      correctly mixes grocery and Vital Kitchen items in real display-position order, each
      tagged with `product_type`; UI branches correctly on it for each card shape.
- [ ] Product details: grocery via `GET /api/home/products/{id}`, Vital Kitchen via
      `GET /api/vital-kitchen/bowls/{id}` — both routes tested from a merged Home Sections
      card tap (i.e. the app picks the right endpoint from `product_type`, not by guessing).
- [ ] `GET /api/cart` parses `data.groceries` / `data.vital_kitchen` correctly (not the old flat shape).
- [ ] Add/update/remove grocery items still works unchanged.
- [ ] Add/update/remove Vital Kitchen items as a guest (`X-Guest-Token`, no login) — should
      succeed exactly like groceries; confirm the section is no longer forced empty for guests.
- [ ] Add Vital Kitchen items as a guest, then log in with that `guest_token` via
      `POST /api/auth/verify-otp` — confirm the items appear in the now-logged-in user's
      Vital Kitchen cart and the guest cart row is gone (same merge groceries already get).
- [ ] Checkout (`POST /api/orders/from-cart`) still requires login even with items in a
      guest Vital Kitchen cart — confirm it's rejected/redirects to login, not silently
      allowed as a guest.
- [ ] Checkout: grocery-only, Vital-Kitchen-only, and combined — each produces the correct
      `order`/`salad_orders` combination in the response.
- [ ] Checkout without `scheduled_delivery_at` when groceries are in the cart → 422 with the
      expected message; succeeds when Vital-Kitchen-only.
- [ ] Vital Kitchen "now" vs "scheduled" (today/tomorrow) both succeed.
- [ ] Online payment: Razorpay amount shown to the user equals grocery + Vital Kitchen combined.
- [ ] Confirm the app never computes/sums a payment amount itself — the Razorpay SDK is
      always initialized from `razorpay_order.amount`/`order_id`/`key_id` verbatim from the
      checkout create-order response, not from `overall_grand_total` or any client sum.
- [ ] `overall_grand_total` on `GET /api/cart` matches `payable_amount` from checkout when
      no tip override/wallet is applied; confirm the UI doesn't break when they legitimately
      differ (tip changed at checkout, or wallet applied).
- [ ] Search renders both `products` and `vital_kitchen_products`, each tagged correctly.
- [ ] Bowl detail screen calls the new endpoint and handles the 404 case.
- [ ] `GET /api/orders` renders a merged, newest-first list; each card branches UI on
      `order_type` (`"grocery"` vs `"vital_kitchen"`).
- [ ] Place a Vital Kitchen checkout with **2-3 different bowls in one cart** → confirm it
      appears as **ONE** order card in `GET /api/orders` (not one card per bowl), with
      `items_count` matching the number of distinct bowls and `items[]` listing all of them.
- [ ] Tap that order card → `GET /api/orders/{id}?type=vital_kitchen` returns the same
      full batch (all bowls), not just one.
- [ ] Download/view the invoice for that same multi-bowl order → **one PDF**, listing every
      bowl and one combined grand total (not one PDF per bowl).
- [ ] Reorder that same multi-bowl order (`POST /api/orders/{id}/reorder?type=vital_kitchen`)
      → confirm **all** bowls from the batch are added back to the Vital Kitchen cart, not
      just one.
- [ ] Single-bowl Vital Kitchen checkout still works identically (batch-of-one, same shapes).
- [ ] Grocery order list/detail/receipt/reorder still work unchanged alongside Vital Kitchen
      entries in the same merged list.
- [ ] `GET /api/vital-kitchen/bowls/{id}` returns correct `is_in_cart`/`cart_quantity`/
      `cart_item_id`/`is_wishlisted` for a logged-in user, a guest with a token, and an
      anonymous request (all `false`/`0`/`null`) — confirm it matches the same bowl's card
      state in Home Sections (§2.1).
- [ ] `POST /api/wishlist/toggle` with `type: "vital_kitchen"` adds/removes a bowl; confirm
      it doesn't affect the grocery wishlist and vice versa (separate toggle state).
- [ ] `DELETE /api/wishlist/{bowlId}?type=vital_kitchen` removes only the Vital Kitchen entry.
- [ ] `GET /api/wishlist` renders both types in one list, each branching UI correctly on
      `product_type` (bowl entries never have a `pricing` object).

## 10. Rollback considerations
All new columns/tables are additive (`salad_carts`, `salad_cart_items`, new `SaladOrder`
columns, widened `notification_templates.trigger_event` enum) — safe to roll back
migrations independently. The one **behavior** rollback risk is the grocery
schedule-only change: reverting `OrderController::storeFromCart`'s validation would need to
happen in lockstep with any mobile release that stops sending `scheduled_delivery_at`, or
older app versions will start hitting the new mandatory-schedule 422 unexpectedly.
