# Build and stock BOMs from your catalog via the API

The end-to-end AI-assistant workflow — search your Shopify catalog, register materials in bulk, create BOMs, check buildable quantities, and adjust pre-assembled stock over MCP.

Once a Claude or ChatGPT connection (or an `asmk_` key) is set up under Assemblified's **Settings → API & agent
access** (see [AI / Agent access](/features/agent-access/overview/)), an assistant can take a store from bare
catalog to fully modelled BOMs without any copy-pasting of IDs. This guide shows the canonical
flow and the snippets an assistant would run.

:::note
Everything below runs through the `run` tool as small JavaScript snippets against the typed `app`
object. A **write-scope** connection is required for the registration/creation steps; the search
and buildable steps work with a read-only one.
:::

## 1. Find the variants in your Shopify catalog

`shopify.searchVariants` accepts Shopify's own search filter syntax — the same queries you'd type
in the admin search box:

```js
const page = await app.shopify.searchVariants({
    query: "sku:BOLT-* AND vendor:Acme",
    first: 50,
});
return page.variants.map((v) => ({ id: v.variantId, sku: v.sku, title: v.displayName }));
```

Page through big result sets with `after: page.pageInfo.endCursor`. If you already know the ids,
`shopify.getVariants({ variantIds: [...] })` hydrates up to 100 at once.

<span id="2-register-them-as-raw-materials--in-one-call"></span>

## 2. Register them as materials — in one call

```js
return await app.rawMaterials.registerFromShopifyVariants({
    variantIds: ["53680817373507", "53680817439043" /* …up to 100 */],
});
```

Each item reports `created: true` (newly registered) or `false` (already known — refreshed).
Purely internal components that don't exist in Shopify are created as **virtual** materials in
bulk, with duplicate protection:

```js
return await app.rawMaterials.createMany({
    items: [
        { productName: "Packaging Foam", variantName: "Default", unit: "pcs", inventoryQuantity: 500 },
        { productName: "Assembly Glue", variantName: "50ml", sku: "GLUE-50" },
    ],
    skipExisting: true, // SKU first, (productName, variantName) fallback
    dryRun: true, // preview first — flip off to commit
});
```

`inventoryQuantity` is a virtual material's opening stock, placed at your default location (your first
Shopify location when none is set). Stock is kept per location and a material's total is the sum of its
locations, so later changes go to a location with `inventory.restock`; the total cannot be set directly.

## 3. Create the BOMs

`billOfMaterials.createMany` takes up to 25 BOMs per call; unknown Shopify component references
are auto-registered along the way, and `skipExisting: true` skips variants that already have a BOM:

```js
return await app.billOfMaterials.createMany({
    items: [
        {
            productId: "15330758263107",
            variantId: "53680816652611",
            productName: "Gift Box Deluxe",
            variantName: "Default",
            rawMaterialReferences: [
                { nodeId: "53680817373507", quantity: 2 },
                { nodeId: "VMAT-VAR-…", quantity: 1 },
            ],
        },
    ],
    skipExisting: true,
});
```

Every batch method returns per-item results — check `results[]` / `failedCount` rather than
assuming the whole batch landed; failed items can be resent alone.

## 4. Change many BOMs at once, or copy one

`billOfMaterials.updateMany` applies **one settings patch** to a whole selection — either explicit
ids (up to 25) or _every_ BOM matching a query, which the server resolves itself so you never have
to page through ids:

```js
// Activate every inactive BOM whose name mentions "Gift box", except one
return await app.billOfMaterials.updateMany({
    selection: {
        mode: "all-matching",
        query: { q: "Gift box", filters: [{ field: "status", op: "in", value: ["inactive"] }] },
        excludedIds: ["BOM-keep-this-one"],
    },
    patch: { status: "active" },
});
```

The patch may set `status`, `dynamicAdjustmentEnabled`, `maintainSameInventoryLevel`,
`autoGenerateMaterialList` (Enhanced plan), `onReturnKeepAssembled` and `tags`. It is per-row commit:
every row comes back with its `id`, its `name` and — if it failed — its error.

`billOfMaterials.duplicate` copies a BOM onto a **different** Shopify variant in one atomic step —
components, subassemblies, tags, additional costs, the automation link and all five behaviour
settings come across, and the copy is always created **inactive** with no pre-assembled stock:

```js
return await app.billOfMaterials.duplicate({
    id: "BOM-source-id",
    name: "Gift Box Deluxe — Red",
    variant: { productId: "15330758263107", variantId: "53680816652611" },
    bomId: "BOM-my-own-id", // mint it yourself, re-send the SAME one on a retry
});
```

A BOM belongs to exactly one variant, so duplicating onto a variant that already has one (or leaving
`variant` out, which means the source's own) fails with `CONFLICT`. Passing `bomId` makes a retry
safe: the second call answers `deduplicated: true` with the copy that already exists instead of
creating a second one.

<span id="4b-work-through-your-sub-assemblies"></span>

## 4b. Work through your subassemblies

Subassemblies (assembly BOMs) have the same four calls as BOMs. `assemblyBills.query` returns
**flat rows** — one line per bill with its costs, its component counts, how many BOMs use it and
the derived `unused` / `empty` / `lowShelf` flags — instead of the full component tree
`assemblyBills.list` hydrates:

```js
return await app.assemblyBills.query({ filters: [{ field: "unused", op: "is", value: true }], pageSize: 25 });
```

Filters are AND-combined, `q` searches name, SKU and description, and `sort.columnId` takes any
sortable field (default: most recently updated first). `assemblyBills.list` still works and still
returns the hydrated tree, but `query` is the one to reach for when you want a list.

`assemblyBills.usage` answers the follow-up question — _who_ consumes one bill — as two flat lists,
the finished goods and the other bills, each with the quantity consumed:

```js
return await app.assemblyBills.usage({ id: "ASM-…" });
```

`assemblyBills.updateMany` applies **one settings patch** — `onReturnKeepAssembled` and/or
`onlyConsumePreassembled` — to explicit ids or to every bill matching a query, resolved server-side:

```js
return await app.assemblyBills.updateMany({
    selection: { mode: "all-matching", query: { filters: [{ field: "lowShelf", op: "is", value: true }] } },
    patch: { onlyConsumePreassembled: false },
});
```

Every row comes back with its `id`, its `name` and — if it failed — its error, and
`changedAssemblyIds` names the rows that were actually written.

`assemblyBills.duplicate` copies a bill's BOM onto a new id in one atomic step: component
materials, nested bills, additional costs and both behaviour settings come across, and the copy
starts with no pre-assembled stock:

```js
return await app.assemblyBills.duplicate({
    sourceId: "ASM-source-id",
    assemblyId: "ASM-my-own-id", // mint it yourself, re-send the SAME one on a retry
    name: "Frame assembly — Mk II",
    sku: "FRAME-MK2",
});
```

Passing `assemblyId` makes a retry safe: the second call answers `deduplicated: true` with the copy
that already exists instead of creating a second one.

### Editing a bill's components

Three calls change what a bill is made of. `assemblyBills.updateMaterialQuantity` sets one
component's quantity — a material by default, or a nested bill with `scope: "subAssembly"`:

```js
await app.assemblyBills.updateMaterialQuantity({ assemblyId: "ASM-…", nodeId: "45812…", quantity: 4 });
```

`assemblyBills.addSubAssembly` nests other bills inside this one, all at the same quantity, and
`assemblyBills.removeSubAssembly` takes one back out. Nesting is all-or-nothing: if any id is already
referenced, nothing is added.

```js
await app.assemblyBills.addSubAssembly({ assemblyId: "ASM-…", subAssemblyIds: ["ASM-frame", "ASM-lid"], quantity: 1 });
await app.assemblyBills.removeSubAssembly({ assemblyId: "ASM-…", nodeId: "ASM-lid" });
```

Removing a nested bill only removes the reference — the nested bill itself stays in your catalogue.
Each of these recalculates the parent bill's cost once.

### Deleting a bill that has reservations

`assemblyBills.delete` and `assemblyBills.deleteMany` refuse a bill that is still used in a BOM or
that carries active safety-stock reservations. Releasing those reservations is an explicit choice,
never something a delete does quietly:

```js
await app.assemblyBills.delete({ assemblyId: "ASM-…", overrides: { releaseReservations: true } });
```

The reservations are released first, and if any release fails nothing is deleted.

## 5. Ask what you can build

`billOfMaterials.buildable` computes the same number the app's **Buildable** column shows —
live Shopify component levels, virtual levels and nested pre-assembled stock included:

```js
const { items } = await app.billOfMaterials.buildable({ ids: ["BOM-…"] });
return items.map((i) => ({ bom: i.bomId, perLocation: i.perLocation, total: i.totals.maxBuildable }));
```

Real per-location levels for any mix of materials come from `inventory.levels`, and
`shopify.listLocations` is the canonical way to resolve location ids and names.

### Check an assembly BOM on its own

Use `assemblyBills.buildable` to ask how many **additional units** you can make from an assembly
BOM's components. It uses the same capacity calculation as the app's Buildable display, including
live Shopify materials, virtual materials, nested pre-assembled stock and waste. Non-essential
materials do not limit the answer. Units already on this assembly's own shelf are separate and
are never added to this capacity.

```js
const { items, notFound } = await app.assemblyBills.buildable({
    ids: ["ASM-frame"],
    locationIds: ["101176672579"],
});
return { items, notFound };
```

Pass either `id` or `ids`, with 1–10 submitted nonempty IDs; use `assemblyBills.query` or
`assemblyBills.get` to find them. Optional `locationIds` accepts up to 50 nonempty strings;
omitting it or passing `[]` selects all locations. Repeated entries still count toward the limits.
Do not pass both ID forms, extra fields or `kind`. Strings are not trimmed for you.

Each result identifies the assembly with `assemblyId` and `kind: "assemblyBill"`. The inherited
`bomId` is an alias for that same assembly ID; `variantId` is empty because an assembly BOM has
no Shopify variant. Missing assembly IDs appear in `notFound`. A failed source read fails the
whole request; it is not an answer of zero.

Read `perLocation` for each location's `maxBuildable`, `sellable` and up to **three ranked limiting
components**, tightest first. Each component includes its identity, name, path through nested
assemblies, source, effective quantity needed, available quantity, individual capacity and shortfall.
Shortfall is what is missing at one unit above the tree's capacity. The single `bottleneck` on the
assembly instead pools stock across locations and assumes you can move it. For example, locations
that can build 3 and 2 units give `totals.maxBuildable: 5`, while pooled stock may allow 7. These
ranked components and the pooled bottleneck are a bounded explanation, not a complete purchasing list.

`sellable` respects nested assemblies set to consume only pre-assembled stock. `hasSellableSplit`
can be true even when `maxBuildable` and `sellable` agree, including when only the root assembly
has that setting. Its own shelf stock still neither adds to nor caps the additional capacity.
Assembly location rules are not applied by this read, so do not treat it as a promise of what a
particular production run will consume at pinned locations. The read reserves no stock.

The assembly's own shelf records decide which locations appear, **including records with zero
stock**. If your chosen locations exclude every recorded location, the result has zero totals,
no location rows and `globalFallback: false`. Only an assembly with **no shelf records anywhere**
uses `globalFallback: true`: it returns no location rows and calculates from saved global quantities,
even if you supplied locations. Treat that fallback as a global estimate, not a location-specific
stock check. Compare readings on stable stock; separate reads are not an atomic snapshot.

To read stock already assembled, use `inventory.preassembledLevels` instead. The existing
`billOfMaterials.buildable` call and its REST endpoint keep their behavior; this assembly capacity
call is available through MCP.

## 6. Record what's already on the shelf

When finished goods are physically assembled (or counted during a stock-take), adjust the
pre-assembled quantity directly — no work order needed:

```js
// Stock-take: SET the level (retry-safe — prefer absolute over delta for counts)
await app.billOfMaterials.adjustPreassembled({
    id: "BOM-…",
    locationId: "101176672579",
    absolute: 12,
});

// Or record 3 freshly built units
await app.billOfMaterials.adjustPreassembled({ id: "BOM-…", locationId: "101176672579", delta: 3 });
```

`adjustPreassembledMany` batches up to 25 adjustments for a full stock-take, and
`assemblyBills.adjustPreassembled` does the same for subassemblies. A BOM with **Only sell
pre-assembled** enabled automatically re-anchors its Shopify availability to the new pre-assembled
quantity.

## 7. Switch finished goods to "only sell pre-assembled"

`billOfMaterials.setOnlySellPreassembled` turns the setting on or off for a whole selection in one
call. It needs the **Enhanced** plan, and switching it **on** always requires you to say what should
happen to the stock numbers — there is no default:

- `adoptShopify` — rebase each BOM's pre-assembled stock to what Shopify is selling right now.
- `pushPreassembled` — keep the pre-assembled numbers and re-anchor Shopify to them.

```js
await app.billOfMaterials.setOnlySellPreassembled({
    selection: { mode: "explicit", ids: ["BOM-…", "BOM-…"] },
    enabled: true,
    stockDirection: "adoptShopify",
});

// Or every finished good matching a search, minus a couple you excluded in the UI
await app.billOfMaterials.setOnlySellPreassembled({
    selection: { mode: "all-matching", query: { q: "gift box" }, excludedIds: ["BOM-…"] },
    enabled: false,
});
```

Three things worth knowing:

- **The Shopify re-anchor is queued, not immediate.** `results[]` tells you the app-side write
  landed; the Shopify side finishes in the background. Read the BOM's `syncState` (`queued`,
  `failed`, or empty when it is done) to find out how it ended — the same badge the finished-goods
  list shows.
- **Enabling clears the other two stock behaviours.** Only sell pre-assembled, dynamic inventory
  adjustment and maintain-same-inventory-level are mutually exclusive, so turning this one on turns
  the other two off. Turning it off changes nothing else.
- **A finished good with no usable Shopify inventory item is reported as failed and is not
  switched** — check `results[]` before assuming every row landed.