> For the complete documentation index, see [llms.txt](https://docs.datajet-app.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.datajet-app.com/functions/functions/families-and-variables.md). Agents can also search and read this documentation through its [MCP server](https://docs.datajet-app.com/~gitbook/mcp).

# Families and Variables

Families decide which checkout data a function receives as input; variables parameterize that data — tags to check, collections to match, attribute keys to read.

Functions run in a sandbox with no API access — the only data your code sees is the `input` object, and its contents are fixed when the function is created by choosing a **family**. The family can't be changed later, so pick the one that covers everything your rule needs.

When creating a function, the modal shows the exact **Available input** for the selected family and category. In the editor, autocomplete knows the same shape — type `input.` to explore what's available.

Every family except *Address + Variant*, *Customer + Lines* and *Vendor hours* (validation only) and *Delivery groups* (delivery only) is available in the validation, delivery, payment and discount categories — the same family selects the same data in each (discount inputs additionally carry cart line `id`s for targeting). Discounts with the Shipping class receive a second input for the delivery run, which adds each delivery group's options (`handle` and `title`; plus the group `id`, `deliveryMethodType` and `cost` where the family's query has room). See [Discount classes](https://docs.datajet-app.com/functions/functions/discounts.md#discount-classes). [Cart Transform](https://docs.datajet-app.com/functions/functions/cart-transform.md) is the exception: it supports the *General* and *Tags* families only.

## Families

| Family                     | Input data                                                                                                                                                                                                                                                                                                                                                                                                                    | Variables                                                                                                                                               |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| General                    | Broad cart snapshot: totals, buyer identity and customer (name, amount spent, number of orders), lines and products, purchasing company                                                                                                                                                                                                                                                                                       | —                                                                                                                                                       |
| Product                    | Cart lines with variant ID and title (`null` for a product's only, default variant), product tags, collection membership, a product metafield, a line attribute, a cart attribute                                                                                                                                                                                                                                             | `hasProductTags`, `inAnyCollection`, `productMetafieldNamespace`, `productMetafieldKey`, `lineAttributeKey`, `cartAttributeKey`                         |
| Customer                   | Customer identity, tags, a customer metafield, amount spent, order count                                                                                                                                                                                                                                                                                                                                                      | `hasCustomerTags`, `customerMetafieldNamespace`, `customerMetafieldKey`                                                                                 |
| Customer + Discounts       | Whether the buyer is logged in, customer tags and a customer metafield, cart total, and each line's quantity, product title and product tags, total and discounts (amount, target, value, and `marker`, the title of the DataJet discount it comes from). The discount category also gets the codes the buyer typed (`enteredDiscountCodes` with `rejectable`). See [Customer + Discounts family](#customer-discounts-family) | `hasCustomerTags`, `hasProductTags`, `customerMetafieldNamespace`, `customerMetafieldKey`                                                               |
| Customer + Lines           | Whether the buyer is logged in, email, customer ID and a customer metafield, plus cart lines with line and variant IDs, SKUs, product tags, quantity, line total and up to five line attributes. Use it to compare the cart with data your backend stores on the customer. Validation only                                                                                                                                    | `customerMetafieldNamespace`, `customerMetafieldKey`, `hasProductTags`, `lineAttributeKey1` to `lineAttributeKey5`                                      |
| Address                    | Shipping address fields, product tags, a cart attribute                                                                                                                                                                                                                                                                                                                                                                       | `hasProductTags`, `cartAttributeKey`                                                                                                                    |
| Address + Customer         | Shipping address, customer identity and tags, the selected delivery option                                                                                                                                                                                                                                                                                                                                                    | `hasCustomerTags`                                                                                                                                       |
| Address + Product          | Shipping address, product tags and SKUs                                                                                                                                                                                                                                                                                                                                                                                       | `hasProductTags`                                                                                                                                        |
| Address + Variant          | Shipping country, province and zip with the selected delivery option, the buyer's country, B2B company, variant IDs, SKUs and a variant metafield, product tags. Validation only                                                                                                                                                                                                                                              | `hasProductTags`, `variantMetafieldNamespace`, `variantMetafieldKey`                                                                                    |
| Address + Coordinates      | Shipping address with approximate latitude/longitude, the selected delivery option (title, handle, carrier service `code` — null for non-carrier rates, method type) and every available delivery option (handle, title), a cart attribute, a line attribute, shop local date, shop local time-of-day cutoff, checkout step                                                                                                   | `cartAttributeKey`, `lineAttributeKey`, `cutoffTime`                                                                                                    |
| Address + Localized fields | Shipping address, the selected delivery option, localized checkout fields (such as tax IDs), SKUs, product tags                                                                                                                                                                                                                                                                                                               | `hasProductTags`, `localizedFieldKeys`                                                                                                                  |
| Attributes                 | Cart lines with up to five line attributes and a cart attribute, product tags, collection membership, a product metafield                                                                                                                                                                                                                                                                                                     | `lineAttributeKey1` to `lineAttributeKey5`, `cartAttributeKey`, `hasProductTags`, `inAnyCollection`, `productMetafieldNamespace`, `productMetafieldKey` |
| Billing address            | Billing address fields, product tags                                                                                                                                                                                                                                                                                                                                                                                          | `hasProductTags`                                                                                                                                        |
| Billing + Shipping address | Both billing and shipping address fields                                                                                                                                                                                                                                                                                                                                                                                      | —                                                                                                                                                       |
| Cart                       | Full cost breakdown (subtotal, tax, duty, compare-at), cart and line attributes                                                                                                                                                                                                                                                                                                                                               | `cartAttributeKey`, `lineAttributeKey`                                                                                                                  |
| Cart totals                | Subtotal, tax and duty totals, billing country, shipping country, delivery option cost, vendors, line subtotals and discount allocations, product and customer tags                                                                                                                                                                                                                                                           | `hasProductTags`, `hasCustomerTags`                                                                                                                     |
| Discounts                  | Every discount on each cart line — product discounts **and** each line's share of order-wide codes — with amount, type and value, line subtotal and total, product type, handle, title, vendor, gift card flag and collection membership, a cart and line attribute, shop local date. The discount category also gets the codes the buyer entered. See [Discounts family](#discounts-family)                                  | `cartAttributeKey`, `lineAttributeKey`, `inAnyCollection`                                                                                               |
| Delivery groups            | Each delivery group with **its own cart lines** (quantity, subtotal and total, discount allocations with their type, vendor, title, product tags), the group's shipping country and province, group type and delivery options. Delivery only                                                                                                                                                                                  | `hasProductTags`                                                                                                                                        |
| Nested lines               | Cart lines with their parent line (bundles and add-ons), product tags, collection membership, a product metafield, line attribute                                                                                                                                                                                                                                                                                             | `hasProductTags`, `inAnyCollection`, `productMetafieldNamespace`, `productMetafieldKey`, `lineAttributeKey`                                             |
| Selling plan               | Selling plan allocations on cart lines (subscriptions), variant weight and weight unit, SKUs, product tags                                                                                                                                                                                                                                                                                                                    | `hasProductTags`                                                                                                                                        |
| Shipping                   | The selected delivery option (title, method type), every available delivery option (handle, title), shipping country code, product and customer tags, up to four cart attributes                                                                                                                                                                                                                                              | `hasProductTags`, `hasCustomerTags`, `cartAttributeKey`, `cartAttributeKey2`, `cartAttributeKey3`, `cartAttributeKey4`                                  |
| Tags                       | Product and customer tags together, line attributes                                                                                                                                                                                                                                                                                                                                                                           | `hasProductTags`, `hasCustomerTags`, `lineAttributeKey`                                                                                                 |
| Time                       | Shop local time comparisons, product and customer tags                                                                                                                                                                                                                                                                                                                                                                        | `hasProductTags`, `hasCustomerTags`, `dateTimeAfter`, `dateTimeBefore`, `timeAfter`, `timeBefore`                                                       |
| Vendor hours               | Shop local date and eight time-of-day checkpoints, a shop JSON metafield (for example opening hours per vendor), each line's vendor, product tags and quantity, the function's own query variables. See [Vendor hours family](#vendor-hours-family). Validation only                                                                                                                                                          | `c1` to `c8`, `scheduleMetafieldNamespace`, `scheduleMetafieldKey`, `hasProductTags`                                                                    |

### Discounts family

Use it for rules that depend on what the buyer **actually pays** for some products: a minimum spend on a collection after discounts, a limit on how much discount an order can get, or a check on which codes were used.

**How the amounts work** (checked against real checkouts):

* `line.cost.subtotalAmount` is the line **before any discount**.
* `line.cost.totalAmount` is the line after **product** discounts only. It never includes order-wide codes.
* `line.discountAllocations` lists **every** discount on the line: product discounts, and the line's share of each order-wide discount. Shopify splits an order-wide discount across lines in proportion to their value (a 10% code on a 52.00 line allocates 5.20 to it; 5.00 off a 52.00 + 20.00 cart allocates 3.61 and 1.39).
* So the amount the buyer pays for a line after **all** discounts is `subtotalAmount − sum of discountAllocations`.
* Order-wide codes already show up at the cart step and on every checkout step.
* `input.cart.cost.subtotalAmount` is the cart **after product discounts** but before order-wide ones, so don't use it as a "before any discount" total.
* Prices include tax when the store shows prices with tax included.

Each allocation's `discountApplication` tells you what kind of discount it is:

| Field              | Values                                                                                                                                   |
| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
| `targetSelection`  | `ALL` — an order-wide discount; `ENTITLED` / `EXPLICIT` — a product discount                                                             |
| `allocationMethod` | `ACROSS` — one amount split across lines; `EACH` — applied to each line                                                                  |
| `targetType`       | `LINE_ITEM` (shipping discounts never appear on cart lines)                                                                              |
| `value`            | `{ __typename: "PricingPercentageValue", value }` for a percentage (`"10.0"`), or `{ __typename: "MoneyV2", amount }` for a fixed amount |

**Discount codes.** Validation, delivery and payment functions can't read the code text — Shopify doesn't provide it — but `targetSelection: "ALL"` tells you an order-wide discount applied and the allocations tell you how much. Discount-category functions also get `input.enteredDiscountCodes: [{ code }]`, the codes the buyer typed (gift cards excluded). In a discount function the discounts on each line may not be complete, because Shopify works out all discounts together.

**Collections.** Set the `inAnyCollection` query variable; each product gets `inCollections: [{ collectionId, isMember }]`, like the Product family. See the [collection minimum example](https://docs.datajet-app.com/functions/functions/examples.md#collection-minimum-after-all-discounts).

### Customer + Discounts family

Use it for rules that combine **who the buyer is** with **which discounts they get**: a customer group that must not use discount codes, a budget or credit discount for tagged customers, or "this discount only, nothing else" for some customers.

* `input.cart.buyerIdentity` is `null` for guests. Check `isAuthenticated` and `customer` before reading tags or the metafield.
* `customer.hasTags` and `customer.metafield` work as in the Customer family (`hasCustomerTags`, `customerMetafieldNamespace`, `customerMetafieldKey`).
* Each line's `product.hasTags` answers for the tags in the `hasProductTags` query variable, e.g. to leave products tagged `no-budget` out of a budget discount (put their line ids in the order discount's `excludedCartLineIds`).
* `line.discountAllocations` works as in the [Discounts family](#discounts-family) (in the discount category without `targetType`, which is always `LINE_ITEM` on cart lines), with one extra field: `discountApplication.marker.value` is the title of the DataJet discount the allocation comes from, and `null` for any other discount (Shopify discounts, other apps, codes). Shipping discounts never appear on cart lines.
* The discount category also gets `input.enteredDiscountCodes: [{ code, rejectable }]`, so a discount function can reject codes for some customers with `enteredDiscountCodesReject`. See [Rejecting discount codes](https://docs.datajet-app.com/functions/functions/discounts.md#rejecting-discount-codes).

See the example [Block tagged customers from using discount codes](https://docs.datajet-app.com/functions/functions/examples.md#block-tagged-customers-from-using-discount-codes).

## Two kinds of variables

Functions have two variable systems, opened from the segmented buttons in the editor toolbar:

* **Function** and **Global** — *code variables*: values your code reads through the `vars` object, like `vars.MAX_ORDER_TOTAL`. Use them instead of hardcoding thresholds and settings.
* **Query** — *query variables*: values that parameterize the function's **data query** on Shopify's side, like which tags each product is checked against.

## Code variables

Code variables use the **same format as** [**script variables**](https://docs.datajet-app.com/misc/variables.md): keys are `type#NAME` (a bare name implies `short_text`), plus an optional `metadata` object that turns variables into merchant-friendly input fields.

```json
{
  "short_text#MAX_ORDER_TOTAL": "5000",
  "checkbox#BLOCK_PO_BOXES": true,
  "metadata": {
    "MAX_ORDER_TOTAL": { "subtype": "number", "helpText": "Orders above this total are blocked" }
  }
}
```

Your code reads the stripped names through `vars`:

```javascript
if (parseFloat(input.cart.cost.totalAmount.amount) > parseFloat(vars.MAX_ORDER_TOTAL)) {
  return ['Orders above ' + vars.MAX_ORDER_TOTAL + ' are not allowed'];
}
return [];
```

* **Function** variables belong to one function. **Global** variables are shared with scripts and with every function on the store; a function variable overrides a global with the same name.
* The `metadata` property never reaches your code — it only drives the input fields. All metadata options from [script variables](https://docs.datajet-app.com/misc/variables.md) are supported.
* Values keep their JSON types: a `checkbox` arrives as a boolean, `json` as an object. There is no `secrets` access inside functions — don't store credentials in variables (the sandbox has no network access to use them anyway).

### Editing configuration from the dashboard

On the main dashboard's **Functions** tab, clicking a function expands its **Function configuration** — the same metadata-driven form merchants use for script tasks. Anyone can adjust values (a threshold, a toggle) without opening the code; saving applies to the live function on the next checkout.

### Vendor hours family

Use it to block checkout when a vendor in the cart is outside its business hours, for example on a marketplace where each vendor has its own opening times.

**Functions have no clock.** Shopify doesn't give a function the current time. It only answers yes/no questions you set up in advance: "is it 09:00 yet?". This family asks eight such questions, called **checkpoints**. You set them as the query variables `c1` to `c8` (`"HH:MM:SS"`), and your code gets `input.shop.localTime.c1` to `c8`: `true` once the shop's local time reaches that time of day. Times are in the store's timezone (**Settings > General**).

* Use the distinct opening and closing times of your vendors as checkpoints, sorted from earliest to latest. Midnight never needs one.
* Which checkpoints are `true` tells your code where "now" falls between them, to the minute.
* A checkpoint is `true` **at** its time. A closing time of 22:00 starts blocking at 22:00, not 22:01.
* There is no day of the week in the input. Work it out from `input.shop.localTime.date` (`"YYYY-MM-DD"`).
* Your code also gets the function's own query variables as `input.validation.input.jsonValue`, so it knows which time each checkpoint holds.
* Keep the hours themselves in a shop JSON metafield and point `scheduleMetafieldNamespace` / `scheduleMetafieldKey` at it. Your code reads it as `input.shop.schedule.jsonValue`.

**More than eight times.** One function holds eight checkpoints. If your vendors use more distinct times across the week, split them over **several functions of this family**. Give each function a group of vendors whose times fit in eight, its own checkpoints, and its own metafield (or its own part of a shared one). Group vendors that share times, so fewer functions are needed. Each function counts as one active function on your plan, and Shopify allows at most **25** active validation functions per store.

**Keeping it in sync.** When hours change, the checkpoints and the metafield must change together. A scheduled DataJet script can read your vendors' hours, work out the groups, and write each function's checkpoints and metafield. See the [vendor hours example](https://docs.datajet-app.com/functions/functions/examples.md#vendor-opening-hours).

## Query variables

Checkout data is fetched by a query that runs **before** your code — so anything dynamic in that query has to be set up front. That's what query variables are for: they parameterize the function's data query on Shopify's side. For example, `hasProductTags` controls which tags each product is checked against, and the result arrives in your `input` already resolved.

Open the **Query** button in the editor and provide a JSON object with the family's keys:

```json
{
  "hasProductTags": ["limited", "preorder"],
  "inAnyCollection": ["gid://shopify/Collection/123456789"]
}
```

| Variable                                              | Type                           | What it does                                                                                                   |
| ----------------------------------------------------- | ------------------------------ | -------------------------------------------------------------------------------------------------------------- |
| `hasProductTags`                                      | array of strings               | Each product in `input` gets `hasTags: [{ tag, hasTag }]` for these tags                                       |
| `hasCustomerTags`                                     | array of strings               | The customer gets `hasTags: [{ tag, hasTag }]` for these tags                                                  |
| `inAnyCollection`                                     | array of collection IDs        | Each product gets `inCollections: [{ collectionId, isMember }]`                                                |
| `productMetafieldNamespace` / `productMetafieldKey`   | string                         | Each product gets `metafield: { value }` for this namespace/key                                                |
| `variantMetafieldNamespace` / `variantMetafieldKey`   | string                         | Each variant gets `metafield: { value }` for this namespace/key                                                |
| `customerMetafieldNamespace` / `customerMetafieldKey` | string                         | The customer gets `metafield: { value }`                                                                       |
| `cartAttributeKey`                                    | string                         | The cart gets `attribute: { value }` for this key                                                              |
| `cartAttributeKey2` / `3` / `4`                       | string                         | Shipping family: the cart gets `attribute2`, `attribute3`, `attribute4`: `{ value }` for these keys            |
| `lineAttributeKey`                                    | string                         | Each cart line gets `attribute: { value }` for this key                                                        |
| `lineAttributeKey1` to `lineAttributeKey5`            | string                         | Attributes family: each cart line gets `attr1` to `attr5`: `{ value }` for these keys                          |
| `localizedFieldKeys`                                  | array of strings               | The cart gets `localizedFields: [{ key, value }]` for these fields, such as `TAX_CREDENTIAL_IT`                |
| `dateTimeAfter` / `dateTimeBefore`                    | string `"YYYY-MM-DDTHH:MM:SS"` | `input.shop.localTime` gets a boolean comparison against shop local time                                       |
| `timeAfter` / `timeBefore`                            | string `"HH:MM:SS"`            | Same, for time of day                                                                                          |
| `c1` to `c8`                                          | string `"HH:MM:SS"`            | Vendor hours family: `input.shop.localTime.c1` to `c8` are `true` once the shop's local time reaches each time |
| `scheduleMetafieldNamespace` / `scheduleMetafieldKey` | string                         | Vendor hours family: the shop gets `schedule: { jsonValue }` for this JSON metafield                           |

**Reading the resolved values in code:**

```javascript
// hasProductTags: ["limited"]
var product = input.cart.lines[0].merchandise.product;
var isLimited = product && (product.hasTags || []).some(function (t) { return t.hasTag; });

// cartAttributeKey: "gift_wrap"
var giftWrap = input.cart.attribute && input.cart.attribute.value;

// Delivery groups family: lines are nested under each group
(input.cart.deliveryGroups || []).forEach(function (group) {
  var groupTotal = group.cartLines.reduce(function (sum, line) {
    return sum + parseFloat(line.cost.totalAmount.amount);
  }, 0);
});

// Shipping family, cartAttributeKey2: "locker_id"
var lockerId = input.cart.attribute2 && input.cart.attribute2.value;
(input.cart.deliveryGroups || []).forEach(function (group) {
  var country = group.deliveryAddress && group.deliveryAddress.countryCode;
});

// Time family, timeAfter: "22:00:00"
var isLate = input.shop.localTime.timeAfter;
```

### Notes

* Only the family's own query variables are accepted — unknown keys are rejected on save.
* List variables can have at most **100 items** (Shopify's input query limit).
* Collection IDs can be provided as plain numbers (`123456789`) — they are converted to full Shopify IDs automatically.
* Empty values are dropped, so you can leave template keys you don't use untouched.
* Families without variables (*General*, *Billing + Shipping address*) need no setup — their input is fixed.
* Changing variables affects the live function on the next checkout, just like saving code.
