Nano Store - Ecommerce Docs
Developer Resourcesb2b-second-inventory

B2B Second Inventory Stock Feature Overview

Phase 3 of the bb (B2B second inventory) area — a stock counter per variant, an append-only movement ledger, adjust and bulk adjust, a low-stock threshold, stock import and export jobs, and an hourly report-only drift check.

B2B Second Inventory (bb) — Stock Feature Overview

1. Purpose

Phase 3 gives bb staff stock for the bb catalog. Each bb variant has one counter row and an append-only ledger of every change to it. The tables, routes, permission codes and audit entries are separate from retail inventory: retail code never reads them, and a bb stock write never touches a retail table.

Phase 3 covers:

  • One stock row per variant: quantity, lowStockThreshold, a derived stockStatus, a version that guards the threshold
  • adjust (one variant) and bulk/adjust (up to 100 variants) with a reason, an optional note and a signed delta
  • A movement history per variant and per product
  • A low-stock threshold per variant
  • Import (a quantityDelta file) and export (a stock report) as bb_catalog_job rows, entity inventory
  • An hourly reconcile that creates a missing stock row and flags drift, and never repairs a counter

It does not cover holds, reservations, oversell or pricing. Orders, which sell and restock this stock, are documented in the Orders API reference and Orders Deploy Notes.

Every route is mounted by BbAdminAggregateModule. The reconcile handler is mounted by MaintenanceWorkerModule.


2. Surface Matrix

SurfacePathAuth
Stock list, reads, threshold, adjust/api/admin/bb/inventoryJWT + BB_Inventory_READ or BB_Inventory_UPDATE
Bulk adjust/api/admin/bb/inventory/bulk/adjustJWT + BB_Inventory_UPDATE
Stock jobs/api/admin/bb/jobs/inventoryJWT + BB_Catalog_* combined with BB_Inventory_*

All routes are admin-only and IP-throttled. There is no public or storefront surface. Reads use ADMIN_READ (30 per 60 s), single writes ADMIN_WRITE (10 per 60 s), bulk adjust ADMIN_BULK_WRITE (5 per 60 s).

The full route list is in the stock API reference.


3. Who Can Do What

Phase 3 adds one module, BB_Inventory, with the five actions CREATE, READ, UPDATE, DELETE, RESTORE. It is assignable to a bb role.

CapabilityCodes the caller must hold (all of them)
See the stock list, one variant, a product, or a ledgerBB_Inventory_READ
Adjust, bulk adjust, change the thresholdBB_Inventory_UPDATE
Submit a stock importBB_Catalog_CREATE, BB_Inventory_CREATE, BB_Inventory_UPDATE
Submit a stock export, list jobs, fetch a job, fetch the template or a resultBB_Catalog_READ, BB_Inventory_READ
Cancel a stock jobBB_Catalog_UPDATE, BB_Inventory_UPDATE

BB_Inventory_DELETE and BB_Inventory_RESTORE exist because every module gets all five actions. No phase 3 route checks them. The stock export has no deleted view, so the RESTORE check a catalog export with includeDeleted needs never applies.

A job's required codes are checked again when the worker claims it. A role that loses a code after submitting fails the job with BB_JOB_AUTHORIZATION_REVOKED.

A superadmin passes every check, and the bb permissions are never granted to retail roles. The permission rows do not exist until permissions:sync runs, and it grants them to no role. See Deploy.


4. Stock Rules

What a row is

  • quantity is a whole number from 0 to 1,000,000,000. It never goes negative.
  • lowStockThreshold defaults to 5, range 0 to 1,000,000,000. 0 means never warn.
  • stockStatus is derived by the database: out_of_stock at 0 or less, low_stock at or below the threshold, otherwise in_stock. It is never written.
  • version starts at 1 and guards the threshold only. A stock change never bumps it.
  • lastMovementAt is null until the first movement. driftDetectedAt is set only by the reconciler.

Every new variant gets its row in the same transaction, at 0. The migration also created a row for every existing variant, deleted ones included, so a restore finds its row.

Adjusting

A change is a signed non-zero whole number, at most 1,000,000 up or down per request. It carries a reason and an optional note of up to 1,000 characters (trimmed; blank means none).

ReasonSign it accepts
restockpositive only
damage, theftnegative only
recount, correctioneither
importeither; written only by the import job, not accepted from the API

A wrong sign answers 400 BB_INVENTORY_REASON_SIGN_MISMATCH. A change that would go below 0 answers 409 BB_INVENTORY_INSUFFICIENT_STOCK with details.variantPublicId. A change that would pass 1,000,000,000 answers 400 BB_INVENTORY_QUANTITY_LIMIT.

Each accepted change writes one ledger row (quantityDelta, quantityAfter, reason, note, an actor snapshot) and one bb.inventory.adjust audit row in the same transaction. A refused change writes nothing.

Bulk adjust

One reason and one note for the request, a delta per item, 1 to 100 items. Two items for one variant are refused with 400 BB_INVENTORY_BULK_DUPLICATE_VARIANT. Items run in one transaction with a savepoint each: a refused item lands in failed[] with its code and the rest commit. succeeded[] and failed[].publicId hold variant public ids.

Threshold

PATCH .../configuration takes lowStockThreshold and the version the caller loaded. A stale version answers 409 BB_INVENTORY_VERSION_CONFLICT even when the value matches. A value equal to the current one writes nothing and does not bump version. A real change bumps version by 1 and writes a bb.inventory.update audit row.

Deleting a variant that holds stock

Deleting a variant whose quantity is above 0 answers 409 BB_VARIANT_HAS_STOCK. Write the stock off first (a damage, theft, recount or correction adjust), then delete. A variant at 0 deletes as before. Deleting a variant keeps its stock row and its ledger; the ledger still shows under the product with the deleted variant's name.

Concurrent writers

An adjust locks the product, then the variant (share locks), then updates the row with a guard in the WHERE. Two adjusts of one row queue on the row lock, and the second re-checks its guard on the first one's result. Sibling variants do not queue. A deadlock or lock timeout answers 409 BB_CATALOG_BUSY and nothing partial commits.


5. Idempotency

adjust, bulk/adjust and the export need an Idempotency-Key header (400 IDEMPOTENCY_KEY_REQUIRED without it). The same key and body replays the first answer without a second movement. The same key with a different body answers 409 IDEMPOTENCY_KEY_CONFLICT, and a key still in flight answers 409 IDEMPOTENCY_REQUEST_IN_PROGRESS.

A client that loses the response must retry with the same key. Editing the form and sending again is a new key and a new movement.

The import takes its key in the same header and keeps the key on the job row.


6. Import and Export Jobs

Stock jobs are bb_catalog_job rows with entity inventory. The pipeline, states, limits (5,000 rows in, 50,000 out, 25 MB, 2 active jobs per admin, one worker) and sweeps are the catalog's: see the catalog feature page and the catalog backend page. This section covers what is different for stock.

Import file

Header row, exact names, in this order:

variantPublicId,quantityDelta,note
ColumnRule
variantPublicIdRequired. The UUID of a live variant of a live product. Anything else is a row error variant_not_live
quantityDeltaRequired. Whole number, optional leading + or -, at most 9 digits, not 0, at most 1,000,000 either way. Anything else is a row error delta_format
noteOptional. Trimmed; blank means none; at most 1,000 characters (note_too_long)

The file states changes, not totals. The movement reason is always import and its correlationId is the job's public id. Two lines for one variant are refused (duplicate_variant), never summed. Rows are written in ascending (product, variant) order, each in its own savepoint. A below-zero or over-the-cap change is a row error (insufficient_stock, quantity_limit); the other rows are still checked. If any row failed, the job fails and nothing is imported: the import is one transaction.

The template route returns the header row only.

The same file twice

A unique index on the file's SHA-256 refuses a second stock import of byte-identical content while an earlier one is queued, processing or completed: 409 BB_JOB_INVENTORY_FILE_ALREADY_IMPORTED. A failed or cancelled job frees the file. To apply the same changes again on purpose, change a note and upload again. A retry of the same request with the same Idempotency-Key replays the first job instead of failing.

The guard is a safety net against a double click or a re-sent file. It does not stop two different files that move the same variant.

Export file

A CSV report of live variants of live products, ordered by variant. Body (both optional): search (product name or SKU contains, max 200 characters) and stockStatus. includeDeleted is not a field; sending it is a 400. More than 50,000 matches answers 400 BB_JOB_EXPORT_TOO_LARGE.

variantPublicId,productPublicId,productName,variantName,sku,quantity,lowStockThreshold,stockStatus,lastMovementAt

The export is a report, not a round trip. Its column is quantity, the import's is quantityDelta, on purpose: re-importing an export as deltas would add the counter to itself. stockStatus is the wire value (in_stock, low_stock, out_of_stock). lastMovementAt is ISO 8601 or empty.


7. Hourly Reconcile

A cron fires at the top of every hour (Asia/Kathmandu) and enqueues maintenance.reconcile_bb_inventory on the existing MAINTENANCE queue with an hour-bucket job id, so two instances in one hour enqueue one job. Under API_RUNTIME_PROFILE=fast the scheduler does not run. Nothing else depends on it.

It is report-only. It never changes a counter. Two independent passes:

  1. Heal orphans. A live variant with no stock row gets one at 0, up to 500 per run, with no movement and no audit row. Each is logged as an ERROR, because every creation path should have made the row. Until then, the variant answers 404 BB_INVENTORY_NOT_FOUND on stock routes.
  2. Detect drift. Up to 1,000 rows per run, live rows only (variant and product not deleted; a soft-deleted variant is not examined). Flagged rows come first, then never-audited, then oldest-audited, so the batch rotates. Each examined row has last_reconciled_at stamped, clean or not; updated_at is left alone so the default list order does not change.

A row drifts when any of these holds: the newest movement's quantityAfter is not the counter (or there is no movement and the counter is not 0); a flagged row has no correction movement newer than its flag; or a movement's quantityAfter - quantityDelta does not equal the previous movement's quantityAfter among the movements since the last audit. A drifted row logs bb_inventory drift variant=... quantity=... ledgerAfter=... as an ERROR and sets driftDetectedAt once (it keeps the first detection time).

How a flag clears

Nothing clears it by hand and nothing repairs the counter. An operator reads the ledger and records a correction adjust (either sign) that makes the counter match reality. At the next pass the row has a correction newer than its flag, only the movements after that correction are chain-checked, and if the counter equals the newest quantityAfter the row is clean: the pass sets driftDetectedAt back to null. Until that pass runs (up to one rotation), the flag stays. At 1,000 rows per run, one full rotation of 50,000 variants takes about 50 hours; flagged rows go first, so a flagged row is rechecked on the next run.

The list route's drifted=true filter shows flagged rows. GET responses never expose lastReconciledAt.

The job never throws: a failing pass is logged as [failure] on BbInventoryReconcileProcessor and the next hour runs again. [success] is logged only when both passes finished and no row failed to read or stamp, with healed, examined, drifted.


8. Error UX Mapping

CodeSuggested UI
BB_INVENTORY_INSUFFICIENT_STOCKInline "That would take stock below zero." Keep the form values, refresh the on-hand figure
BB_INVENTORY_REASON_SIGN_MISMATCHInline on the reason field
BB_INVENTORY_QUANTITY_LIMITInline on the change field
BB_INVENTORY_VERSION_CONFLICTRefresh the row, re-present the threshold form
BB_INVENTORY_NOT_FOUNDTransient: "Stock isn't set up for this variant yet. Try again shortly." The hourly heal fixes it
BB_VARIANT_HAS_STOCKInline on delete: "This variant still has stock. Write it off first."
BB_JOB_INVENTORY_FILE_ALREADY_IMPORTEDUnder the file field, as an announced alert
BB_CATALOG_BUSYRetry prompt; nothing was written
A response that never arrived"This may have gone through." Show the history, then retry with the same idempotency key. An edit mints a new key and a second movement

9. See Also