Metadata-Version: 2.4
Name: vault-funeral-tech-embed
Version: 0.1.6
Summary: Embeddable Vault Funeral Tech UI components for Django
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: Django>=4.0
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"

# vault-funeral-tech-embed

Django package for embedding Vault Funeral Tech commerce components. Serves the prebuilt IIFE assets and provides template tags for all components — no React build step required.

## Installation

```bash
pip install vault-funeral-tech-embed
```

Add to `INSTALLED_APPS`:

```python
INSTALLED_APPS = [
    ...
    "vault_embed",
]
```

Run collectstatic to copy the embed assets into your static root:

```bash
python manage.py collectstatic
```

## Configuration

Add to `settings.py`:

```python
import os

VAULT_API_URL = os.environ.get("VAULT_API_URL", "https://api.yourdomain.com")

# Optional — override brand theme
VAULT_THEME = {
    "primaryColor": "#2d6a4f",
    "fontFamily": "Inter, sans-serif",
    "borderRadius": "6px",
}
```

| Setting | Description |
|---|---|
| `VAULT_API_URL` | **Required.** Vault backend base URL. |
| `VAULT_THEME` | Dict of theme overrides: `primaryColor`, `fontFamily`, `borderRadius`. |

## Authentication

Most components work without a token (browse-only). Components that require a logged-in customer (`vault_family_product_catalog`, `vault_order_list`, `vault_order_details`) show a "not logged in" alert if no token is present.

Obtain a per-user token server-side by calling the Vault partner token endpoint, then pass it to `vault_head`:

```python
# views.py
import json, urllib.request

def catalog_view(request):
    token = _get_vault_token(
        email=request.user.email,
        first_name=request.user.first_name,
        last_name=request.user.last_name,
        external_id=str(request.user.id),
    )
    return render(request, "catalog.html", {"vault_token": token})

def _get_vault_token(email, first_name="", last_name="", external_id=None):
    from django.conf import settings
    api_url = settings.VAULT_API_URL
    partner_key = settings.VAULT_PARTNER_API_KEY
    body = {"email": email, "first_name": first_name, "last_name": last_name}
    if external_id:
        body["external_id"] = external_id
    req = urllib.request.Request(
        f"{api_url}/api/v1/auth/partner/token",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", "Authorization": f"Bearer {partner_key}"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=5) as resp:
        return json.loads(resp.read()).get("token", "")
```

```django
{% vault_head token=vault_token %}
```

To invalidate all tokens for a user (e.g. on logout), call the invalidate endpoint server-side:

```python
def vault_logout(request):
    _vault_invalidate_token(email=request.user.email)
    # or by external_id: _vault_invalidate_token(external_id=str(request.user.id))

def _vault_invalidate_token(email=None, external_id=None):
    from django.conf import settings
    api_url = settings.VAULT_API_URL
    partner_key = settings.VAULT_PARTNER_API_KEY
    body = {}
    if email:
        body["email"] = email
    if external_id:
        body["external_id"] = external_id
    req = urllib.request.Request(
        f"{api_url}/api/v1/auth/partner/invalidate",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json", "Authorization": f"Bearer {partner_key}"},
        method="POST",
    )
    with urllib.request.urlopen(req, timeout=5) as resp:
        return json.loads(resp.read())
```

## Quick Start

```django
{% load vault_embed %}
<!DOCTYPE html>
<html>
<head>
  {% vault_head token=vault_token %}
</head>
<body>
  {% vault_store_home primary_color="#4076C0" accent_color="#8B6F8E" %}
  {% vault_checkout primary_color="#4076C0" accent_color="#8B6F8E" %}
</body>
</html>
```

## JavaScript Events

The IIFE components communicate with your page via DOM custom events. Listen for them with `document.addEventListener`.

| Event | Fired by | `event.detail` |
|---|---|---|
| `vault:product-click` | `vault-product-catalog`, `vault-store-home` | `{ id, title, handle, … }` |
| `vault:category-click` | `vault-store-home` | `{ id, name, handle }` |
| `vault:order-click` | `vault-order-list` | Full order object |
| `vault:order-back` | `vault-order-details` | — |
| `vault:cart-updated` | Cart changes | `{ itemCount }` |
| `vault:open-checkout` | Dispatch this to open the checkout modal | — |
| `vault:order-placed` | `vault-checkout` | `{ order_id }` — fires once the Medusa order is confirmed |

---

## Template Tags

All component tags accept these optional theme override params: `primary_color`, `accent_color`, `font_family`, `card_border_radius`, `button_border_radius`, `class_name`.

---

### `{% vault_head %}`

Outputs the stylesheet `<link>`, global config `<script>`, and the embed JS bundle. Place once inside `<head>`, before any component tags.

```django
{% vault_head %}
{% vault_head token=vault_token primary_color="#2d6a4f" %}
```

| Param | Default | Description |
|---|---|---|
| `token` | `""` | Per-user customer JWT. |
| `api_url` | `settings.VAULT_API_URL` | Vault backend base URL. |
| `primary_color` | — | CTA color override (applied globally). |

---

### `{% vault_store_home %}`

Full storefront landing page. When authenticated, shows a welcome banner with monthly order stats and an "Order again" row. Below that: category grid, new arrivals, and curated collection rows.

Dispatches `vault:product-click` and `vault:category-click`.

```django
{% vault_store_home primary_color="#4076C0" accent_color="#8B6F8E" %}
```

| Param | Default | Description |
|---|---|---|
| `show_categories` | `True` | Show the category grid. |
| `show_new_arrivals` | `True` | Show the new arrivals row. |
| `show_collections` | `True` | Show curated collection rows. |

---

### `{% vault_product_catalog %}`

Filterable, paginated product grid. Dispatches `vault:product-click` when a card is clicked.

```django
{% vault_product_catalog limit=12 category_handle="caskets" display_search=True show_family_badges=True %}
```

| Param | Default | Description |
|---|---|---|
| `limit` | `12` | Products per page. |
| `category_id` | — | Filter by Medusa category ID. |
| `category_handle` | — | Filter by category handle, e.g. `"caskets"`. Comma-separated for multiple. |
| `vendor_id` | — | Filter to a specific vendor. |
| `brand_id` | — | Filter to a specific brand. |
| `columns` | `"auto"` | `2`, `3`, `4`, or `"auto"`. |
| `show_sort` | `True` | Show the sort dropdown. |
| `show_pagination` | `True` | Show pagination controls. |
| `display_search` | `False` | Show the search bar. |
| `show_family_badges` | `False` | Badge products already in the family catalog. |

To filter by category after a `vault:category-click` event:

```js
document.addEventListener('vault:category-click', function(e) {
    var cat = document.querySelector('vault-product-catalog')
    cat.setAttribute('category-handle', e.detail.handle)
})
```

---

### `{% vault_family_product_catalog %}`

Shows only products a funeral home has added to their family catalog, with per-product markup applied to the displayed price. Requires authentication — shows a "not logged in" alert if no token is present. The funeral home ID is derived automatically from the JWT.

```django
{% vault_family_product_catalog limit=12 columns=3 primary_color="#4076C0" %}
```

| Param | Default | Description |
|---|---|---|
| `limit` | `12` | Products per page. |
| `category_id` | — | Filter by category ID. |
| `category_handle` | — | Filter by category handle. |
| `columns` | `"auto"` | `2`, `3`, `4`, or `"auto"`. |
| `show_sort` | `True` | Show the sort dropdown. |
| `show_pagination` | `True` | Show pagination controls. |

---

### `{% vault_brand_list %}`

Searchable grid of all brands, matching the storefront `/store/brands` layout. Dispatches `vault:brand-click` when a card is clicked.

```django
{% vault_brand_list primary_color="#4076C0" %}
```

To navigate to a filtered catalog on brand click:

```js
document.addEventListener('vault:brand-click', function(e) {
    var cat = document.querySelector('vault-product-catalog')
    cat.setAttribute('brand-id', e.detail.id)
    // show catalog view
})
```

---

### `{% vault_cart %}`

Cart panel showing line items, quantities, and subtotal. Meant to be shown as a sidebar or drawer toggled by your own button.

```django
{% vault_cart primary_color="#4076C0" %}
```

Listen for cart count changes to update a badge:

```js
window.addEventListener('vault:cart-updated', function(e) {
    document.getElementById('cart-badge').textContent = e.detail.itemCount
})
```

---

### `{% vault_checkout %}`

Multi-step checkout modal (address → shipping → payment → confirmation). Place once per page; it stays hidden until opened. The Stripe publishable key is fetched automatically from the Vault API.

```django
{% vault_checkout primary_color="#4076C0" %}
```

Open from your own button:

```js
document.dispatchEvent(new CustomEvent('vault:open-checkout'))
```

Once an order is confirmed, `vault:order-placed` fires with the Medusa order ID:

```js
document.addEventListener('vault:order-placed', function(e) {
  console.log('Order confirmed:', e.detail.order_id)
})
```

> **Note:** `vault:order-placed` fires asynchronously — the Medusa order is created via Stripe webhook after payment completes. The confirmation screen polls for up to 30 seconds and dispatches this event once the order ID is available.

---

### `{% vault_order_list %}`

Paginated list of the authenticated customer's past orders. Requires authentication — shows a "not logged in" alert if no token is present. Dispatches `vault:order-click` with the full order object when a row is clicked.

```django
{% vault_order_list primary_color="#4076C0" page_size=10 %}
```

| Param | Default | Description |
|---|---|---|
| `page_size` | `10` | Orders per page. |

---

### `{% vault_order_details %}`

Full detail view for a single order — line items, shipping address, totals, and invoice download. Initially empty; call `element.setOrder(order)` from JS to populate it. Dispatches `vault:order-back` when the back button is clicked.

```django
{% vault_order_details primary_color="#4076C0" element_id="vault-order-details" %}
```

| Param | Default | Description |
|---|---|---|
| `element_id` | `"vault-order-details"` | HTML `id` for the element so JS can target it. |

Wire it to `vault_order_list`:

```js
document.addEventListener('vault:order-click', function(e) {
    document.getElementById('vault-order-details').setOrder(e.detail)
    // swap visible views
})

document.addEventListener('vault:order-back', function() {
    // swap back to order list
})
```

---

## Full Example

```django
{% load vault_embed %}
<!DOCTYPE html>
<html>
<head>
  {% vault_head token=vault_token %}
</head>
<body>
  <div style="display:flex; gap:2rem;">
    <div style="flex:1;">

      <!-- Store home (default view) -->
      <div id="home-view">
        {% vault_store_home primary_color="#4076C0" accent_color="#8B6F8E" %}
      </div>

      <!-- Catalog view -->
      <div id="catalog-view" style="display:none;">
        {% vault_product_catalog limit=12 primary_color="#4076C0" display_search=True %}
      </div>

      <!-- Order history -->
      <div id="orders-view" style="display:none;">
        {% vault_order_list primary_color="#4076C0" %}
      </div>

      <!-- Order detail (populated by JS) -->
      <div id="order-detail-view" style="display:none;">
        {% vault_order_details primary_color="#4076C0" %}
      </div>

    </div>

    <!-- Cart sidebar -->
    <div id="cart-panel" style="width:300px; display:none;">
      {% vault_cart primary_color="#4076C0" %}
    </div>
  </div>

  {% vault_checkout primary_color="#4076C0" %}

  <script>
    // Category click → switch to catalog filtered by that category
    document.addEventListener('vault:category-click', function(e) {
      var cat = document.querySelector('vault-product-catalog')
      if (cat) cat.setAttribute('category-handle', e.detail.handle)
      showView('catalog')
    })

    // Product click → show product details (using vault-product-details web component)
    document.addEventListener('vault:product-click', function(e) {
      // Set product-id on a <vault-product-details> element and show it
    })

    // Order click → show order detail
    document.addEventListener('vault:order-click', function(e) {
      document.getElementById('vault-order-details').setOrder(e.detail)
      showView('order-detail')
    })

    document.addEventListener('vault:order-back', function() {
      showView('orders')
    })

    function showView(name) {
      ['home', 'catalog', 'orders', 'order-detail'].forEach(function(v) {
        document.getElementById(v + '-view').style.display = v === name ? 'block' : 'none'
      })
    }
  </script>
</body>
</html>
```

---

## Related

- **React / npm**: [`@vault-funeral-tech/embed`](https://www.npmjs.com/package/@vault-funeral-tech/embed) — use this package when building a React app.

## License

MIT
