> 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/discounts.md). Agents can also search and read this documentation through its [MCP server](https://docs.datajet-app.com/~gitbook/mcp).

# Discounts

Apply automatic product, order and shipping discounts at checkout with JavaScript.

A discount function applies automatic discounts to cart lines, the whole order or delivery options. Your code inspects the cart and returns a list of operations with discount candidates.

```javascript
var candidates = input.cart.lines.map(function (line) {
  return {
    targets: [{ cartLine: { id: line.id } }],
    value: { percentage: { value: 10 } },
  };
});

return {
  operations: [
    { productDiscountsAdd: { selectionStrategy: 'FIRST', candidates: candidates } },
  ],
};
```

The cart lines are in `input.cart.lines`, each with an `id` your candidates target. The discount's own settings are in `input.discount` (`discountClasses`).

### Discount classes

When you add a discount function, pick one or more **discount classes**. They decide what the discount can reduce and when your code runs:

| Class    | Discounts                                    | Your code runs with           |
| -------- | -------------------------------------------- | ----------------------------- |
| Products | Individual cart lines                        | `input.target === 'lines'`    |
| Order    | The order subtotal                           | `input.target === 'lines'`    |
| Shipping | Delivery options, e.g. free Express shipping | `input.target === 'delivery'` |

New discount functions default to **Products** and **Order**. You can change the classes later with **Edit**; the family stays fixed.

Shopify runs the code once for Products/Order (the *lines run*) and once for Shipping (the *delivery run*). If you select both kinds, the same code runs twice per checkout, so check `input.target` and return the operations for that run. Each run keeps only its own operations and ignores the rest.

The two runs receive different input. The lines run gets cart lines with their `id`s. The delivery run gets `input.cart.deliveryGroups[].deliveryOptions`, each with a `handle` and `title`, in every family. The **Available input** preview in the Add new dialog shows both shapes, and the editor's autocomplete narrows `input` once you check `input.target`.

{% hint style="info" %}
The function's **title** is shown to buyers at checkout as the discount name — pick something merchant-shippable like `10% off accessories`.
{% endhint %}

### Operations

Return an array of operations, or `{ operations: [...] }`. Each operation is an object with exactly one of these keys:

| Operation             | Shape                                                                        | Effect                                                                    |
| --------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Product discounts     | `{ productDiscountsAdd: { selectionStrategy: 'FIRST', candidates: [...] } }` | Discounts individual cart lines (lines run)                               |
| Order discounts       | `{ orderDiscountsAdd: { selectionStrategy: 'FIRST', candidates: [...] } }`   | Discounts the order subtotal (lines run)                                  |
| Shipping discounts    | `{ deliveryDiscountsAdd: { selectionStrategy: 'ALL', candidates: [...] } }`  | Discounts delivery options (delivery run)                                 |
| Reject discount codes | `{ enteredDiscountCodesReject: { codes: [{ code }], message } }`             | Removes codes the buyer typed and shows `message` in checkout (lines run) |

Each candidate is:

```javascript
{
  message: 'Loyalty discount',                 // optional, shown next to the discount
  targets: [{ cartLine: { id: line.id } }],    // product discounts target cart lines
  // targets: [{ orderSubtotal: { excludedCartLineIds: [] } }],  // order discounts
  // targets: [{ deliveryOption: { handle: option.handle } }],   // shipping discounts
  value: { percentage: { value: 10 } },        // or { fixedAmount: { amount: '10.0' } }
}
```

`selectionStrategy` decides what happens when several candidates match the same target. For product and order discounts, `FIRST` applies the first one and `MAXIMUM` the largest. Shipping discounts only support `ALL`, which applies every matching candidate. Returning an empty array applies no discount. Operations of any other shape are ignored.

A shipping candidate targets a single delivery option (`{ deliveryOption: { handle } }`). To discount every option, add one target per option. To make an option free, use `{ percentage: { value: 100 } }`.

#### Rejecting discount codes

`enteredDiscountCodesReject` removes discount codes the buyer typed, for the whole cart. It needs the codes in the input, so use the **Customer + Discounts** family, whose lines run gets `input.enteredDiscountCodes: [{ code, rejectable }]`. Only reject codes with `rejectable: true`; Shopify marks some codes as not rejectable, so back the rule up with a validation if it must never be bypassed. A code that is already applied when the function starts rejecting it is removed on the next checkout update. Rejecting a code your input didn't contain makes the function fail. Write the message in the buyer's language.

### How DataJet manages the discount

* Discount functions appear in the Shopify admin under **Discounts** as automatic discounts.
* The function covers the classes you pick: **product**, **order** and **shipping**. DataJet discounts are automatic: buyers don't type a code to get them. A discount function can still reject codes buyers type (see [Rejecting discount codes](#rejecting-discount-codes)).
* Enabling in the Functions Console activates the discount immediately (no start/end scheduling); disabling deactivates it.
* **Combines with**: by default DataJet discounts combine with other product, order and shipping discounts. Change it per function in **Edit** (Combines with). When discounts can't be combined, Shopify applies the one that gives the buyer the bigger saving and drops the other, including a code the buyer typed.
* Every DataJet discount carries a metafield `$app:datajet-functions.function` with its title. The **Customer + Discounts** family reads it on each line's discounts as `discountApplication.marker.value`, so a function can tell a DataJet discount apart from other discounts. Discounts created before this was added get the metafield the next time you save them.
* Shopify allows at most **25 active automatic discounts per store** — this cap is shared with the discounts the merchant creates outside DataJet.

### Examples

**10% off products with a tag** (use the *Product* family with the `hasProductTags` variable):

```javascript
var candidates = [];

input.cart.lines.forEach(function (line) {
  var product = line.merchandise && line.merchandise.product;
  var tagged = product && product.hasTags && product.hasTags.some(function (t) { return t.hasTag; });
  if (tagged) {
    candidates.push({
      message: 'Sale',
      targets: [{ cartLine: { id: line.id } }],
      value: { percentage: { value: 10 } },
    });
  }
});

if (!candidates.length) return { operations: [] };
return { operations: [{ productDiscountsAdd: { selectionStrategy: 'FIRST', candidates: candidates } }] };
```

**Free Express shipping for members** (use the *Tags* family with the `hasCustomerTags` variable set to `["member"]`, and the **Shipping** class):

```javascript
if (input.target !== 'delivery') return { operations: [] };

var customer = input.cart.buyerIdentity && input.cart.buyerIdentity.customer;
var isMember = customer && customer.hasTags.some(function (t) { return t.hasTag; });
if (!isMember) return { operations: [] };

var targets = [];
input.cart.deliveryGroups.forEach(function (group) {
  group.deliveryOptions.forEach(function (option) {
    if (/express/i.test(option.title || '')) {
      targets.push({ deliveryOption: { handle: option.handle } });
    }
  });
});

if (!targets.length) return { operations: [] };
return {
  operations: [
    {
      deliveryDiscountsAdd: {
        selectionStrategy: 'ALL',
        candidates: [
          { message: 'Free Express for members', targets: targets, value: { percentage: { value: 100 } } },
        ],
      },
    },
  ],
};
```

When a cart ships in several parts, each shipment is its own delivery group with its own options. The loop above discounts the Express option in every group and leaves groups without one unchanged. Match options by `title`, the name set up in the shipping settings. Use the `handle` only to target the option you matched; don't hardcode it.

**Order discount above a threshold from vars** (use the *General* or *Cart* family; set `MIN_ORDER_TOTAL` and `ORDER_DISCOUNT_PERCENT` as code variables):

```javascript
var total = parseFloat(input.cart.cost.totalAmount.amount);
var min = parseFloat(vars.MIN_ORDER_TOTAL || '200');
var percent = parseFloat(vars.ORDER_DISCOUNT_PERCENT || '5');

if (total < min) return { operations: [] };

return {
  operations: [
    {
      orderDiscountsAdd: {
        selectionStrategy: 'FIRST',
        candidates: [
          {
            message: percent + '% off orders over ' + min,
            targets: [{ orderSubtotal: { excludedCartLineIds: [] } }],
            value: { percentage: { value: percent } },
          },
        ],
      },
    },
  ],
};
```

### Notes

* Discount functions don't use the **Run on** steps. They run whenever the cart changes: the lines run for Products/Order, the delivery run for Shipping (once delivery options are known).
* All amounts are in the presentment currency (what the buyer pays).
* If your code throws, no discount is applied (fail open).
* See also: [Cart and Checkout Validation](https://docs.datajet-app.com/functions/functions/cart-and-checkout-validation.md), [Delivery Customization](https://docs.datajet-app.com/functions/functions/delivery-customization.md), [Payment Customization](https://docs.datajet-app.com/functions/functions/payment-customization.md).
