> ## Documentation Index
> Fetch the complete documentation index at: https://docs.vizochok.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Cart Synchronization

> How VIZOCHOK keeps the AI-managed cart in sync with your backend cart state via webhooks and SDK events.

VIZOCHOK's cart system follows a simple principle: **your backend is the source of truth for the cart**. The AI manages the shopping experience, but every cart operation goes through your webhook for validation and persistence.

***

## Architecture

There are three participants in the cart flow:

<CardGroup cols={3}>
  <Card title="SDK Widget" icon="browser">
    Receives `cart_changed` events via WebSocket to update the UI. Never talks to your backend directly for cart operations.
  </Card>

  <Card title="VIZOCHOK Backend" icon="brain">
    AI Agent decides what to add/remove. Calls your webhooks server-to-server for validation.
  </Card>

  <Card title="Your Backend" icon="server">
    Source of truth for cart state. Validates operations, checks stock, persists the real cart.
  </Card>
</CardGroup>

***

## Cart Operation Flow

<Steps>
  <Step title="Customer requests cart action">
    Customer says "Add this milk to my cart" in the chat.
  </Step>

  <Step title="AI Agent calls your cart webhook">
    The agent calls `add_to_selection(sku="milk-001", qty=1)` which sends a POST to your `cart_url`:

    ```json theme={null}
    {
      "action": "add",
      "store_id": "store-1",
      "session_id": "user-123",
      "sku": "milk-001",
      "name": "Молоко Lactel 2.5%",
      "quantity": 1,
      "price": 45.90
    }
    ```
  </Step>

  <Step title="Your backend confirms or rejects">
    **Success:** `{"ok": true}`

    **Failure:** `{"ok": false, "reason": "out_of_stock"}`
  </Step>

  <Step title="Agent updates state and responds">
    Agent updates internal cart state, generates a confirmation message, and sends via WebSocket:

    * `text_delta` / `text_end` (AI message)
    * `event {type: "item_selected", sku, name, ...}`
    * `cart_changed {action, items[], total}`
  </Step>

  <Step title="SDK fires onCartChanged callback">
    Your frontend receives the `onCartChanged(cart)` callback and updates the cart badge/sidebar.
  </Step>
</Steps>

***

## Initial Cart Loading

<Steps>
  <Step title="New WebSocket connection">
    Customer opens the chat widget and connects via WebSocket.
  </Step>

  <Step title="VIZOCHOK calls your cart GET webhook">
    ```
    GET https://your-api.com/api/vizochok/cart/items
      ?store_id=store-1&session_id=user-123
    ```
  </Step>

  <Step title="Your backend returns current cart">
    ```json theme={null}
    {
      "items": [
        {"sku": "bread-01", "name": "Хліб", "price": 32.00, "quantity": 1, "unit": "pcs"},
        {"sku": "butter-05", "name": "Масло", "price": 89.50, "quantity": 1, "unit": "pcs"}
      ]
    }
    ```
  </Step>

  <Step title="AI starts with context">
    The AI agent starts the conversation knowing the customer already has bread and butter in their cart.
  </Step>
</Steps>

<Info>
  The `session_id` parameter matches the `userId` you pass to the SDK widget config, or an auto-generated identifier if `userId` is not provided. Use this to look up the correct cart on your side.
</Info>

***

## Handling Cart Events in Your Frontend

Register the `onCartChanged` callback in the widget config to keep your cart UI in sync with AI-managed changes. For the full callback API, event types, and integration examples, see [Events & Callbacks](/widget/events).

### CartItem Structure

Each item in `cart.items` contains:

```typescript theme={null}
interface CartItem {
  sku: string;         // Product SKU
  name: string;        // Product name
  price: number;       // Unit price
  promo_price?: number; // Promotional price (if on sale)
  brand?: string;      // Brand name
  quantity: number;    // Quantity in cart
}
```

***

## Handling Rejections

When your backend rejects a cart operation (e.g., product is out of stock), the AI handles it gracefully:

<Steps>
  <Step title="AI initiates cart action">
    AI: "I'll add that milk to your cart."
  </Step>

  <Step title="Your webhook rejects">
    Your backend returns: `{"ok": false, "reason": "out_of_stock"}`
  </Step>

  <Step title="AI suggests alternatives">
    AI: "Sorry, that milk is currently out of stock. Would you like to try a different brand?"
  </Step>
</Steps>

Common rejection reasons:

| Reason              | When to Return                    |
| ------------------- | --------------------------------- |
| `out_of_stock`      | Product is not available          |
| `product_not_found` | SKU does not exist in your system |
| `quantity_exceeded` | Requested quantity exceeds stock  |
| `missing_sku`       | No SKU provided in the request    |
| `missing_params`    | Required parameters are missing   |

The AI will suggest alternatives when a product is unavailable, using the same search and recommendation system.

***

## Cart Operations

The AI can perform four cart operations through your webhook:

| Action            | Description                             | Required Fields                    |
| ----------------- | --------------------------------------- | ---------------------------------- |
| `add`             | Add a product to the cart               | `sku`, `name`, `quantity`, `price` |
| `remove`          | Remove a product from the cart          | `sku`                              |
| `update_quantity` | Change the quantity of an existing item | `sku`, `quantity`                  |
| `clear`           | Remove all items from the cart          | (none)                             |

For the complete webhook request/response specification, see [Cart Webhook](/webhooks/cart).

***

## Without Webhooks

If you do not configure cart webhooks, VIZOCHOK still tracks the cart internally during the conversation. However:

* Cart state is session-only (not persisted to your backend)
* No stock validation on add
* The `onCartChanged` event still fires in the SDK
* Your frontend would need to reconcile the AI cart with your real cart

<Tip>
  For the best experience, we strongly recommend implementing cart webhooks. This ensures the AI always works with real inventory data and the customer's actual cart state.
</Tip>
