# Formula imports

Import reviewed formulas with tolerance, ingredients, outputs, costs, process steps, and per-formula results.

Canonical HTML: https://developer.shelfcycle.com/guides/formulas

Import reviewed production formulas with ingredients, outputs, recurring costs, substitute products, and process steps, then keep a separate result for each formula.

## Access and preparation

Use `POST /formulas/batch` with `formulas:write` and the acting person's current Work Order update permission. The organization's Work Orders must be enabled for that person. In `GET /me`, `effectiveCapabilities.formulas.create` reports scope and permission availability, while `formulas.workOrderV2Eligible` also includes Work Order availability. `writeReadiness.formulas.create` includes that availability too. The import checks it again, including for previews.

Prepare the products in ShelfCycle first. Formula lines use exact product codes, matched case-insensitively within the organization. The first code on each line is the preferred product; later codes are substitutes in priority order.

## Preview an import

Send 1 to 50 items, each with a unique, stable `clientItemId` and a `payload`. Preview with `dryRun=true` to receive ordered `ready` or `failed` results without saving formulas. A preview does not require an `Idempotency-Key`.

Replace the example product codes and ledger account UUID with the reviewed values for your formula.

```bash
curl "$SHELFCYCLE_API_BASE_URL/formulas/batch?dryRun=true" \
  -X POST \
  -H "Authorization: Bearer $SHELFCYCLE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "items": [
      {
        "clientItemId": "formula-001",
        "payload": {
          "name": "Northstar cleaning blend",
          "description": "Reviewed standard blend",
          "tolerance": 5,
          "ingredients": [
            { "label": "Base", "quantity": "80", "unit": "kg", "productCodes": ["BASE-A", "BASE-B"] },
            { "label": "Additive", "quantity": "20", "unit": "kg", "productCodes": ["ADDITIVE-A"] }
          ],
          "outputs": [
            { "label": "Finished blend", "quantity": "100", "unit": "kg", "productCodes": ["BLEND-A"], "kind": "PRODUCT" }
          ],
          "processSteps": [
            { "name": "Blend", "attrs": [{ "key": "Instruction", "value": "Mix until uniform." }] }
          ],
          "costs": [
            {
              "description":"Blending charge",
              "ledgerAccountId":"11111111-1111-4111-8111-111111111111",
              "amount":"2250.125",
              "currencyCode":"USD",
              "basis":"PER_BATCH",
              "split":{"scope":"one","outputIndex":0}
            }
          ]
        }
      }
    ]
  }'
```

## Describe the formula

Each payload requires `name`, `ingredients`, and `outputs`. Optional fields are `description`, `autotag`, `processSteps`, and `costs`.

- Every ingredient or output has `label`, `quantity`, `unit`, and at least one `productCodes` value.
- Units are `g`, `kg`, `lb`, `ml`, `L`, `gal`, or `each`. Quantities must satisfy the formula's normal save rules.
- Ingredients can set `isPackage`. Every output must set `kind` to `PRODUCT` or `WASTE`; an omitted classification returns a failure for that formula.
- Process steps have a `name` and `attrs`, with each attribute expressed as `key` and `value`.

Each formula can contain up to 100 product-code entries across ingredients and outputs, counting repeats. The name after trimming and the optional description each support up to 2400 UTF-8 bytes; count bytes rather than characters for non-ASCII text. Keep the complete request at or below 2 MB.

## Include recurring costs

Each optional cost requires `description`, `ledgerAccountId`, nonnegative `amount` in cents, supported `currencyCode`, `basis`, and `split`. Send an exact decimal string for fractional cents, such as `"2250.125"`; JSON numbers are also accepted. Currency is required and normalized to a supported uppercase code. Optional `supplierId` supplies a default supplier and may be `null`.

Formula basis is `PER_BATCH`, multiplied by the work order's batch count, or `FIXED`, once per work order. These are template defaults; account, supplier, and exchange-rate eligibility are checked when the work order is created. An accepted template is not proof that every later work order can use those choices.

Choose an allocation using positions in this payload's `outputs` array, starting at zero and including `WASTE` rows:

- `{"scope":"one","outputIndex":0}` selects the first output.
- `{"scope":"all","method":"BY_EQUAL_SPLIT"}` includes all outputs. Automatic methods are `BY_EQUAL_SPLIT`, `BY_QUANTITY_SPLIT`, `BY_WEIGHT_SPLIT`, and `BY_MATERIAL_VALUE_SPLIT`.
- `chosen` selects at least two distinct `outputIndexes` and a method. For a template with two outputs, a custom split can be `{"scope":"chosen","outputIndexes":[0,1],"method":"BY_RATIO_SPLIT","weights":{"0":"1","1":"3"}}`. Weight keys use those same index strings, values are nonnegative decimal strings, and custom weights belong only to `BY_RATIO_SPLIT`.

Use positions rather than saved cost/output IDs. A missing output or malformed cost fails only that formula, with correction details naming the affected cost when appropriate. Omit `costs` or send `[]` for no costs. Costs follow the existing preview, independent-item result, and stable-key retry rules. This is template creation; it does not update costs on an existing formula.

## Set the Formula tolerance

Optional `tolerance` is a finite numeric percentage from `0.5` to `100`; the example uses `5` for 5%. Omit it to use 0.5%. An invalid supplied value fails only that Formula. Keep the intended value unchanged when retrying an import.

The saved tolerance applies when confirming a draft Formula work order. Positive input and output quantity corrections after confirmation do not compare against Formula tolerance; they still follow the work order's normal inventory checks. Existing work orders retain their saved tolerance when a template changes, and new work orders use the updated template setting.

## Save and retain results

After reviewing the preview, submit the same body without `dryRun=true` and add a stable `Idempotency-Key`, such as `formula-library:approved-import-001`. Execution returns `data.results` in input order with `clientItemId`, `mode: "createFormula"`, and `status: "succeeded"` or `"failed"`. A saved item includes `data.id`, `name`, `number`, and `resultAction: "created"`; `data.counts` summarizes the results.

A failed formula does not undo successful formulas. Its `failures` and `error` explain what to correct, including unknown or archived products, unsuitable quantities or units, an existing formula name, or oversized content. Missing or repeated item IDs, missing names, or duplicate trimmed names within a request are request-level errors, so correct those before submission.

This endpoint saves reusable formulas. It does not start a work order or receive, consume, or produce inventory.

## Resume safely

If a request is interrupted, repeat the identical body, item order, `clientItemId` values, and `Idempotency-Key`. Recorded outcomes are returned and only pending items continue. A completed retry reports `idempotencyStatus: "replayed"`. Correcting a failed formula is a new intended request and uses a new stable key; omit already successful formulas from that corrected request.

`X-RateLimit-Cost` reports the submitted item count. Divide larger approved libraries into requests of at most 50 formulas and keep each request's identity and results together.
