{
  "schemaVersion": 1,
  "sensitiveFieldsExcluded": true,
  "generatedAt": "1970-01-01T00:00:00.000Z",
  "packageName": "@happyvertical/smrt-inventory",
  "packageVersion": "0.42.6",
  "sourceManifestPath": "dist/manifest.json",
  "agentDocPath": "AGENTS.md",
  "sourceHashes": {
    "manifest": "e7b34ff83fdea2a6eae7609296c05988a8ab4e2d6df22cee3651da0ea4fb08ca",
    "packageJson": "60fbc7d32ce6a76d7c12da86111283d820a8426169e22ad54980232ce0c91938",
    "agents": "a771bf16d21cabbe43a77d5cb87ca7dedbf2e68d1928cf804cf4fefaad7a765f"
  },
  "exports": [
    ".",
    "./manifest",
    "./manifest.json"
  ],
  "dependencies": {
    "@happyvertical/logger": "catalog:",
    "@happyvertical/smrt-core": "workspace:*",
    "@happyvertical/smrt-tenancy": "workspace:*",
    "@happyvertical/sql": "catalog:",
    "@happyvertical/smrt-vitest": "workspace:*",
    "@types/node": "24.13.2",
    "typescript": "5.9.3",
    "vite": "8.1.4",
    "vitest": "4.1.10"
  },
  "smrtDependencies": [
    "@happyvertical/smrt-core",
    "@happyvertical/smrt-tenancy",
    "@happyvertical/smrt-vitest"
  ],
  "sdkDependencies": [
    "@happyvertical/logger",
    "@happyvertical/sql"
  ],
  "tags": [],
  "risks": [],
  "objects": [
    {
      "name": "InventoryLocationCollection",
      "qualifiedName": "@happyvertical/smrt-inventory:InventoryLocationCollection",
      "collection": "inventorylocations",
      "tableName": "inventory_locations",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtCollection",
      "fields": [],
      "relationships": [],
      "methods": [
        "findActive",
        "findByCode",
        "findByKind",
        "findByPlace"
      ],
      "methodSignatures": [
        {
          "name": "findActive",
          "async": true,
          "params": [
            "kind?: InventoryLocationKind"
          ],
          "returns": "Promise<InventoryLocation[]>"
        },
        {
          "name": "findByCode",
          "async": true,
          "params": [
            "code: string"
          ],
          "returns": "Promise<InventoryLocation | null>"
        },
        {
          "name": "findByKind",
          "async": true,
          "params": [
            "kind: InventoryLocationKind"
          ],
          "returns": "Promise<InventoryLocation[]>"
        },
        {
          "name": "findByPlace",
          "async": true,
          "params": [
            "placeId: string"
          ],
          "returns": "Promise<InventoryLocation[]>"
        }
      ],
      "surfaces": [],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    },
    {
      "name": "StockLevelCollection",
      "qualifiedName": "@happyvertical/smrt-inventory:StockLevelCollection",
      "collection": "stocklevels",
      "tableName": "inventory_stock_levels",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtCollection",
      "fields": [],
      "relationships": [],
      "methods": [
        "findByLocation",
        "findBySku",
        "getLevel",
        "totalForLocation",
        "totalForSku"
      ],
      "methodSignatures": [
        {
          "name": "findByLocation",
          "async": true,
          "params": [
            "locationId: string"
          ],
          "returns": "Promise<StockLevel[]>"
        },
        {
          "name": "findBySku",
          "async": true,
          "params": [
            "skuId: string"
          ],
          "returns": "Promise<StockLevel[]>"
        },
        {
          "name": "getLevel",
          "async": true,
          "params": [
            "skuId: string",
            "locationId: string",
            "state?: StockState"
          ],
          "returns": "Promise<StockLevel | null>"
        },
        {
          "name": "totalForLocation",
          "async": true,
          "params": [
            "locationId: string",
            "state?: StockState"
          ],
          "returns": "Promise<number>"
        },
        {
          "name": "totalForSku",
          "async": true,
          "params": [
            "skuId: string",
            "state?: StockState"
          ],
          "returns": "Promise<number>"
        }
      ],
      "surfaces": [],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    },
    {
      "name": "StockMovementCollection",
      "qualifiedName": "@happyvertical/smrt-inventory:StockMovementCollection",
      "collection": "stockmovements",
      "tableName": "inventory_stock_movements",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtCollection",
      "fields": [],
      "relationships": [],
      "methods": [
        "findByLocation",
        "findByReason",
        "findBySku",
        "findBySource"
      ],
      "methodSignatures": [
        {
          "name": "findByLocation",
          "async": true,
          "params": [
            "locationId: string"
          ],
          "returns": "Promise<StockMovement[]>"
        },
        {
          "name": "findByReason",
          "async": true,
          "params": [
            "reasonCode: StockMovementReason"
          ],
          "returns": "Promise<StockMovement[]>"
        },
        {
          "name": "findBySku",
          "async": true,
          "params": [
            "skuId: string"
          ],
          "returns": "Promise<StockMovement[]>"
        },
        {
          "name": "findBySource",
          "async": true,
          "params": [
            "sourceType: string",
            "sourceId: string"
          ],
          "returns": "Promise<StockMovement[]>"
        }
      ],
      "surfaces": [],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    },
    {
      "name": "InventoryLocation",
      "qualifiedName": "@happyvertical/smrt-inventory:InventoryLocation",
      "collection": "inventorylocations",
      "tableName": "inventory_locations",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtObject",
      "fields": [
        {
          "name": "tenantId",
          "type": "text",
          "required": false,
          "columnType": "UUID"
        },
        {
          "name": "code",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "name",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "kind",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": "warehouse"
        },
        {
          "name": "placeId",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "active",
          "type": "boolean",
          "required": false,
          "columnType": "BOOLEAN",
          "default": true
        }
      ],
      "relationships": [],
      "methods": [],
      "tenant": {
        "scoped": true,
        "mode": "optional",
        "field": "tenantId"
      },
      "conflictColumns": [
        "code",
        "tenant_id"
      ],
      "surfaces": [
        {
          "kind": "api",
          "name": "inventorylocations.list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
          "path": "/inventorylocations",
          "method": "GET"
        },
        {
          "kind": "api",
          "name": "inventorylocations.get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
          "path": "/inventorylocations/[id]",
          "method": "GET"
        },
        {
          "kind": "api",
          "name": "inventorylocations.create",
          "operation": "create",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
          "path": "/inventorylocations",
          "method": "POST"
        },
        {
          "kind": "api",
          "name": "inventorylocations.update",
          "operation": "update",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
          "path": "/inventorylocations/[id]",
          "method": "PATCH"
        },
        {
          "kind": "cli",
          "name": "inventorylocation_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "cli",
          "name": "inventorylocation_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "cli",
          "name": "inventorylocation_create",
          "operation": "create",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "cli",
          "name": "inventorylocation_update",
          "operation": "update",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "cli",
          "name": "inventorylocation_delete",
          "operation": "delete",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "mcp",
          "name": "inventorylocation_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        },
        {
          "kind": "mcp",
          "name": "inventorylocation_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
        }
      ],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    },
    {
      "name": "StockLevel",
      "qualifiedName": "@happyvertical/smrt-inventory:StockLevel",
      "collection": "stocklevels",
      "tableName": "inventory_stock_levels",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtObject",
      "fields": [
        {
          "name": "tenantId",
          "type": "text",
          "required": false,
          "columnType": "UUID"
        },
        {
          "name": "skuId",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "locationId",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "state",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": "available"
        },
        {
          "name": "qty",
          "type": "decimal",
          "required": false,
          "columnType": "REAL"
        }
      ],
      "relationships": [],
      "methods": [],
      "tenant": {
        "scoped": true,
        "mode": "optional",
        "field": "tenantId"
      },
      "conflictColumns": [
        "sku_id",
        "location_id",
        "state",
        "tenant_id"
      ],
      "surfaces": [
        {
          "kind": "api",
          "name": "stocklevels.list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockLevel",
          "path": "/stocklevels",
          "method": "GET"
        },
        {
          "kind": "api",
          "name": "stocklevels.get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockLevel",
          "path": "/stocklevels/[id]",
          "method": "GET"
        },
        {
          "kind": "cli",
          "name": "stocklevel_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockLevel"
        },
        {
          "kind": "cli",
          "name": "stocklevel_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockLevel"
        },
        {
          "kind": "mcp",
          "name": "stocklevel_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockLevel"
        },
        {
          "kind": "mcp",
          "name": "stocklevel_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockLevel"
        }
      ],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    },
    {
      "name": "StockMovement",
      "qualifiedName": "@happyvertical/smrt-inventory:StockMovement",
      "collection": "stockmovements",
      "tableName": "inventory_stock_movements",
      "packageName": "@happyvertical/smrt-inventory",
      "extends": "SmrtObject",
      "fields": [
        {
          "name": "tenantId",
          "type": "text",
          "required": false,
          "columnType": "UUID"
        },
        {
          "name": "skuId",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "locationId",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "fromState",
          "type": "text",
          "required": false,
          "columnType": "TEXT"
        },
        {
          "name": "toState",
          "type": "text",
          "required": false,
          "columnType": "TEXT"
        },
        {
          "name": "qty",
          "type": "decimal",
          "required": false,
          "columnType": "REAL"
        },
        {
          "name": "reasonCode",
          "type": "text",
          "required": true,
          "columnType": "TEXT",
          "default": "adjustment"
        },
        {
          "name": "sourceType",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "sourceId",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "note",
          "type": "text",
          "required": false,
          "columnType": "TEXT",
          "default": ""
        },
        {
          "name": "occurredAt",
          "type": "datetime",
          "required": false,
          "columnType": "TIMESTAMP"
        }
      ],
      "relationships": [],
      "methods": [],
      "tenant": {
        "scoped": true,
        "mode": "optional",
        "field": "tenantId"
      },
      "conflictColumns": [
        "id"
      ],
      "surfaces": [
        {
          "kind": "api",
          "name": "stockmovements.list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockMovement",
          "path": "/stockmovements",
          "method": "GET"
        },
        {
          "kind": "api",
          "name": "stockmovements.get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockMovement",
          "path": "/stockmovements/[id]",
          "method": "GET"
        },
        {
          "kind": "cli",
          "name": "stockmovement_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockMovement"
        },
        {
          "kind": "cli",
          "name": "stockmovement_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockMovement"
        },
        {
          "kind": "mcp",
          "name": "stockmovement_list",
          "operation": "list",
          "objectName": "@happyvertical/smrt-inventory:StockMovement"
        },
        {
          "kind": "mcp",
          "name": "stockmovement_get",
          "operation": "get",
          "objectName": "@happyvertical/smrt-inventory:StockMovement"
        }
      ],
      "relationshipFeatures": [
        "uuidColumns"
      ],
      "tags": [],
      "risks": []
    }
  ],
  "surfaces": [
    {
      "kind": "api",
      "name": "inventorylocations.list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
      "path": "/inventorylocations",
      "method": "GET"
    },
    {
      "kind": "api",
      "name": "inventorylocations.get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
      "path": "/inventorylocations/[id]",
      "method": "GET"
    },
    {
      "kind": "api",
      "name": "inventorylocations.create",
      "operation": "create",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
      "path": "/inventorylocations",
      "method": "POST"
    },
    {
      "kind": "api",
      "name": "inventorylocations.update",
      "operation": "update",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation",
      "path": "/inventorylocations/[id]",
      "method": "PATCH"
    },
    {
      "kind": "cli",
      "name": "inventorylocation_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "cli",
      "name": "inventorylocation_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "cli",
      "name": "inventorylocation_create",
      "operation": "create",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "cli",
      "name": "inventorylocation_update",
      "operation": "update",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "cli",
      "name": "inventorylocation_delete",
      "operation": "delete",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "mcp",
      "name": "inventorylocation_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "mcp",
      "name": "inventorylocation_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:InventoryLocation"
    },
    {
      "kind": "api",
      "name": "stocklevels.list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockLevel",
      "path": "/stocklevels",
      "method": "GET"
    },
    {
      "kind": "api",
      "name": "stocklevels.get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockLevel",
      "path": "/stocklevels/[id]",
      "method": "GET"
    },
    {
      "kind": "cli",
      "name": "stocklevel_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockLevel"
    },
    {
      "kind": "cli",
      "name": "stocklevel_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockLevel"
    },
    {
      "kind": "mcp",
      "name": "stocklevel_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockLevel"
    },
    {
      "kind": "mcp",
      "name": "stocklevel_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockLevel"
    },
    {
      "kind": "api",
      "name": "stockmovements.list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockMovement",
      "path": "/stockmovements",
      "method": "GET"
    },
    {
      "kind": "api",
      "name": "stockmovements.get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockMovement",
      "path": "/stockmovements/[id]",
      "method": "GET"
    },
    {
      "kind": "cli",
      "name": "stockmovement_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockMovement"
    },
    {
      "kind": "cli",
      "name": "stockmovement_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockMovement"
    },
    {
      "kind": "mcp",
      "name": "stockmovement_list",
      "operation": "list",
      "objectName": "@happyvertical/smrt-inventory:StockMovement"
    },
    {
      "kind": "mcp",
      "name": "stockmovement_get",
      "operation": "get",
      "objectName": "@happyvertical/smrt-inventory:StockMovement"
    }
  ],
  "prompts": [],
  "relationshipsV2": {
    "foreignKeyFields": 0,
    "crossPackageRefFields": 0,
    "junctionCollections": 0,
    "hierarchicalObjects": 0,
    "polymorphicAssociations": 0,
    "uuidColumns": 9
  },
  "agentDoc": "# @happyvertical/smrt-inventory\n\nMulti-location stock tracking. Strictly industry-neutral — the same primitives serve apparel, furniture, automotive, CPG, electronics, and any other vertical that counts discrete units across locations.\n\n## Models\n\n| Model | Purpose |\n|---|---|\n| _(catalog shapes — `Product`, `Material`, `ProductVariant`, `Sku` — live in `@happyvertical/smrt-products`)_ | Sku is the smallest sellable / countable unit; its `attributes` JSON carries axis-value pins. ProductVariant is the per-product axis declaration. Import either from `@happyvertical/smrt-products` directly. |\n| `InventoryLocation` | Warehouse / factory / retail / in-transit / virtual. Open-ended `kind` string. Optional `placeId` references `@happyvertical/smrt-places`. `conflictColumns: ['code', 'tenant_id']`. |\n| `StockLevel` | Materialized `qty` for a `(skuId, locationId, state)` tuple. Upserted in place. **Mutated only by `StockService`.** States: `available`, `allocated`, `wip`, `qc_hold`, `damaged`. |\n| `StockMovement` | Append-only audit log. Every `StockService` mutation writes one (or two for `transfer`). `sourceType` + `sourceId` carry cross-package attribution. |\n\nAll three inventory models (`InventoryLocation`, `StockLevel`, `StockMovement`) use `@TenantScoped({ mode: 'optional' })` + nullable `tenantId` so they can be used either tenant-scoped or globally. The catalog shapes (`Product`, `Material`, `ProductVariant`, `Sku`) live in `@happyvertical/smrt-products` and carry their own tenant decoration there.\n\n## StockService — the only sanctioned way to mutate stock\n\n```typescript\nimport { createStockService } from '@happyvertical/smrt-inventory';\n\nconst service = await createStockService({ db });\nawait service.receive(skuId, locationId, qty, { sourceType, sourceId });\nawait service.reserve(skuId, locationId, qty, { sourceType, sourceId });\nawait service.release(skuId, locationId, qty, { sourceType, sourceId });\nawait service.fulfill(skuId, locationId, qty, { sourceType, sourceId });\nawait service.transfer(skuId, fromLocId, toLocId, qty, { sourceType, sourceId });\nawait service.adjust(skuId, locationId, delta, { sourceType, sourceId });\n```\n\n| Method | Behavior | Movement reason |\n|---|---|---|\n| `receive` | +qty available — purchase receipt, return, production produce | `receipt` |\n| `reserve` | available → allocated. Throws `InsufficientStockError` on overdraw | `reservation` |\n| `release` | allocated → available (order cancel) | `release` |\n| `fulfill` | -qty allocated. Stock leaves the building | `fulfillment` |\n| `transfer` | move stock between locations (writes two movements) | `transfer_out`, `transfer_in` |\n| `adjust` | signed delta — cycle counts and one-off corrections | `adjustment` |\n\nAll methods reject zero / negative / non-finite quantities except `adjust`, which accepts non-zero signed deltas. Negative deltas that would drive a state below zero throw `InsufficientStockError`.\n\n## Opt-in DispatchBus hooks\n\nOff by default. Wire them up explicitly in the application's `smrt.ts`:\n\n```typescript\nimport { installInventoryDispatchHandlers } from '@happyvertical/smrt-inventory';\n\nconst handlers = await installInventoryDispatchHandlers({\n  dispatchBus: bus,\n  db, // or stockService: existingService\n});\n```\n\nThis subscribes to:\n- `contract:created` → calls `service.reserve()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Contract', payload.contractId)`\n- `fulfillment:shipped` → calls `service.fulfill()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Fulfillment', payload.fulfillmentId)`\n\nBoth handlers are atomic across lines: a shortfall on line N rolls back lines 1..N-1 so the event is all-or-nothing. Without this guarantee, `DispatchBus` would only log the async handler error and a partially-reserved (or partially-fulfilled) contract would have no compensating event to fix it.\n\nPer-handler toggles: `installContractReserved`, `installFulfillmentShipped`. The `production_order:posted` hook is deliberately not installed here — it depends on the BOM model and ships in `@happyvertical/smrt-manufacturing` (issue #1250).\n\n## Schema migration (Phase 1 release)\n\nThe `Sku` model moved out of this package and into `@happyvertical/smrt-products`. Previously it lived in this package's `inventory_skus` table; it now lives in `product_skus` over there.\n\n**Upgrade procedure** for deployed consumers:\n\n1. **Let the framework create the destination table first.** Boot the new version once with `@happyvertical/smrt-products` registered in your `SmrtClassOptions`; the lazy `syncSchema` path will create `product_skus` with the right primary key, NOT NULL, UNIQUE (`code`, `tenant_id`), and indexes — they're derived from the `Sku` model decorators and would be stripped by a raw `CREATE TABLE AS SELECT`.\n\n2. **Idempotently copy rows across.** SQLite + Postgres:\n\n   ```sql\n   BEGIN;\n   INSERT INTO product_skus (\n     id, slug, context, created_at, updated_at,\n     tenant_id, product_id, code, barcode, name,\n     attributes, weight_grams, parent_sku_id, active\n   )\n   SELECT\n     id, slug, context, created_at, updated_at,\n     tenant_id, product_id, code, barcode, name,\n     attributes, weight_grams, parent_sku_id, active\n   FROM inventory_skus\n   WHERE NOT EXISTS (\n     SELECT 1 FROM product_skus p WHERE p.id = inventory_skus.id\n   );\n   COMMIT;\n   ```\n\n3. **Drop the legacy table** once you've verified row counts match:\n\n   ```sql\n   DROP TABLE IF EXISTS inventory_skus;\n   ```\n\n`StockLevel.skuId` and `StockMovement.skuId` carry plain string ids that still resolve to the same rows after the rename, so no inventory data has to move.\n\n## Gotchas\n\n- **Movements are append-only.** The materialized `StockLevel` row is derived state; the `StockMovement` ledger is the source of truth. Never let CRUD UIs expose update/delete on the movement table. If you find yourself wanting to \"fix\" a movement row, write a compensating `adjust()` call instead.\n- **Never call `StockLevel.create()` or `save()` directly.** Going around `StockService` silently desyncs the audit log and breaks cycle counts.\n- **Cross-industry constraint.** This package's vocabulary stays generic: `InventoryLocation`, `StockLevel`, `StockMovement`. Apparel-specific concepts (`Style`, `Makeup`, `Colorway`, fashion `Season`, tech-pack metadata) and their analogues in furniture / automotive / CPG live in the relevant template package, never here. PRs that introduce industry vocabulary should be rejected.\n- **Cross-package references are plain strings.** `skuId`, `placeId`, `sourceId` — all plain string ids, never `@foreignKey()`. Inventory's stock-motion logic only ever reads StockLevel/StockMovement; it doesn't follow `skuId` back to the catalog's Sku table, so the layering stays loose.\n- **`conflictColumns` include `tenant_id`** on `InventoryLocation` and `StockLevel`. NULL-matching semantics (`(code, NULL) IS NOT DISTINCT FROM (code, NULL)`) are handled by `@happyvertical/sql >= 0.74.0` natively, so two saves with the same `(code, NULL)` tuple correctly merge in place. Pass `nullsDistinct: true` at the sql layer to opt back into NULL-distinct semantics.\n- **Atomic per-method, transactional across composition.** Each `StockService` mutation (`receive` / `reserve` / `release` / `fulfill` / `transfer` / `adjust`) wraps every write in a single `db.transaction(...)` (via `@happyvertical/sql >= 0.74.0`). Partial failure rolls the whole call back — level writes and the matching `StockMovement` audit row commit together or not at all. `transfer` writes both legs (source decrement, destination increment, and both audit rows) inside one tx, so a failure mid-`transfer` is fully reverted.\n  Callers composing multiple `StockService` calls into one logical unit (e.g. consuming materials line-by-line for a production order) should wrap them in `await stockService.withTransaction(async (tx) => { ... })` — `tx` is a tx-bound `StockService` with the same public API; mutation calls inside the callback share one transaction and either all commit or all roll back.\n  If the underlying SQL adapter does not expose `transaction()` (extremely rare — all four built-in `@happyvertical/sql >= 0.74.0` adapters implement it), the service degrades to non-atomic serial writes and emits a one-time `console.warn`.\n- **Concurrent reservations: tightened, not bulletproof.** `@happyvertical/sql >= 0.74.0` serialises null-aware *upserts* via a per-key in-process lock (SQLite) or advisory lock (Postgres). That lock fixed the row-creation race (issue #1246) — two concurrent `create()` calls on the same conflict-column tuple no longer race the underlying `INSERT ... ON CONFLICT`. It does NOT serialise the read-modify-write compound that `reserve` / `fulfill` / `transfer` / `adjust` perform on an existing row: each method reads the current level (`SELECT`), computes the new value in JS, then writes it back (`UPDATE` via `save()` on the loaded row). The whole compound is inside one `db.transaction(...)` from round-3, so the level write and audit row commit together — but two concurrent transactions on the same `(skuId, locationId)` can each see the same starting balance, compute the same decrement, and double-spend. Awaited (serial) calls always behave correctly. Use a job queue (e.g. `@happyvertical/smrt-jobs`) or your own mutex when you need hard atomicity across concurrent callers. The full fix is `SELECT ... FOR UPDATE` inside the same transaction (Postgres) or upgrading the journal mode (SQLite); deferred until we see a real high-contention workload that warrants it.\n\n## Source attribution\n\nEvery `StockMovement` carries `sourceType` + `sourceId` so downstream queries can reconstruct \"what caused this movement\". Conventions used by the built-in dispatch handlers:\n\n| sourceType | Emitter | Note |\n|---|---|---|\n| `Contract` | `smrt-commerce` `contract:created` | All reservation/release/fulfilment legs caused by a contract |\n| `Fulfillment` | `smrt-commerce` `fulfillment:shipped` | Outbound shipment |\n| `PurchaseOrder` | (your code) | Inbound receipt |\n| `CycleCount` | (your code) | Adjustments from physical counts |\n| `TransferOrder` | (your code) | Both legs of a transfer |\n| `ProductionOrder` | `smrt-manufacturing` (issue #1250) | Materials consumed + finished goods produced |\n"
}