Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(inventory): replenishment level for transfer kanbans (#1889)

Naveen Kashyapf43846bae661
diff --git a/.ai/lessons.md b/.ai/lessons.md
index a0d3227f33..fd5d2cf29b 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3416,6 +3416,26 @@ of `salesInvoice`; backfilled by `20261006220901_sales-invoice-opportunity-backf
**Applies to:** `packages/react/src/utils/generatedAvatar.ts`; any isomorphic code that imports JSON from a dependency.
+## A migration on main can carry a timestamp ahead of UTC
+
+**Context:** `supabase migration new` stamps a migration with the current UTC time. A migration merged to `main` (`20261009141827_link-custom-field-type.sql`) carried a time about 2.5 hours ahead of UTC, likely from a local clock.
+
+**Problem:** Every migration created after the pull got an older timestamp than that file. Production's `supabase db push` refuses a migration that sorts before one it already applied, so the new migrations would have failed to deploy. The clobber check and every test passed; nothing local shows it.
+
+**Rule:** After you pull `main`, compare your migrations' timestamps with the newest one on `main` (`ls packages/database/supabase/migrations | tail`). If yours sort first, rename them to sort after it, keep their order and content, and use a non-`000000` HHMMSS. Re-generate a generated `authz migration` file first, then rename it with the rest.
+
+**Applies to:** `packages/database/supabase/migrations/`; every branch that adds a migration.
+
+## The license-header fixer only sees files git tracks
+
+**Context:** `pnpm --filter @carbon/checks license-headers -- <paths>` writes the SPDX header. It walks `git ls-files --cached`.
+
+**Problem:** A new, untracked file is not in that list, so the fixer reports "0 fixed" and the file keeps no header until the `spdx-license-header` check fails at commit.
+
+**Rule:** Run `git add -N <new files>` (intent to add; it records no content) before the fixer, then run the fixer with those paths.
+
+**Applies to:** every new source file outside generated output.
+
## A value two layers must agree on lives once, in the client-safe pure module
**Context:** The accounting enable wizard (ERP) and the `activate-accounting` server function both decide whether Migration Clearing totals zero. The wizard uses the answer to offer "Enable accounting". The server function uses it to refuse the enable. The wizard steps also pass the cutover date to each other in a search param.
diff --git a/.ai/plans/2026-10-06-kanban-internal-replenishment-level.md b/.ai/plans/2026-10-06-kanban-internal-replenishment-level.md
new file mode 100644
index 0000000000..3531c360b6
--- /dev/null
+++ b/.ai/plans/2026-10-06-kanban-internal-replenishment-level.md
@@ -0,0 +1,1129 @@
+# Kanban Internal Replenishment Level — implementation plan
+
+**Spec:** .ai/specs/2026-10-06-kanban-internal-replenishment-level.md
+**Research:** .ai/research/kanban-internal-replenishment-level.md
+**Run record:** .ai/runs/2026-10-06-kanban-internal-replenishment-level.md
+**Branch:** naveenkash/kanban-circuit-replenishment-spec
+
+## Ground rules for the executor
+
+- 🛑 Ask the user before each step that writes to the local database. These steps are marked **(DB write — ask first)**. This includes `pnpm db:migrate` and every live-database test.
+- 🛑 Ask the user before each commit. Commit only through `/check-and-commit`. Never push.
+- Start every new source file with its SPDX header. Run `pnpm --filter @carbon/checks license-headers` to write it. Do not type it by hand.
+- Wrap every new UI string in Lingui `t` or `<Trans>`. `/check-and-commit` runs `/translate`.
+- Never use JavaScript `Date`. Never use `Math.round` or `.toFixed` on a quantity.
+- If a fact in this plan turns out false in the code, STOP and report. Do not improvise.
+- Do not change the demo datasets (`packages/database/src/datasets/`). Their Transfer kanbans stay scan-only.
+
+## Corrections to the spec found while planning
+
+The spec is updated with each of these. The plan follows the updated spec.
+
+| # | Spec said | Code says | Plan does |
+|---|---|---|---|
+| 1 | The `kanbans` view selects `k.*`, so the new column appears | Postgres expands `k.*` when it creates the view | Recreate the view in the migration |
+| 2 | Scalar `get_kanban_projected_quantity(kanban_id, company_id)` | The kanbans list needs one query for the page | One set-returning function, `get_kanban_projected_quantities(company_id, kanban_ids)` |
+| 3 | The sweep sends one event with no `companyId` | An Inngest concurrency key on a missing field is unsafe | `util.sweep_kanban_levels()` sends one event per company, with `kanbanIds` |
+| 4 | Inngest function in `functions/inventory/` | That directory does not exist | `packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts` |
+| 5 | Statement handler in `event-system/functions/` | The only table statement handler, `apply_item_stock_quantities`, is in `handlers/` | Both new trigger bodies go in `event-system/handlers/` |
+| 6 | The handler sends every armed kanban it touches | An event with no work still costs a function run | The handler and the interceptor send only kanbans below their level |
+| 7 | A pgTAP test captures `send_inngest_event` | The DB tests are plain psql scripts; none captures a `net.http_post` call | Test the SQL selection (`util.kanban_level_breaches()`); prove the send path in the browser test |
+| 8 | `getKanbanLevelStatus` | One concept, one name | `getKanbanProjectedQuantities` |
+| 9 | The header loader reads the kanban's names for the badge | `getStockTransfer` selects `*`, so `kanbanId` arrives with no new read | The badge reads `kanbanId` only |
+| 10 | A blank level on save clears the level | zod omits a blank optional field, so the UPDATE keeps the old value | `upsertKanban` writes `null` when the field is blank or the system is not Transfer |
+
+## Progress
+
+- [x] Task 1: Write the schema migration (verified, not committed)
+- [x] Task 2: Add the two trigger bodies and ship them with `authz migration` (verified, not committed)
+- [x] Task 3: Apply the migrations and regenerate types (DB write — ask first) (verified, not committed)
+- [x] Task 4: Add the SQL test script (verified, not committed)
+- [x] Task 5: Add the pure stock-transfer helpers in `@carbon/database` (verified, not committed)
+- [x] Task 6: Switch `insertStockTransfer` to the shared helper (verified, not committed)
+- [x] Task 7: Declare the `carbon/kanban.level-check` event (verified, not committed)
+- [x] Task 8: Add the `kanban-replenish` server function (verified, not committed)
+- [x] Task 9: Add the live-database test for `kanban-replenish` (verified, not committed)
+- [x] Task 10: Add the Inngest function `kanbanLevelCheckFunction` (verified, not committed)
+- [x] Task 11: Route the scan through `kanban-replenish` (verified, not committed)
+- [x] Task 12: Extend `kanbanValidator` and `upsertKanban` (verified, not committed)
+- [x] Task 13: Add the glossary term (verified, not committed)
+- [x] Task 14: Add the Replenishment Level field to `KanbanForm` (verified, not committed)
+- [x] Task 15: Show the level and projected quantity on the kanbans list (verified, not committed)
+- [x] Task 16: Show the origin on stock transfers (verified, not committed)
+- [x] Task 17: Print the level on the kanban label (verified, not committed)
+- [x] Task 18: Update the docs, the kanban rule and the AGENTS files (verified, not committed)
+- [x] Task 19: Run the final gates and the browser test (gates green; browser test passed 2026-10-09, playbook .ai/playbooks/kanban-replenishment-level.md)
+
+## Dependencies
+
+- Task 2 needs Task 1 (the trigger bodies call `get_kanban_projected_quantities`).
+- Task 3 needs Tasks 1 and 2.
+- Tasks 4, 5, 7, 12, 13 and 17 need Task 3 only. They are independent of each other.
+- Task 6 needs Task 5.
+- Task 8 needs Tasks 5 and 7.
+- Tasks 9, 10 and 11 need Task 8. They are independent of each other.
+- Task 14 needs Tasks 12 and 13.
+- Tasks 15 and 16 need Task 3. They are independent of each other.
+- Task 18 needs Tasks 8–17.
+- Task 19 needs every other task.
+
+---
+
+## Task 1: Write the schema migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_kanban-replenishment-level.sql` (the command makes the name)
+- Copy from (precedent): `packages/database/supabase/migrations/20260908143722_kanban-transfer.sql` (view), `packages/database/supabase/migrations/20261004183512_scheduled-jobs-from-database.sql:156-193` (sweep and cron)
+
+**Steps:**
+1. Run `pnpm db:migrate:new kanban-replenishment-level`.
+2. Run this query against the local database. It is read-only.
+ ```sql
+ SELECT count(*) FROM "kanban"
+ WHERE "replenishmentSystem" = 'Transfer' AND "fromStorageUnitId" = "storageUnitId";
+ ```
+3. If the count is above 0, STOP and report. The new CHECK would fail on those rows.
+4. Write this SQL into the new file, exactly:
+
+```sql
+-- Kanban replenishment level: a Transfer kanban fires when the projected
+-- quantity at its To storage unit is below this level.
+-- Spec: .ai/specs/2026-10-06-kanban-internal-replenishment-level.md
+
+-- 1. The level on the kanban
+ALTER TABLE "kanban" ADD COLUMN IF NOT EXISTS "replenishmentLevel" NUMERIC;
+
+ALTER TABLE "kanban" DROP CONSTRAINT IF EXISTS "kanban_replenishmentLevel_check";
+ALTER TABLE "kanban"
+ ADD CONSTRAINT "kanban_replenishmentLevel_check"
+ CHECK ("replenishmentLevel" IS NULL OR "replenishmentLevel" >= 0);
+
+COMMENT ON COLUMN "kanban"."replenishmentLevel" IS
+ 'Transfer kanbans only. When the projected quantity at the To storage unit is below this level, Carbon creates a Released stock transfer for "quantity". NULL = scan-only.';
+
+-- A Transfer kanban must not feed itself. The zod refine exists; this stops API writes.
+ALTER TABLE "kanban" DROP CONSTRAINT IF EXISTS "kanban_transfer_distinct_storage_units_check";
+ALTER TABLE "kanban"
+ ADD CONSTRAINT "kanban_transfer_distinct_storage_units_check"
+ CHECK (
+ "replenishmentSystem" <> 'Transfer'
+ OR "fromStorageUnitId" IS NULL
+ OR "storageUnitId" IS NULL
+ OR "fromStorageUnitId" <> "storageUnitId"
+ );
+
+-- From a ledger row to its armed kanbans
+CREATE INDEX IF NOT EXISTS "kanban_level_lookup_idx"
+ ON "kanban" ("companyId", "itemId", "storageUnitId")
+ WHERE "replenishmentSystem" = 'Transfer' AND "replenishmentLevel" IS NOT NULL;
+
+-- 2. The kanbans view expands k.* at creation, so recreate it to expose the new column.
+DROP VIEW IF EXISTS "kanbans";
+CREATE VIEW "kanbans" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ k.*,
+ i.name,
+ i."readableIdWithRevision",
+ j."jobId" as "jobReadableId",
+ l.name as "locationName",
+ s.name as "storageUnitName",
+ fs.name as "fromStorageUnitName",
+ su.name as "supplierName",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath"
+FROM "kanban" k
+JOIN "item" i ON k."itemId" = i."id"
+LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+JOIN "location" l ON k."locationId" = l."id"
+LEFT JOIN "storageUnit" s ON k."storageUnitId" = s."id"
+LEFT JOIN "storageUnit" fs ON k."fromStorageUnitId" = fs."id"
+LEFT JOIN "supplier" su ON k."supplierId" = su."id"
+LEFT JOIN "job" j ON k."jobId" = j."id";
+
+-- 3. The origin on the stock transfer
+ALTER TABLE "stockTransfer" ADD COLUMN IF NOT EXISTS "kanbanId" TEXT;
+
+ALTER TABLE "stockTransfer" DROP CONSTRAINT IF EXISTS "stockTransfer_kanbanId_fkey";
+ALTER TABLE "stockTransfer"
+ ADD CONSTRAINT "stockTransfer_kanbanId_fkey"
+ FOREIGN KEY ("kanbanId", "companyId") REFERENCES "kanban" ("id", "companyId")
+ ON DELETE SET NULL ("kanbanId");
+
+CREATE INDEX IF NOT EXISTS "stockTransfer_kanbanId_idx"
+ ON "stockTransfer" ("kanbanId") WHERE "kanbanId" IS NOT NULL;
+
+-- 4. Projected quantity for the armed kanbans of one company.
+-- kanban_ids NULL = every armed kanban of the company.
+-- On-hand uses item_ledger_on_hand_contribution, the itemStockQuantities definition.
+CREATE OR REPLACE FUNCTION get_kanban_projected_quantities(
+ company_id TEXT,
+ kanban_ids TEXT[] DEFAULT NULL
+)
+RETURNS TABLE ("kanbanId" TEXT, "replenishmentLevel" NUMERIC, "projectedQuantity" NUMERIC)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public, pg_temp
+AS $$
+ SELECT
+ k."id",
+ k."replenishmentLevel",
+ COALESCE(on_hand."quantity", 0) + COALESCE(inbound."quantity", 0)
+ FROM "kanban" k
+ LEFT JOIN LATERAL (
+ SELECT SUM(item_ledger_on_hand_contribution(il."quantity", il."trackedEntityStatus")) AS "quantity"
+ FROM "itemLedger" il
+ WHERE il."companyId" = k."companyId"
+ AND il."locationId" = k."locationId"
+ AND il."itemId" = k."itemId"
+ AND il."storageUnitId" = k."storageUnitId"
+ ) on_hand ON true
+ LEFT JOIN LATERAL (
+ SELECT SUM(stl."outstandingQuantity") AS "quantity"
+ FROM "stockTransferLine" stl
+ JOIN "stockTransfer" st
+ ON st."id" = stl."stockTransferId" AND st."companyId" = stl."companyId"
+ WHERE stl."companyId" = k."companyId"
+ AND st."status" IN ('Released', 'In Progress')
+ AND stl."itemId" = k."itemId"
+ AND stl."toStorageUnitId" = k."storageUnitId"
+ ) inbound ON true
+ WHERE k."companyId" = company_id
+ AND (kanban_ids IS NULL OR k."id" = ANY (kanban_ids))
+ AND k."replenishmentSystem" = 'Transfer'
+ AND k."replenishmentLevel" IS NOT NULL
+ AND k."fromStorageUnitId" IS NOT NULL
+ AND k."storageUnitId" IS NOT NULL;
+$$;
+
+-- 5. Backstop sweep: every armed kanban below its level, one row per company.
+CREATE OR REPLACE FUNCTION util.kanban_level_breaches()
+RETURNS TABLE ("companyId" TEXT, "kanbanIds" TEXT[])
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ SELECT c."companyId", array_agg(p."kanbanId" ORDER BY p."kanbanId")
+ FROM (
+ SELECT DISTINCT "companyId" FROM "kanban"
+ WHERE "replenishmentSystem" = 'Transfer' AND "replenishmentLevel" IS NOT NULL
+ ) c
+ CROSS JOIN LATERAL get_kanban_projected_quantities(c."companyId") p
+ WHERE p."projectedQuantity" < p."replenishmentLevel"
+ GROUP BY c."companyId";
+$$;
+
+CREATE OR REPLACE FUNCTION util.sweep_kanban_levels()
+RETURNS void
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ breach RECORD;
+BEGIN
+ FOR breach IN SELECT * FROM util.kanban_level_breaches() LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', breach."companyId", 'kanbanIds', to_jsonb(breach."kanbanIds"))
+ );
+ END LOOP;
+END;
+$$;
+
+REVOKE ALL ON FUNCTION util.kanban_level_breaches() FROM PUBLIC;
+REVOKE ALL ON FUNCTION util.sweep_kanban_levels() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'kanban-level-sweeper') THEN
+ PERFORM cron.unschedule('kanban-level-sweeper');
+ END IF;
+ PERFORM cron.schedule('kanban-level-sweeper', '7 * * * *', 'SELECT util.sweep_kanban_levels();');
+END;
+$$;
+```
+
+5. Do not add the `itemLedger` statement handler or the `kanban` interceptor here. Task 2 ships them.
+
+**Verify:**
+```bash
+ls packages/database/supabase/migrations | grep kanban-replenishment-level
+# Expected: one file, <timestamp>_kanban-replenishment-level.sql, newer than every other migration
+pnpm --filter @carbon/checks test
+# Expected: no failure that names the new migration
+```
+
+If `no-authz-ddl-in-migrations` flags `get_kanban_projected_quantities` or a `util.*` function, STOP and report.
+
+**Out of scope:** the `kanbanReplenishmentSystem` enum (no rename to `Internal`); `kanban.quantity` (stays `INTEGER`); RLS policies (no new table).
+
+---
+
+## Task 2: Add the two trigger bodies and ship them with `authz migration`
+
+**Depends on:** Task 1
+**Files:**
+- Create: `packages/database/src/event-system/handlers/queue_kanban_level_checks.sql`
+- Create: `packages/database/src/event-system/handlers/sync_kanban_level_check.sql`
+- Modify: `packages/database/src/event-system/attachments.ts` — the `itemLedger` entry and a new `kanban` entry
+- Create: `packages/database/supabase/migrations/<timestamp>_kanban-level-check-triggers.sql` (generated)
+- Copy from (precedent): `packages/database/src/event-system/handlers/apply_item_stock_quantities.sql` (statement handler), `packages/database/src/event-system/handlers/sync_job_complete_or_canceled.sql` (interceptor that calls `util.send_inngest_event`)
+
+**Steps:**
+1. Create `queue_kanban_level_checks.sql` with exactly this content:
+
+```sql
+CREATE OR REPLACE FUNCTION public.queue_kanban_level_checks()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ touched JSONB;
+ target RECORD;
+ below TEXT[];
+BEGIN
+ -- A seed, a restore or a test fixture loads ledger rows in bulk.
+ -- The hourly sweep (util.sweep_kanban_levels) covers those.
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- Only batched_new exists on INSERT and only batched_old on DELETE.
+ IF TG_OP = 'DELETE' THEN
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_old
+ WHERE "storageUnitId" IS NOT NULL;
+ ELSE
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_new
+ WHERE "storageUnitId" IS NOT NULL;
+ END IF;
+
+ IF touched IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ FOR target IN
+ SELECT k."companyId", array_agg(DISTINCT k."id") AS "kanbanIds"
+ FROM jsonb_to_recordset(touched) AS t("companyId" TEXT, "itemId" TEXT, "storageUnitId" TEXT)
+ JOIN "kanban" k
+ ON k."companyId" = t."companyId"
+ AND k."itemId" = t."itemId"
+ AND k."storageUnitId" = t."storageUnitId"
+ WHERE k."replenishmentSystem" = 'Transfer'
+ AND k."replenishmentLevel" IS NOT NULL
+ GROUP BY k."companyId"
+ LOOP
+ SELECT array_agg(p."kanbanId" ORDER BY p."kanbanId")
+ INTO below
+ FROM get_kanban_projected_quantities(target."companyId", target."kanbanIds") p
+ WHERE p."projectedQuantity" < p."replenishmentLevel";
+
+ IF below IS NOT NULL THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', target."companyId", 'kanbanIds', to_jsonb(below))
+ );
+ END IF;
+ END LOOP;
+
+ RETURN NULL;
+END;
+$function$;
+```
+
+2. Create `sync_kanban_level_check.sql` with exactly this content:
+
+```sql
+CREATE OR REPLACE FUNCTION public.sync_kanban_level_check(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public', 'extensions'
+AS $function$
+DECLARE
+ is_below BOOLEAN;
+BEGIN
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN;
+ END IF;
+
+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN
+ RETURN;
+ END IF;
+
+ IF (p_new->>'replenishmentSystem') IS DISTINCT FROM 'Transfer'
+ OR (p_new->>'replenishmentLevel') IS NULL
+ THEN
+ RETURN;
+ END IF;
+
+ -- An UPDATE that changes nothing the level check reads does not re-check.
+ IF p_operation = 'UPDATE'
+ AND (p_new->'replenishmentLevel') IS NOT DISTINCT FROM (p_old->'replenishmentLevel')
+ AND (p_new->'replenishmentSystem') IS NOT DISTINCT FROM (p_old->'replenishmentSystem')
+ AND (p_new->'quantity') IS NOT DISTINCT FROM (p_old->'quantity')
+ AND (p_new->'itemId') IS NOT DISTINCT FROM (p_old->'itemId')
+ AND (p_new->'locationId') IS NOT DISTINCT FROM (p_old->'locationId')
+ AND (p_new->'storageUnitId') IS NOT DISTINCT FROM (p_old->'storageUnitId')
+ AND (p_new->'fromStorageUnitId') IS NOT DISTINCT FROM (p_old->'fromStorageUnitId')
+ THEN
+ RETURN;
+ END IF;
+
+ SELECT EXISTS (
+ SELECT 1
+ FROM get_kanban_projected_quantities(p_new->>'companyId', ARRAY[p_new->>'id']) p
+ WHERE p."projectedQuantity" < p."replenishmentLevel"
+ ) INTO is_below;
+
+ IF is_below THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', p_new->>'companyId', 'kanbanIds', jsonb_build_array(p_new->>'id'))
+ );
+ END IF;
+END;
+$function$;
+```
+
+3. In `attachments.ts`, replace the `itemLedger` entry (lines 112-114) with:
+ ```ts
+ itemLedger: {
+ statement: [
+ "apply_item_stock_quantities",
+ "broadcast_table_changes",
+ "queue_kanban_level_checks"
+ ]
+ },
+ ```
+4. Add a `kanban` entry between `jobOperationStepRecord` and `journal`:
+ ```ts
+ kanban: { after: ["sync_kanban_level_check"] },
+ ```
+5. Run `pnpm --filter @carbon/database authz migration kanban-level-check-triggers`.
+6. Open the generated file. Confirm it holds both `CREATE OR REPLACE FUNCTION` bodies. Confirm it holds `set_event_triggers('itemLedger', …)` with all three statement functions. Confirm it holds `set_event_triggers('kanban', …)`.
+7. Do not edit the generated file.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/database test
+# Expected: pass; migration.test.ts reports no unshipped helper or attachment
+```
+
+If `authz migration` refuses because a new file would create an overload, STOP and report.
+
+**Out of scope:** the `stockTransfer` and `stockTransferLine` attachments (no change); `util.send_inngest_event` (not managed).
+
+---
+
+## Task 3: Apply the migrations and regenerate types (DB write — ask first)
+
+**Depends on:** Tasks 1, 2
+**Files:**
+- Modify (generated): `packages/database/src/types.ts`, swagger files written by `pnpm db:migrate`
+
+**Steps:**
+1. 🛑 Ask the user for permission to run `pnpm db:migrate` against the local database.
+2. Run `pnpm db:migrate`. It applies both migrations, runs `authz sync`, and regenerates the types.
+3. Run `pnpm run generate:types`.
+4. Never edit `packages/database/src/types.ts` by hand.
+
+**Verify:**
+```bash
+grep -n '"replenishmentLevel"' packages/database/src/types.ts | head -3
+# Expected: at least one line (kanban Row and the kanbans view Row)
+grep -n 'kanbanId: string | null' packages/database/src/types.ts | head -3
+# Expected: at least one line (stockTransfer Row)
+grep -n 'get_kanban_projected_quantities' packages/database/src/types.ts
+# Expected: one Functions entry
+pnpm --filter @carbon/database authz check
+# Expected: 0 tables, 0 functions out of sync
+```
+
+**Out of scope:** `pnpm db:check:backups` (Task 19 runs it).
+
+---
+
+## Task 4: Add the SQL test script
+
+**Depends on:** Task 3
+**Files:**
+- Create: `packages/database/supabase/tests/kanban-replenishment-level.test.sql`
+- Copy from (precedent): `packages/database/supabase/tests/scheduled-job-sweeps.test.sql` (structure, `pg_temp.expect`, `BEGIN … ROLLBACK`)
+
+**Steps:**
+1. Start the file with the header comment and run command of the precedent, with this file's name.
+2. Open with `\set ON_ERROR_STOP on`, `BEGIN;`, `SET LOCAL "app.sync_in_progress" = 'true';`, `SET LOCAL statement_timeout = '30s';`.
+3. Copy `pg_temp.expect(label text, actual boolean, expected boolean)` from the precedent.
+4. Borrow fixture rows in one `DO $proof$ … $proof$;` block:
+ 1. Select one pair of distinct `storageUnit` rows `a` and `b` with the same `companyId` and `locationId`.
+ 2. Select one `item` row of that company.
+ 3. If either select finds nothing, `RAISE EXCEPTION 'test needs a seeded company'`.
+5. Insert a `kanban`: `replenishmentSystem = 'Transfer'`, From = `a`, To = `b`, `quantity = 5`, `replenishmentLevel = 10`, `createdBy = 'system'`.
+6. Insert an `itemLedger` row: `entryType = 'Positive Adjmt.'`, `documentType = 'Inventory Receipt'`, at `b`, quantity 12.
+7. Assert these, in order, with `pg_temp.expect`:
+ 1. `get_kanban_projected_quantities(companyId, ARRAY[kanbanId])` returns `projectedQuantity = 12`.
+ 2. `util.kanban_level_breaches()` has no row naming the kanban.
+ 3. Insert a ledger row of −3 at `b`. The breach set now names the kanban (projected 9).
+ 4. Insert a `stockTransfer` (`status = 'Released'`) with one `stockTransferLine` a → b, quantity 5. The breach set no longer names the kanban (projected 14).
+ 5. Set the line's `pickedQuantity = 5`. Insert ledger rows −5 at `a` and +5 at `b`. Projected stays 14.
+ 6. Set the transfer `status = 'Completed'`. Projected stays 14.
+ 7. Insert a second kanban with `replenishmentLevel = NULL`. The function returns no row for it.
+ 8. In a nested `BEGIN … EXCEPTION WHEN check_violation` block, update the first kanban to `fromStorageUnitId = storageUnitId`. Expect the exception.
+ 9. In a nested block, update the first kanban to `replenishmentLevel = -1`. Expect `check_violation`.
+8. End the file with `ROLLBACK;`.
+
+**Verify:** (DB write — ask first; the script rolls back)
+```bash
+pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/kanban-replenishment-level.test.sql
+# Expected: exit 0, ROLLBACK, no ERROR line
+```
+
+If an insert fails on a missing NOT NULL column, read the table's `Insert` type in `packages/database/src/types.ts`. Add the column.
+
+**Out of scope:** capturing `util.send_inngest_event` calls (no precedent; the browser test covers the send).
+
+---
+
+## Task 5: Add the pure stock-transfer helpers in `@carbon/database`
+
+**Depends on:** Task 3
+**Files:**
+- Create: `packages/database/src/stock-transfer.ts`
+- Create: `packages/database/src/stock-transfer.test.ts`
+- Modify: `packages/database/package.json` — add the export `"./stock-transfer": "./src/stock-transfer.ts"` next to `"./sequence"`
+- Copy from (precedent): `packages/database/src/supersession-pick.ts` and its test (pure module shape, relative `.ts` imports, `vitest`)
+
+**Steps:**
+1. Export this type and four values from `stock-transfer.ts`:
+ ```ts
+ export type StockTransferLineDraft = {
+ itemId: string;
+ fromStorageUnitId?: string | null;
+ toStorageUnitId?: string | null;
+ quantity?: number;
+ requiresSerialTracking?: boolean;
+ requiresBatchTracking?: boolean;
+ };
+ export function expandSerialTrackedLines<T extends StockTransferLineDraft>(lines: T[]): T[];
+ export function isBelowReplenishmentLevel(projectedQuantity: number, replenishmentLevel: number): boolean;
+ export const KANBAN_REPLENISHMENT_NOTE_PREFIX = "Kanban replenishment";
+ export function kanbanReplenishmentNote(input: KanbanReplenishmentNoteInput): KanbanReplenishmentNote;
+ ```
+2. Copy the body of `expandSerialTrackedLines` from the `reduce` in `insertStockTransfer` (`apps/erp/app/modules/inventory/inventory.service.ts`, the `linesWithExpandedSerialTracking` block). Keep its behavior exactly:
+ 1. Drop a line whose `quantity` is set and not an integer.
+ 2. Split a serial-tracked line of quantity > 1 into that many lines of quantity 1.
+ 3. Keep every other line as it is.
+3. Make `isBelowReplenishmentLevel` return `projectedQuantity < replenishmentLevel`. Strict, per spec Open Question 2.
+4. Define the note input as a discriminated union on the signal:
+ ```ts
+ export type KanbanReplenishmentNoteInput = {
+ itemReadableId: string;
+ fromStorageUnitName: string;
+ toStorageUnitName: string;
+ quantity: number;
+ unitOfMeasureCode: string | null;
+ signal:
+ | { type: "scan"; userName: string }
+ | { type: "level"; replenishmentLevel: number; projectedQuantity: number };
+ };
+ ```
+5. Return the Tiptap document `{ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] }`.
+6. Build `text` in this form. Leave out the unit when `unitOfMeasureCode` is null.
+ - Scan: `Kanban replenishment — MAT-KAPTON, A1-L3 → CleanRoom, 10 EA. Signal: scan by Jane Doe.`
+ - Level: `Kanban replenishment — MAT-KAPTON, A1-L3 → CleanRoom, 10 EA. Signal: level 4 (projected 3).`
+7. Write `String(n)` for each number. Do not round.
+8. In the test file, cover these cases:
+ 1. Serial line of quantity 3 → 3 lines of quantity 1.
+ 2. Batch line of quantity 3 → 1 line of quantity 3.
+ 3. Untracked line of quantity 2.5 → dropped.
+ 4. `isBelowReplenishmentLevel(10, 10)` → false; `(9, 10)` → true.
+ 5. The scan note text and the level note text, each as one exact string.
+ 6. The note with `unitOfMeasureCode: null` has no trailing unit.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/database test -- stock-transfer
+# Expected: all stock-transfer tests pass
+pnpm exec turbo run typecheck --filter=@carbon/database
+# Expected: 0 errors
+```
+
+**Out of scope:** formatting numbers by locale (the note is English free text, like the scan route's strings).
+
+---
+
+## Task 6: Switch `insertStockTransfer` to the shared helper
+
+**Depends on:** Task 5
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — `insertStockTransfer`
+
+**Steps:**
+1. Import `expandSerialTrackedLines` from `@carbon/database/stock-transfer`.
+2. Replace the `linesWithExpandedSerialTracking` `reduce` with `const linesWithExpandedSerialTracking = expandSerialTrackedLines(lines);`.
+3. Change nothing else in the function.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+**Out of scope:** moving `insertStockTransfer` into a server function (the wizard keeps its RLS path).
+
+---
+
+## Task 7: Declare the `carbon/kanban.level-check` event
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/lib/src/events.ts` — the `Events` type
+- Copy from (precedent): `packages/lib/src/events.ts:563-570` (events sent by Postgres)
+
+**Steps:**
+1. Add this entry next to `"carbon/workflow-run-retention.process"`:
+ ```ts
+ // Sent by the database (queue_kanban_level_checks, sync_kanban_level_check,
+ // util.sweep_kanban_levels), never by app code. Every id is a Transfer
+ // kanban whose projected quantity was below its replenishment level.
+ "carbon/kanban.level-check": {
+ data: { companyId: string; kanbanIds: string[] };
+ };
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/lib
+# Expected: 0 errors
+```
+
+**Out of scope:** `packages/lib/src/trigger.ts` (`taskToEvent`); no app code sends this event.
+
+---
+
+## Task 8: Add the `kanban-replenish` server function
+
+**Depends on:** Tasks 5, 7
+**Files:**
+- Create: `packages/server-functions/src/kanban-replenish/index.ts`
+- Modify: `packages/server-functions/src/invoke.ts` — add `"kanban-replenish": () => import("./kanban-replenish"),` in alphabetical order
+- Modify (generated): `packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap`
+- Copy from (precedent): `packages/server-functions/src/seed-company/index.ts` (`permissions: "system"`), `packages/server-functions/src/issue/index.ts:802-819` (`getNextSequence` inside a transaction), `packages/server-functions/src/assign-serial-numbers/index.ts:85-99` (`.forUpdate()`)
+
+**Steps:**
+1. Declare the input schema:
+ ```ts
+ export const kanbanReplenishInput = z.discriminatedUnion("mode", [
+ z.object({ mode: z.literal("scan"), kanbanId: z.string().min(1) }),
+ z.object({ mode: z.literal("level"), kanbanIds: z.array(z.string().min(1)).optional() })
+ ]);
+ ```
+2. Declare the reasons. The first three strings are the scan route's current error strings; keep them exact.
+ ```ts
+ export const KANBAN_REPLENISH_REASONS = {
+ missingStorageUnit: "Kanban is missing a from or to storage unit",
+ foreignStorageUnit: "Storage unit does not belong to the kanban location",
+ missingItem: "Failed to get item",
+ notTransfer: "Kanban is not a transfer kanban",
+ notArmed: "Kanban has no replenishment level"
+ } as const;
+ ```
+3. Declare the result type:
+ ```ts
+ export type KanbanReplenishOutcome =
+ | { kanbanId: string; outcome: "created"; id: string; stockTransferId: string }
+ | { kanbanId: string; outcome: "at-level"; projectedQuantity: number }
+ | { kanbanId: string; outcome: "invalid"; reason: (typeof KANBAN_REPLENISH_REASONS)[keyof typeof KANBAN_REPLENISH_REASONS] };
+ export type KanbanReplenishResult = { results: KanbanReplenishOutcome[] };
+ ```
+4. Define the function with `name: "kanban-replenish"`, `input: kanbanReplenishInput`, `permissions: "system"`. Add the comment: `// Both callers elevate: the scan route after requirePermissions, the job with no user.`
+5. In `run(ctx, input)`, do the steps below in ONE `ctx.db.transaction().execute(async (trx) => { … })`. Read only on `trx`.
+6. Lock the kanbans:
+ 1. Select `id, itemId, locationId, replenishmentSystem, replenishmentLevel, quantity, fromStorageUnitId, storageUnitId` from `kanban`.
+ 2. Filter `companyId = ctx.companyId`.
+ 3. In scan mode, filter `id = input.kanbanId`.
+ 4. In level mode with `kanbanIds`, filter `id in kanbanIds`. If `kanbanIds` is an empty array, return `{ results: [] }` before the query.
+ 5. In level mode with no `kanbanIds`, filter `replenishmentSystem = 'Transfer'` and `replenishmentLevel is not null`.
+ 6. Add `.orderBy("id").forUpdate()`. The order stops two calls from deadlocking.
+7. If scan mode found no row, throw `NotFoundError("Kanban not found")`.
+8. Classify each locked kanban. Stop at the first rule that matches:
+ 1. If `replenishmentSystem !== "Transfer"` → `invalid`, `notTransfer`.
+ 2. If either storage unit is null → `invalid`, `missingStorageUnit`.
+ 3. If level mode and `replenishmentLevel` is null → `invalid`, `notArmed`.
+9. Read the storage units of the remaining kanbans in one query: `storageUnit` `id, name, locationId`, `companyId = ctx.companyId`, `id in [...]`.
+10. If a kanban's From or To storage unit is absent, or its `locationId` differs from the kanban's, mark it `invalid`, `foreignStorageUnit`. This is the CWE-639 guard moved from the route.
+11. In level mode, read projected quantity in one query:
+ ```ts
+ sql<{ kanbanId: string; replenishmentLevel: number; projectedQuantity: number }>`
+ SELECT * FROM get_kanban_projected_quantities(${ctx.companyId}, ${ids}::text[])
+ `.execute(trx)
+ ```
+12. For each remaining kanban, if `!isBelowReplenishmentLevel(projectedQuantity, replenishmentLevel)`, mark it `at-level`. Write nothing for it.
+13. Read the items in one query: `item` `id, readableIdWithRevision, itemTrackingType, unitOfMeasureCode`, `companyId = ctx.companyId`, `id in [...]`. A missing item → `invalid`, `missingItem`.
+14. In scan mode, read `user.fullName` for `ctx.userId`. Use `"unknown user"` if it is null.
+15. For each kanban to replenish, in `id` order:
+ 1. Take `stockTransferId = await getNextSequence(trx, "stockTransfer", ctx.companyId)`.
+ 2. Build the note with `kanbanReplenishmentNote`. Use `readableIdWithRevision ?? itemId` for the item.
+16. Insert every header in one statement into `stockTransfer`: `stockTransferId, locationId, status: "Released", companyId, kanbanId, notes, createdBy: ctx.userId`. Return `["id", "kanbanId", "stockTransferId"]`.
+17. Build the lines with `expandSerialTrackedLines`, one draft per kanban:
+ - `itemId`, `fromStorageUnitId`, `toStorageUnitId: storageUnitId`, `quantity`
+ - `requiresSerialTracking: itemTrackingType === "Serial"`
+ - `requiresBatchTracking: itemTrackingType === "Batch"`
+18. Insert every line in one statement into `stockTransferLine`, with `stockTransferId` (the header `id`), `companyId` and `createdBy: ctx.userId`.
+19. Return `{ results }` with one outcome per locked kanban, in `id` order.
+20. Log each `created` outcome with `getLogger("server-functions", "kanban-replenish")`.
+21. Export the function as the module default.
+22. Run `pnpm --filter @carbon/server-functions exec vitest run -u src/permissions-manifest.test.ts`.
+23. Review the snapshot diff. It must add only `"kanban-replenish": "system"`.
+
+If Kysely refuses the Tiptap object for the `notes` JSON column, STOP and report.
+If `getNextSequence` throws because the company has no `stockTransfer` sequence row, STOP and report.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/server-functions test
+# Expected: pass, including permissions-manifest and invoke tests
+pnpm exec turbo run typecheck --filter=@carbon/server-functions --concurrency=1
+# Expected: 0 errors
+```
+
+**Out of scope:** storage-rule evaluation (spec Open Question 7); a shortage check on the From bin (Open Question 8); `n × quantity` catch-up (Open Question 3).
+
+---
+
+## Task 9: Add the live-database test for `kanban-replenish`
+
+**Depends on:** Task 8
+**Files:**
+- Create: `packages/server-functions/src/kanban-replenish/kanban-test-fixture.ts`
+- Create: `packages/server-functions/src/kanban-replenish/kanban-replenish.test.ts`
+- Copy from (precedent): `packages/server-functions/src/post-payment/payment-test-fixture.ts` (scratch company, `cleanup()`), `packages/server-functions/src/post-memo/post-memo-transaction.test.ts` (`databaseTest`, `try … finally cleanup`)
+
+**Steps:**
+1. In the fixture, call `connectLocalTestDatabase()`.
+2. Build a scratch company with a random prefix, as the precedent does.
+3. Insert, in one transaction with `SET LOCAL "app.sync_in_progress" = 'true'`:
+ 1. `companyGroup` and `company` (copy from the precedent).
+ 2. One `location`.
+ 3. Two `storageUnit` rows at that location, `A` (From) and `B` (To).
+ 4. One untracked `item` with `readableId = "KB-TEST-ITEM"`.
+ 5. One `sequence` row for `stockTransfer`.
+ 6. One `kanban`: Transfer, A → B, `quantity = 5`, `replenishmentLevel = 10`.
+4. Read every NOT NULL column without a default from the `Insert` types in `packages/database/src/types.ts`.
+5. Return `{ db, companyId, kanbanId, fromId, toId, itemId, adjustToBin(delta), cleanup }`. `adjustToBin` inserts one `itemLedger` row of `delta` at `B`.
+6. Copy `cleanup()` from the precedent: delete the company, the company group, and the per-company tables, then `db.destroy()`.
+7. Call the function as the callers do: `serverFns.system({ db, companyId, userId: "system" }).invoke("kanban-replenish", …)`.
+8. Write one `databaseTest` per case. Each one calls `cleanup()` in `finally`.
+ 1. `adjustToBin(12)`, level mode → `at-level`, no `stockTransfer` row.
+ 2. `adjustToBin(9)`, level mode → one `created`. Check the header: `kanbanId` set, `status = "Released"`, `createdBy = "system"`. Check the notes text starts `Kanban replenishment`. Check one line A → B for 5.
+ 3. Case 2, then level mode again → `at-level` (projected 14), still one header.
+ 4. Case 2, then set `pickedQuantity = 5` and post ledger rows −5 at A and +5 at B → level mode gives `at-level`.
+ 5. Case 4, then `adjustToBin(-6)` (projected 8) → one more `created`.
+ 6. `adjustToBin(12)`, scan mode → `created`; notes text contains `Signal: scan by`.
+ 7. Update the kanban to From = To → the update throws a check violation.
+ 8. A level-mode call with a `kanbanIds` entry from another company → no outcome for it.
+
+**Verify:** (DB write — ask first; the fixture creates and deletes its own company)
+```bash
+pnpm --filter @carbon/server-functions test -- kanban-replenish
+# Expected: 8 tests pass when SUPABASE_DB_URL is local; 8 skipped otherwise
+```
+
+**Out of scope:** two concurrent calls (the fixture has one connection; the `FOR UPDATE` lock is the guard).
+
+---
+
+## Task 10: Add the Inngest function `kanbanLevelCheckFunction`
+
+**Depends on:** Task 8
+**Files:**
+- Create: `packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts`
+- Modify: `packages/jobs/src/inngest/functions/tasks/index.ts` — export it
+- Modify: `packages/jobs/src/inngest/index.ts` — import it and add it to `functions` under `// Tasks`
+- Copy from (precedent): `packages/jobs/src/inngest/functions/tasks/recalculate.ts`
+
+**Steps:**
+1. Write the function:
+ ```ts
+ export const kanbanLevelCheckFunction = inngest.createFunction(
+ {
+ id: "kanban-level-check",
+ retries: 3,
+ concurrency: { limit: 1, scope: "env", key: '"kanban-level:" + event.data.companyId' }
+ },
+ { event: "carbon/kanban.level-check" },
+ async ({ event, step, logger }) => {
+ const { companyId, kanbanIds } = event.data;
+ const result = await step.run("replenish", () =>
+ serverFns
+ .system({ db: getJobDatabaseClient(), companyId, userId: "system" })
+ .invokeOrThrow("kanban-replenish", { mode: "level", kanbanIds })
+ );
+ // log each created and each invalid outcome; return result
+ }
+ );
+ ```
+2. Do not add `debounce`. The local Inngest dev server cannot run it (`.ai/lessons.md:541`).
+3. Log each `created` outcome with `logger.info`. Log each `invalid` outcome with `logger.warn`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs
+# Expected: 0 errors
+pnpm --filter @carbon/jobs test
+# Expected: pass
+```
+
+**Out of scope:** a cron trigger in Inngest (pg_cron owns the hourly sweep).
+
+---
+
+## Task 11: Route the scan through `kanban-replenish`
+
+**Depends on:** Task 8
+**Files:**
+- Modify: `apps/erp/app/routes/api+/kanban.$id.tsx` — the `Transfer` branch (lines 351-428) and the imports
+
+**Steps:**
+1. Keep the `!kanban.data.itemId` guard and its error string.
+2. Delete the storage-unit query, the item query and the `insertStockTransfer` call in this branch.
+3. Call:
+ ```ts
+ const replenish = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("kanban-replenish", { mode: "scan", kanbanId: id });
+ ```
+4. If `replenish.error` is set, log it and return `{ data: null, error: "Failed to create stock transfer" }`.
+5. Read `const outcome = replenish.data.results[0]`.
+6. If `outcome.outcome === "invalid"`, return `{ data: null, error: outcome.reason }`.
+7. If `outcome.outcome === "created"`, return `{ data: path.to.stockTransfer(outcome.id), error: null }`.
+8. Otherwise return `{ data: null, error: "Failed to create stock transfer" }`.
+9. Remove `insertStockTransfer` from the `~/modules/inventory` import if nothing else in the file uses it.
+10. Import `serverFns` from `@carbon/server-functions`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+**Out of scope:** the `Buy` and `Make` branches; the `role: "employee"` check in the loader.
+
+---
+
+## Task 12: Extend `kanbanValidator` and `upsertKanban`
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.models.ts` — `kanbanValidator`
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — `upsertKanban`
+- Modify: `apps/erp/app/modules/inventory/inventory.models.test.ts`
+
+**Steps:**
+1. Add to the object: `replenishmentLevel: zfd.numeric(z.number().min(0, { message: "Replenishment level must be 0 or more" }).optional()),`.
+2. Add one refine after the existing ones:
+ ```ts
+ .refine(
+ (data) =>
+ data.replenishmentSystem === "Transfer" || data.replenishmentLevel === undefined,
+ {
+ message: "Only a transfer kanban can have a replenishment level",
+ path: ["replenishmentLevel"]
+ }
+ )
+ ```
+3. In `upsertKanban`, set the level on the row before the insert or update:
+ ```ts
+ const replenishmentLevel =
+ row.replenishmentSystem === "Transfer" ? (row.replenishmentLevel ?? null) : null;
+ ```
+4. Spread `{ ...row, replenishmentLevel }` into both the `insert` and the `update`. A blank field then clears the level.
+5. Add tests to `inventory.models.test.ts`:
+ 1. Transfer with level 10 → valid.
+ 2. Transfer with no level → valid.
+ 3. Buy with level 10 → error on `replenishmentLevel`.
+ 4. Transfer with level −1 → error on `replenishmentLevel`.
+
+**Verify:**
+```bash
+pnpm --filter erp test -- inventory.models
+# Expected: all tests pass
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+**Out of scope:** the `kanbans.new.tsx` and `kanbans.$id.tsx` actions (they pass the validated row through unchanged).
+
+---
+
+## Task 13: Add the glossary term
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `docs/content/src/glossary/terms.ts` — the `// ── Kanbans (KanbanForm) ──` block (around lines 916-935)
+- Copy from (precedent): the `"kanban-auto-release"` entry in the same block
+
+**Steps:**
+1. Add:
+ ```ts
+ "kanban-replenishment-level": {
+ term: msg`Replenishment Level`,
+ definition: msg`On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity.`,
+ href: "/docs/reference/kanban"
+ },
+ ```
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/content
+# Expected: 0 errors
+```
+
+**Out of scope:** the `"replenishment-system"` term (Task 18 fixes its text).
+
+---
+
+## Task 14: Add the Replenishment Level field to `KanbanForm`
+
+**Depends on:** Tasks 12, 13
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx`
+- Copy from (precedent): the `Number` field with `termId` in `apps/erp/app/modules/accounting/ui/PaymentTerms/PaymentTermForm.tsx:127-133`
+
+**Steps:**
+1. Render the current Quantity field (lines 227-232) only when `!isTransfer`.
+2. After the To Storage Unit field, when `isTransfer`, render:
+ 1. Quantity: `name="quantity"`, `minValue={1}`, helper text `The quantity moved from the From storage unit on each signal.`
+ 2. Replenishment Level: `Number`, `name="replenishmentLevel"`, `label={t\`Replenishment Level\`}`, `termId="kanban-replenishment-level"`, `minValue={0}`, helper text `When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only.`
+3. In `onItemChange` (lines 103-107), keep `Transfer` when the user already chose it:
+ ```ts
+ setSelectedReplenishmentSystem((current) =>
+ current === "Transfer" ? current : item.data?.replenishmentSystem === "Make" ? "Make" : "Buy"
+ );
+ ```
+4. Make sure `initialValues` carries `replenishmentLevel`. Check the two routes that render the form (`x+/inventory+/kanbans.new.tsx`, `kanbans.$id.tsx`). Pass `replenishmentLevel: kanban.replenishmentLevel ?? undefined` where the edit route builds `initialValues`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+pnpm run lint
+# Expected: no new Biome errors
+```
+
+**Out of scope:** the field order of Buy and Make kanbans.
+
+---
+
+## Task 15: Show the level and projected quantity on the kanbans list
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — add `getKanbanProjectedQuantities`
+- Modify: `apps/erp/app/routes/x+/inventory+/kanbans.tsx` — the loader and the component
+- Modify: `apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx` — the props and two columns
+- Copy from (precedent): the `quantity` column (`KanbansTable.tsx:388-405`), the `Status` pill in `apps/erp/app/modules/sales/ui/SalesRules/SalesRulesTable.tsx:114-126`, `useQuantityFormatter` from `~/hooks/useQuantityFormatter`
+
+**Steps:**
+1. Add the service function after `getKanban`:
+ ```ts
+ /** @mcp read */
+ export async function getKanbanProjectedQuantities(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ kanbanIds: string[]
+ ) {
+ return client.rpc("get_kanban_projected_quantities", {
+ company_id: companyId,
+ kanban_ids: kanbanIds
+ });
+ }
+ ```
+2. In the loader, after `getKanbans`, collect the ids of rows with `replenishmentSystem === "Transfer"` and a non-null `replenishmentLevel`.
+3. If the list is not empty, call `getKanbanProjectedQuantities` once.
+4. If that call fails, log it and use an empty map. Do not fail the page.
+5. Return `projectedQuantities: Record<string, number>` (kanban id → `projectedQuantity`).
+6. Pass `projectedQuantities` to `KanbansTable` as a new prop.
+7. Add a column after the `quantity` column: `accessorKey: "replenishmentLevel"`, header `t\`Replenishment Level\``, blank when null, `meta: { icon: <LuHash /> }`.
+8. Add a column after it: `id: "projectedQuantity"`, header `t\`Projected (To)\``.
+ 1. If the row has no entry in `projectedQuantities`, render nothing.
+ 2. Otherwise render the number with `useQuantityFormatter`.
+ 3. If the number is below `replenishmentLevel`, also render `<Status color="red"><Trans>Below level</Trans></Status>`.
+9. Run `pnpm run generate:mcp`. Keep the generated diff.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+git status --short | grep -i mcp
+# Expected: the generated MCP metadata changed only by the new read tool
+```
+
+**Out of scope:** sorting or filtering on the projected column (it is not a table column).
+
+---
+
+## Task 16: Show the origin on stock transfers
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `apps/erp/app/modules/inventory/inventory.service.ts` — `getStockTransfers`
+- Modify: `apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx` — a Source column
+- Modify: `apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx` — a Kanban badge
+- Copy from (precedent): `apps/erp/app/modules/workflows/workflows.service.ts:31-50` (derived filter), `apps/erp/app/modules/workflows/ui/WorkflowsTable.tsx:98-122` (derived column), `KanbansTable.tsx:141-158` (Badge around a Link)
+
+**Steps:**
+1. In `getStockTransfers`, split `args.filters` into `source` filters and column filters, as the precedent does.
+2. For a `source` filter with value `Kanban`, add `query.not("kanbanId", "is", null)`.
+3. For value `Manual`, add `query.is("kanbanId", null)`.
+4. Pass only the column filters to `setGenericQueryFilters`.
+5. Import `Filter` from `~/utils/query`.
+6. In `StockTransfersTable`, add a column after `status`:
+ - `id: "source"`, header `t\`Source\``
+ - cell: `kanbanId` set → `<Badge variant="blue"><Trans>Kanban</Trans></Badge>`, else `<Badge variant="gray"><Trans>Manual</Trans></Badge>`
+ - `meta.filter`: static options `Kanban` and `Manual`; `meta.filterHeader: t\`Source\``
+ - `meta.exportValue`: `row.kanbanId ? "Kanban" : "Manual"`
+7. In `StockTransferHeader`, after `<StockTransferStatus … />` (line 171), when `routeData?.stockTransfer?.kanbanId` is set, render:
+ ```tsx
+ <Badge variant="outline">
+ <Link to={path.to.kanban(kanbanId)} className="flex flex-row items-center gap-1">
+ <LuScanQrCode />
+ <Trans>Kanban</Trans>
+ </Link>
+ </Badge>
+ ```
+8. Add `Link` to the `react-router` import. Import `LuScanQrCode` from `react-icons/lu`, the icon the Kanbans nav entry uses.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+**Out of scope:** `StockTransferNotes.tsx` (the note renders as any note); MES stock-transfer screens.
+
+---
+
+## Task 17: Print the level on the kanban label
+
+**Depends on:** Task 3
+**Files:**
+- Modify: `packages/documents/src/pdf/KanbanLabelPDF.tsx` — `KanbanLabel` and the QTY block (lines 216-225)
+- Modify: `apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx` — the mapping (lines 93-106)
+- Modify: `packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts` — `KanbanCardItem` (lines 10-23) and `resolveKanbanData` (lines 58-91)
+- Modify: `packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx` — `renderKanbanCardPDF` (lines 220-240)
+
+**Steps:**
+1. Add `replenishmentLevel?: number | null;` to `KanbanLabel`.
+2. If `label.replenishmentLevel` is not null, render a `<Text>` under the `QTY:` text. Use the same style.
+3. Print `MIN: {label.replenishmentLevel}` plus the same unit suffix as `QTY:`.
+4. In the label route mapping, add `replenishmentLevel: kanban.replenishmentLevel`.
+5. In `KanbanCardItem`, add `replenishmentLevel: number | null;`.
+6. In `resolveKanbanData`, map `replenishmentLevel: kanban.replenishmentLevel ?? null`.
+7. In `renderKanbanCardPDF`, pass `replenishmentLevel: item.replenishmentLevel`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/documents --filter=@carbon/jobs --filter=erp
+# Expected: 0 errors
+```
+
+**Out of scope:** the ZPL path (it throws for kanban cards today).
+
+---
+
+## Task 18: Update the docs, the kanban rule and the AGENTS files
+
+**Depends on:** Tasks 8–17
+**Files:**
+- Modify: `docs/content/docs/reference/kanban.mdx`
+- Modify: `docs/content/src/glossary/terms.ts` — the `"replenishment-system"` definition only if it names kanbans (leave it if it is about items only)
+- Modify: `.claude/rules/kanban-system.md`
+- Modify: `packages/server-functions/AGENTS.md` only if it lists functions by name
+- Modify: `apps/erp/app/modules/inventory/AGENTS.md` — the kanban section, if it has one
+
+**Steps:**
+1. Load the `carbon-docs` skill before you edit `kanban.mdx`.
+2. In `kanban.mdx`, fix the stale text:
+ 1. Line 3 description: name the stock transfer as the third outcome.
+ 2. Line 17: list `Buy`, `Make` and `Transfer`.
+ 3. Line 28 callout: delete the claim that the form offers only Buy and Make.
+ 4. The `StatusFlow` (lines 37-40): add `Transfer`.
+3. Add fields: From storage unit, To storage unit, Replenishment level (`<Term>kanban replenishment level</Term>`).
+4. Add one section, "Replenishment level", in at most 6 sentences. Cover these 5 facts:
+ 1. Projected quantity = on-hand + open inbound transfers.
+ 2. The signal fires strictly below the level.
+ 3. One signal creates one transfer of Quantity.
+ 4. Three paths wake the check: a stock movement, a kanban save, the hourly sweep.
+ 5. The transfer carries the "Kanban replenishment" note and shows Source `Kanban`.
+5. State that the level path needs the Vault secret `inngest_event_url`, as every database-sent event does.
+6. Add the label's `MIN:` line to the Output table row for Label.
+7. Add the troubleshooting errors `"Kanban is missing a from or to storage unit"`, `"Storage unit does not belong to the kanban location"` and `"Only a transfer kanban can have a replenishment level"`.
+8. In `.claude/rules/kanban-system.md`:
+ 1. Add `replenishmentLevel` to the data model and `kanban_transfer_distinct_storage_units_check` to its constraints.
+ 2. Add `stockTransfer.kanbanId`, `get_kanban_projected_quantities`, the two handlers and the sweep.
+ 3. Replace the Transfer scan bullet: the scan calls `kanban-replenish` with `mode: "scan"`.
+ 4. Add a "Level signal" section: the three wake paths, `kanbanLevelCheckFunction`, strict `<`, supply netting.
+ 5. Fix the stale `getKanban(client, kanbanId)` signature to `getKanban(client, kanbanId, companyId)`.
+ 6. Add the new files to the `paths:` frontmatter.
+9. Do the STE-80 review pass on every changed `.ai/` file.
+
+**Verify:**
+```bash
+pnpm --filter docs typecheck
+# Expected: 0 errors
+cd docs && for l in $(grep -oh "](/docs/[^)]*)" content/docs/reference/kanban.mdx | sed 's|](/docs/||;s|)||' | sort -u); do [ -f "content/docs/$l.mdx" ] || [ -f "content/docs/$l/index.mdx" ] || echo "MISSING $l"; done
+# Expected: no MISSING line
+```
+
+**Out of scope:** a changelog entry (not requested); the MES docs.
+
+---
+
+## Task 19: Run the final gates and the browser test
+
+**Depends on:** every other task
+**Files:** none
+
+**Steps:**
+1. Run the scoped gates below.
+2. 🛑 Ask the user before the browser test. Run it with `/test` only on a yes (memory: no browser unless asked).
+3. Browser test, after `/auth`:
+ 1. Create a Transfer kanban: From bin A, To bin B, Quantity 5, Replenishment Level 10. Confirm the list shows the level and Projected (To).
+ 2. Post an inventory adjustment of +12 at B. Confirm no stock transfer appears.
+ 3. Post an adjustment of −3 at B. Within 1 minute, one Released stock transfer appears: Source `Kanban`, a note starting "Kanban replenishment", one line A → B for 5.
+ 4. Open it. Confirm the Kanban badge opens the kanban.
+ 5. Post a second −3 at B. Confirm no second transfer appears.
+ 6. Pick and post the line in full. Confirm no new transfer appears.
+ 7. Scan the kanban's order URL. Confirm a transfer appears with "Signal: scan by".
+ 8. Print the label. Confirm `MIN: 10` under `QTY: 5`.
+4. If step 3.3 shows no transfer, check the Inngest dev server for `kanban-level-check`. If no event arrived, check the Vault secret `inngest_event_url`. Report; do not change code to work around it.
+5. Run `/self-review` on the branch.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --filter=@carbon/database --filter=@carbon/server-functions --filter=@carbon/jobs --filter=@carbon/documents --filter=@carbon/lib
+# Expected: 0 errors
+pnpm run lint
+# Expected: 0 errors
+pnpm --filter @carbon/database test && pnpm --filter @carbon/server-functions test && pnpm --filter @carbon/jobs test && pnpm --filter erp test
+# Expected: all pass
+pnpm --filter @carbon/checks test
+# Expected: pass (spdx-license-header, no-authz-ddl-in-migrations, no-raw-rounding)
+pnpm db:check:backups
+# Expected: existing backups still restore (DB read — ask first)
+```
+
+**Out of scope:** pushing the branch; opening the PR; the demo datasets (their Transfer kanbans stay scan-only).
diff --git a/.ai/playbooks/kanban-replenishment-level.md b/.ai/playbooks/kanban-replenishment-level.md
new file mode 100644
index 0000000000..656a233354
--- /dev/null
+++ b/.ai/playbooks/kanban-replenishment-level.md
@@ -0,0 +1,78 @@
+# Kanban replenishment level (Transfer kanban)
+
+Last tested: 2026-10-13
+Routes: `/x/inventory/kanbans/new?location=<id>`, `/x/inventory/kanbans/<id>`, `/api/kanban/<id>` (scan),
+`/x/inventory/stock-transfers?filter=source:eq:Kanban`, `/x/stock-transfer/<id>`,
+`/x/inventory/quantities/<itemId>/details` (Update Inventory), `/file/kanban/labels/order.pdf?ids=<id>`
+
+## Prerequisites
+- Dev stack up, with the Inngest dev server. `pnpm db:migrate` sets the Vault secret `inngest_event_url`.
+ Check that `carbon-kanban-level-check` is registered:
+ `curl -s localhost:<inngest port>/v0/gql -d '{"query":"{ functions { slug } }"}' -H 'content-type: application/json'`.
+- Carbon Development → Manufacturing Plant (`loc_DNvXGZG8keWBKLrUhgd6sH`). An untracked item with
+ stock in one storage unit and 0 in another. Used: `FST-M6-A286`, From `A1-L1` (151), To `A1-L2` (0).
+ Do not use the `PLN-` items.
+- Projected quantity counts EVERY open transfer into the To unit, the scan's ones too. Re-read it before
+ you predict the next signal:
+ `SELECT * FROM get_kanban_projected_quantities('<companyId>', ARRAY['<kanbanId>']);`
+
+## Steps
+### 1. Form
+- New Kanban → Replenishment System combobox (the one showing "Buy") → option "Transfer".
+ Fields appear in this order: Item, System, Location, From, To, Quantity, Replenishment Level
+ (with a "What is Replenishment Level?" help button). With Buy there is no level field.
+- Pick Transfer BEFORE the item. Then pick the item: the system stays Transfer, and To fills with the
+ item's default bin.
+- From = To → submit → "From and to storage units must be different".
+### 2. Create (save path)
+- To = A1-L2, Quantity 5, Level 3 → requestSubmit "Create Kanban".
+- Within about 10 s: one Released transfer, created by System. Note: "Kanban replenishment — FST-M6-A286,
+ A1-L1 → A1-L2, 5 EA. Signal: level 3 (projected 0)." Line A1-L1 → A1-L2, quantity 5.
+- List row: Replenishment Level 3, Projected (To) 5, no pill. Both columns are hidden by default: turn them on from the column picker first.
+### 3. Stock movement path
+- Item quantities page → Update Inventory → Storage Unit A1-L2, Positive Adjustment, Quantity 8 → Save.
+ Projected 13, so no transfer.
+- Edit the kanban, Level 10 → Update Kanban. 13 is not below 10, so no transfer.
+- Update Inventory → A1-L2, Negative Adjustment, Quantity 4 → Save. Projected 9 is below 10, so one transfer
+ appears about 1 s later. Note "…Signal: level 10 (projected 9)."
+### 4. Scan
+- Open `/api/kanban/<id>` → redirects to a new transfer. The scanner needs inventory create permission. Note "…Signal: scan by <name>.", created by you.
+### 5. Marking
+- Stock Transfers list: the Source column shows Kanban or Manual. `?filter=source:eq:Kanban` and `:Manual` split them.
+- Transfer header meta line: "Created … by System · [Kanban]". The badge opens `/x/inventory/kanbans/<id>`.
+### 6. Label
+- `fetch('/file/kanban/labels/order.pdf?ids=<id>')` from the logged-in page. Decompress the Flate streams
+ (no pdftotext here). The text runs `A1-L1 -> A1-L2`, `QTY: 5`, `MIN: 10`. The unit suffix comes from
+ `purchaseUnitOfMeasureCode`, which a Transfer kanban leaves empty, so neither line shows a unit.
+### 7. Below level pill and clearing
+- Set a level above projected + quantity: one transfer fires, and the list shows "<n> Below level" in red.
+- Clear the level (see Selector Notes) → stored NULL; Level and Projected render blank.
+
+## Selector Notes
+- Comboboxes: click the combobox ref, then pick the option with
+ `[...document.querySelectorAll('[role=option],[cmdk-item]')].find(x=>x.textContent.trim().startsWith('A1-L2')).click()`.
+- The level is a react-aria Number field. Read it from `[role=dialog] input[name=replenishmentLevel]`.
+- **Wait about 8–10 s after opening the edit drawer before you touch it.** A click while it slides in lands
+ on the overlay and closes the drawer. The URL then drops to `/x/inventory/kanbans` with no query.
+- To CHANGE a value that is already set, do not `fill` (it appends: "20" + "30" became 2030).
+ Focus and select from script, then press keys:
+ `el.focus(); el.select()` on the last visible non-named input in the dialog, `press Backspace`
+ (or type), then focus another input to blur.
+- `fill @ref ""` does not clear the field. The hidden input keeps the old value.
+- Submit with `form.requestSubmit(submitButton)`. Button texts: "Create Kanban", "Update Kanban", "Save".
+- `psql -c` with two statements prints only the last result. Run one statement per check.
+
+## Common Failures
+- A level far above the quantity creates one transfer per signal, including the hourly sweep. If you
+ type a wrong level, clear it at once, or the sweep keeps adding transfers.
+
+## Behaviour since 2026-10-13
+- A level signal moves the fewest whole Quantities that reach the level in ONE transfer
+ (level 30, Quantity 10, empty To unit → one transfer for 30). A scan still moves one Quantity.
+- Draft transfers count as supply: Reopen a kanban transfer, run `SELECT util.sweep_kanban_levels();`,
+ and no duplicate appears. Delete it (Delete is enabled only in Draft) and the sweep replaces it.
+- Two kanbans on one item and To unit: one shortfall → one transfer; the other reports at-level.
+- The ids change when the database is rebuilt. Re-read company, location, storage unit and item ids first.
+- The Inngest dev server port changes with the stack. Read it from `docker ps` (container `*-inngest-1`).
+- A decimal Quantity shows "Quantity must be a whole number". The Quantity field clamps 0 to 1 and
+ the level field refuses a minus sign, so neither invalid value can come from the UI.
diff --git a/.ai/research/kanban-internal-replenishment-level.md b/.ai/research/kanban-internal-replenishment-level.md
new file mode 100644
index 0000000000..0fe96bd64c
--- /dev/null
+++ b/.ai/research/kanban-internal-replenishment-level.md
@@ -0,0 +1,174 @@
+# Kanban Internal Replenishment with a Replenishment Level: Best Practices Survey
+
+## Summary
+
+This survey asks how 6 systems replenish a point-of-use bin from a bulk bin inside one site. It covers two triggers: a card scan, and the bin's quantity falling below a level. All 6 systems model the same 5 facts. The facts are the item, the source bin, the destination bin, a threshold, and a fixed replenish quantity. Every system that evaluates the threshold automatically counts open inbound transfers as supply, or it creates duplicates. Every system marks the automatic transfer with a structural origin field, not only a note. Two systems (SAP, Epicor) evaluate on the stock posting itself; three (D365 WMS, Odoo, NetSuite WMS) run a batch. The threshold has 3 common names: reorder point, minimum, and trigger quantity. The replenish quantity has 2: kanban quantity and reorder quantity.
+
+## Competitors Surveyed
+
+- **SAP S/4HANA (PP-KAB)** — the reference kanban model: control cycles, stock-transfer strategies, the quantity signal, and a 7-state kanban lifecycle.
+- **Microsoft Dynamics 365 SCM** — lean withdrawal kanban (card-driven transfer jobs) and warehouse Min/Max replenishment (batch, per location).
+- **Epicor Kinetic** — per-bin minimum on `PartBinInfo` with a cascading supply bin; the closest match to the request.
+- **Odoo** — reordering rules on a sub-location with an Internal Transfers route; the simplest open-source model.
+- **NetSuite WMS** — bin Replen Min/Max on a Preferred bin, fed from bulk bins by replenishment tasks.
+- **Fishbowl** — location-group reorder point and order-up-to level; shows what a system without per-bin levels looks like.
+
+## Key Consensus Patterns
+
+### 1. The rule holds 5 facts: item, source bin, destination bin, threshold, fixed quantity
+
+- **SAP**: the control cycle names the supply area (destination storage location), the supplying storage location, the kanban quantity, and for one-card kanban a trigger quantity.
+- **D365 lean**: the transfer activity holds From location and To location; the rule holds Default quantity per kanban and a Fixed kanban quantity (number of cards).
+- **Epicor**: `PartBinInfo` holds a bin minimum and a supply source bin per (part, site, warehouse, bin).
+- **Odoo**: the reordering rule holds `location_id`, `product_min_qty`, `product_max_qty` and a Pull From route with a source location.
+- **NetSuite WMS**: the bin record holds WMS Replen Min Qty, Max Qty, Replen Qty and Round Qty; the source is a bulk bin.
+- **Rationale**: a replenishment loop is a fixed pair of bins for one item. No system puts the source bin on the item or on the destination bin alone.
+
+### 2. Open inbound transfers count as supply before a new transfer is created
+
+- **Odoo**: `qty_forecast = virtual_available + qty_in_progress`; `virtual_available` includes confirmed incoming moves, so the next run sees the open transfer and creates nothing.
+- **Fishbowl**: `Needed = Order Up To Level − On Hand + On Order − Allocated − Not Available`; the Include Transfer Orders option adds open transfers to On Order.
+- **D365 WMS**: demand replenishment first looks for open replenishment work with unreserved quantity and deducts it.
+- **SAP**: a kanban that is EMPTY or IN PROCESS cannot be set EMPTY again (`PK155`), and a signal lock window ignores a repeated scan.
+- **Epicor**: the trigger is edge-based: a bin "has to be above and then fall below" the minimum.
+- **Rationale**: the destination bin's on-hand rises only when the transfer is picked. Without netting, every stock movement in between creates another transfer.
+
+### 3. The automatic transfer carries a structural origin, not only free text
+
+- **Odoo**: `stock.picking.origin = OP/00012` (the reordering rule's name); a manual internal transfer has an empty origin.
+- **Epicor**: `MtlQueue.TranType` is `RAU-STK` for automatic and `RMN-STK` for manual replenishment.
+- **D365 lean**: the document is a kanban transfer job with a kanban card id, a different object from a manual transfer.
+- **D365 WMS**: the work carries `Work order type = Replenishment` and the template name.
+- **SAP**: the kanban row (`PKPS`) stores the reservation or material document number; the board opens it from the kanban.
+- **Rationale**: a filter, a report and a reverse link all need a column. A note is for the human who opens the document.
+
+### 4. Two trigger styles: on the stock posting, or on a schedule
+
+- **SAP quantity signal**: the withdrawal posting draws down the kanban's actual quantity; at zero the kanban becomes EMPTY and the strategy fires at once.
+- **Epicor**: the posting transaction that drops the bin below its minimum creates the Material Queue record at once.
+- **D365 WMS Min/Max**: a batch job, recommended once a day.
+- **Odoo**: a daily cron, plus an immediate run when a sales order confirmation pushes the forecast below the minimum.
+- **NetSuite WMS**: on-demand "Generate Replenishment" or a scheduled run with a frequency and run window.
+- **Rationale**: a shop-floor kanban expects the card to behave like a scan: the signal fires when the bin empties. A daily batch suits a warehouse pick face, not a lineside bin.
+
+### 5. The threshold is strict "below", and the replenish quantity is fixed per signal
+
+- **NetSuite WMS**: "When an item's on-hand quantity in a bin is less than the quantity set in the WMS Replen Min Qty field, NetSuite WMS generates replenishment tasks."
+- **Epicor**: "reduce the OH qty in a bin below THAT BIN's minimum".
+- **SAP**: event-driven kanban has a fixed kanban quantity; a larger demand is split into several kanbans, each of the fixed quantity.
+- **Odoo**: the exception. It orders max − forecast when forecast ≤ min, so the quantity varies.
+- **Rationale**: a kanban is a container. A fixed quantity keeps the card, the label and the transfer in agreement.
+
+### 6. Source = destination is refused
+
+- **SAP**: the 311 posting refuses it with `M7 104` "Stock to be removed from storage same as stock to be placed into storage".
+- **Odoo**: a parent location and its child cannot both be replenish locations.
+- **Rationale**: a transfer into its own source bin moves nothing and loops forever under an automatic trigger.
+
+## Answers to Research Questions
+
+1. **Which entity holds the rule, and what are its fields?** — One rule per (item, destination bin). It holds a source bin, a threshold and a fixed quantity (Pattern 1). Examples: SAP control cycle, Epicor `PartBinInfo`, Odoo orderpoint, NetSuite bin record.
+2. **What document does the trigger create, and when does stock move?** — A transfer document that a person picks later. SAP strategy `0001` creates a reservation and posts at FULL; strategy `0002` posts the 311 at once. D365 creates a transfer job, Odoo an Internal Transfers picking in state `confirmed`/`assigned`, Epicor a Material Queue row, NetSuite an RPLN open task. Only SAP `0002` moves stock at signal time.
+3. **How does the system avoid a duplicate while a transfer is pending?** — Three ways. Odoo, Fishbowl and D365 WMS net open inbound transfers against the threshold. SAP refuses a second EMPTY signal on the same kanban. Epicor triggers only on the downward edge. See Pattern 2.
+4. **How is the automatic transfer told apart from a manual one?** — By an origin field. Odoo uses `origin`, Epicor `TranType`, D365 the work order type or kanban card id. SAP stores the element number on the kanban row. See Pattern 3.
+5. **Event or schedule, and what latency?** — SAP and Epicor fire on the posting. D365 WMS and Odoo run daily. NetSuite WMS runs on demand or on a schedule. See Pattern 4.
+6. **Which term should Carbon use?** — "Reorder point" is the industry term for a location-level threshold and Carbon already uses it on `itemPlanning`. For a bin-level kanban threshold the systems use "minimum" (Epicor, NetSuite, D365 WMS) or "trigger quantity" (SAP one-card kanban). The user asked for "Replenishment level". See the recommendation.
+7. **Does any system check the source bin's stock before it creates the transfer?** — Not found. SAP, D365 and Odoo create the element and let the pick fail or wait (Odoo state `confirmed` = Waiting). NetSuite reports a failed run only when no bin needs replenishment. Carried into the spec as an open question.
+
+## Competitor-Specific Details
+
+### SAP S/4HANA (PP-KAB)
+
+- Stock-transfer strategies: `0001` and `0003` create a reservation and post the 311 at FULL. `0002` posts the 311 at EMPTY. `0006` creates a WM transfer requirement and posts at TO confirmation. Customizing `OM12`.
+- The quantity signal (`PK22`) needs no customizing. The system draws down IN USE kanbans first, then the oldest FULL one. At zero the kanban becomes EMPTY and the control cycle's strategy fires. Stock-transfer strategies work with it.
+- One-card kanban: a trigger quantity on the control cycle. Replenishment fires when the actual quantity "reaches or falls below" it.
+- Statuses: WAIT, EMPTY, IN PROCESS, IN TRANSIT, FULL, IN USE, ERROR. EMPTY only from FULL, IN USE or WAIT (`PK155`). A signal lock in minutes (`AUSSP`) ignores a repeated scan.
+- `PK31` kanban correction reverses the last signal: it flags the reservation for deletion and reverses the goods receipt document.
+- Partial fill: the user overwrites the actual quantity at FULL.
+
+### Microsoft Dynamics 365 SCM
+
+- Lean: a withdrawal kanban rule's transfer activity holds From location and To location. A fixed-quantity rule creates a new transfer job only when a card is registered Empty, by scan or when the handling unit is received. Alert boundary minimum turns the board red; it creates nothing.
+- Warehouse Min/Max: a replenishment template line holds Minimum quantity, Maximum quantity, Replenishment unit (rounding) and a Select products query with a location profile. Fixed locations let an empty location be replenished. The output is work of type Replenishment with a Pick line and a Put line. It runs as a daily batch.
+
+### Epicor Kinetic
+
+- `PartBinInfo` holds a bin minimum and a supply source bin, with cascading: "if bin A is low, pull from bin B; if B is low, pull from C; if C is low, buy or make".
+- The posting that drops the bin below its minimum creates a `MtlQueue` row with `TranType = RAU-STK`, `FromWhse`/`FromBinNum`, `ToWhse`/`ToBinNum` and `RequestQty`. A handler selects it on the handheld and processing deletes the row.
+- The trigger is edge-based: a bin already below minimum never fires again until it rises above and falls below.
+- The Replenishment Workbench (AMM) is a manual pass; one site runs an hourly custom function instead.
+
+### Odoo
+
+- `stock.warehouse.orderpoint`: `location_id`, `product_min_qty`, `product_max_qty`, `route_id`, `trigger = auto | manual`.
+- `stock.location.replenish_location` marks a sub-location as a replenishment target; a parent and a child cannot both be set.
+- The Pull From route (Operation Type = Internal Transfers, Take From Stock) creates a `stock.picking` with `origin = OP/00012`. States: `draft`, `waiting`, `confirmed`, `assigned`, `done`, `cancel`.
+- `qty_forecast` includes confirmed incoming moves, so the next scheduler run creates no duplicate.
+- The cron runs daily; `auto` rules also fire on sales order confirmation.
+
+### NetSuite WMS
+
+- Bin fields: WMS Replen Min Qty, WMS Replen Max Qty, WMS Replen Qty, WMS Replen Round Qty. Target = the item's Preferred bin; source = a bulk bin.
+- Required = Max − on-hand, rounded down to Round Qty, split into one task per Replen Qty.
+- Triggers: a report, "Generate & Release", or a schedule record with frequency and run window. The task is a WMS Open Task of type RPLN; completion converts it to a closed task.
+- Base NetSuite's Reorder Point and Preferred Stock Level are per location, never per bin.
+
+### Fishbowl
+
+- Reorder Point ("also known as min") and Order Up To Level ("also known as max") are per location group. No per-bin level exists.
+- The Replenish wizard adds parts to one Transfer Order (types Ship, Move, Putaway; statuses Entered, Issued, Fulfilled). It is manual.
+- No "created from" field marks a wizard-created transfer.
+
+## Recommended Approach for Carbon
+
+1. **Keep the rule on the `kanban` row.** Carbon's Transfer kanban already holds the item, the source bin (`fromStorageUnitId`), the destination bin (`storageUnitId`) and the fixed `quantity`. Add one column for the threshold. This follows Epicor's `PartBinInfo` and SAP's control cycle (Pattern 1).
+2. **Name the threshold "Replenishment Level" in the UI, as the user asked.** Store it as `replenishmentLevel`. Do not reuse "reorder point": Carbon uses that term for the location-level `itemPlanning.reorderPoint`, and one word must keep one meaning. Define it as "a strict minimum: the kanban fires when the destination bin's projected quantity is below this level" (Pattern 5; NetSuite "less than", Epicor "below").
+3. **Fire on the stock posting, with a scheduled backstop.** Evaluate the level when an `itemLedger` row lands on the destination bin for a kanban item. SAP's quantity signal and Epicor fire the same way (Pattern 4). Add a low-frequency sweep for the two cases a posting does not cover: a raised level and a deleted transfer.
+4. **Net open inbound transfers.** Projected quantity at the destination bin = on-hand + outstanding quantity of Released and In Progress transfers into that bin for the item. Carbon's stock transfer wizard RPC already computes this sum. Create a transfer only when projected < level (Pattern 2; Odoo, Fishbowl).
+5. **Replenish the fixed kanban `quantity` per signal.** Do not order up to a maximum. A kanban is a container, and the card's label states its quantity (Pattern 5; SAP, D365, NetSuite Replen Qty).
+6. **Mark the transfer with a column and a note.** Add `stockTransfer.kanbanId` as the structural origin (Pattern 3; Odoo `origin`, Epicor `TranType`). Write the requested "Kanban replenishment" note for the person who opens the transfer.
+7. **Refuse source = destination at the database.** The zod refine exists today; add a CHECK so an API write cannot create a self-feeding loop (Pattern 6; SAP `M7 104`).
+8. **Create the transfer even when the source bin is short.** No surveyed system checks the source bin first; the pick reports the shortage. This matches Carbon's scan path today.
+
+## Sources
+
+- https://help.sap.com/saphelp_470/helpdata/en/cb/7f8e3143b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/en/cb/7f8e0a43b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/en/cb/7f8e1743b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/en/2a/f8378defb711d188b80000e8214d78/content.htm
+- https://help.sap.com/saphelp_470/helpdata/EN/cb/7f8ae243b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/EN/cb/7f8ac843b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/EN/cb/7f8ad543b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/en/cb/7f8c9943b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/en/cb/7f8c5843b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_470/helpdata/EN/cb/7f8d0e43b711d189410000e829fbbd/content.htm
+- https://help.sap.com/saphelp_me60/helpdata/en/17/60bd534f22b44ce10000000a174cb4/content.htm
+- https://learning.sap.com/courses/configuring-sap-s-4hana-cloud-public-edition-manufacturing-execution/configuring-replenishment-strategies_a88b2e91-7022-4c11-8424-8874468c9cb4
+- https://leanx.eu/en/sap/table/pkps.html
+- https://www.michaelmanagement.com/sap-error-messages/en/pk/pk155
+- https://michaelmanagement.com/sap-error-messages/en/m7/m7104
+- https://learn.microsoft.com/en-us/dynamicsax-2012/kanban-rules-form
+- https://learn.microsoft.com/en-us/dynamicsax-2012/activity-details-form
+- https://learn.microsoft.com/en-us/training/modules/create-process-fixed-kanbans-dyn365-supply-chain-mgmt/4-process
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/warehousing/replenishment
+- https://learn.microsoft.com/en-us/dynamics365/supply-chain/warehousing/tasks/set-up-min-max-replenishment-process
+- https://www.epiusers.help/t/description-of-the-kanban-process/86758
+- https://www.epiusers.help/t/stocking-kanban/136817
+- https://epiusers.help/t/replenishment-workbench-not-capturing-everything/112040
+- https://www.epiusers.help/t/material-queue-to-locations/126261
+- https://www.odoo.com/documentation/17.0/applications/inventory_and_mrp/inventory/warehouses_storage/replenishment/reordering_rules.html
+- https://www.odoo.com/documentation/17.0/applications/inventory_and_mrp/inventory/warehouses_storage/inventory_management/use_locations.html
+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/stock/models/stock_orderpoint.py
+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/stock/models/stock_location.py
+- https://raw.githubusercontent.com/odoo/odoo/17.0/addons/stock/models/stock_picking.py
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2278346.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1541441806.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1541442254.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_0807023240.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_1541442264.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_156382533850.html
+- https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_N2305626.html
+- https://help.fishbowlinventory.com/advanced/s/article/Transfer-Order
+- https://help.fishbowlinventory.com/advanced/s/article/Part
+- https://help.fishbowlinventory.com/drive/s/article/Drive-Reorder-Report
+- https://www.fishbowlinventory.com/blog/touring-the-transfer-order-module
diff --git a/.ai/runs/2026-10-06-kanban-internal-replenishment-level.md b/.ai/runs/2026-10-06-kanban-internal-replenishment-level.md
new file mode 100644
index 0000000000..cc85f695fa
--- /dev/null
+++ b/.ai/runs/2026-10-06-kanban-internal-replenishment-level.md
@@ -0,0 +1,22 @@
+# Feature run: Kanban internal replenishment with a replenishment level
+
+- Date: 2026-10-06
+- Mode: fully-autonomous (non-interactive session; the ask is research + spec only)
+- Request: On a Kanban circuit, it currently creates a PO or Job requirement (when triggered). We need an additional option on a Kanban circuit to request a replenishment from another Storage Unit. The Kanban circuit should have: 'Internal' option, Storage Unit To, Storage Unit From, Quantity to replenish, Replenishment level (see screen shot below for suggested layout + description). When triggered, a Released Stock transfer should be created. The stock transfer should include a note stating 'Kanban replenishment' or similar, to differentiate from a manually created stock transfer. This action should be triggered in the following ways: Scan QR code (or URL depending on the setting) - existing functionality; Quantity in the 'To' storage Location dropping below the 'Replenishment level'. "can u research on this and make a in depth and detailed spec"
+- Phase plan: research [run — ERP inventory domain, never invent replenishment logic] · spec [run — data model change + cross-module (inventory, jobs)] · plan [skip — the user asked for research and a spec only] · execute [skip — same] · test [skip — same] · self-review [skip — same]
+- Note: the request mentions a screenshot. No image reached this session. The spec records the layout from the text only.
+
+## Decisions
+- Spec gate (every Open Question resolved): resolved autonomously, 13 questions, each by codebase precedent, then research, then recommendation. The most consequential: keep the stored enum value `Transfer` instead of renaming it `Internal` (Q1); one transfer of the fixed quantity per signal (Q3); event-driven on `itemLedger` plus an hourly sweep (Q5). The user reviews all 13 before `/plan`. — 2026-10-06
+- Autonomy: fully-autonomous — the session is non-interactive and the user cannot answer mid-run. Open questions are resolved by codebase precedent, then research, then recommendation, and listed for the user to overturn. — 2026-10-06
+- Scope: stop after the spec. /plan and /execute are deferred to a later run that the user starts. — 2026-10-06
+
+## Phase log
+- research: done — `.ai/research/kanban-internal-replenishment-level.md` (SAP, Dynamics 365, Epicor, Odoo, NetSuite WMS, Fishbowl; 6 consensus patterns, 7 questions answered, 8 recommendations). STE-80 pass done.
+- spec: done — `.ai/specs/2026-10-06-kanban-internal-replenishment-level.md`, status draft. Open Questions 1–13 resolved autonomously and marked for review. STE-80 pass done.
+- plan: done (2026-10-09) — `.ai/plans/2026-10-06-kanban-internal-replenishment-level.md`, 19 tasks. The planning pass found 10 spec facts that the code contradicts; the spec is corrected and its Changelog lists them. The user removed the demo dataset seeding from scope. STE-80 pass done on the plan and the spec.
+- execute: Tasks 1–18 done and verified (2026-10-09), not committed. Task 19 gates green: typecheck of 8 packages, Biome on 25 changed files, tests (database 419, server-functions 462 incl. 8 live-database, jobs 933, documents 57, content 17, checks 278, erp 1992), the SQL test script, `db:check:datasets`, `db:check:backups`, docs typecheck, and a rolled-back probe that proves both triggers queue `carbon/kanban.level-check`.
+- test / self-review: not run — the browser test waits for the user's approval.
+
+## Outcome
+- Implemented, uncommitted. Next step for the user: approve the browser test and say how to commit.
diff --git a/.ai/specs/2026-10-06-kanban-internal-replenishment-level.md b/.ai/specs/2026-10-06-kanban-internal-replenishment-level.md
new file mode 100644
index 0000000000..1cd52f65d5
--- /dev/null
+++ b/.ai/specs/2026-10-06-kanban-internal-replenishment-level.md
@@ -0,0 +1,447 @@
+# Kanban Internal Replenishment with a Replenishment Level
+
+> Status: implemented (PR #1889; browser-tested 2026-10-13)
+> Author: Carbon team (drafted by Claude in an autonomous `/feature` run)
+> Date: 2026-10-06
+> Research: `.ai/research/kanban-internal-replenishment-level.md`
+> Run record: `.ai/runs/2026-10-06-kanban-internal-replenishment-level.md`
+
+## TLDR
+
+A `Transfer` kanban already moves stock from one storage unit to another inside a location. A scan creates a Released stock transfer for the kanban's quantity. This spec adds a second trigger: a **replenishment level** on the kanban. When the projected quantity at the destination storage unit falls below that level, Carbon creates the same Released stock transfer with no scan. Both triggers write the transfer through one new server function, `kanban-replenish`. The transfer records its origin in a new `stockTransfer.kanbanId` column and in a "Kanban replenishment" note. A user can tell it from a manual transfer. The level check runs when an `itemLedger` row lands on the destination bin, when a kanban is saved, and on an hourly backstop sweep. Open inbound transfers count as supply, so one shortfall creates one transfer.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant W as "Stock write (any posting)"
+ participant PG as "Postgres"
+ participant IN as "Inngest kanban-level-check"
+ participant SF as "Server fn kanban-replenish"
+ participant ST as "Stock transfer (Released)"
+ participant OP as "Operator (scan)"
+ W->>PG: INSERT itemLedger at the To bin
+ PG->>PG: queue_kanban_level_checks finds armed kanbans below level
+ PG-->>IN: send_inngest_event carbon/kanban.level-check
+ IN->>SF: invoke, mode "level", kanbanIds
+ SF->>PG: lock kanbans FOR UPDATE, re-read projected quantity
+ SF->>ST: projected < level, insert header + line + note + kanbanId
+ OP->>SF: GET /api/kanban/:id, mode "scan"
+ SF->>ST: always insert header + line + note + kanbanId
+ ST-->>PG: pick writes itemLedger, loop repeats
+```
+
+## Problem Statement
+
+A `Transfer` kanban today fires only when a person scans it. Nothing watches the destination bin. If the card is lost, nobody scans. If backflush consumes the bin with nobody at it, nobody scans. The lineside bin runs dry and the job stops. The user asked for a kanban that also fires when the quantity in the "To" storage unit drops below a level.
+
+Three gaps block that today. Facts are from the code, with file and line.
+
+| Gap | Where | Fact |
+|---|---|---|
+| No threshold | `kanban` table (`packages/database/src/types.ts:27507-27527`) | The row holds `quantity`, `storageUnitId` (To) and `fromStorageUnitId` (From). It has no level column. |
+| No origin on the transfer | `stockTransfer` (`20251007014240_stock-transfers.sql:75-97`) | No `kanbanId`, `source` or reference column. `notes` is Tiptap JSON, default `{}`. The scan writes no note (`api+/kanban.$id.tsx:402-416`). The list shows no source column (`StockTransfersTable.tsx`). |
+| No per-bin watcher | `itemLedger` attachments (`packages/database/src/event-system/attachments.ts:112-114`) | `itemLedger` runs `apply_item_stock_quantities` and `broadcast_table_changes` only. It has no `events: true`. `itemStockQuantities` is per location, not per bin (`20260812002454…sql:68-77`). |
+
+Two more facts shape the design:
+
+- The scan path creates the transfer with the user's RLS client through `insertStockTransfer` (`inventory.service.ts:4248-4350`), an ERP service. An Inngest function cannot import it. A shared write must live in `packages/server-functions` (root `AGENTS.md`, "Never chain Supabase-client writes and call it a transaction").
+- The destination bin's on-hand rises only when a picker posts the transfer line (`post-stock-transfer/index.ts:192-215` writes −qty at From and +qty at To). Between creation and pick, a naive check fires again on every stock movement. The wizard RPC already nets open inbound transfers (`20260923134421…sql:81-93, 194`).
+
+## Background: what exists today
+
+Read `.claude/rules/kanban-system.md` first. In short:
+
+| Surface | Today |
+|---|---|
+| Enum `kanbanReplenishmentSystem` | `Buy`, `Make`, `Transfer` (`20260908143722_kanban-transfer.sql:13`) |
+| `Transfer` fields | `fromStorageUnitId` (From), `storageUnitId` (To), `quantity`, `locationId` |
+| Validator | `kanbanValidator` requires both bins for `Transfer` and refuses From = To (`inventory.models.ts:292-316`) |
+| Scan | `api+/kanban.$id.tsx:351-428`: validates both bins belong to the company and location, reads `itemTrackingType`, calls `insertStockTransfer`, redirects to the transfer |
+| Transfer created | status `Released`, one line, `createdBy` = the scanner, no note, no link to the kanban |
+| Collision rule | none for `Transfer`; every scan makes a new transfer |
+| Label | prints `From -> To` and `QTY: {quantity}` (`KanbanLabelPDF.tsx:194-201`) |
+| Demo data | one `Transfer` kanban per dataset (`data/*/inventory.ts`) |
+
+## Proposed Solution
+
+### Vocabulary
+
+One term per concept, used in code, UI and docs:
+
+| Term | Meaning | Not called |
+|---|---|---|
+| **Transfer kanban** | a kanban with `replenishmentSystem = 'Transfer'` | internal kanban (see Open Question 1) |
+| **From storage unit** | `kanban.fromStorageUnitId`, the bulk bin | source bin |
+| **To storage unit** | `kanban.storageUnitId`, the point-of-use bin | destination bin, lineside |
+| **Quantity** | `kanban.quantity`, the unit one signal moves: a scan moves one Quantity, a level signal moves whole multiples of it | reorder quantity, lot size |
+| **Replenishment level** | `kanban.replenishmentLevel`, the strict minimum for the To storage unit | reorder point (that term is `itemPlanning.reorderPoint`, per location) |
+| **Projected quantity** | on-hand at the To storage unit + outstanding quantity of open transfers into it | available, forecast |
+| **Signal** | one event that creates one transfer: a scan or a level breach | trigger |
+| **Kanban replenishment** | a stock transfer with `kanbanId` set | auto transfer |
+
+### The rule
+
+A Transfer kanban gains one optional field, **Replenishment level**:
+
+- `NULL` means scan-only. The kanban behaves exactly as today.
+- A number ≥ 0 arms the level signal. When projected quantity < level, Carbon creates one transfer for the fewest whole Quantities that reach the level.
+
+The level applies to `Transfer` kanbans only in this version. The column is generic so a later spec can arm `Buy` and `Make` kanbans the same way (see Out of scope).
+
+### Signal A — scan (existing, re-routed)
+
+The scan keeps its behaviour: every scan creates a transfer, with no level test. Two changes:
+
+1. The route calls the new server function `kanban-replenish` with `mode: "scan"` instead of `insertStockTransfer`.
+2. The transfer carries `kanbanId` and the note.
+
+### Signal B — level
+
+**Projected quantity** at the To storage unit for the kanban's item:
+
+```
+projected = SUM(item_ledger_on_hand_contribution(il.quantity, il.trackedEntityStatus))
+ WHERE il.itemId = k.itemId AND il.storageUnitId = k.storageUnitId
+ AND il.locationId = k.locationId AND il.companyId = k.companyId
+ + SUM(stl.outstandingQuantity)
+ FROM stockTransferLine stl JOIN stockTransfer st
+ WHERE st.status IN ('Released','In Progress')
+ AND stl.itemId = k.itemId AND stl.toStorageUnitId = k.storageUnitId
+ AND st.companyId = k.companyId
+```
+
+Rules:
+
+- The on-hand term uses `item_ledger_on_hand_contribution`, the same function `itemStockQuantities` uses (`20260812002454…sql:36-49`). Rejected tracked stock does not count. The wizard RPC counts it; this spec does not copy that.
+- The inbound term counts every open transfer into the bin, manual or kanban. A manual transfer that is already on its way fills the bin too.
+- The condition is strict: `projected < replenishmentLevel`. A bin at exactly the level does not fire. This follows NetSuite "less than" and Epicor "below" (research, Pattern 5), and the user's words "dropping below".
+- One level signal creates one transfer for `n × quantity`, with `n = ceil((level − projected) / quantity)` (`levelReplenishmentQuantity`). Level 20, Quantity 5, nothing projected: one transfer for 20. A scan still moves one Quantity (see Open Question 3).
+- Two kanbans can watch the same item at the same To storage unit. Within one call, the server function adds each new transfer to the projected quantity of the next kanban on that item and storage unit, so they never fill the same gap twice.
+- The level check never evaluates a kanban whose From storage unit or To storage unit is `NULL`, or whose `replenishmentLevel` is `NULL`.
+
+**When the check runs.** Three paths wake it. Each sends one Inngest event, `carbon/kanban.level-check`, with `{ companyId, kanbanIds }`.
+
+| Path | Mechanism | Covers |
+|---|---|---|
+| Stock movement | New statement handler `queue_kanban_level_checks` on `itemLedger` (declared in `attachments.ts`, body in `event-system/handlers/`). It joins the touched rows (`batched_new`, or `batched_old` on DELETE) to `kanban` on (`companyId`, `itemId`, `storageUnitId` = To) where `replenishmentSystem = 'Transfer'` and `replenishmentLevel IS NOT NULL`. It keeps only the kanbans below their level and sends one event per company with their ids. | every posting that changes the To bin: backflush, issue, picking, counts, adjustments, the kanban's own transfer pick |
+| Kanban saved | New `after` row interceptor `sync_kanban_level_check` on `kanban` (INSERT, or UPDATE when `replenishmentLevel`, `quantity`, `itemId`, `locationId`, `storageUnitId`, `fromStorageUnitId` or `replenishmentSystem` changed). It sends the event for that one kanban when it is below its level. | arming a kanban, raising its level |
+| Backstop sweep | `util.kanban_level_breaches()` + `util.sweep_kanban_levels()`, pg_cron `kanban-level-sweeper` at `7 * * * *` (hourly). The breaches function returns one row per company: the armed kanbans below their level. The sweep sends one event per row, with `companyId` and `kanbanIds`. | a deleted Released transfer, a transfer completed short, a lost event, a missing Vault secret at write time |
+
+Both trigger bodies return at once when `app.sync_in_progress` is set. A seed, a restore and a test fixture write in bulk under that flag; the hourly sweep covers them.
+
+The handler and the sweep follow the pattern of `20261004183512_scheduled-jobs-from-database.sql:156-193`. `util.send_inngest_event` never raises and no-ops when `inngest_event_url` is unset (`20261002170250…sql:60-86`), so an OLTP write never fails on this path.
+
+**The Inngest function** `kanbanLevelCheckFunction` (`packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts`):
+
+- Trigger: event `carbon/kanban.level-check`, data `{ companyId, kanbanIds }`. Every sender sets both.
+- Flow control: `concurrency: { limit: 1, scope: "env", key: '"kanban-level:" + event.data.companyId' }`. No `debounce` (lesson: the local Inngest dev server cannot run it, `.ai/lessons.md:541`).
+- Body: one `step.run("replenish")` that calls `serverFns.system({ db: getJobDatabaseClient(), companyId, userId: "system" }).invokeOrThrow("kanban-replenish", { mode: "level", kanbanIds })`. A thrown error makes Inngest retry.
+- It logs each created transfer and each invalid kanban. An invalid kanban is an outcome in the result list, not a throw.
+
+**The server function** `kanban-replenish` (`packages/server-functions/src/kanban-replenish/index.ts`) is the only writer of a kanban replenishment. Input:
+
+```ts
+{ mode: "scan", kanbanId: string }
+| { mode: "level", kanbanIds: string[] } // at least one id; every sender names the kanbans
+```
+
+`permissions` depends on the mode: `scan` needs `create: "inventory"`, `level` is `"system"`. The scan route calls the function as the scanner (`serverFns.as`), so it keeps the check that the `stockTransfer` RLS rule made before. Only the job calls level mode, and it has no user.
+
+Behaviour, in one Kysely transaction per call:
+
+1. Lock the kanbans: `SELECT … FROM kanban WHERE companyId = $1 AND id IN (…) ORDER BY id FOR UPDATE`. The lock serialises two concurrent signals for one kanban. The order stops two calls from deadlocking.
+2. If `replenishmentSystem <> 'Transfer'`, a storage unit is missing, or (level mode) the level is NULL, the outcome is `{ kanbanId, outcome: "invalid", reason }`.
+3. Read the storage units in one query. Check both belong to `companyId` and `kanban.locationId` (the CWE-639 guard from `api+/kanban.$id.tsx:362-383`, moved here).
+4. If `mode = "level"`: read projected quantity on `trx` in one query with `get_kanban_projected_quantities(company_id, kanban_ids)`. If `projected >= replenishmentLevel`, the outcome is `{ outcome: "at-level", projectedQuantity }` and nothing is written for that kanban.
+5. Read the items in one query. Build the lines with the pure helper `expandSerialTrackedLines`. The helper is new in `@carbon/database/stock-transfer`, extracted from `insertStockTransfer`. Both writers then split a serial line of qty > 1 into qty-1 lines the same way.
+6. Take one `stockTransferId` per new transfer from `getNextSequence(trx, "stockTransfer", companyId)`.
+7. Insert every header in one statement. Set `status = 'Released'`, `locationId`, `companyId`, `kanbanId`, `notes` (the Tiptap document below), and `createdBy = userId`: the scanner in scan mode, `"system"` in level mode.
+8. Insert every line in one statement: `itemId`, `fromStorageUnitId`, `toStorageUnitId`, `quantity`, `requiresSerialTracking`, `requiresBatchTracking`.
+9. Return `{ results }`, one outcome per locked kanban. A created outcome carries `{ outcome: "created", stockTransferId, id }`.
+
+The note is a Tiptap document with one paragraph:
+
+> Kanban replenishment — {item readableIdWithRevision}, {From storage unit name} → {To storage unit name}, {quantity} {uom}. Signal: scan by {user name} | level {replenishmentLevel} (projected {projected}).
+
+The text is English only. `notes` is free text the user may edit; the durable origin is `kanbanId`. The Tiptap shape is `{ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text }] }] }`, the shape `StockTransferNotes.tsx` reads.
+
+**Idempotency.** The transaction's `FOR UPDATE` lock plus the inbound term of projected quantity make a second signal a no-op while the first transfer is open. After the pick posts, the To bin's on-hand rises by the picked amount and the outstanding term falls by the same amount. Projected quantity does not change, so no new transfer fires. Only a further draw-down fires one.
+
+**Storage rules.** Storage rules on the `stockTransfer` surface run in two places today: the manual wizard at creation (`x+/stock-transfer+/new.tsx:42-71`) and the status route at Released and Completed (`$id.status.tsx:53-93`). The scan path runs none (`kanban-system.md:70`). The line pick routes (`$id.line.quantity.tsx`, `$id.scan.$lineId.tsx`) run none. The level path runs none, like the scan path. See Open Question 7.
+
+**Source bin shortage.** The function creates the transfer even when the From storage unit holds less than `quantity`. The picker sees the shortage at pick time, as today. See Open Question 8.
+
+### The created stock transfer
+
+| Field | Scan | Level |
+|---|---|---|
+| `status` | `Released` | `Released` |
+| `createdBy` | the scanner | `"system"` (`EmployeeAvatar.tsx:27` renders it) |
+| `kanbanId` | the kanban | the kanban |
+| `notes` | "Kanban replenishment … Signal: scan by …" | "Kanban replenishment … Signal: level …" |
+| line | item, From → To, `quantity`, tracking flags | same |
+| `assignee` | null | null |
+
+A transfer with `kanbanId` set is a **kanban replenishment**. The stock transfer header shows a "Kanban" badge that links to the kanban. The stock transfers list gains a **Source** column, `Manual` or `Kanban`, filterable.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| Where the rule lives | one new column on `kanban`, no new table | The row already holds item, From, To, quantity and location (research, Pattern 1). A new table would split one rule across two rows. |
+| Name of the threshold | `replenishmentLevel`, UI "Replenishment Level" | The user's term. "Reorder point" is taken by `itemPlanning.reorderPoint` (per location). One word, one meaning. |
+| Comparison | strict `projected < level` | NetSuite "less than", Epicor "below", the user's "dropping below". |
+| Quantity per signal | the fixed `quantity`, one transfer | A kanban is a container; the label prints the quantity (research, Pattern 5). Order-up-to-max is Odoo's model, not kanban's. |
+| Supply netting | every transfer into the To bin that is not Completed (Draft, Released, In Progress) counts as supply | Odoo, Fishbowl and D365 WMS all net pending supply (Pattern 2). The wizard RPC is the Carbon precedent. |
+| On-hand function | `item_ledger_on_hand_contribution` | Same definition as `itemStockQuantities`. Rejected tracked stock must not satisfy a lineside level. |
+| Primary trigger | `itemLedger` statement handler → Inngest event | Every on-hand change writes `itemLedger`. SAP's quantity signal and Epicor fire on the posting (Pattern 4). A daily batch is too slow for a lineside bin. |
+| Backstop | hourly pg_cron sweep with a has-work check | Covers deleted transfers and lost events. Same pattern as the notification digest sweeper. |
+| Writer | server function `kanban-replenish`, Kysely transaction | Apps and jobs share the write (root `AGENTS.md`). An Inngest function cannot import `~/modules`. |
+| Serialisation | `FOR UPDATE` on the kanban row + Inngest concurrency 1 per company | Two events for one kanban within a second must create one transfer. The DB lock is the real guard; Inngest flow control is a cost saver. |
+| Origin marking | `stockTransfer.kanbanId` column + Tiptap note | Column for filters and the back-link (Pattern 3); note because the user asked for it and it is what the picker reads. |
+| From = To | DB CHECK on `kanban` | The zod refine exists; an API write bypasses it. A self-feeding kanban loops forever under the level signal (Pattern 6). |
+| Scope of the level | `Transfer` only, column generic | The user asked for internal replenishment. Buy and Make need a collision model this spec does not design. |
+| Multi-tenancy (heuristic 1) | no new table; new columns on tables with composite PK `("id","companyId")` | `kanban` and `stockTransfer` already comply. |
+| Service shape (heuristic 2) | server function returns `{ data, error }`; ERP services unchanged | `defineServerFn` contract. |
+| RLS (heuristic 3) | no new table; `kanbanId` inherits `stockTransfer` policies | The level path writes through Kysely as `system`, which bypasses RLS by design, like `dispatch.ts` and `mrp.ts`. |
+| Permissions (heuristic 4) | the scan route stays `role: "employee"` and calls the function with `serverFns.as`; scan mode needs `create: "inventory"`; level mode is `"system"`; kanban CRUD stays `inventory_*` | Before this change the scan inserted through the RLS client, and `stockTransfer` RLS asks for `inventory_create`. A `system` call would have dropped that check for every employee. |
+| Form (heuristic 5) | `ValidatedForm` + `kanbanValidator` + existing route actions | One new `Number` field. |
+| Module layout (heuristic 6) | models in `inventory.models.ts`, services in `inventory.service.ts`, UI in `ui/Kanbans/` | No new files in the module except the badge component. |
+| Backward compatibility (heuristic 7) | additive columns, nullable; the enum is unchanged | Existing kanbans and transfers are untouched. The API gains optional fields. |
+| Realtime | none added | `stockTransfer` already has `broadcast_table_changes`; the list refreshes when the system creates a transfer. |
+| Notifications | none in this version | Not requested. The Source column and realtime list make the transfer visible. See Out of scope. |
+
+## Data Model Changes
+
+One migration, `pnpm db:migrate:new kanban-replenishment-level`.
+
+```sql
+-- 1. The level on the kanban
+ALTER TABLE "kanban"
+ ADD COLUMN "replenishmentLevel" NUMERIC
+ CONSTRAINT "kanban_replenishmentLevel_check" CHECK ("replenishmentLevel" IS NULL OR "replenishmentLevel" >= 0);
+
+COMMENT ON COLUMN "kanban"."replenishmentLevel" IS
+ 'Transfer kanbans only. When projected quantity at the To storage unit is below this level, Carbon creates a Released stock transfer for "quantity". NULL = scan-only.';
+
+-- A Transfer kanban must not feed itself. The zod refine exists; this stops API writes.
+ALTER TABLE "kanban"
+ ADD CONSTRAINT "kanban_transfer_distinct_storage_units_check"
+ CHECK ("replenishmentSystem" <> 'Transfer'
+ OR "fromStorageUnitId" IS NULL OR "storageUnitId" IS NULL
+ OR "fromStorageUnitId" <> "storageUnitId");
+
+-- Fast lookup from a ledger row to its armed kanbans
+CREATE INDEX "kanban_level_lookup_idx"
+ ON "kanban" ("companyId", "itemId", "storageUnitId")
+ WHERE "replenishmentSystem" = 'Transfer' AND "replenishmentLevel" IS NOT NULL;
+
+-- 2. The origin on the stock transfer
+ALTER TABLE "stockTransfer"
+ ADD COLUMN "kanbanId" TEXT,
+ ADD CONSTRAINT "stockTransfer_kanbanId_fkey"
+ FOREIGN KEY ("kanbanId", "companyId") REFERENCES "kanban" ("id", "companyId")
+ ON DELETE SET NULL ON UPDATE CASCADE;
+
+CREATE INDEX "stockTransfer_kanbanId_idx" ON "stockTransfer" ("kanbanId") WHERE "kanbanId" IS NOT NULL;
+
+-- 3. The kanbans view expands k.* when it is created, so recreate it
+-- (same body as 20260908143722_kanban-transfer.sql) to expose replenishmentLevel.
+
+-- 4. Projected quantity for the armed kanbans of one company (NULL ids = all).
+-- Used by the server function, both trigger bodies, the sweep and the kanbans list.
+CREATE OR REPLACE FUNCTION get_kanban_projected_quantities(company_id TEXT, kanban_ids TEXT[] DEFAULT NULL)
+RETURNS TABLE ("kanbanId" TEXT, "replenishmentLevel" NUMERIC, "projectedQuantity" NUMERIC)
+LANGUAGE sql STABLE SECURITY INVOKER SET search_path = public, pg_temp AS $$
+ -- per armed kanban: on-hand at the To bin (item_ledger_on_hand_contribution)
+ -- + SUM(outstandingQuantity) of transfer lines into it whose transfer is not Completed
+$$;
+
+-- 5. Backstop sweep (same shape as util.sweep_workflow_run_retention)
+CREATE OR REPLACE FUNCTION util.kanban_level_breaches()
+RETURNS TABLE ("companyId" TEXT, "kanbanIds" TEXT[]) ...; -- armed kanbans below level, per company
+
+CREATE OR REPLACE FUNCTION util.sweep_kanban_levels() RETURNS void ...;
+ -- one util.send_inngest_event('carbon/kanban.level-check', {companyId, kanbanIds}) per breach row
+
+-- cron: unschedule 'kanban-level-sweeper' if it exists, then schedule it at '7 * * * *'.
+```
+
+The two trigger bodies live in the event-system source tree, not in the migration (`attachments.ts` doc comment, lines 28-35):
+
+- `packages/database/src/event-system/handlers/queue_kanban_level_checks.sql` — statement handler on `itemLedger`, beside `apply_item_stock_quantities`. It reads `batched_new` (`batched_old` on DELETE), joins `kanban` through `kanban_level_lookup_idx`, keeps the kanbans below their level, and calls `util.send_inngest_event('carbon/kanban.level-check', jsonb_build_object('companyId', c, 'kanbanIds', ids))` once per company. Declare it in `attachments.ts`: `itemLedger: { statement: ["apply_item_stock_quantities", "broadcast_table_changes", "queue_kanban_level_checks"] }`. It must list all three; the helper replaces the whole list.
+- `packages/database/src/event-system/handlers/sync_kanban_level_check.sql` — `after` row interceptor on `kanban`. Declare `kanban: { after: ["sync_kanban_level_check"] }`.
+- Run `authz migration` to ship the attachment change, as the file's comment instructs.
+
+The `kanbans` view selects `k.*`, but Postgres expands `k.*` when it creates the view. The migration recreates the view so `replenishmentLevel` appears. The `stockTransfer` list and detail read the table directly (`inventory.service.ts:576, 631`), so `kanbanId` needs no view change.
+
+The exact SQL is in the plan, `.ai/plans/2026-10-06-kanban-internal-replenishment-level.md`, Tasks 1 and 2. Verify it with a psql script beside `supabase/tests/scheduled-job-sweeps.test.sql`.
+
+After the migration: `pnpm run generate:types`.
+
+### Index note
+
+`itemLedger_companyId_locationId_itemId_idx` serves the on-hand sub-query; the planner filters `storageUnitId` on the matched rows. Run `EXPLAIN ANALYZE` on `get_kanban_projected_quantities` against a seeded company before deciding whether to add `("companyId","itemId","storageUnitId")`.
+
+## API / Service Changes
+
+### `packages/server-functions`
+
+- New `src/kanban-replenish/index.ts`, registered in `src/invoke.ts` and exported per `packages/server-functions/AGENTS.md`. Input and behaviour as in "Signal B". It reads on `trx` while the transaction is open (AGENTS.md rule, line 86).
+- The job calls level mode with `serverFns.system` and `userId: "system"`. The scan route calls scan mode with `serverFns.as` and the scanner's client and `userId`.
+
+### `@carbon/database`
+
+- New pure helpers in `packages/database/src/stock-transfer.ts` (export `@carbon/database/stock-transfer`), with a unit test: `expandSerialTrackedLines(lines)`, `isBelowReplenishmentLevel`, `kanbanReplenishmentNote`. `insertStockTransfer` (`inventory.service.ts:4285-4303`) switches to it so the wizard and the kanban writer split serial lines the same way.
+
+### `@carbon/jobs`
+
+- New `kanbanLevelCheckFunction` in `functions/tasks/`, registered in `packages/jobs/src/inngest/index.ts`.
+- New event type `carbon/kanban.level-check` in `packages/lib/src/events.ts`: `{ companyId: string; kanbanIds: string[] }`. Only the database sends it.
+
+### ERP routes and services
+
+| File | Change |
+|---|---|
+| `api+/kanban.$id.tsx` | The `Transfer` branch calls `serverFns.as({ client, db: getDatabaseClient(), companyId, userId }).invoke("kanban-replenish", { mode: "scan", kanbanId })` and redirects to `path.to.stockTransfer(result.id)`. The bin-ownership guard moves into the server function. The branch keeps its error strings. |
+| `inventory.models.ts` | `kanbanValidator` gains `replenishmentLevel: zfd.numeric(z.number().min(0).optional())`. A new refine: `replenishmentLevel` is only allowed when `replenishmentSystem === "Transfer"` (error on `replenishmentLevel`). |
+| `inventory.service.ts` | `upsertKanban` writes `replenishmentLevel` as `null` when the field is blank or the system is not Transfer (zod omits a blank optional field, so a plain spread would keep the old value). `getStockTransfers` and `getStockTransfer` already select `*`, so `kanbanId` arrives; `getStockTransfers` accepts a derived `source` filter (`kanbanId IS NULL` / `IS NOT NULL`), as `getWorkflows` does for its status. |
+| `x+/inventory+/kanbans.tsx` | The loader also calls a new `getKanbanProjectedQuantities(client, companyId, kanbanIds)` for the armed kanbans on the page, through `get_kanban_projected_quantities`. One query per page load. |
+| `x+/stock-transfer+/$id.tsx` | No change. The header badge reads `kanbanId` from the existing loader data. |
+
+### Docs
+
+- `docs/content/docs/reference/kanban.mdx` is stale: lines 17 and 28 say the form offers only `Buy` and `Make`. Update it for `Transfer`, the Replenishment Level field, the level signal, and the "Kanban replenishment" note. Add the new error strings to its error list.
+- Add a glossary entry `kanban-replenishment-level` in `docs/content/src/glossary/terms.ts` and use it as the field's `termId`.
+
+## UI Changes
+
+### `KanbanForm.tsx`
+
+Field order for a `Transfer` kanban, top to bottom:
+
+1. Item
+2. Replenishment System (`Transfer`)
+3. Location
+4. From Storage Unit
+5. To Storage Unit
+6. Quantity — helper text: "The quantity moved from the From storage unit on each signal."
+7. Replenishment Level — new `Number`, `minValue={0}`, optional, `termId="kanban-replenishment-level"`. Helper text: "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+
+Rules:
+
+- The level field renders only when `replenishmentSystem === "Transfer"`. Changing the system away from `Transfer` clears it.
+- Buy and Make keep their current order (Item, Quantity, System, Buy fields, Location, Storage Unit, Make fields).
+- Adjacent fix: `onItemChange` (`KanbanForm.tsx:105-107`) resets the system to `Make` or `Buy` from the item. If the user has already chosen `Transfer`, keep it. Today a user who picks Transfer first and the item second loses the choice.
+
+### `KanbansTable.tsx`
+
+- New column **Replenishment Level** after **Reorder Qty.**; blank for scan-only.
+- New column **Projected (To)** for armed Transfer kanbans, from the loader's `getKanbanProjectedQuantities`. Render the number, and a `Below level` status pill when `projected < replenishmentLevel`. Blank for other rows.
+- The storage-unit column keeps `from → to`.
+
+### Stock transfers
+
+- `StockTransferHeader.tsx`: when `kanbanId` is set, show a `Kanban` badge that links to `path.to.kanban(kanbanId)`.
+- `StockTransfersTable.tsx`: new **Source** column with values `Manual` and `Kanban`, with a filter. Sort and filter run on `kanbanId IS NULL`.
+- `StockTransferNotes.tsx`: no change; the note renders as any other note.
+
+### Label
+
+`KanbanLabelPDF.tsx` prints `MIN: {replenishmentLevel}` under `QTY:` when the level is set. Thread the field through both label paths: `labels.$action[.]pdf.tsx` and `print-job/resolvers.ts` + `renderers.tsx` (`kanban-system.md`, Gotchas).
+
+### i18n
+
+Wrap every new UI string in Lingui `t` or `<Trans>`. Run `/translate` at commit time. The note text and the server function's error strings are not translated, like the scan route's strings today.
+
+## Demo datasets
+
+No change in this version. Each dataset's Transfer kanban stays scan-only, with no replenishment level. The new column is nullable, so the datasets apply as they do today.
+
+## Testing
+
+| Layer | Test |
+|---|---|
+| Unit | `expandSerialTrackedLines` (new): qty 3 serial → 3 lines of 1; batch and untracked unchanged. |
+| Unit | `kanbanValidator`: level refused on Buy/Make, allowed on Transfer, negative refused. |
+| Server function | `kanban-replenish` with the local database fixture (`local-database-test-fixture.ts`): (a) level mode at level → no write; (b) below level → one transfer with `kanbanId`, `createdBy = system`, note present; (c) a second call while the first is Released → no write; (d) after the line is picked in full → no write; (e) a further draw-down → one more transfer; (f) scan mode at level → still creates; (g) From = To rejected by the CHECK. |
+| SQL | psql script beside `scheduled-job-sweeps.test.sql`: projected quantity sums on-hand and outstanding inbound; `util.kanban_level_breaches()` names the kanban below level only, and not while a Released transfer covers the gap; both CHECKs refuse bad rows. |
+| Statement handler | No repo test captures a `net.http_post` call, so the browser test proves the send path end to end. The SQL test covers the selection the handler shares with the sweep. |
+| Browser (`/test`) | Create a Transfer kanban with level 10 and quantity 5. Issue stock from the To bin until on-hand is 8. Open Stock Transfers: one Released transfer, Source `Kanban`, note present, badge links back. Pick it. No second transfer appears. |
+
+## Acceptance Criteria
+
+- [ ] A user creates a Transfer kanban with From bin A, To bin B, quantity 5, level 10. The kanbans list shows the level and the projected quantity for bin B.
+- [ ] On-hand at bin B is 12. A job backflush consumes 3. Within 1 minute one stock transfer exists: status `Released`, one line A → B for 5, `createdBy` `system`, Source `Kanban`, notes start with "Kanban replenishment".
+- [ ] While that transfer is Released or In Progress, further consumption at bin B creates no second transfer. A second transfer appears only when projected quantity (on-hand + outstanding) is below 10 again.
+- [ ] The picker posts the line in full. On-hand at B rises by 5 and no new transfer appears.
+- [ ] Scanning the kanban's order QR code creates a transfer every time, regardless of level. Its `createdBy` is the scanner and its note ends "Signal: scan by …".
+- [ ] A kanban with no level never creates a transfer without a scan.
+- [ ] A Buy or Make kanban cannot save a level; the form shows the field only for Transfer.
+- [ ] Saving a Transfer kanban with From = To fails in the form and at the database.
+- [ ] The stock transfers list filters by Source `Kanban` and the header badge opens the kanban.
+- [ ] The label prints `MIN: 10` under `QTY: 5` for that kanban.
+- [ ] A deleted Released kanban transfer is replaced within 1 hour by the sweep when the bin is still below level.
+- [ ] `pnpm db:check:datasets` passes with no dataset change.
+- [ ] The docs page for kanban describes Transfer, the level and the note.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| The level signal fires on every `itemLedger` statement for an armed bin | Low | The statement handler joins through a partial index and sends one event per company. The server function writes nothing at level. Lesson `.ai/lessons.md:2733` on write cost applies: an event with no work is cheap but not free. |
+| Two signals in one second create two transfers | Med | `FOR UPDATE` on the kanban row inside the transaction; the second reads the first's outstanding quantity. Inngest concurrency 1 per company reduces contention. Test (c). |
+| `inngest_event_url` is unset in a self-hosted install | Med | `send_inngest_event` no-ops. The hourly sweep also depends on it. Document the secret in `event-system.md` and the kanban docs page; the kanbans list still shows `Below level` so the gap is visible. |
+| A wrong, very high level moves a large quantity in one signal | Low | The level is a deliberate setting; the transfer note states the level and the projected quantity. |
+| Picking lists also move stock into a lineside To bin | Low | Picking credits unclaimed on-hand at the bin (`supersession-system.md`, Lineside credit). A kanban transfer into a lineside bin becomes unclaimed stock a job's pick credits. No double count; a job may pick less. |
+| Automatic transfer bypasses storage rules | Low | Same as the scan today. No rule runs at pick time either, so a kanban transfer never meets a storage rule. Open Question 7. |
+| The From bin is empty | Low | The transfer is created; the picker sees the shortage. The sweep does not retry a transfer that exists. Open Question 8. |
+| `notes` is editable and the note can be deleted | Low | `kanbanId` is the durable origin; the note is for the reader. |
+| Local dev cannot run Inngest `debounce` | Low | The function uses none. |
+
+## Out of scope (this version)
+
+- Arming `Buy` and `Make` kanbans with a level. Needs a collision model: Make has `jobId`, Buy has none.
+- A notification when a kanban transfer is created. Add `NotificationEvent.StockTransferCreated` later if asked.
+- A workflow moment `inventory.stockTransferCreated` or a `stockTransfer.create` action.
+- Order-up-to-maximum quantities.
+- Edge-based triggering (fire only when crossing the level), Epicor style. Level-based with supply netting is self-correcting and simpler.
+- MES surfaces. The transfer appears in the existing stock transfer screens.
+- A replenishment level on the demo datasets' Transfer kanbans.
+
+## Open Questions
+
+> Every question below was resolved autonomously because the session had no human available. Each resolution is marked **Autonomous** and lists the alternative. The user can overturn any of them before `/plan`.
+
+- [x] **1. The user asked for an "Internal" option. Keep the stored value `Transfer`, or rename it?** Why it matters: a rename touches the enum, the route branch, the table filter, the label, the docs and four datasets. — **Autonomous:** keep `Transfer` as the stored value and the UI label. The document it creates is a Stock Transfer, and one concept keeps one name. Alternative A: `ALTER TYPE "kanbanReplenishmentSystem" RENAME VALUE 'Transfer' TO 'Internal'` plus the code and data changes above. Alternative B: a UI-only label "Internal" over the stored `Transfer`. B is rejected: `Enumerable` renders the stored value, and it gives one concept two names.
+- [x] **2. Strictly below the level, or at or below?** — **Autonomous:** strictly below (`<`). The user wrote "dropping below"; NetSuite and Epicor use "less than" / "below". Alternative: `<=`, SAP's one-card "reaches or falls below".
+- [x] **3. One transfer for `quantity`, or enough transfers to reach the level?** — **Changed 2026-10-13 after browser testing:** one transfer of `n × quantity`, `n = ceil((level − projected) / quantity)`. The first resolution (one `quantity` per signal) topped a level of 20 with Quantity 5 up by one transfer per signal, about one an hour from the sweep, which read as a fault. A scan still moves one `quantity`.
+- [x] **4. Column, note, or both for the origin?** — **Autonomous:** both. `stockTransfer.kanbanId` for filters and the back-link; the Tiptap note because the user asked for it. Alternative: note only (rejected: not filterable, editable).
+- [x] **5. Event-driven, scheduled, or both?** — **Autonomous:** event-driven on `itemLedger` plus an hourly sweep. SAP and Epicor fire on the posting; a lineside bin cannot wait for a daily batch. Alternative: sweep only every 5 minutes (simpler, but 5-minute latency and a has-work scan every 5 minutes).
+- [x] **6. Count open inbound transfers as supply?** — **Autonomous, widened 2026-10-13:** yes, every transfer that is not Completed. Draft was added after browser testing: a kanban transfer reopened to Draft for an edit dropped out of supply, and the next sweep created a duplicate. Odoo, Fishbowl and D365 WMS do; the wizard RPC is the precedent. Alternative: edge-based trigger (Epicor). Rejected: a lost or deleted transfer would never re-fire.
+- [x] **7. Evaluate storage rules on the level path?** — **Autonomous:** no, same as the scan path. No human can acknowledge a warning. Alternative: evaluate, and on an `error` rule skip the transfer and log. Can be added inside the server function.
+- [x] **8. Create the transfer when the From bin is short?** — **Autonomous:** yes. No surveyed system checks the source first; the pick reports the shortage. Alternative: skip and show `Source bin short` on the kanbans list.
+- [x] **9. Field order on the form: From before To, or To before From as the user's list reads?** Why it matters: the screenshot the user mentioned did not reach this session. — **Autonomous:** From then To, matching the table's `from → to` and the label. Alternative: To then From.
+- [x] **10. Include the `onItemChange` fix that drops `Transfer`?** — **Autonomous:** yes, one guard in a file this spec already edits. Alternative: leave it (a user who picks the item first is unaffected).
+- [x] **11. `createdBy` for the level path?** — **Autonomous:** `"system"`, like `mrp.ts` and `dispatch.ts`. The note names the signal. Alternative: the kanban's `createdBy` (misleading in the audit trail).
+- [x] **12. Numeric type of the level?** — **Autonomous:** `NUMERIC`, because on-hand is `NUMERIC`. `kanban.quantity` is `INTEGER`; this spec leaves it. Alternative: `INTEGER` to match `quantity`.
+- [x] **13. Which on-hand definition at the bin?** — **Autonomous:** `item_ledger_on_hand_contribution`, the `itemStockQuantities` definition that excludes Rejected tracked stock. Alternative: the wizard RPC's raw `SUM(quantity)`.
+
+## Changelog
+
+- 2026-10-13: Browser-testing fixes. A level signal moves `n × quantity` to reach the level in one transfer. Draft transfers count as supply (`20261012232517_kanban-replenishment-level.sql`; never deployed, so the change went into that migration). Two kanbans on one item and To storage unit share supply within a call. A decimal Quantity shows "Quantity must be a whole number". Switching a kanban away from Transfer clears its From storage unit.
+- 2026-10-13: Self-review fixes. Scan mode needs `create: "inventory"` and runs as the scanner (`serverFns.as`); a `system` call had dropped the check that `stockTransfer` RLS made. `kanbanIds` is required in level mode. The new kanbans list columns are hidden by default. Only one QR code popover opens at a time.
+- 2026-10-09: Implemented (Tasks 1–18). Deviations: the migrations are now `20261012232517` / `20261012232520` (renamed twice to sort after the newest `main` migration); the stock transfer header shows the Kanban badge in its meta line, because the header is now `DocumentPageHeader`; the docs page also gained a "never fires" troubleshooting entry and a screenshot slot.
+- 2026-10-09: Demo dataset seeding removed from scope on the user's request. The datasets' Transfer kanbans stay scan-only.
+- 2026-10-09: Planned (`.ai/plans/2026-10-06-kanban-internal-replenishment-level.md`). Corrections from the code:
+ - The migration recreates the `kanbans` view.
+ - One set-returning `get_kanban_projected_quantities` replaces the scalar function.
+ - The sweep sends one event per company.
+ - The Inngest function lives in `functions/tasks/`.
+ - Both trigger bodies live in `event-system/handlers/`. They skip under `app.sync_in_progress` and send only kanbans below level.
+ - The DB tests are psql scripts, not pgTAP.
+ - `upsertKanban` writes a blank level as `null`.
+ - The server function locks all its kanbans in one transaction.
+- 2026-10-09: Corrected the storage-rules facts: no rule runs at pick time on a stock transfer line, so a kanban transfer meets no storage rule at all. Risk row updated.
+- 2026-10-06: Created. Research in `.ai/research/kanban-internal-replenishment-level.md`. Open Questions 1–13 resolved autonomously (no human in the session); the user reviews them before `/plan`.
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index b257739af9..43f0f808b0 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -36,6 +36,7 @@ The wake path (`20260721184852_event-queue-wake.sql`, rewired by `20261002170250
- `util.sweep_event_queue()` — pg_cron job `event-queue-sweeper` re-wakes every minute while *visible* messages (`vt <= clock_timestamp()`) sit in `pgmq.q_event_system`.
- **Why `util`, not `public`:** a public function is auto-exposed as a PostgREST RPC, and a non-superuser reference to a function that transitively calls `net.http_post` segfaults the backend (pg_net 0.20 / PG15) — a remote-DoS surface a `REVOKE` can't close because the crash precedes the privilege check. anon/authenticated have no `USAGE` on `util`, so the API can't reach it. The trigger and pg_cron call it as the owner (superuser), where the pg_net path is safe.
- Two scheduled jobs are woken the same way, only when there is work (`20261004183512_scheduled-jobs-from-database.sql`): `util.sweep_notification_digest()` (pg_cron `notification-digest-sweeper`, every 15 min → `carbon/notification-digest.process`) and `util.sweep_workflow_run_retention()` (`workflow-run-retention-sweeper`, 04:00 UTC → `carbon/workflow-run-retention.process`). Each asks a `util.*_has_work()` function that repeats its Inngest function's thresholds. The notification purge needs no Inngest at all: pg_cron `notification-purge` runs `util.purge_notifications()` at 03:00 UTC.
+- The kanban level check is woken the same way (`20261012232517_kanban-replenishment-level.sql`): `util.sweep_kanban_levels()` (pg_cron `kanban-level-sweeper`, `7 * * * *`) sends one `carbon/kanban.level-check` per company that `util.kanban_level_breaches()` names. Between sweeps, the `queue_kanban_level_checks` statement handler on `itemLedger` and the `sync_kanban_level_check` interceptor on `kanban` send the same event, only for Transfer kanbans below their level (see `kanban-system.md`).
- The same helper sends `carbon/notify` (job-completed) from `sync_job_complete_or_canceled` and `carbon/embedding-queue.process` from `util.sweep_embedding_queue()` (see EMBEDDING below).
## Database (functions are files, not migrations)
diff --git a/.claude/rules/kanban-system.md b/.claude/rules/kanban-system.md
index 68081f3801..4c443811c6 100644
--- a/.claude/rules/kanban-system.md
+++ b/.claude/rules/kanban-system.md
@@ -4,6 +4,10 @@ paths:
- "apps/erp/app/modules/inventory/ui/Kanbans/*.tsx"
- "packages/documents/src/pdf/KanbanLabelPDF.tsx"
- "packages/database/supabase/migrations/*kanban*.sql"
+ - "packages/server-functions/src/kanban-replenish/**"
+ - "packages/database/src/stock-transfer.ts"
+ - "packages/database/src/event-system/handlers/*kanban*.sql"
+ - "packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts"
---
# Kanban System
@@ -14,7 +18,7 @@ stock transfer (`Transfer`). Lives in the inventory module.
## Data model
-Table `kanban` (initial migration `20250909012102_kanban.sql`; current state spans 7 migrations).
+Table `kanban` (initial migration `20250909012102_kanban.sql`; newest `20261012232517_kanban-replenishment-level.sql`, plus the generated `20261012232520_kanban-level-check-triggers.sql` for its interceptor).
**Composite PK `("id", "companyId")`.** Key columns:
- `id` TEXT default `id('kb')`, `itemId` FK→item (CASCADE), `companyId` FK→company
@@ -26,6 +30,13 @@ Table `kanban` (initial migration `20250909012102_kanban.sql`; current state spa
For a `Transfer` kanban this is the **destination** (to) bin.
- `fromStorageUnitId` FK→storageUnit (nullable) — the **source** bin for a `Transfer` kanban
(`20260908143722_kanban-transfer.sql`)
+- `replenishmentLevel` NUMERIC (nullable, `>= 0`) — arms a `Transfer` kanban's level signal
+ (`20261012232517_kanban-replenishment-level.sql`). NULL = scan-only. `upsertKanban` writes NULL
+ when the form field is blank or the system is not Transfer (zod omits a blank optional field,
+ so a plain spread would keep the old value on update). It also writes `fromStorageUnitId` NULL
+ for a non-Transfer kanban, so a switch to Buy or Make drops the stale source bin.
+- CHECK `kanban_transfer_distinct_storage_units_check` — a Transfer kanban's From and To bins
+ differ (the zod refine alone let an API write create a self-feeding kanban).
- `supplierId` FK→supplier, `purchaseUnitOfMeasureCode` FK→unitOfMeasure, `conversionFactor` NUMERIC default 1 (Buy fields)
- `autoRelease` BOOL, `autoStartJob` BOOL, `completedBarcodeOverride` TEXT, `jobId` FK→job ON DELETE SET NULL (Make fields; `jobId`/auto-start added in `20251001001426_kanban-jobs.sql`)
- audit: `createdAt/By`, `updatedAt/By`
@@ -46,7 +57,7 @@ RLS: SELECT = any employee role; INSERT/UPDATE/DELETE = `inventory_create`/`inve
## Code surfaces
- Validator `kanbanValidator`: `apps/erp/app/modules/inventory/inventory.models.ts`. Fields match columns above; enum is `kanbanReplenishmentSystemTypes` (`Buy`/`Make`/`Transfer`, distinct from the item-level `replenishmentSystemTypes`). `.refine`s require: `supplierId` when `Buy`; `fromStorageUnitId` + `storageUnitId` (and that they differ) when `Transfer`.
-- Services: `apps/erp/app/modules/inventory/inventory.service.ts` — `getKanbans(client, locationId, companyId, args)`, `getKanban(client, kanbanId)`, `upsertKanban`, `deleteKanban`. Reads go through the `kanbans` view; writes hit `kanban`.
+- Services: `apps/erp/app/modules/inventory/inventory.service.ts` — `getKanbans(client, locationId, companyId, args)`, `getKanban(client, kanbanId, companyId)`, `getKanbanProjectedQuantities(client, companyId, kanbanIds)` (RPC `get_kanban_projected_quantities`, used by the list's Projected (To) column), `upsertKanban`, `deleteKanban`. Reads go through the `kanbans` view; writes hit `kanban`. The view expands `k.*` at creation, so a new `kanban` column needs the view recreated.
- `kanbanOutputTypes` + validator: `apps/erp/app/modules/settings/settings.models.ts`. Set via `x+/settings+/inventory.tsx`.
- UI: `apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx` and `KanbansTable.tsx`.
Form shows Buy fields (supplier/UoM/conversion), Make fields (autoRelease, autoStartJob — gated on autoRelease, completedBarcodeOverride), or Transfer fields (From Storage Unit + the reused storage-unit field relabeled "To Storage Unit") conditionally. Dropdown offers `Buy`/`Make`/`Transfer`.
@@ -67,17 +78,46 @@ API routes in `apps/erp/app/routes/api+/`: `kanban.$id.tsx`, `kanban.collision.$
`kanban.$id.tsx` (the "order"/create scan) branches on `replenishmentSystem`:
- **Make** — if a job is already linked (`jobReadableId`) it redirects to the collision route (no duplicate job); otherwise creates a job from the item, links it (`updateKanbanJob`), then `autoRelease` runs MRP + schedules and `autoStartJob` redirects into MES to start the first operation.
- **Buy** — reuses an existing draft/planned PO for the supplier (or creates one), adds a PO line with the kanban qty (applying `conversionFactor`/`purchaseUnitOfMeasureCode`/storage unit), redirects to the PO.
-- **Transfer** — creates a new stock transfer (`insertStockTransfer`, status `Released`) with one line: `itemId`, `fromStorageUnitId` → `storageUnitId` (to), `quantity` (the "original amount"), and serial/batch flags derived from `item.itemTrackingType`. Redirects to the stock transfer, where the qty can be **partially picked** (`stockTransferLine.pickedQuantity`) at pick time. Each scan makes a new transfer (no collision concept). Storage rules are NOT evaluated on scan (a QR scan can't show the acknowledge dialog the interactive wizard uses).
+- **Transfer** — calls the `kanban-replenish` server function with `mode: "scan"`, which writes a Released stock transfer with one line: `itemId`, `fromStorageUnitId` → `storageUnitId` (to), `quantity`, and serial/batch flags from `item.itemTrackingType` (a serial line of qty > 1 splits into qty-1 lines, `expandSerialTrackedLines`). The transfer carries `stockTransfer.kanbanId` and a Tiptap note "Kanban replenishment — … Signal: scan by <user>." Redirects to the stock transfer, where the qty can be **partially picked** at pick time. Each scan makes a new transfer, with no level test. Storage rules are NOT evaluated (a QR scan can't show the acknowledge dialog the interactive wizard uses). The route calls it with `serverFns.as` (the scanner's client): scan mode needs `create: "inventory"`, the same check the `stockTransfer` RLS rule made when the route inserted directly. Never switch this call to `serverFns.system` — that lets any employee create transfers. The server function re-checks that both bins belong to the company and the kanban's location (CWE-639).
- **Buy and Make** — not a kanban option (the enum has no such value).
`start`/`complete` resolve the linked job's active operation and redirect to the MES operation start/complete endpoints; `link` navigates to the job/operation.
+## Level signal (Transfer kanbans with `replenishmentLevel`)
+
+Spec: `.ai/specs/2026-10-06-kanban-internal-replenishment-level.md`.
+
+- **Projected quantity** = on-hand at the To bin (`item_ledger_on_hand_contribution`, so Rejected
+ tracked stock does not count) + `outstandingQuantity` of every stock transfer line into it whose
+ transfer is not Completed (Draft counts: a reopened kanban transfer is still supply), manual or kanban. One function computes it: `get_kanban_projected_quantities(company_id, kanban_ids)`.
+- Fires **strictly below** the level (`isBelowReplenishmentLevel`, `@carbon/database/stock-transfer`).
+ One level signal = one transfer of `n × quantity`, `n = ceil((level − projected) / quantity)`
+ (`levelReplenishmentQuantity`), so the level is reached in one signal. A scan moves one `quantity`.
+ Kanbans sharing an item and To bin share supply within a call (`addedInbound` in the server function).
+- The open transfer counts as supply, so a second signal for the same shortfall writes nothing, and
+ the pick moves stock from "inbound" to "on-hand" without changing the projected quantity.
+- Three wake paths, all sending `carbon/kanban.level-check` `{ companyId, kanbanIds }` and only for
+ kanbans already below level:
+ - `queue_kanban_level_checks` — statement handler on `itemLedger` (any posting at the To bin).
+ - `sync_kanban_level_check` — `after` interceptor on `kanban` (arming or editing a level).
+ - `util.sweep_kanban_levels()` — pg_cron `kanban-level-sweeper` at `7 * * * *`, over
+ `util.kanban_level_breaches()`: covers a deleted transfer, a transfer completed short, a lost event.
+ Both trigger bodies return early under `app.sync_in_progress` (seeds, restores, test fixtures).
+ All three need the Vault secret `inngest_event_url`.
+- `kanbanLevelCheckFunction` (`functions/tasks/kanban-level-check.ts`, concurrency 1 per company, no
+ `debounce`) calls `kanban-replenish` with `mode: "level"` (`"system"` permission; `kanbanIds` required). The server function locks the kanbans
+ `FOR UPDATE` in id order and re-reads the projected quantity inside its transaction, so a stale or
+ duplicate event is a no-op. `createdBy` is `"system"` on this path.
+- A kanban replenishment is a stock transfer with `kanbanId` set: the stock transfers list has a
+ derived **Source** column (Kanban / Manual, filtered on `kanbanId IS [NOT] NULL` in
+ `getStockTransfers`) and the header shows a Kanban badge linking to the kanban.
+
## Labels & QR
- QR PNG route: `apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx`, 36px modules, **color-coded by action**: order=black `#000000`, start=emerald `#059669`, complete=blue `#2563eb`. (The old doc claiming "no color differentiation" was stale.)
- Label PDF route: `apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx` — takes `?ids=` (comma-separated), fetches kanbans from the `kanbans` view, converts thumbnails to base64, renders `KanbanLabelPDF`.
-- `KanbanLabelPDF`: `packages/documents/src/pdf/KanbanLabelPDF.tsx` (exported via `@carbon/documents/pdf`). Letter page, **2×3 grid = 6 labels/page**; each shows the action-colored QR, item thumbnail, name, readable id, storage-unit/location, `QTY: {quantity} {uom}`, and supplier name. QR color matches the PNG route.
-- `KanbansTable` renders Create/Start/Complete affordances per `kanbanOutput`: `label`→PDF links, `qrcode`→hover-card iframes, `url`→copyable API links. Start/Complete show for Make only. Bulk "Print Labels" opens the PDF for selected ids (`action: "order"`).
+- `KanbanLabelPDF`: `packages/documents/src/pdf/KanbanLabelPDF.tsx` (exported via `@carbon/documents/pdf`). Letter page, **2×3 grid = 6 labels/page**; each shows the action-colored QR, item thumbnail, name, readable id, storage-unit/location, `QTY: {quantity} {uom}` (plus `MIN: {replenishmentLevel}` when a level is set — no unit, because `uom` here is the purchase unit and the level is in stock units), and supplier name. QR color matches the PNG route.
+- `KanbansTable` renders Create/Start/Complete affordances per `kanbanOutput`: `label`→PDF links, `qrcode`→hover-card iframes (one open at a time: `KanbanQrCodeHoverCard` reads a table-level `OpenQrCodeContext`), `url`→copyable API links. Start/Complete show for Make only. Bulk "Print Labels" opens the PDF for selected ids (`action: "order"`).
## Gotchas
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index d75baecea3..7385679461 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -9,10 +9,10 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
- **Item Ledger** — append-only log of every inventory movement (`itemLedger` table). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions.
- **Receipt** — inbound inventory from POs, transfers, customer RMAs (source "Sales Return Order"), or rental units coming back (source "Rental Agreement"). Lines link to `purchaseOrderLine`, jobs, or `salesReturnOrderLine`. Posting creates ledger entries and tracked entities; RMA receipts re-enter at the original outbound cost (shipment consumption rows), current cost for blind returns, or zero when the return reason flags `inventoryValueZero`, and reactivate the SAME tracked entity On Hold (ReturnEntityForm re-tags the Consumed entity instead of minting a new serial). A rental receipt holds no `receiptLine`: each unit is a `receiptFixedAssetLine` with `rentalAgreementLineId`, and posting returns the unit on its agreement and moves its `fixedAsset.locationId` to the receipt's location, with no `itemLedger` row or journal for a `Rental` line (see sales AGENTS → Rentals → Deliver and return). A rental receipt cannot be voided.
- **Shipment** — outbound inventory to customers, or return flows: source "Purchase Return Order" ships supplier returns (Cr Inventory / Dr GRNI at carried cost), source "Sales Return Order" ships rejected RMA claims back to the customer (On Hold entities allowed in lines.tracking for that source only), source "Rental Agreement" delivers rental units: each unit is a `shipmentFixedAssetLine` with `rentalAgreementLineId`, posting puts it On Rent and writes no `itemLedger`, `costLedger` or journal row, and its PDF prints as a "Delivery Ticket".
-- **Stock Transfer** — moves inventory between storage units within the same location.
+- **Stock Transfer** — moves inventory between storage units within the same location. A transfer with `kanbanId` set is a kanban replenishment (written by the `kanban-replenish` server function); the list shows it as Source "Kanban".
- **Warehouse Transfer** — moves inventory between locations (inter-location).
- **Picking List** — generated pick instructions with FEFO/FIFO ordering and tracked entity allocation.
-- **Kanban** — pull-based replenishment signal between storage units.
+- **Kanban** — pull-based replenishment signal (Buy, Make, or Transfer between storage units). A Transfer kanban with `replenishmentLevel` also fires automatically when the projected quantity at its To storage unit drops below the level. See `.claude/rules/kanban-system.md`.
- **Inventory Count** — physical/cycle count. Posted is terminal (there is no count-level "Rectify" — fixing a posted movement happens per-movement via `correctStockMovement`). Created with an optional scope (`storageUnitIds` + `itemType`) recorded in the header's `scope` JSONB (written at create; not yet read back). `generateInventoryCountLines` snapshots on-hand into `inventoryCountLine` rows, **excluding Rejected AND Consumed tracked lots**. The count **detail** table filters lines by item type / storage unit / storage type / tags / material attributes via the `inventoryCountLines` **view** (line → item → subtype tables → storageUnit, flattened) — the same generic column-filter set the quantities screen uses. There is no material-attribute scope at create time.
## Safety
@@ -52,9 +52,9 @@ pnpm exec turbo run typecheck --filter=erp # the app's package name is "erp",
| `receiptFixedAssetLine` | One fixed asset per row on a receipt: `purchaseOrderLineId` (a PO receipt) XOR `rentalAgreementLineId` (a rental receipt; CHECK `receiptFixedAssetLine_source_check`), `received`, `serialNumber`. The rental return fields: `meter`, `notes`, `takeOutOfService` + `outOfServiceReason` (CHECK: a tick needs a reason; the UI saves both as one `outOfService` field), `residualDestination` (`Fleet` / `Inventory`, a `Sale` line only). Edited through `receipt+/fixed-asset-lines.update.tsx` (`receiptFixedAssetLineUpdateValidator`), which refuses a line on a non-Draft receipt |
| `shipment` / `shipmentLine` | Outbound documents to customers |
| `shipmentFixedAssetLine` | One fixed asset per row on a shipment: `salesOrderLineId` (a sales order shipment) XOR `rentalAgreementLineId` (a rental shipment; CHECK `shipmentFixedAssetLine_source_check`), `shipped`, `serialNumber`, and `meter` (a rental unit's meter out). Edited through `shipment+/fixed-asset-lines.update.tsx` (`shipmentFixedAssetLineUpdateValidator`), which refuses a line on a non-Draft shipment. A reader that means a sales order line filters `salesOrderLineId IS NOT NULL` |
-| `stockTransfer` / `stockTransferLine` | Intra-location moves between storage units |
+| `stockTransfer` / `stockTransferLine` | Intra-location moves between storage units; `stockTransfer.kanbanId` marks a kanban replenishment |
| `warehouseTransfer` / `warehouseTransferLine` | Inter-location moves |
-| `kanban` | Pull-based replenishment signals |
+| `kanban` | Pull-based replenishment signals; `replenishmentLevel` arms a Transfer kanban |
| `batchProperty` | Custom property definitions for batch-tracked items |
| `pickingList` / `pickingListLine` | Pick instructions with tracked entity allocation |
| `pickMethod` | Default storage unit and pick strategy per item at a location |
diff --git a/apps/erp/app/modules/inventory/inventory.models.test.ts b/apps/erp/app/modules/inventory/inventory.models.test.ts
index 0fa0c93ea1..e3dedd6c49 100644
--- a/apps/erp/app/modules/inventory/inventory.models.test.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.test.ts
@@ -4,6 +4,7 @@
import { describe, expect, it } from "vitest";
import {
+ kanbanValidator,
receiptFixedAssetLineUpdateValidator,
resolveStockTransferPickForward,
shipmentFixedAssetLineUpdateValidator,
@@ -176,3 +177,62 @@ describe("receiptFixedAssetLineUpdateValidator", () => {
expect(r.success).toBe(false);
});
});
+
+describe("kanbanValidator replenishmentLevel", () => {
+ const transfer = {
+ itemId: "item-1",
+ replenishmentSystem: "Transfer",
+ quantity: "5",
+ locationId: "loc-1",
+ fromStorageUnitId: "su-a",
+ storageUnitId: "su-b"
+ };
+
+ const errorPaths = (r: ReturnType<typeof kanbanValidator.safeParse>) =>
+ r.success ? [] : r.error.issues.map((issue) => issue.path.join("."));
+
+ it("accepts a level on a Transfer kanban", () => {
+ const r = kanbanValidator.safeParse({
+ ...transfer,
+ replenishmentLevel: "10"
+ });
+ expect(r.success).toBe(true);
+ if (r.success) expect(r.data.replenishmentLevel).toBe(10);
+ });
+
+ it("accepts a Transfer kanban with no level (scan-only)", () => {
+ const r = kanbanValidator.safeParse(transfer);
+ expect(r.success).toBe(true);
+ if (r.success) expect(r.data.replenishmentLevel).toBeUndefined();
+ });
+
+ it("refuses a level on a Buy kanban", () => {
+ const r = kanbanValidator.safeParse({
+ itemId: "item-1",
+ replenishmentSystem: "Buy",
+ quantity: "5",
+ locationId: "loc-1",
+ supplierId: "sup-1",
+ replenishmentLevel: "10"
+ });
+ expect(errorPaths(r)).toContain("replenishmentLevel");
+ });
+
+ it("refuses a decimal quantity with a readable message", () => {
+ const r = kanbanValidator.safeParse({ ...transfer, quantity: "2.5" });
+ expect(r.success).toBe(false);
+ if (!r.success) {
+ expect(r.error.issues.map((issue) => issue.message)).toContain(
+ "Quantity must be a whole number"
+ );
+ }
+ });
+
+ it("refuses a negative level", () => {
+ const r = kanbanValidator.safeParse({
+ ...transfer,
+ replenishmentLevel: "-1"
+ });
+ expect(errorPaths(r)).toContain("replenishmentLevel");
+ });
+});
diff --git a/apps/erp/app/modules/inventory/inventory.models.ts b/apps/erp/app/modules/inventory/inventory.models.ts
index f4edb3ad38..bd9248ed61 100644
--- a/apps/erp/app/modules/inventory/inventory.models.ts
+++ b/apps/erp/app/modules/inventory/inventory.models.ts
@@ -281,14 +281,23 @@ export const kanbanValidator = z
autoStartJob: zfd.checkbox(),
completedBarcodeOverride: zfd.text(z.string().optional()),
quantity: zfd.numeric(
- z.number().int().min(1, { message: "Quantity must be at least 1" })
+ z
+ .number()
+ .int({ message: "Quantity must be a whole number" })
+ .min(1, { message: "Quantity must be at least 1" })
),
locationId: z.string().min(1, { message: "Location is required" }),
storageUnitId: zfd.text(z.string().optional()),
fromStorageUnitId: zfd.text(z.string().optional()),
supplierId: zfd.text(z.string().optional()),
purchaseUnitOfMeasureCode: zfd.text(z.string().optional()),
- conversionFactor: zfd.numeric(z.number().min(0).default(1))
+ conversionFactor: zfd.numeric(z.number().min(0).default(1)),
+ replenishmentLevel: zfd.numeric(
+ z
+ .number()
+ .min(0, { message: "Replenishment level must be 0 or more" })
+ .optional()
+ )
})
.refine(
(data) => (data.replenishmentSystem === "Buy" ? !!data.supplierId : true),
@@ -324,6 +333,16 @@ export const kanbanValidator = z
message: "From and to storage units must be different",
path: ["storageUnitId"]
}
+ )
+ // Only a Transfer kanban has a To storage unit to watch.
+ .refine(
+ (data) =>
+ data.replenishmentSystem === "Transfer" ||
+ data.replenishmentLevel === undefined,
+ {
+ message: "Only a transfer kanban can have a replenishment level",
+ path: ["replenishmentLevel"]
+ }
);
export const receiptValidator = z.object({
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index 56bdf1dc26..8c53975589 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -9,6 +9,7 @@ import {
type LinesideClaim,
linesideCredit
} from "@carbon/database/picked-consumption";
+import { expandSerialTrackedLines } from "@carbon/database/stock-transfer";
import { consumableInWholeAssemblies } from "@carbon/database/supersession-pick";
import { storage } from "@carbon/files";
import { getLogger } from "@carbon/logger";
@@ -20,7 +21,7 @@ import { nanoid } from "nanoid";
import type { z } from "zod";
import { getNextSequence } from "~/modules/settings/settings.service";
import type { StorageItem } from "~/types";
-import type { GenericQueryFilters } from "~/utils/query";
+import type { Filter, GenericQueryFilters } from "~/utils/query";
import {
LIST_COUNT,
setGenericQueryFilters,
@@ -577,6 +578,20 @@ export async function getKanban(
.single();
}
+/** @mcp read */
+export async function getKanbanProjectedQuantities(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ kanbanIds: string[]
+) {
+ // Projected quantity at each armed Transfer kanban's To storage unit:
+ // on-hand plus the outstanding quantity of open transfers into it.
+ return client.rpc("get_kanban_projected_quantities", {
+ company_id: companyId,
+ kanban_ids: kanbanIds
+ });
+}
+
/** @mcp read */
export async function getStockTransfer(
client: SupabaseClient<Database>,
@@ -652,7 +667,23 @@ export async function getStockTransfers(
query = query.eq("locationId", args.locationId);
}
- query = setGenericQueryFilters(query, args, [
+ // "source" is derived: Kanban means the transfer has a kanbanId, Manual
+ // means it has none. There is no source column, so translate it into a
+ // kanbanId null test and keep it out of the generic column filters.
+ const sourceFilters: Filter[] = [];
+ const columnFilters: Filter[] = [];
+ for (const filter of args.filters ?? []) {
+ (filter.column === "source" ? sourceFilters : columnFilters).push(filter);
+ }
+ for (const filter of sourceFilters) {
+ if (filter.value === "Kanban") {
+ query = query.not("kanbanId", "is", null);
+ } else if (filter.value === "Manual") {
+ query = query.is("kanbanId", null);
+ }
+ }
+
+ query = setGenericQueryFilters(query, { ...args, filters: columnFilters }, [
{ column: "stockTransferId", ascending: false }
]);
return query;
@@ -2490,22 +2521,43 @@ export async function upsertKanban(
})
| (Omit<z.infer<typeof kanbanValidator>, "id"> & {
id: string;
+ companyId: string;
updatedBy: string;
customFields?: Json;
})
) {
// kanban has no customFields column.
const { customFields: _customFields, ...row } = kanban;
+ // zod omits a blank optional field, so a plain spread would keep the old
+ // level on update. Write null when the field is blank or the kanban is not
+ // a Transfer kanban.
+ // The same goes for the From storage unit, which only a Transfer kanban uses:
+ // switching a kanban to Buy or Make must not keep a stale source bin.
+ const isTransfer = row.replenishmentSystem === "Transfer";
+ const replenishmentLevel = isTransfer
+ ? (row.replenishmentLevel ?? null)
+ : null;
+ const fromStorageUnitId = isTransfer ? (row.fromStorageUnitId ?? null) : null;
if ("createdBy" in row) {
- return client.from("kanban").insert(row).select("id").single();
+ return client
+ .from("kanban")
+ .insert({ ...row, replenishmentLevel, fromStorageUnitId })
+ .select("id")
+ .single();
}
+ // Scoped by company, not left to RLS: the update names its row by id, and a
+ // user can belong to several companies.
+ const { companyId, ...update } = row;
return client
.from("kanban")
.update({
- ...sanitize(row),
+ ...sanitize(update),
+ replenishmentLevel,
+ fromStorageUnitId,
updatedAt: datetime.timestamp()
})
.eq("id", row.id)
+ .eq("companyId", companyId)
.select("id")
.single();
}
@@ -4514,6 +4566,19 @@ export async function insertStockTransfer(
}> {
const { locationId, lines, companyId, createdBy, customFields } = input;
+ // Before the sequence, so a refused line does not use up a transfer number.
+ let linesWithExpandedSerialTracking: typeof lines;
+ try {
+ linesWithExpandedSerialTracking = expandSerialTrackedLines(lines);
+ } catch (err) {
+ return {
+ data: null,
+ error: {
+ message: getErrorMessage(err, "Failed to prepare stock transfer lines")
+ }
+ };
+ }
+
let stockTransferId = input.stockTransferId;
if (!stockTransferId) {
const sequence = await client.rpc("get_next_sequence", {
@@ -4529,26 +4594,6 @@ export async function insertStockTransfer(
stockTransferId = sequence.data;
}
- const linesWithExpandedSerialTracking = lines.reduce<typeof lines>(
- (acc, line) => {
- if (line.quantity && !Number.isInteger(line.quantity)) {
- return acc;
- }
- if (line.requiresSerialTracking && line.quantity && line.quantity > 1) {
- acc.push(
- ...Array.from({ length: line.quantity }, () => ({
- ...line,
- quantity: 1
- }))
- );
- } else {
- acc.push(line);
- }
- return acc;
- },
- []
- );
-
const createTransfer = await client
.from("stockTransfer")
.insert({
diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx
index 5cc6a338f1..88a64a6bc2 100644
--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx
+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbanForm.tsx
@@ -102,8 +102,14 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {
}
// The item-level enum can be "Buy and Make", which a kanban cannot be —
// map anything other than "Make" (incl. "Buy and Make"/null) to "Buy".
- setSelectedReplenishmentSystem(
- item.data?.replenishmentSystem === "Make" ? "Make" : "Buy"
+ // A user who already chose Transfer keeps it: the item's own
+ // replenishment says nothing about moving stock between storage units.
+ setSelectedReplenishmentSystem((current) =>
+ current === "Transfer"
+ ? current
+ : item.data?.replenishmentSystem === "Make"
+ ? "Make"
+ : "Buy"
);
if (storageUnit.data?.defaultStorageUnitId) {
setStorageUnitId(storageUnit.data.defaultStorageUnitId);
@@ -224,12 +230,14 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {
isReadOnly={isEditing}
/>
- <Number
- name="quantity"
- label={t`Quantity`}
- minValue={1}
- helperText={t`The quantity of the item to be reordered on scan-based replenishment.`}
- />
+ {!isTransfer && (
+ <Number
+ name="quantity"
+ label={t`Quantity`}
+ minValue={1}
+ helperText={t`The quantity of the item to be reordered on scan-based replenishment.`}
+ />
+ )}
<SelectControlled
value={selectedReplenishmentSystem}
@@ -314,6 +322,24 @@ const KanbanForm = ({ initialValues, onClose }: KanbanFormProps) => {
onChange={(value) => setStorageUnitId(value?.id ?? null)}
/>
+ {isTransfer && (
+ <>
+ <Number
+ name="quantity"
+ label={t`Quantity`}
+ minValue={1}
+ helperText={t`The quantity moved from the From storage unit on each signal.`}
+ />
+ <Number
+ name="replenishmentLevel"
+ label={t`Replenishment Level`}
+ termId="kanban-replenishment-level"
+ minValue={0}
+ helperText={t`When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only.`}
+ />
+ </>
+ )}
+
{selectedReplenishmentSystem === "Make" && (
<>
<Boolean
diff --git a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
index 54d4347753..7d794d0e58 100644
--- a/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Kanbans/KanbansTable.tsx
@@ -20,6 +20,7 @@ import {
MENU_ITEM_SHORTCUTS,
MenuItem,
PulsingDot,
+ Status,
Tooltip,
TooltipContent,
TooltipTrigger,
@@ -29,7 +30,15 @@ import {
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useMemo, useState } from "react";
+import type { Dispatch, ReactNode, SetStateAction } from "react";
+import {
+ createContext,
+ memo,
+ useCallback,
+ useContext,
+ useMemo,
+ useState
+} from "react";
import {
LuBlocks,
LuCalendar,
@@ -62,6 +71,7 @@ import {
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
import { usePermissions, useUrlParams } from "~/hooks";
+import { useQuantityFormatter } from "~/hooks/useQuantityFormatter";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { kanbanOutputTypes } from "~/modules/settings/settings.models";
import { useSuppliers } from "~/stores";
@@ -75,20 +85,96 @@ type KanbansTableProps = {
count: number;
locationId: string;
kanbanOutput: (typeof kanbanOutputTypes)[number];
+ /** Kanban id → projected quantity at its To storage unit (armed Transfer kanbans only). */
+ projectedQuantities: Record<string, number>;
};
const defaultColumnVisibility = {
createdBy: false,
+ // Blank for every Buy and Make kanban; shown from the column picker.
+ replenishmentLevel: false,
+ projectedQuantity: false,
supplierName: false,
createdAt: false,
updatedBy: false,
updatedAt: false
};
+type KanbanQrCodeAction = "order" | "start" | "complete";
+
+// One QR code popover open at a time across the whole table. Each hover card
+// closes only after its own delay, so moving across the Create / Start /
+// Complete badges used to leave several popovers open on top of each other.
+const OpenQrCodeContext = createContext<
+ [string | null, Dispatch<SetStateAction<string | null>>] | null
+>(null);
+
+function KanbanQrCodeHoverCard({
+ kanbanId,
+ action,
+ label,
+ tooltip
+}: {
+ kanbanId: string;
+ action: KanbanQrCodeAction;
+ label: ReactNode;
+ tooltip: ReactNode;
+}) {
+ const openQrCode = useContext(OpenQrCodeContext);
+ const key = `${kanbanId}:${action}`;
+ const isOpen = openQrCode ? openQrCode[0] === key : undefined;
+
+ return (
+ <HoverCard
+ open={isOpen}
+ onOpenChange={(open) =>
+ openQrCode?.[1]((current) =>
+ open ? key : current === key ? null : current
+ )
+ }
+ >
+ <Tooltip>
+ <TooltipTrigger>
+ <HoverCardTrigger>
+ <Badge
+ variant="outline"
+ className="flex flex-row items-center gap-1 cursor-pointer"
+ >
+ <LuQrCode />
+ {label}
+ </Badge>
+ </HoverCardTrigger>
+ </TooltipTrigger>
+ <TooltipContent>{tooltip}</TooltipContent>
+ </Tooltip>
+ <HoverCardContent
+ align="center"
+ className="size-[236px] overflow-hidden z-[100] bg-white p-4"
+ >
+ <iframe
+ seamless
+ title={"Kanban QR Code"}
+ width="198"
+ height="198"
+ src={path.to.file.kanbanQrCode(kanbanId, action)}
+ />
+ </HoverCardContent>
+ </HoverCard>
+ );
+}
+
const KanbansTable = memo(
- ({ data, count, locationId, kanbanOutput }: KanbansTableProps) => {
+ ({
+ data,
+ count,
+ locationId,
+ kanbanOutput,
+ projectedQuantities
+ }: KanbansTableProps) => {
const [params] = useUrlParams();
const { t } = useLingui();
+ const formatQuantity = useQuantityFormatter();
+ const openQrCode = useState<string | null>(null);
const permissions = usePermissions();
const [people] = usePeople();
@@ -253,112 +339,35 @@ const KanbansTable = memo(
)}
{kanbanOutput === "qrcode" && (
<HStack>
- <HoverCard>
- <Tooltip>
- <TooltipTrigger>
- <HoverCardTrigger>
- <Badge
- variant="outline"
- className="flex flex-row items-center gap-1 cursor-pointer"
- >
- <LuQrCode />
- <Trans>Create</Trans>
- </Badge>
- </HoverCardTrigger>
- </TooltipTrigger>
- <TooltipContent>
- {t`QR Code to create a ${getKanbanCreateNoun(row.original.replenishmentSystem)} for this kanban`}
- </TooltipContent>
- </Tooltip>
- <HoverCardContent
- align="center"
- className="size-[236px] overflow-hidden z-[100] bg-white p-4"
- >
- <iframe
- seamless
- title={"Kanban QR Code"}
- width="198"
- height="198"
- src={path.to.file.kanbanQrCode(
- row.original.id!,
- "order"
- )}
- />
- </HoverCardContent>
- </HoverCard>
+ <KanbanQrCodeHoverCard
+ kanbanId={row.original.id!}
+ action="order"
+ label={<Trans>Create</Trans>}
+ tooltip={t`QR Code to create a ${getKanbanCreateNoun(row.original.replenishmentSystem)} for this kanban`}
+ />
{row.original.replenishmentSystem === "Make" && (
<>
- <HoverCard>
- <Tooltip>
- <TooltipTrigger>
- <HoverCardTrigger>
- <Badge
- variant="outline"
- className="flex flex-row items-center gap-1 cursor-pointer"
- >
- <LuQrCode />
- <Trans>Start</Trans>
- </Badge>
- </HoverCardTrigger>
- </TooltipTrigger>
- <TooltipContent>
- <Trans>
- QR Code to start the next operation for this
- kanban
- </Trans>
- </TooltipContent>
- </Tooltip>
- <HoverCardContent
- align="center"
- className="size-[236px] overflow-hidden z-[100] bg-white p-4"
- >
- <iframe
- seamless
- title={"Kanban QR Code"}
- width="198"
- height="198"
- src={path.to.file.kanbanQrCode(
- row.original.id!,
- "start"
- )}
- />
- </HoverCardContent>
- </HoverCard>
-
- <HoverCard>
- <Tooltip>
- <TooltipTrigger>
- <HoverCardTrigger>
- <Badge
- variant="outline"
- className="flex flex-row items-center gap-1 cursor-pointer"
- >
- <LuQrCode />
- Complete
- </Badge>
- </HoverCardTrigger>
- </TooltipTrigger>
- <TooltipContent>
+ <KanbanQrCodeHoverCard
+ kanbanId={row.original.id!}
+ action="start"
+ label={<Trans>Start</Trans>}
+ tooltip={
+ <Trans>
+ QR Code to start the next operation for this kanban
+ </Trans>
+ }
+ />
+ <KanbanQrCodeHoverCard
+ kanbanId={row.original.id!}
+ action="complete"
+ label={<Trans>Complete</Trans>}
+ tooltip={
+ <Trans>
QR Code to complete the current operation for this
kanban
- </TooltipContent>
- </Tooltip>
- <HoverCardContent
- align="center"
- className="size-[236px] overflow-hidden z-[100] bg-white p-4"
- >
- <iframe
- seamless
- title={"Kanban QR Code"}
- width="198"
- height="198"
- src={path.to.file.kanbanQrCode(
- row.original.id!,
- "complete"
- )}
- />
- </HoverCardContent>
- </HoverCard>
+ </Trans>
+ }
+ />
</>
)}
</HStack>
@@ -411,6 +420,44 @@ const KanbansTable = memo(
icon: <LuHash />
}
},
+ {
+ accessorKey: "replenishmentLevel",
+ header: t`Replenishment Level`,
+ cell: ({ row }) =>
+ row.original.replenishmentLevel === null ||
+ row.original.replenishmentLevel === undefined
+ ? null
+ : formatQuantity(row.original.replenishmentLevel),
+ meta: {
+ icon: <LuHash />
+ }
+ },
+ {
+ id: "projectedQuantity",
+ header: t`Projected (To)`,
+ cell: ({ row }) => {
+ const projected = row.original.id
+ ? projectedQuantities[row.original.id]
+ : undefined;
+ if (projected === undefined) return null;
+ const level = row.original.replenishmentLevel;
+ const isBelowLevel =
+ level !== null && level !== undefined && projected < level;
+ return (
+ <HStack spacing={2}>
+ <span>{formatQuantity(projected)}</span>
+ {isBelowLevel && (
+ <Status color="red">
+ <Trans>Below level</Trans>
+ </Status>
+ )}
+ </HStack>
+ );
+ },
+ meta: {
+ icon: <LuHash />
+ }
+ },
{
accessorKey: "replenishmentSystem",
header: t`Replenishment`,
@@ -559,7 +606,16 @@ const KanbansTable = memo(
}
}
],
- [items, kanbanOutput, params, people, suppliers, t]
+ [
+ formatQuantity,
+ items,
+ kanbanOutput,
+ params,
+ people,
+ projectedQuantities,
+ suppliers,
+ t
+ ]
);
const renderContextMenu = useCallback(
@@ -692,38 +748,40 @@ const KanbansTable = memo(
}, []);
return (
- <Table<Kanban>
- count={count}
- columns={columns}
- data={data}
- defaultColumnVisibility={defaultColumnVisibility}
- primaryAction={
- <div className="flex items-center gap-2">
- <Combobox
- asButton
- size="sm"
- value={locationId}
- options={locations}
- onChange={(selected) => {
- // hard refresh because initialValues update has no effect otherwise
- window.location.href = getLocationPath(selected);
- }}
- />
- <Button variant="secondary" asChild leftIcon={<LuSettings />}>
- <Link to={path.to.inventorySettings}>Settings</Link>
- </Button>
- {permissions.can("create", "inventory") && (
- <New label={t`Kanban`} to={path.to.newKanban} />
- )}
- </div>
- }
- renderActions={renderActions}
- renderContextMenu={renderContextMenu}
- title={t`Kanbans`}
- table="kanban"
- withSavedView
- withSelectableRows
- />
+ <OpenQrCodeContext.Provider value={openQrCode}>
+ <Table<Kanban>
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnVisibility={defaultColumnVisibility}
+ primaryAction={
+ <div className="flex items-center gap-2">
+ <Combobox
+ asButton
+ size="sm"
+ value={locationId}
+ options={locations}
+ onChange={(selected) => {
+ // hard refresh because initialValues update has no effect otherwise
+ window.location.href = getLocationPath(selected);
+ }}
+ />
+ <Button variant="secondary" asChild leftIcon={<LuSettings />}>
+ <Link to={path.to.inventorySettings}>Settings</Link>
+ </Button>
+ {permissions.can("create", "inventory") && (
+ <New label={t`Kanban`} to={path.to.newKanban} />
+ )}
+ </div>
+ }
+ renderActions={renderActions}
+ renderContextMenu={renderContextMenu}
+ title={t`Kanbans`}
+ table="kanban"
+ withSavedView
+ withSelectableRows
+ />
+ </OpenQrCodeContext.Provider>
);
}
);
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
index 4bf792a83a..173b5427a4 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferHeader.tsx
@@ -5,6 +5,7 @@
import type { Result } from "@carbon/auth";
import { useRuleViolations } from "@carbon/ee/rules";
import {
+ Badge,
Button,
DropdownMenuIcon,
DropdownMenuItem,
@@ -17,9 +18,10 @@ import {
LuCircleCheck,
LuCirclePlay,
LuLoaderCircle,
+ LuScanQrCode,
LuTrash
} from "react-icons/lu";
-import { useFetcher, useParams } from "react-router";
+import { Link, useFetcher, useParams } from "react-router";
import { DateTime, EmployeeAvatar, PrintButton } from "~/components";
import Assignee, { useOptimisticAssignment } from "~/components/Assignee";
import { DocumentPageHeader } from "~/components/DocumentPage";
@@ -105,6 +107,17 @@ const StockTransferHeader = () => {
Completed{" "}
<DateTime value={stockTransfer.completedAt} variant="relative" />
</Trans>
+ ) : null,
+ stockTransfer.kanbanId ? (
+ <Badge key="kanban" variant="outline">
+ <Link
+ to={path.to.kanban(stockTransfer.kanbanId)}
+ className="flex flex-row items-center gap-1"
+ >
+ <LuScanQrCode />
+ <Trans>Kanban</Trans>
+ </Link>
+ </Badge>
) : null
]}
menuItems={
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
index 92b287980a..95c4e53a06 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import {
+ Badge,
Button,
Combobox,
MENU_ITEM_SHORTCUTS,
@@ -20,6 +21,7 @@ import {
LuClock,
LuMapPin,
LuPencil,
+ LuScanQrCode,
LuTrash,
LuUser
} from "react-icons/lu";
@@ -137,6 +139,33 @@ const StockTransfersTable = memo(
icon: <LuClock />
}
},
+ {
+ id: "source",
+ header: t`Source`,
+ cell: ({ row }) =>
+ row.original.kanbanId ? (
+ <Badge variant="blue">
+ <Trans>Kanban</Trans>
+ </Badge>
+ ) : (
+ <Badge variant="gray">
+ <Trans>Manual</Trans>
+ </Badge>
+ ),
+ meta: {
+ icon: <LuScanQrCode />,
+ filterHeader: t`Source`,
+ filter: {
+ type: "static",
+ options: [
+ { value: "Kanban", label: t`Kanban` },
+ { value: "Manual", label: t`Manual` }
+ ]
+ },
+ exportValue: (row: StockTransfer) =>
+ row.kanbanId ? "Kanban" : "Manual"
+ }
+ },
{
accessorKey: "assignee",
header: t`Assignee`,
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 78ae79752c..e21286da86 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -13,17 +13,14 @@ import { trackWorkEvent } from "@carbon/lib/telemetry";
import { getLogger } from "@carbon/logger";
import { runLocationSchedule } from "@carbon/planning";
import { Loading } from "@carbon/react";
+import { serverFns } from "@carbon/server-functions";
import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { Suspense } from "react";
import type { LoaderFunctionArgs } from "react-router";
import { Await, useLoaderData } from "react-router";
import { Redirect } from "~/components/Redirect";
-import {
- getDefaultStorageUnitForJob,
- getKanban,
- insertStockTransfer
-} from "~/modules/inventory";
+import { getDefaultStorageUnitForJob, getKanban } from "~/modules/inventory";
import { getItemReplenishment, getSupplierPartPricing } from "~/modules/items";
import {
getActiveJobOperationByJobId,
@@ -393,79 +390,29 @@ async function handleKanban({
return { data: null, error: "Failed to create stock transfer" };
}
- if (!kanban.data.fromStorageUnitId || !kanban.data.storageUnitId) {
- return {
- data: null,
- error: "Kanban is missing a from or to storage unit"
- };
- }
-
- // Defense in depth: confirm BOTH storage units belong to this company and
- // this kanban's location before moving stock. A stock transfer is
- // intra-location, and the ids could have been set to another location's (or
- // company's) bin — validate rather than trust the stored ids (CWE-639).
- const storageUnits = await client
- .from("storageUnit")
- .select("id")
- .in("id", [kanban.data.fromStorageUnitId, kanban.data.storageUnitId])
- .eq("companyId", companyId)
- .eq("locationId", kanban.data.locationId!);
-
- const validIds = new Set((storageUnits.data ?? []).map((s) => s.id));
- if (
- !validIds.has(kanban.data.fromStorageUnitId) ||
- !validIds.has(kanban.data.storageUnitId)
- ) {
- return {
- data: null,
- error: "Storage unit does not belong to the kanban location"
- };
+ // kanban-replenish re-reads the kanban under companyId, checks both
+ // storage units belong to the kanban's location (CWE-639), and writes the
+ // Released transfer with its kanbanId and "Kanban replenishment" note.
+ // Run as the scanner: a scan needs inventory create permission, the same
+ // check the stock transfer's RLS rule makes.
+ const replenish = await serverFns
+ .as({ client, db: getDatabaseClient(), companyId, userId })
+ .invoke("kanban-replenish", { mode: "scan", kanbanId: id });
+
+ if (replenish.error) {
+ logger.error("Kanban operation failed", { error: replenish.error });
+ return { data: null, error: "Failed to create stock transfer" };
}
- // Derive tracking from the item so the transfer line demands the right
- // serial/batch handling at pick time. insertStockTransfer expands a
- // serial-tracked line of qty > 1 into individual qty-1 lines.
- const item = await client
- .from("item")
- .select("itemTrackingType")
- .eq("id", kanban.data.itemId)
- .eq("companyId", companyId)
- .single();
-
- if (item.error) {
- logger.error("Kanban operation failed", { error: item.error });
- return { data: null, error: "Failed to get item" };
+ const outcome = replenish.data.results[0];
+ if (outcome?.outcome === "invalid") {
+ return { data: null, error: outcome.reason };
}
-
- const trackingType = item.data?.itemTrackingType;
-
- const createStockTransfer = await insertStockTransfer(client, {
- locationId: kanban.data.locationId!,
- lines: [
- {
- itemId: kanban.data.itemId,
- fromStorageUnitId: kanban.data.fromStorageUnitId,
- toStorageUnitId: kanban.data.storageUnitId,
- quantity: kanban.data.quantity!,
- requiresSerialTracking: trackingType === "Serial",
- requiresBatchTracking: trackingType === "Batch"
- }
- ],
- companyId,
- createdBy: userId
- });
-
- if (createStockTransfer.error || !createStockTransfer.data) {
- logger.error("Kanban operation failed", {
- error: createStockTransfer.error
- });
- return { data: null, error: "Failed to create stock transfer" };
+ if (outcome?.outcome === "created") {
+ return { data: path.to.stockTransfer(outcome.id), error: null };
}
- return {
- data: path.to.stockTransfer(createStockTransfer.data.id),
- error: null
- };
+ return { data: null, error: "Failed to create stock transfer" };
} else {
return {
data: null,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 118720a225..67ca03d000 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1554,
+ "totalTools": 1555,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},
@@ -203,8 +203,9 @@
{"name":"inventory_getItemLedgerActivity","classification":"READ","paramCount":5,"schema":"b898b72c5939","response":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getItemLedgerBalance","classification":"READ","paramCount":3,"schema":"33e76470e057","response":"cddf8275afa1","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getItemLedgerPage","classification":"READ","paramCount":4,"schema":"7ef5489d0abf","response":"07a99b26121b","injectAuth":"companyId","permission":"inventory:view","paginates":true},
- {"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"c5aa7a081ed4","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"fa96e94d8dda","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
+ {"name":"inventory_getKanban","classification":"READ","paramCount":1,"schema":"369f807bc840","response":"2fd5e28a7273","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getKanbanProjectedQuantities","classification":"READ","paramCount":1,"schema":"eb1d8d941f5f","response":"98903cc375ce","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getKanbans","classification":"READ","paramCount":2,"schema":"c3aa3d6832b9","response":"87bc6f56aff6","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
{"name":"inventory_getPickingList","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"227255936b96","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListAvailability","classification":"READ","paramCount":1,"schema":"0a4ec3e7319b","response":"none","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getPickingListLine","classification":"READ","paramCount":1,"schema":"063a6777d378","response":"b51ad23d436f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
@@ -241,10 +242,10 @@
{"name":"inventory_getShippingTermsList","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"ce08332e0ce6","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockMovementEffectiveQuantity","classification":"READ","paramCount":1,"schema":"a40494d32d29","response":"2e1967d88231","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockMovements","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"eba78a8fe017","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
- {"name":"inventory_getStockTransfer","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"0f59b3fa09f8","injectAuth":"companyId","permission":"inventory:view","paginates":false},
+ {"name":"inventory_getStockTransfer","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"69c0eeefc47c","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockTransferLine","classification":"READ","paramCount":1,"schema":"0bbd6a946791","response":"a34287fc1477","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStockTransferLines","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"bcb01288cc29","injectAuth":"companyId","permission":"inventory:view","paginates":false},
- {"name":"inventory_getStockTransfers","classification":"READ","paramCount":4,"schema":"acb88488ed54","response":"77ebb4ee443b","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
+ {"name":"inventory_getStockTransfers","classification":"READ","paramCount":4,"schema":"acb88488ed54","response":"a0e62ff2e059","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
{"name":"inventory_getStockTransferTracking","classification":"READ","paramCount":1,"schema":"38111ae0fa2a","response":"20f8627b948f","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStorageType","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"4bbb50609deb","injectAuth":"companyId","permission":"inventory:view","paginates":false},
{"name":"inventory_getStorageTypes","classification":"READ","paramCount":3,"schema":"c61cae75d189","response":"28837d034643","injectAuth":"companyId","permission":"inventory:view","paginates":true,"defaults":"always"},
@@ -290,7 +291,7 @@
{"name":"inventory_updateWarehouseTransfer","classification":"WRITE","paramCount":10,"schema":"a809aeb69e6d","response":"3797626bd17e","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false},
{"name":"inventory_updateWarehouseTransferStatus","classification":"WRITE","paramCount":2,"schema":"70cb7f36b2a6","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"inventory:update","paginates":false,"context":"updatedBy=userId"},
{"name":"inventory_upsertBatchProperty","classification":"WRITE","paramCount":6,"schema":"6fcfef7093ed","response":"bcde375ebd4c","injectAuth":"companyId+createdBy+updatedBy+userId","permission":"inventory:create+update","paginates":false},
- {"name":"inventory_upsertKanban","classification":"WRITE","paramCount":14,"schema":"9500a3f1264b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id","defaults":"create"},
+ {"name":"inventory_upsertKanban","classification":"WRITE","paramCount":15,"schema":"bda2d2c1b9ff","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id","defaults":"create"},
{"name":"inventory_upsertPickingList","classification":"WRITE","paramCount":7,"schema":"dbe65909f79e","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_upsertReceipt","classification":"WRITE","paramCount":9,"schema":"fd0848682b0b","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
{"name":"inventory_upsertShipment","classification":"WRITE","paramCount":10,"schema":"efe95221a775","response":"3797626bd17e","injectAuth":"companyId+createdBy+updatedBy","permission":"inventory:create+update","paginates":false,"upsert":"id"},
diff --git a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
index 39eb5ba8cd..65faef9b3d 100644
--- a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
@@ -101,6 +101,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
fromStorageUnitName: kanban.fromStorageUnitName,
supplierName: kanban.supplierName,
quantity: kanban.quantity ?? 0,
+ replenishmentLevel: kanban.replenishmentLevel,
unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,
thumbnail: thumbnails[kanban.id!] || null
};
diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
index 39f24738cb..6bc369c1e3 100644
--- a/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
+++ b/apps/erp/app/routes/x+/inventory+/kanbans.$id.tsx
@@ -36,7 +36,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "inventory"
});
@@ -53,6 +53,7 @@ export async function action({ request }: ActionFunctionArgs) {
const updateKanban = await upsertKanban(client, {
id,
...d,
+ companyId,
updatedBy: userId
});
@@ -84,6 +85,7 @@ export default function EditKanbanRoute() {
supplierId: kanban?.supplierId ?? "",
purchaseUnitOfMeasureCode: kanban?.purchaseUnitOfMeasureCode ?? "",
conversionFactor: kanban?.conversionFactor ?? 1,
+ replenishmentLevel: kanban?.replenishmentLevel ?? undefined,
autoRelease: kanban?.autoRelease ?? false,
autoStartJob: kanban?.autoStartJob ?? false,
completedBarcodeOverride: kanban?.completedBarcodeOverride ?? ""
diff --git a/apps/erp/app/routes/x+/inventory+/kanbans.tsx b/apps/erp/app/routes/x+/inventory+/kanbans.tsx
index 4d94a97ae4..6030b0c0e9 100644
--- a/apps/erp/app/routes/x+/inventory+/kanbans.tsx
+++ b/apps/erp/app/routes/x+/inventory+/kanbans.tsx
@@ -5,12 +5,13 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { getLogger } from "@carbon/logger";
import { RecordOutlet, VStack } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData } from "react-router";
-import { getKanbans } from "~/modules/inventory";
+import { getKanbanProjectedQuantities, getKanbans } from "~/modules/inventory";
import KanbansTable from "~/modules/inventory/ui/Kanbans/KanbansTable";
import { getLocationsList } from "~/modules/resources";
import { getKanbanOutputSetting } from "~/modules/settings";
@@ -19,6 +20,7 @@ import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
import { getGenericQueryFilters } from "~/utils/query";
+const logger = getLogger("erp", "kanbans");
export const handle: Handle = {
breadcrumb: msg`Kanbans`,
to: path.to.kanbans,
@@ -87,16 +89,47 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
+ // One query for every armed Transfer kanban on the page. A failure only
+ // hides the Projected (To) column; the list still loads.
+ const armedKanbanIds = (kanbans.data ?? [])
+ .filter(
+ (kanban) =>
+ kanban.replenishmentSystem === "Transfer" &&
+ kanban.replenishmentLevel !== null &&
+ kanban.id
+ )
+ .map((kanban) => kanban.id!);
+
+ const projectedQuantities: Record<string, number> = {};
+ if (armedKanbanIds.length > 0) {
+ const projected = await getKanbanProjectedQuantities(
+ client,
+ companyId,
+ armedKanbanIds
+ );
+ if (projected.error) {
+ logger.error("Failed to load kanban projected quantities", {
+ companyId,
+ error: projected.error
+ });
+ } else {
+ for (const row of projected.data ?? []) {
+ projectedQuantities[row.kanbanId] = row.projectedQuantity;
+ }
+ }
+ }
+
return {
count: kanbans.count ?? 0,
kanbans: kanbans.data ?? [],
kanbanOutput: kanbanOutput.data?.kanbanOutput ?? "qrcode",
- locationId
+ locationId,
+ projectedQuantities
};
}
export default function KanbansRoute() {
- const { count, kanbans, locationId, kanbanOutput } =
+ const { count, kanbans, locationId, kanbanOutput, projectedQuantities } =
useLoaderData<typeof loader>();
return (
@@ -106,6 +139,7 @@ export default function KanbansRoute() {
count={count}
locationId={locationId}
kanbanOutput={kanbanOutput}
+ projectedQuantities={projectedQuantities}
/>
<RecordOutlet />
</VStack>
diff --git a/docs/content/docs/reference/kanban.mdx b/docs/content/docs/reference/kanban.mdx
index cbeb5ffd35..963997593c 100644
--- a/docs/content/docs/reference/kanban.mdx
+++ b/docs/content/docs/reference/kanban.mdx
@@ -1,33 +1,34 @@
---
title: Kanban
-description: Scan-based pull replenishment. A kanban card ties an item to a bin, and scanning it fires a purchase order or a job.
+description: Scan-based pull replenishment. A kanban card ties an item to a bin, and a signal fires a purchase order, a job, or a stock transfer.
---
-A <Term>kanban</Term> is a physical pull signal represented by a printed card, QR code, or URL. It links an item, location, storage unit, and reorder quantity. Scanning the signal creates the purchase order or job needed to refill the bin.
+A <Term>kanban</Term> is a physical pull signal represented by a printed card, QR code, or URL. It links an item, location, storage unit, and reorder quantity. Scanning the signal creates the purchase order, job, or stock transfer needed to refill the bin.
-A [reordering policy](/docs/reference/reordering) calculates suggestions from on-hand quantity, demand, and reorder points. Kanban replenishment is manual: scanning creates an order immediately. Use policies for planning-driven replenishment and kanban for scan-driven shop-floor pull.
+A [reordering policy](/docs/reference/reordering) calculates suggestions from on-hand quantity, demand, and reorder points. Kanban replenishment is direct: a signal creates a real document immediately. Use policies for planning-driven replenishment and kanban for shop-floor pull.
+
+<Screenshot label="Kanbans list with the Replenishment Level and Projected (To) columns, one transfer kanban showing the Below level pill" />
## What a kanban holds
-Each kanban is a small record: an item, where it lives, how much to reorder, and how to reorder it.
+Each kanban is a small record: an item, where it lives, how much to reorder, and how to reorder it. For a `Transfer` kanban, the form shows Item, Replenishment System, Location, From Storage Unit, To Storage Unit, Quantity, and Replenishment Level, in that order.
<FieldTable>
<Field name="Item" required>The part, material, tool, or consumable this card replenishes.</Field>
- <Field name="Quantity" required>How much to reorder each time the card is scanned (at least 1).</Field>
- <Field name="Replenishment system" required>How the scan replenishes: `Buy` (raise a purchase order) or `Make` (create a job). See <Term>replenishment system</Term>.</Field>
+ <Field name="Quantity" required>How much to reorder on each signal (at least 1). On a `Transfer` kanban, this is the quantity moved from the From storage unit.</Field>
+ <Field name="Replenishment system" required>How the signal replenishes: `Buy` (raise a purchase order), `Make` (create a job), or `Transfer` (create a stock transfer between two storage units in the location). See <Term>replenishment system</Term>.</Field>
<Field name="Location" required>The location whose stock this card refills.</Field>
- <Field name="Storage unit">The bin the reordered stock lands in. Defaults from the item's pick method for that location if left blank.</Field>
+ <Field name="Storage unit">The bin the reordered stock lands in. Defaults from the item's pick method for that location if left blank. (`Buy` and `Make`.)</Field>
+ <Field name="From storage unit" required>The storage unit the stock moves out of. It must be in the kanban's location. (`Transfer` only.)</Field>
+ <Field name="To storage unit" required>The storage unit this card refills. It must be in the kanban's location and must be different from the From storage unit. (`Transfer` only.)</Field>
+ <Field name="Replenishment level">The <Term id="kanban-replenishment-level">replenishment level</Term> for the To storage unit, 0 or more. Leave it blank for a scan-only kanban. (`Transfer` only.)</Field>
<Field name="Supplier">Who to buy from. **Required for `Buy` kanbans.**</Field>
- <Field name="Purchase unit of measure / Conversion factor">The unit you buy in and how many stock units that equals — applied to the PO line. (`Buy` only.)</Field>
+ <Field name="Purchase unit of measure / Conversion factor">The unit you buy in and how many stock units that equals. Carbon applies both to the PO line. (`Buy` only.)</Field>
<Field name="Auto Release">On a `Make` scan, release the created job to the floor immediately instead of leaving it in draft. (`Make` only.)</Field>
<Field name="Auto Start Job">On a `Make` scan, drop the operator straight into the first operation in MES. Requires Auto Release. (`Make` only.)</Field>
<Field name="Completion Barcode">The code operators scan to mark the job complete; auto-generated when left blank. (`Make` only.)</Field>
</FieldTable>
-<Callout type="note">
-The replenishment system enum has three values (`Buy`, `Make`, `Buy and Make`), but the kanban form only offers **Buy** and **Make**. A kanban set to `Buy and Make` is rejected at scan time — a single card fires one clear action, not both.
-</Callout>
-
## The scan flow
Each kanban has scan targets for `order`, `start`, and `complete`. A scan opens a URL, runs the action, and redirects to the resulting document. QR codes are black for order, emerald for start, and blue for complete.
@@ -35,16 +36,23 @@ Each kanban has scan targets for `order`, `start`, and `complete`. A scan opens
The **order** scan (the create signal) branches on the replenishment system:
<StatusFlow>
- <Status name="Buy" accent>The scan finds an open (`Draft` or `Planned`) purchase order for that supplier and adds a line for the kanban's quantity — or creates a new draft PO if none exists — then drops you on the purchase order. It applies the kanban's conversion factor, purchase unit, and storage unit to the line.</Status>
+ <Status name="Buy" accent>The scan finds an open (`Draft` or `Planned`) purchase order for that supplier and adds a line for the kanban's quantity. If none exists, it creates a new draft PO. It applies the kanban's conversion factor, purchase unit, and storage unit to the line, then drops you on the purchase order.</Status>
<Status name="Make">The scan creates a <Term id="job">job</Term> for the item at the kanban's quantity, copies the item's method onto it, and links the job back to the card. With **Auto Release** on, it also runs planning and scheduling and marks the job `Ready`; with **Auto Start Job** on, it sends the operator straight into the first operation in MES.</Status>
+ <Status name="Transfer">The scan creates a `Released` stock transfer for the kanban's quantity, from the From storage unit to the To storage unit, then drops you on the transfer. A scan always creates a transfer, whether or not the kanban has a replenishment level.</Status>
</StatusFlow>
**Start** and **complete** scans only apply to `Make` kanbans. They resolve the linked job's active operation and hand off to the MES operation start / complete screens, so an operator can drive the whole build from the same card that created the job.
<Callout type="warning">
-A `Make` kanban links to the job it created (`jobId`). If you scan **order** again while that job is still open, Carbon doesn't create a duplicate — it routes you to a collision screen that shows the existing job and offers to remove the link so a fresh scan can start over. Once the job is completed or cancelled, the link clears automatically and the card is free to fire again.
+A `Make` kanban links to the job it created (`jobId`). If you scan **order** again while that job is still open, Carbon doesn't create a duplicate. It routes you to a collision screen that shows the existing job and offers to remove the link so a fresh scan can start over. Once the job is completed or cancelled, the link clears automatically and the card is free to fire again.
</Callout>
+## Replenishment level
+
+A `Transfer` kanban with a replenishment level refills its To storage unit without a scan. The projected quantity is the on-hand quantity at the To storage unit plus the outstanding quantity of every stock transfer into it that is not `Completed`. When the projected quantity is strictly below the level, Carbon creates one `Released` stock transfer for the fewest whole multiples of the kanban's Quantity that reach the level. With a level of 20, a Quantity of 5 and an empty storage unit, one transfer moves 20.
+
+Three events start the check: a stock movement at the To storage unit, a save of the kanban, and an hourly sweep. Each transfer has a "Kanban replenishment" note and shows `Kanban` in the **Source** column. The database sends the signals through the Vault secret `inngest_event_url`, so without it a level never fires ([environment variables](/docs/platform/self-hosting/environment-variables#jobs--cache)).
+
## Output format
How a card is rendered is a per-company setting, **Kanban Output**, with three modes:
@@ -52,17 +60,17 @@ How a card is rendered is a per-company setting, **Kanban Output**, with three m
| Mode | What a card is |
| --- | --- |
| QR code | A scannable QR code (the default), color-coded per action. |
-| Label | A printed PDF label — six to a page — with the QR, item thumbnail, name, storage unit, quantity, and supplier. |
+| Label | A printed PDF label, six to a page, with the QR, item thumbnail, name, storage unit, quantity, and supplier. When the kanban has a replenishment level, a `MIN:` line prints under `QTY:`. |
| URL | A copyable link that hits the same scan endpoint directly. |
-For `Make` kanbans, the list view also surfaces the **start** and **complete** affordances; `Buy` kanbans show only the order signal, since there's no job to start.
+For `Make` kanbans, the list view also surfaces the **start** and **complete** affordances. `Buy` and `Transfer` kanbans show only the order signal, since there's no job to start. Two columns are hidden by default: **Replenishment Level** and **Projected (To)**. Turn them on from the column picker. **Projected (To)** shows a **Below level** pill when the projected quantity is under the level.
## Kanban vs. reordering policy
Both replenish stock, but they're different tools:
<Callout type="info" title="A kanban is a signal, not a plan">
-A [reordering policy](/docs/reference/reordering) is evaluated by the planning engine, which computes suggested orders from on-hand, demand, and reorder points. A kanban skips all of that: a human scan creates a real purchase order or job on the spot. Reach for a kanban when the shop floor pulls material by hand and you want the refill to be one scan away.
+A [reordering policy](/docs/reference/reordering) is evaluated by the planning engine, which computes suggested orders from on-hand, demand, and reorder points. A kanban skips all of that: a scan creates a real purchase order, job, or stock transfer on the spot. A replenishment level applies only to a `Transfer` kanban, and it creates a stock transfer. Reach for a kanban when the shop floor pulls material by hand and you want the refill to be one scan away.
</Callout>
## Related
@@ -72,17 +80,17 @@ A [reordering policy](/docs/reference/reordering) is evaluated by the planning e
Where stock lives, the storage units a kanban refills, and how on-hand is tracked.
</Card>
<Card title="Reordering policy" href="/docs/reference/reordering">
- The planning-driven alternative — when and how much each part replenishes automatically.
+ The planning-driven alternative: when and how much each part replenishes automatically.
</Card>
</Cards>
<AgentContext>
## Troubleshooting
-Exact errors from scanning kanban cards.
+Exact errors from saving and scanning kanban cards.
### "… is not supported"
-The **order** scan hit a kanban whose replenishment system is **`Buy and Make`**. A single card fires one clear action, so only `Buy` and `Make` are supported at scan. Set the kanban to `Buy` or `Make`.
+The **order** scan hit a kanban whose replenishment system is **`Buy and Make`**. A single card fires one clear action, so only `Buy`, `Make`, and `Transfer` are supported at scan. Set the kanban to one of those.
### "Supplier is required"
A `Buy` kanban has no supplier. The order scan needs to know who to raise the purchase order against — set the supplier on the kanban.
@@ -99,6 +107,21 @@ A **start** or **complete** scan ran on a kanban that has no linked job yet. Tho
### "Kanban is not active"
The scanned card isn't found or belongs to a different company. Confirm the card is current and scoped to your company.
+### "Kanban is missing a from or to storage unit"
+A `Transfer` scan (or level check) ran on a kanban with no From or no To storage unit. Set both on the kanban. The form also refuses to save with "From storage unit is required" or "To storage unit is required".
+
+### "Storage unit does not belong to the kanban location"
+The From or To storage unit of a `Transfer` kanban is not in the kanban's location, or does not belong to the company. Pick storage units from the kanban's own location.
+
+### "Only a transfer kanban can have a replenishment level"
+The form refuses a replenishment level on a `Buy` or `Make` kanban. Clear the level, or set the replenishment system to `Transfer`. A related save error is "From and to storage units must be different": a `Transfer` kanban cannot feed itself.
+
+### A transfer kanban with a level never fires
+The level check runs in the jobs runner, and the database sends its signals through the Vault secret `inngest_event_url`. If the secret is missing, `util.send_inngest_event` does nothing, so no transfer is created. A scan still works. Check that the projected quantity (on-hand at the To storage unit plus outstanding quantity on stock transfers into it that are not `Completed`) is strictly below the level. The hourly sweep is the pg_cron job `kanban-level-sweeper`, at minute 7. A forgotten `Draft` stock transfer into the To storage unit also counts as supply, so it can keep the kanban from firing. Release it, or delete it if nobody needs it.
+
+### "Failed to create stock transfer"
+The `Transfer` scan failed for a reason other than the storage-unit checks above, for example a missing item. Check the kanban's item and retry.
+
### The list view shows no Start / Complete affordances
-Only `Make` kanbans surface **start** and **complete**; `Buy` kanbans show just the order signal, because there's no job to start. How cards render (QR code, Label, or URL) is the per-company **Kanban Output** setting.
+Only `Make` kanbans surface **start** and **complete**; `Buy` and `Transfer` kanbans show just the order signal, because there's no job to start. How cards render (QR code, Label, or URL) is the per-company **Kanban Output** setting.
</AgentContext>
diff --git a/docs/content/src/glossary/terms.ts b/docs/content/src/glossary/terms.ts
index 14cd31aa57..65c84483e7 100644
--- a/docs/content/src/glossary/terms.ts
+++ b/docs/content/src/glossary/terms.ts
@@ -1112,6 +1112,11 @@ export const terms = {
term: msg`Auto Release`,
definition: msg`When the kanban card is scanned, the job is automatically moved out of draft and released to the floor.`
},
+ "kanban-replenishment-level": {
+ term: msg`Replenishment Level`,
+ definition: msg`On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity.`,
+ href: "/docs/reference/kanban"
+ },
"kanban-auto-start-job": {
term: msg`Auto Start Job`,
definition: msg`Skip the released-but-not-started state — the job starts immediately on scan.`
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 06fcb88934..0e2ccdbf5b 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -94,6 +94,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| `./legacy-documents` | Server-only. The one detection of legacy documents (`.ai/specs/implemented/2026-10-08-accounting-cutover.md` section 5a): posted, dated on or after the cutover, with no journal. Each function (`legacySalesInvoices`, `legacyPayments`, `legacyShipments`, `legacyAdjustmentCostRows`, `legacyJobMovements`, `legacyDepreciationRunLines`, …) returns a Kysely query, not rows: the `activate-accounting` server function executes it, and `getLegacyDocumentCounts` (`./accounting-cutover-reads`) counts the same rows for the wizard. Also `LEGACY_DOCUMENT_FAMILIES` (the families in the order the enable writes them), `LegacyDocumentCounts`, `assetsLeavingWithoutJournal` and `REBUILT_DISPOSAL_METHOD` |
| `./deposit-scope` | `loadSalesInvoiceDocumentIds` (the rental agreements / sales orders each sales invoice bills, one query) and `loadDepositScope` (a deposit payment's document + readable id) — the reads behind "a customer deposit funds only its own document", shared by `replaceInvoiceSettlements` and `post-payment` |
| `./sequence` | `getNextSequences` (`count` numbers in one statement; `getNextSequence` is its count-of-one) / `getNextRevisionSequence` / `getNextSerialNumbers` — the one allocator for document and serial numbers (date tokens in the company timezone) |
+| `./stock-transfer` | `expandSerialTrackedLines`, `isBelowReplenishmentLevel`, `levelReplenishmentQuantity` (the fewest whole kanban quantities that reach a level), `kanbanReplenishmentNote` — the stock-transfer line and kanban-note rules shared by the ERP's `insertStockTransfer` and the `kanban-replenish` server function |
| `./seed-data` | The company seed data (accounts, sequences, groups + `getGroupId`, …) used by the `seed-company` server function and the dataset tooling |
| *(no subpath)* | `src/sql-effects.ts` — `sqlFunctionEffects(sources)` / `loadSqlFunctionEffects()`: whether a SQL function writes, reads or cannot be told, read off its current definition with `libpg-query` (every migration, then the managed function files). The API generator imports it by path to refuse a `read` tool that calls a writing function. An extension function it meets must be added to `EXTERNAL_READS` or `EXTERNAL_WRITES`; reviewed dynamic SQL to `REVIEWED_DYNAMIC_READS` |
| `./event` | `QueueMessage`, `EventSchema`, `createEventSystemSubscription`, `deleteEventSystemSubscription` |
diff --git a/packages/database/package.json b/packages/database/package.json
index 4ebf755f18..f43974f26e 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -46,6 +46,7 @@
"./ratelimit": "./src/ratelimit.ts",
"./sampling": "./src/sampling.ts",
"./sequence": "./src/sequence.ts",
+ "./stock-transfer": "./src/stock-transfer.ts",
"./seed-data": "./src/seed-data.ts",
"./seed-workflows": "./src/datasets/tiers/workflow-definitions.ts",
"./audit.config": "./src/audit.config.ts",
diff --git a/packages/database/src/event-system/attachments.ts b/packages/database/src/event-system/attachments.ts
index b213bed826..740842a2c4 100644
--- a/packages/database/src/event-system/attachments.ts
+++ b/packages/database/src/event-system/attachments.ts
@@ -128,7 +128,11 @@ export const attachments = {
},
itemCost: { events: true },
itemLedger: {
- statement: ["apply_item_stock_quantities", "broadcast_table_changes"]
+ statement: [
+ "apply_item_stock_quantities",
+ "broadcast_table_changes",
+ "queue_kanban_level_checks"
+ ]
},
itemPlanning: { events: true },
itemPostingGroup: {
@@ -185,6 +189,7 @@ export const attachments = {
jobOperationNote: { statement: ["broadcast_table_changes"] },
jobOperationStep: { statement: ["broadcast_table_changes"] },
jobOperationStepRecord: { statement: ["broadcast_table_changes"] },
+ kanban: { after: ["sync_kanban_level_check"] },
journal: {
after: ["sync_advance_document_sequence"],
events: true,
diff --git a/packages/database/src/event-system/handlers/queue_kanban_level_checks.sql b/packages/database/src/event-system/handlers/queue_kanban_level_checks.sql
new file mode 100644
index 0000000000..bdaea56bc3
--- /dev/null
+++ b/packages/database/src/event-system/handlers/queue_kanban_level_checks.sql
@@ -0,0 +1,63 @@
+CREATE OR REPLACE FUNCTION public.queue_kanban_level_checks()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ touched JSONB;
+ target RECORD;
+ below TEXT[];
+BEGIN
+ -- A seed, a restore or a test fixture loads ledger rows in bulk.
+ -- The hourly sweep (util.sweep_kanban_levels) covers those.
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- Only batched_new exists on INSERT and only batched_old on DELETE.
+ IF TG_OP = 'DELETE' THEN
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_old
+ WHERE "storageUnitId" IS NOT NULL;
+ ELSE
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_new
+ WHERE "storageUnitId" IS NOT NULL;
+ END IF;
+
+ IF touched IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ FOR target IN
+ SELECT k."companyId", array_agg(DISTINCT k."id") AS "kanbanIds"
+ FROM jsonb_to_recordset(touched) AS t("companyId" TEXT, "itemId" TEXT, "storageUnitId" TEXT)
+ JOIN "kanban" k
+ ON k."companyId" = t."companyId"
+ AND k."itemId" = t."itemId"
+ AND k."storageUnitId" = t."storageUnitId"
+ WHERE k."replenishmentSystem" = 'Transfer'
+ AND k."replenishmentLevel" IS NOT NULL
+ GROUP BY k."companyId"
+ LOOP
+ SELECT array_agg(p."kanbanId" ORDER BY p."kanbanId")
+ INTO below
+ FROM get_kanban_projected_quantities(target."companyId", target."kanbanIds") p
+ WHERE p."projectedQuantity" < p."replenishmentLevel";
+
+ IF below IS NOT NULL THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', target."companyId", 'kanbanIds', to_jsonb(below))
+ );
+ END IF;
+ END LOOP;
+
+ RETURN NULL;
+END;
+$function$;
diff --git a/packages/database/src/event-system/handlers/sync_kanban_level_check.sql b/packages/database/src/event-system/handlers/sync_kanban_level_check.sql
new file mode 100644
index 0000000000..bc9e94b7ca
--- /dev/null
+++ b/packages/database/src/event-system/handlers/sync_kanban_level_check.sql
@@ -0,0 +1,49 @@
+CREATE OR REPLACE FUNCTION public.sync_kanban_level_check(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public', 'extensions'
+AS $function$
+DECLARE
+ is_below BOOLEAN;
+BEGIN
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN;
+ END IF;
+
+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN
+ RETURN;
+ END IF;
+
+ IF (p_new->>'replenishmentSystem') IS DISTINCT FROM 'Transfer'
+ OR (p_new->>'replenishmentLevel') IS NULL
+ THEN
+ RETURN;
+ END IF;
+
+ -- An UPDATE that changes nothing the level check reads does not re-check.
+ IF p_operation = 'UPDATE'
+ AND (p_new->'replenishmentLevel') IS NOT DISTINCT FROM (p_old->'replenishmentLevel')
+ AND (p_new->'replenishmentSystem') IS NOT DISTINCT FROM (p_old->'replenishmentSystem')
+ AND (p_new->'quantity') IS NOT DISTINCT FROM (p_old->'quantity')
+ AND (p_new->'itemId') IS NOT DISTINCT FROM (p_old->'itemId')
+ AND (p_new->'locationId') IS NOT DISTINCT FROM (p_old->'locationId')
+ AND (p_new->'storageUnitId') IS NOT DISTINCT FROM (p_old->'storageUnitId')
+ AND (p_new->'fromStorageUnitId') IS NOT DISTINCT FROM (p_old->'fromStorageUnitId')
+ THEN
+ RETURN;
+ END IF;
+
+ SELECT EXISTS (
+ SELECT 1
+ FROM get_kanban_projected_quantities(p_new->>'companyId', ARRAY[p_new->>'id']) p
+ WHERE p."projectedQuantity" < p."replenishmentLevel"
+ ) INTO is_below;
+
+ IF is_below THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', p_new->>'companyId', 'kanbanIds', jsonb_build_array(p_new->>'id'))
+ );
+ END IF;
+END;
+$function$;
diff --git a/packages/database/src/stock-transfer.test.ts b/packages/database/src/stock-transfer.test.ts
new file mode 100644
index 0000000000..a1ca82f116
--- /dev/null
+++ b/packages/database/src/stock-transfer.test.ts
@@ -0,0 +1,124 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { expect, it } from "vitest";
+import {
+ expandSerialTrackedLines,
+ isBelowReplenishmentLevel,
+ kanbanReplenishmentNote,
+ levelReplenishmentQuantity
+} from "./stock-transfer.ts";
+
+const line = {
+ itemId: "item-1",
+ fromStorageUnitId: "su-a",
+ toStorageUnitId: "su-b"
+};
+
+it("splits a serial-tracked line into one line per serial", () => {
+ const lines = expandSerialTrackedLines([
+ { ...line, quantity: 3, requiresSerialTracking: true }
+ ]);
+ expect(lines).toHaveLength(3);
+ expect(lines.every((l) => l.quantity === 1)).toBe(true);
+});
+
+it("keeps a batch-tracked line whole", () => {
+ const lines = expandSerialTrackedLines([
+ { ...line, quantity: 3, requiresBatchTracking: true }
+ ]);
+ expect(lines).toEqual([
+ { ...line, quantity: 3, requiresBatchTracking: true }
+ ]);
+});
+
+it("keeps an untracked or batch line with a fractional quantity", () => {
+ expect(expandSerialTrackedLines([{ ...line, quantity: 2.5 }])).toEqual([
+ { ...line, quantity: 2.5 }
+ ]);
+ expect(
+ expandSerialTrackedLines([
+ { ...line, quantity: 2.25, requiresBatchTracking: true }
+ ])
+ ).toEqual([{ ...line, quantity: 2.25, requiresBatchTracking: true }]);
+});
+
+it("refuses a serial-tracked line with a fractional quantity", () => {
+ expect(() =>
+ expandSerialTrackedLines([
+ { ...line, quantity: 2.5, requiresSerialTracking: true }
+ ])
+ ).toThrow("A serial-tracked line needs a whole quantity, not 2.5");
+});
+
+it("fires strictly below the replenishment level", () => {
+ expect(isBelowReplenishmentLevel(10, 10)).toBe(false);
+ expect(isBelowReplenishmentLevel(9, 10)).toBe(true);
+});
+
+const noteText = (note: ReturnType<typeof kanbanReplenishmentNote>) =>
+ note.content[0].content[0].text;
+
+it("writes the scan note", () => {
+ const note = kanbanReplenishmentNote({
+ itemReadableId: "MAT-KAPTON",
+ fromStorageUnitName: "A1-L3",
+ toStorageUnitName: "CleanRoom",
+ quantity: 10,
+ unitOfMeasureCode: "EA",
+ signal: { type: "scan", userName: "Jane Doe" }
+ });
+ expect(note.type).toBe("doc");
+ expect(noteText(note)).toBe(
+ "Kanban replenishment — MAT-KAPTON, A1-L3 → CleanRoom, 10 EA. Signal: scan by Jane Doe."
+ );
+});
+
+it("writes the level note", () => {
+ const note = kanbanReplenishmentNote({
+ itemReadableId: "MAT-KAPTON",
+ fromStorageUnitName: "A1-L3",
+ toStorageUnitName: "CleanRoom",
+ quantity: 10,
+ unitOfMeasureCode: "EA",
+ signal: { type: "level", replenishmentLevel: 4, projectedQuantity: 3 }
+ });
+ expect(noteText(note)).toBe(
+ "Kanban replenishment — MAT-KAPTON, A1-L3 → CleanRoom, 10 EA. Signal: level 4 (projected 3)."
+ );
+});
+
+it("leaves out the unit when the item has none", () => {
+ const note = kanbanReplenishmentNote({
+ itemReadableId: "MAT-KAPTON",
+ fromStorageUnitName: "A1-L3",
+ toStorageUnitName: "CleanRoom",
+ quantity: 10,
+ unitOfMeasureCode: null,
+ signal: { type: "level", replenishmentLevel: 4, projectedQuantity: 3 }
+ });
+ expect(noteText(note)).toBe(
+ "Kanban replenishment — MAT-KAPTON, A1-L3 → CleanRoom, 10. Signal: level 4 (projected 3)."
+ );
+});
+
+it("moves the fewest whole kanban quantities that reach the level", () => {
+ // level 20, quantity 5, nothing projected: four quantities in one signal
+ expect(levelReplenishmentQuantity(0, 20, 5)).toBe(20);
+ // 15 projected: one quantity reaches the level exactly
+ expect(levelReplenishmentQuantity(15, 20, 5)).toBe(5);
+ // 9 projected, level 10: one quantity, even though it overshoots
+ expect(levelReplenishmentQuantity(9, 10, 5)).toBe(5);
+ // 1 projected, level 30, quantity 10: three quantities
+ expect(levelReplenishmentQuantity(1, 30, 10)).toBe(30);
+});
+
+it("moves nothing at or above the level", () => {
+ expect(levelReplenishmentQuantity(20, 20, 5)).toBe(0);
+ expect(levelReplenishmentQuantity(25, 20, 5)).toBe(0);
+});
+
+it("ignores float noise in the division", () => {
+ expect(levelReplenishmentQuantity(0.1 + 0.2, 10.3, 5)).toBe(10);
+});
diff --git a/packages/database/src/stock-transfer.ts b/packages/database/src/stock-transfer.ts
new file mode 100644
index 0000000000..7005b3236f
--- /dev/null
+++ b/packages/database/src/stock-transfer.ts
@@ -0,0 +1,126 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+// Pure stock-transfer helpers shared by the ERP's interactive writer
+// (`insertStockTransfer`) and the `kanban-replenish` server function, so both
+// build transfer lines and kanban notes the same way.
+
+import { RoundingMode, round } from "./precision.ts";
+
+export type StockTransferLineDraft = {
+ itemId: string;
+ fromStorageUnitId?: string | null;
+ toStorageUnitId?: string | null;
+ quantity?: number;
+ requiresSerialTracking?: boolean;
+ requiresBatchTracking?: boolean;
+};
+
+/**
+ * A serial-tracked line moves one serial per line, so a line of quantity N is
+ * split into N lines of quantity 1. A serial cannot be split, so a
+ * serial-tracked line with a fractional quantity is refused with an error.
+ * Every other line is kept as it is, fractional quantities included (a batch
+ * or untracked item can move 2.5 kg).
+ */
+export function expandSerialTrackedLines<T extends StockTransferLineDraft>(
+ lines: T[]
+): T[] {
+ return lines.flatMap((line) => {
+ if (!line.requiresSerialTracking || !line.quantity) return [line];
+ if (!Number.isInteger(line.quantity)) {
+ throw new Error(
+ `A serial-tracked line needs a whole quantity, not ${String(line.quantity)}`
+ );
+ }
+ if (line.quantity === 1) return [line];
+ return Array.from({ length: line.quantity }, () => ({
+ ...line,
+ quantity: 1
+ }));
+ });
+}
+
+/**
+ * The level signal fires strictly below the level: a To storage unit that
+ * holds exactly the level is full enough.
+ */
+export function isBelowReplenishmentLevel(
+ projectedQuantity: number,
+ replenishmentLevel: number
+): boolean {
+ return projectedQuantity < replenishmentLevel;
+}
+
+/**
+ * How much one level signal moves: the fewest whole kanban quantities that
+ * bring the projected quantity back to the level. A level of 20 with a
+ * quantity of 5 and nothing projected moves 20 in one transfer, not 5 now and
+ * 5 more on each later signal. Returns 0 when nothing is below the level.
+ */
+export function levelReplenishmentQuantity(
+ projectedQuantity: number,
+ replenishmentLevel: number,
+ quantity: number
+): number {
+ if (quantity <= 0) return 0;
+ if (!isBelowReplenishmentLevel(projectedQuantity, replenishmentLevel)) {
+ return 0;
+ }
+ // Round to the internal scale first, so float noise in the division
+ // (5.000000001) does not add a whole extra kanban quantity.
+ const quantities = round(
+ round((replenishmentLevel - projectedQuantity) / quantity),
+ 0,
+ RoundingMode.Up
+ );
+ return quantities * quantity;
+}
+
+export const KANBAN_REPLENISHMENT_NOTE_PREFIX = "Kanban replenishment";
+
+export type KanbanReplenishmentNoteInput = {
+ itemReadableId: string;
+ fromStorageUnitName: string;
+ toStorageUnitName: string;
+ quantity: number;
+ unitOfMeasureCode: string | null;
+ signal:
+ | { type: "scan"; userName: string }
+ | {
+ type: "level";
+ replenishmentLevel: number;
+ projectedQuantity: number;
+ };
+};
+
+export type KanbanReplenishmentNote = {
+ type: "doc";
+ content: [
+ {
+ type: "paragraph";
+ content: [{ type: "text"; text: string }];
+ }
+ ];
+};
+
+/**
+ * The Tiptap document written to `stockTransfer.notes`. It tells a reader
+ * where the transfer came from; the durable origin is `stockTransfer.kanbanId`.
+ */
+export function kanbanReplenishmentNote(
+ input: KanbanReplenishmentNoteInput
+): KanbanReplenishmentNote {
+ const unit = input.unitOfMeasureCode ? ` ${input.unitOfMeasureCode}` : "";
+ const signal =
+ input.signal.type === "scan"
+ ? `scan by ${input.signal.userName}`
+ : `level ${String(input.signal.replenishmentLevel)} (projected ${String(input.signal.projectedQuantity)})`;
+ const text = `${KANBAN_REPLENISHMENT_NOTE_PREFIX} — ${input.itemReadableId}, ${input.fromStorageUnitName} → ${input.toStorageUnitName}, ${String(input.quantity)}${unit}. Signal: ${signal}.`;
+
+ return {
+ type: "doc",
+ content: [{ type: "paragraph", content: [{ type: "text", text }] }]
+ };
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index c8010dbbf0..feccbd922e 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -28737,6 +28737,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanbans.fromStorageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanbans.replenishmentLevel"
+ },
{
$ref: "#/parameters/rowFilter.kanbans.name"
},
@@ -91581,6 +91584,9 @@ export default {
{
$ref: "#/parameters/rowFilter.stockTransfer.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.stockTransfer.kanbanId"
+ },
{
$ref: "#/parameters/select"
},
@@ -91682,6 +91688,9 @@ export default {
{
$ref: "#/parameters/rowFilter.stockTransfer.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.stockTransfer.kanbanId"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -91737,6 +91746,9 @@ export default {
{
$ref: "#/parameters/rowFilter.stockTransfer.tags"
},
+ {
+ $ref: "#/parameters/rowFilter.stockTransfer.kanbanId"
+ },
{
$ref: "#/parameters/body.stockTransfer"
},
@@ -103164,6 +103176,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.replenishmentLevel"
+ },
{
$ref: "#/parameters/select"
},
@@ -103280,6 +103295,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.replenishmentLevel"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -103350,6 +103368,9 @@ export default {
{
$ref: "#/parameters/rowFilter.kanban.fromStorageUnitId"
},
+ {
+ $ref: "#/parameters/rowFilter.kanban.replenishmentLevel"
+ },
{
$ref: "#/parameters/body.kanban"
},
@@ -106141,6 +106162,51 @@ export default {
tags: ["(rpc) xid"]
}
},
+ "/rpc/sync_kanban_level_check": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_new: {
+ format: "jsonb"
+ },
+ p_old: {
+ format: "jsonb"
+ },
+ p_operation: {
+ format: "text",
+ type: "string"
+ },
+ p_table: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_table", "p_operation", "p_new", "p_old"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) sync_kanban_level_check"]
+ }
+ },
"/rpc/get_method_tree": {
get: {
parameters: [
@@ -112611,6 +112677,77 @@ export default {
tags: ["(rpc) get_my_claim"]
}
},
+ "/rpc/get_kanban_projected_quantities": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "company_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text[]",
+ in: "query",
+ name: "kanban_ids",
+ required: false,
+ type: "string"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_kanban_projected_quantities"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ company_id: {
+ format: "text",
+ type: "string"
+ },
+ kanban_ids: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ }
+ },
+ required: ["company_id"],
+ type: "object"
+ }
+ },
+ {
+ $ref: "#/parameters/preferParams"
+ }
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json"
+ ],
+ responses: {
+ "200": {
+ description: "OK"
+ }
+ },
+ tags: ["(rpc) get_kanban_projected_quantities"]
+ }
+ },
"/rpc/delete_old_audit_logs": {
post: {
parameters: [
@@ -130231,6 +130368,10 @@ export default {
format: "text",
type: "string"
},
+ replenishmentLevel: {
+ format: "numeric",
+ type: "number"
+ },
name: {
format: "text",
type: "string"
@@ -160324,6 +160465,10 @@ export default {
type: "string"
},
type: "array"
+ },
+ kanbanId: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -166030,6 +166175,12 @@ export default {
"Note:\nThis is a Foreign Key to `storageUnit.id`.<fk table='storageUnit' column='id'/>",
format: "text",
type: "string"
+ },
+ replenishmentLevel: {
+ description:
+ 'Transfer kanbans only. When the projected quantity at the To storage unit is below this level, Carbon creates a Released stock transfer for "quantity". NULL = scan-only.',
+ format: "numeric",
+ type: "number"
}
},
type: "object"
@@ -181317,6 +181468,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.kanbans.replenishmentLevel": {
+ name: "replenishmentLevel",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.kanbans.name": {
name: "name",
required: false,
@@ -214900,6 +215057,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.stockTransfer.kanbanId": {
+ name: "kanbanId",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.exchangeRateOverride": {
name: "exchangeRateOverride",
description: "exchangeRateOverride",
@@ -221186,6 +221349,14 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.kanban.replenishmentLevel": {
+ name: "replenishmentLevel",
+ description:
+ 'Transfer kanbans only. When the projected quantity at the To storage unit is below this level, Carbon creates a Released stock transfer for "quantity". NULL = scan-only.',
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.salesOrderTransaction": {
name: "salesOrderTransaction",
description: "salesOrderTransaction",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5c0df30b0f..1a5fa56fc2 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -30794,6 +30794,7 @@ export type Database = {
locationId: string
purchaseUnitOfMeasureCode: string | null
quantity: number
+ replenishmentLevel: number | null
replenishmentSystem: Database["public"]["Enums"]["kanbanReplenishmentSystem"]
storageUnitId: string | null
supplierId: string | null
@@ -30815,6 +30816,7 @@ export type Database = {
locationId: string
purchaseUnitOfMeasureCode?: string | null
quantity: number
+ replenishmentLevel?: number | null
replenishmentSystem?: Database["public"]["Enums"]["kanbanReplenishmentSystem"]
storageUnitId?: string | null
supplierId?: string | null
@@ -30836,6 +30838,7 @@ export type Database = {
locationId?: string
purchaseUnitOfMeasureCode?: string | null
quantity?: number
+ replenishmentLevel?: number | null
replenishmentSystem?: Database["public"]["Enums"]["kanbanReplenishmentSystem"]
storageUnitId?: string | null
supplierId?: string | null
@@ -63506,6 +63509,7 @@ export type Database = {
createdBy: string
customFields: Json | null
id: string
+ kanbanId: string | null
locationId: string
notes: Json | null
status: Database["public"]["Enums"]["stockTransferStatus"]
@@ -63522,6 +63526,7 @@ export type Database = {
createdBy: string
customFields?: Json | null
id?: string
+ kanbanId?: string | null
locationId: string
notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
@@ -63538,6 +63543,7 @@ export type Database = {
createdBy?: string
customFields?: Json | null
id?: string
+ kanbanId?: string | null
locationId?: string
notes?: Json | null
status?: Database["public"]["Enums"]["stockTransferStatus"]
@@ -63645,6 +63651,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "stockTransfer_kanbanId_fkey"
+ columns: ["kanbanId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "kanban"
+ referencedColumns: ["id", "companyId"]
+ },
+ {
+ foreignKeyName: "stockTransfer_kanbanId_fkey"
+ columns: ["kanbanId", "companyId"]
+ isOneToOne: false
+ referencedRelation: "kanbans"
+ referencedColumns: ["id", "companyId"]
+ },
{
foreignKeyName: "stockTransfer_locationId_fkey"
columns: ["locationId"]
@@ -79374,6 +79394,7 @@ export type Database = {
purchaseUnitOfMeasureCode: string | null
quantity: number | null
readableIdWithRevision: string | null
+ replenishmentLevel: number | null
replenishmentSystem:
| Database["public"]["Enums"]["kanbanReplenishmentSystem"]
| null
@@ -92081,6 +92102,14 @@ export type Database = {
thumbnailPath: string
}[]
}
+ get_kanban_projected_quantities: {
+ Args: { company_id: string; kanban_ids?: string[] }
+ Returns: {
+ kanbanId: string
+ projectedQuantity: number
+ replenishmentLevel: number
+ }[]
+ }
get_lineside_credit: {
Args: {
p_company_id: string
@@ -93804,6 +93833,10 @@ export type Database = {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
}
+ sync_kanban_level_check: {
+ Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
+ Returns: undefined
+ }
sync_on_maintenance_dispatch_complete: {
Args: { p_new: Json; p_old: Json; p_operation: string; p_table: string }
Returns: undefined
diff --git a/packages/database/supabase/migrations/20261012232517_kanban-replenishment-level.sql b/packages/database/supabase/migrations/20261012232517_kanban-replenishment-level.sql
new file mode 100644
index 0000000000..f8950449ca
--- /dev/null
+++ b/packages/database/supabase/migrations/20261012232517_kanban-replenishment-level.sql
@@ -0,0 +1,162 @@
+-- Kanban replenishment level: a Transfer kanban fires when the projected
+-- quantity at its To storage unit is below this level.
+-- Spec: .ai/specs/2026-10-06-kanban-internal-replenishment-level.md
+
+-- 1. The level on the kanban
+ALTER TABLE "kanban" ADD COLUMN IF NOT EXISTS "replenishmentLevel" NUMERIC;
+
+ALTER TABLE "kanban" DROP CONSTRAINT IF EXISTS "kanban_replenishmentLevel_check";
+ALTER TABLE "kanban"
+ ADD CONSTRAINT "kanban_replenishmentLevel_check"
+ CHECK ("replenishmentLevel" IS NULL OR "replenishmentLevel" >= 0);
+
+COMMENT ON COLUMN "kanban"."replenishmentLevel" IS
+ 'Transfer kanbans only. When the projected quantity at the To storage unit is below this level, Carbon creates a Released stock transfer for "quantity". NULL = scan-only.';
+
+-- A Transfer kanban must not feed itself. The zod refine exists; this stops API writes.
+ALTER TABLE "kanban" DROP CONSTRAINT IF EXISTS "kanban_transfer_distinct_storage_units_check";
+ALTER TABLE "kanban"
+ ADD CONSTRAINT "kanban_transfer_distinct_storage_units_check"
+ CHECK (
+ "replenishmentSystem" <> 'Transfer'
+ OR "fromStorageUnitId" IS NULL
+ OR "storageUnitId" IS NULL
+ OR "fromStorageUnitId" <> "storageUnitId"
+ );
+
+-- From a ledger row to its armed kanbans
+CREATE INDEX IF NOT EXISTS "kanban_level_lookup_idx"
+ ON "kanban" ("companyId", "itemId", "storageUnitId")
+ WHERE "replenishmentSystem" = 'Transfer' AND "replenishmentLevel" IS NOT NULL;
+
+-- 2. The kanbans view expands k.* at creation, so recreate it to expose the new column.
+DROP VIEW IF EXISTS "kanbans";
+CREATE VIEW "kanbans" WITH(SECURITY_INVOKER=true) AS
+SELECT
+ k.*,
+ i.name,
+ i."readableIdWithRevision",
+ j."jobId" as "jobReadableId",
+ l.name as "locationName",
+ s.name as "storageUnitName",
+ fs.name as "fromStorageUnitName",
+ su.name as "supplierName",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath"
+FROM "kanban" k
+JOIN "item" i ON k."itemId" = i."id"
+LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+JOIN "location" l ON k."locationId" = l."id"
+LEFT JOIN "storageUnit" s ON k."storageUnitId" = s."id"
+LEFT JOIN "storageUnit" fs ON k."fromStorageUnitId" = fs."id"
+LEFT JOIN "supplier" su ON k."supplierId" = su."id"
+LEFT JOIN "job" j ON k."jobId" = j."id";
+
+-- 3. The origin on the stock transfer
+ALTER TABLE "stockTransfer" ADD COLUMN IF NOT EXISTS "kanbanId" TEXT;
+
+ALTER TABLE "stockTransfer" DROP CONSTRAINT IF EXISTS "stockTransfer_kanbanId_fkey";
+ALTER TABLE "stockTransfer"
+ ADD CONSTRAINT "stockTransfer_kanbanId_fkey"
+ FOREIGN KEY ("kanbanId", "companyId") REFERENCES "kanban" ("id", "companyId")
+ ON DELETE SET NULL ("kanbanId");
+
+CREATE INDEX IF NOT EXISTS "stockTransfer_kanbanId_idx"
+ ON "stockTransfer" ("kanbanId") WHERE "kanbanId" IS NOT NULL;
+
+-- 4. Projected quantity for the armed kanbans of one company.
+-- kanban_ids NULL = every armed kanban of the company.
+-- On-hand uses item_ledger_on_hand_contribution, the itemStockQuantities definition.
+-- Inbound counts every transfer that is not Completed. Draft counts too: a kanban
+-- transfer reopened to Draft for an edit is still supply, or the next signal
+-- would create a duplicate for the same shortfall.
+CREATE OR REPLACE FUNCTION get_kanban_projected_quantities(
+ company_id TEXT,
+ kanban_ids TEXT[] DEFAULT NULL
+)
+RETURNS TABLE ("kanbanId" TEXT, "replenishmentLevel" NUMERIC, "projectedQuantity" NUMERIC)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public, pg_temp
+AS $$
+ SELECT
+ k."id",
+ k."replenishmentLevel",
+ COALESCE(on_hand."quantity", 0) + COALESCE(inbound."quantity", 0)
+ FROM "kanban" k
+ LEFT JOIN LATERAL (
+ SELECT SUM(item_ledger_on_hand_contribution(il."quantity", il."trackedEntityStatus")) AS "quantity"
+ FROM "itemLedger" il
+ WHERE il."companyId" = k."companyId"
+ AND il."locationId" = k."locationId"
+ AND il."itemId" = k."itemId"
+ AND il."storageUnitId" = k."storageUnitId"
+ ) on_hand ON true
+ LEFT JOIN LATERAL (
+ SELECT SUM(stl."outstandingQuantity") AS "quantity"
+ FROM "stockTransferLine" stl
+ JOIN "stockTransfer" st
+ ON st."id" = stl."stockTransferId" AND st."companyId" = stl."companyId"
+ WHERE stl."companyId" = k."companyId"
+ AND st."status" <> 'Completed'
+ AND stl."itemId" = k."itemId"
+ AND stl."toStorageUnitId" = k."storageUnitId"
+ ) inbound ON true
+ WHERE k."companyId" = company_id
+ AND (kanban_ids IS NULL OR k."id" = ANY (kanban_ids))
+ AND k."replenishmentSystem" = 'Transfer'
+ AND k."replenishmentLevel" IS NOT NULL
+ AND k."fromStorageUnitId" IS NOT NULL
+ AND k."storageUnitId" IS NOT NULL;
+$$;
+
+-- 5. Backstop sweep: every armed kanban below its level, one row per company.
+CREATE OR REPLACE FUNCTION util.kanban_level_breaches()
+RETURNS TABLE ("companyId" TEXT, "kanbanIds" TEXT[])
+LANGUAGE sql
+STABLE
+SECURITY DEFINER
+SET search_path = public
+AS $$
+ SELECT c."companyId", array_agg(p."kanbanId" ORDER BY p."kanbanId")
+ FROM (
+ SELECT DISTINCT "companyId" FROM "kanban"
+ WHERE "replenishmentSystem" = 'Transfer' AND "replenishmentLevel" IS NOT NULL
+ ) c
+ CROSS JOIN LATERAL get_kanban_projected_quantities(c."companyId") p
+ WHERE p."projectedQuantity" < p."replenishmentLevel"
+ GROUP BY c."companyId";
+$$;
+
+CREATE OR REPLACE FUNCTION util.sweep_kanban_levels()
+RETURNS void
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public
+AS $$
+DECLARE
+ breach RECORD;
+BEGIN
+ FOR breach IN SELECT * FROM util.kanban_level_breaches() LOOP
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', breach."companyId", 'kanbanIds', to_jsonb(breach."kanbanIds"))
+ );
+ END LOOP;
+END;
+$$;
+
+REVOKE ALL ON FUNCTION util.kanban_level_breaches() FROM PUBLIC;
+REVOKE ALL ON FUNCTION util.sweep_kanban_levels() FROM PUBLIC;
+
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM cron.job WHERE jobname = 'kanban-level-sweeper') THEN
+ PERFORM cron.unschedule('kanban-level-sweeper');
+ END IF;
+ PERFORM cron.schedule('kanban-level-sweeper', '7 * * * *', 'SELECT util.sweep_kanban_levels();');
+END;
+$$;
diff --git a/packages/database/supabase/migrations/20261012232520_kanban-level-check-triggers.sql b/packages/database/supabase/migrations/20261012232520_kanban-level-check-triggers.sql
new file mode 100644
index 0000000000..7ccc03004e
--- /dev/null
+++ b/packages/database/supabase/migrations/20261012232520_kanban-level-check-triggers.sql
@@ -0,0 +1,123 @@
+-- Generated by `pnpm --filter @carbon/database authz migration` from packages/database/src/authz. Do not edit.
+
+-- Ships these rules to databases where `authz sync` does not run after migrations yet.
+
+CREATE OR REPLACE FUNCTION public.queue_kanban_level_checks()
+ RETURNS trigger
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+DECLARE
+ touched JSONB;
+ target RECORD;
+ below TEXT[];
+BEGIN
+ -- A seed, a restore or a test fixture loads ledger rows in bulk.
+ -- The hourly sweep (util.sweep_kanban_levels) covers those.
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- Only batched_new exists on INSERT and only batched_old on DELETE.
+ IF TG_OP = 'DELETE' THEN
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_old
+ WHERE "storageUnitId" IS NOT NULL;
+ ELSE
+ SELECT jsonb_agg(DISTINCT jsonb_build_object(
+ 'companyId', "companyId", 'itemId', "itemId", 'storageUnitId', "storageUnitId"))
+ INTO touched
+ FROM batched_new
+ WHERE "storageUnitId" IS NOT NULL;
+ END IF;
+
+ IF touched IS NULL THEN
+ RETURN NULL;
+ END IF;
+
+ FOR target IN
+ SELECT k."companyId", array_agg(DISTINCT k."id") AS "kanbanIds"
+ FROM jsonb_to_recordset(touched) AS t("companyId" TEXT, "itemId" TEXT, "storageUnitId" TEXT)
+ JOIN "kanban" k
+ ON k."companyId" = t."companyId"
+ AND k."itemId" = t."itemId"
+ AND k."storageUnitId" = t."storageUnitId"
+ WHERE k."replenishmentSystem" = 'Transfer'
+ AND k."replenishmentLevel" IS NOT NULL
+ GROUP BY k."companyId"
+ LOOP
+ SELECT array_agg(p."kanbanId" ORDER BY p."kanbanId")
+ INTO below
+ FROM get_kanban_projected_quantities(target."companyId", target."kanbanIds") p
+ WHERE p."projectedQuantity" < p."replenishmentLevel";
+
+ IF below IS NOT NULL THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', target."companyId", 'kanbanIds', to_jsonb(below))
+ );
+ END IF;
+ END LOOP;
+
+ RETURN NULL;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.sync_kanban_level_check(p_table text, p_operation text, p_new jsonb, p_old jsonb)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public', 'extensions'
+AS $function$
+DECLARE
+ is_below BOOLEAN;
+BEGIN
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN;
+ END IF;
+
+ IF p_operation NOT IN ('INSERT', 'UPDATE') THEN
+ RETURN;
+ END IF;
+
+ IF (p_new->>'replenishmentSystem') IS DISTINCT FROM 'Transfer'
+ OR (p_new->>'replenishmentLevel') IS NULL
+ THEN
+ RETURN;
+ END IF;
+
+ -- An UPDATE that changes nothing the level check reads does not re-check.
+ IF p_operation = 'UPDATE'
+ AND (p_new->'replenishmentLevel') IS NOT DISTINCT FROM (p_old->'replenishmentLevel')
+ AND (p_new->'replenishmentSystem') IS NOT DISTINCT FROM (p_old->'replenishmentSystem')
+ AND (p_new->'quantity') IS NOT DISTINCT FROM (p_old->'quantity')
+ AND (p_new->'itemId') IS NOT DISTINCT FROM (p_old->'itemId')
+ AND (p_new->'locationId') IS NOT DISTINCT FROM (p_old->'locationId')
+ AND (p_new->'storageUnitId') IS NOT DISTINCT FROM (p_old->'storageUnitId')
+ AND (p_new->'fromStorageUnitId') IS NOT DISTINCT FROM (p_old->'fromStorageUnitId')
+ THEN
+ RETURN;
+ END IF;
+
+ SELECT EXISTS (
+ SELECT 1
+ FROM get_kanban_projected_quantities(p_new->>'companyId', ARRAY[p_new->>'id']) p
+ WHERE p."projectedQuantity" < p."replenishmentLevel"
+ ) INTO is_below;
+
+ IF is_below THEN
+ PERFORM util.send_inngest_event(
+ 'carbon/kanban.level-check',
+ jsonb_build_object('companyId', p_new->>'companyId', 'kanbanIds', jsonb_build_array(p_new->>'id'))
+ );
+ END IF;
+END;
+$function$;
+
+-- event triggers (packages/database/src/event-system/attachments.ts)
+SET lock_timeout = '5s';
+SELECT set_event_triggers('itemLedger', ARRAY[]::text[], ARRAY[]::text[], false, ARRAY['apply_item_stock_quantities', 'broadcast_table_changes', 'queue_kanban_level_checks']::text[]);
+SELECT set_event_triggers('kanban', ARRAY[]::text[], ARRAY['sync_kanban_level_check']::text[], false, ARRAY[]::text[]);
+RESET lock_timeout;
diff --git a/packages/database/supabase/tests/kanban-replenishment-level.test.sql b/packages/database/supabase/tests/kanban-replenishment-level.test.sql
new file mode 100644
index 0000000000..fb5998a318
--- /dev/null
+++ b/packages/database/supabase/tests/kanban-replenishment-level.test.sql
@@ -0,0 +1,163 @@
+-- The kanban replenishment level (20261012232517_kanban-replenishment-level.sql):
+-- the projected quantity at a Transfer kanban's To storage unit, the backstop
+-- breach set, and the two CHECK constraints on the kanban.
+-- Run from the repository root against an existing local database that has at
+-- least one company with two storage units at one location and one item:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/kanban-replenishment-level.test.sql
+-- Every fixture row is confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL "app.sync_in_progress" = 'true';
+SET LOCAL statement_timeout = '30s';
+
+CREATE FUNCTION pg_temp.expect(label text, actual boolean, expected boolean)
+RETURNS void LANGUAGE plpgsql AS $fn$
+BEGIN
+ IF actual IS DISTINCT FROM expected THEN
+ RAISE EXCEPTION '%: expected %, got %', label, expected, actual;
+ END IF;
+END;
+$fn$;
+
+DO $proof$
+DECLARE
+ company text;
+ location text;
+ a text;
+ b text;
+ item text;
+ kanban_id text;
+ scan_only_id text;
+ transfer_id text;
+ line_id text;
+ raised boolean;
+BEGIN
+ -- Fixture: two storage units at one location, and an item with no stock
+ -- and no inbound transfer at the To unit, so the projection starts at 0.
+ SELECT sa."companyId", sa."locationId", sa."id", sb."id", i."id"
+ INTO company, location, a, b, item
+ FROM "storageUnit" sa
+ JOIN "storageUnit" sb
+ ON sb."companyId" = sa."companyId"
+ AND sb."locationId" = sa."locationId"
+ AND sb."id" <> sa."id"
+ JOIN "item" i ON i."companyId" = sa."companyId"
+ WHERE NOT EXISTS (
+ SELECT 1 FROM "itemLedger" il
+ WHERE il."itemId" = i."id" AND il."storageUnitId" = sb."id"
+ )
+ AND NOT EXISTS (
+ SELECT 1 FROM "stockTransferLine" stl
+ WHERE stl."itemId" = i."id" AND stl."toStorageUnitId" = sb."id"
+ )
+ ORDER BY sa."companyId", sa."id", sb."id", i."id"
+ LIMIT 1;
+
+ IF a IS NULL OR b IS NULL OR item IS NULL THEN
+ RAISE EXCEPTION 'test needs a seeded company';
+ END IF;
+
+ INSERT INTO "kanban"
+ ("itemId", "replenishmentSystem", "quantity", "locationId", "storageUnitId",
+ "fromStorageUnitId", "replenishmentLevel", "companyId", "createdBy")
+ VALUES (item, 'Transfer', 5, location, b, a, 10, company, 'system')
+ RETURNING "id" INTO kanban_id;
+
+ INSERT INTO "itemLedger"
+ ("entryType", "documentType", "itemId", "locationId", "storageUnitId", "quantity", "companyId", "createdBy")
+ VALUES ('Positive Adjmt.', 'Inventory Receipt', item, location, b, 12, company, 'system');
+
+ -- 1. On-hand 12, nothing inbound.
+ PERFORM pg_temp.expect('projected: 12 on hand',
+ (SELECT "projectedQuantity" = 12
+ FROM get_kanban_projected_quantities(company, ARRAY[kanban_id])), true);
+
+ -- 2. 12 is not below 10.
+ PERFORM pg_temp.expect('breaches: not below the level',
+ EXISTS (SELECT 1 FROM util.kanban_level_breaches() br
+ WHERE kanban_id = ANY (br."kanbanIds")), false);
+
+ -- 3. Consume 3: projected 9 is below 10.
+ INSERT INTO "itemLedger"
+ ("entryType", "documentType", "itemId", "locationId", "storageUnitId", "quantity", "companyId", "createdBy")
+ VALUES ('Negative Adjmt.', 'Inventory Receipt', item, location, b, -3, company, 'system');
+
+ PERFORM pg_temp.expect('breaches: projected 9 is below 10',
+ EXISTS (SELECT 1 FROM util.kanban_level_breaches() br
+ WHERE kanban_id = ANY (br."kanbanIds")), true);
+
+ -- 4. A Released transfer of 5 to b: projected 14.
+ INSERT INTO "stockTransfer"
+ ("stockTransferId", "locationId", "status", "companyId", "createdBy", "kanbanId")
+ VALUES ('KB-TEST-1', location, 'Released', company, 'system', kanban_id)
+ RETURNING "id" INTO transfer_id;
+
+ INSERT INTO "stockTransferLine"
+ ("stockTransferId", "itemId", "fromStorageUnitId", "toStorageUnitId", "quantity", "companyId", "createdBy")
+ VALUES (transfer_id, item, a, b, 5, company, 'system')
+ RETURNING "id" INTO line_id;
+
+ PERFORM pg_temp.expect('projected: 9 on hand + 5 inbound',
+ (SELECT "projectedQuantity" = 14
+ FROM get_kanban_projected_quantities(company, ARRAY[kanban_id])), true);
+ PERFORM pg_temp.expect('breaches: inbound transfer covers the level',
+ EXISTS (SELECT 1 FROM util.kanban_level_breaches() br
+ WHERE kanban_id = ANY (br."kanbanIds")), false);
+
+ -- 4b. Reopened to Draft, the transfer is still supply (no duplicate).
+ UPDATE "stockTransfer" SET "status" = 'Draft' WHERE "id" = transfer_id;
+ PERFORM pg_temp.expect('projected: a Draft transfer still counts',
+ (SELECT "projectedQuantity" = 14
+ FROM get_kanban_projected_quantities(company, ARRAY[kanban_id])), true);
+ UPDATE "stockTransfer" SET "status" = 'Released' WHERE "id" = transfer_id;
+
+ -- 5. Pick the line: the 5 move from inbound to on-hand.
+ UPDATE "stockTransferLine" SET "pickedQuantity" = 5 WHERE "id" = line_id;
+ INSERT INTO "itemLedger"
+ ("entryType", "documentType", "itemId", "locationId", "storageUnitId", "quantity", "companyId", "createdBy")
+ VALUES
+ ('Transfer', 'Direct Transfer', item, location, a, -5, company, 'system'),
+ ('Transfer', 'Direct Transfer', item, location, b, 5, company, 'system');
+
+ PERFORM pg_temp.expect('projected: picked line counts once',
+ (SELECT "projectedQuantity" = 14
+ FROM get_kanban_projected_quantities(company, ARRAY[kanban_id])), true);
+
+ -- 6. Completing the transfer changes nothing.
+ UPDATE "stockTransfer" SET "status" = 'Completed' WHERE "id" = transfer_id;
+
+ PERFORM pg_temp.expect('projected: completed transfer',
+ (SELECT "projectedQuantity" = 14
+ FROM get_kanban_projected_quantities(company, ARRAY[kanban_id])), true);
+
+ -- 7. A scan-only kanban (no level) is not projected.
+ INSERT INTO "kanban"
+ ("itemId", "replenishmentSystem", "quantity", "locationId", "storageUnitId",
+ "fromStorageUnitId", "replenishmentLevel", "companyId", "createdBy")
+ VALUES (item, 'Transfer', 5, location, b, a, NULL, company, 'system')
+ RETURNING "id" INTO scan_only_id;
+
+ PERFORM pg_temp.expect('projected: scan-only kanban has no row',
+ EXISTS (SELECT 1 FROM get_kanban_projected_quantities(company, ARRAY[scan_only_id])), false);
+
+ -- 8. A Transfer kanban must not feed itself.
+ raised := false;
+ BEGIN
+ UPDATE "kanban" SET "fromStorageUnitId" = "storageUnitId" WHERE "id" = kanban_id;
+ EXCEPTION WHEN check_violation THEN
+ raised := true;
+ END;
+ PERFORM pg_temp.expect('check: from = to is refused', raised, true);
+
+ -- 9. The level cannot be negative.
+ raised := false;
+ BEGIN
+ UPDATE "kanban" SET "replenishmentLevel" = -1 WHERE "id" = kanban_id;
+ EXCEPTION WHEN check_violation THEN
+ raised := true;
+ END;
+ PERFORM pg_temp.expect('check: negative level is refused', raised, true);
+END;
+$proof$;
+
+ROLLBACK;
diff --git a/packages/documents/src/pdf/KanbanLabelPDF.tsx b/packages/documents/src/pdf/KanbanLabelPDF.tsx
index c1364270cc..2ddc310a06 100644
--- a/packages/documents/src/pdf/KanbanLabelPDF.tsx
+++ b/packages/documents/src/pdf/KanbanLabelPDF.tsx
@@ -18,6 +18,7 @@ interface KanbanLabel {
storageUnitName?: string | null;
fromStorageUnitName?: string | null;
quantity: number;
+ replenishmentLevel?: number | null;
unitOfMeasureCode?: string | null;
thumbnail?: string | null;
}
@@ -224,6 +225,20 @@ const KanbanLabelPDF = ({
? ` ${label.unitOfMeasureCode}`
: ""}
</Text>
+ {label.replenishmentLevel != null && (
+ <Text
+ style={{
+ ...tw("text-center"),
+ fontSize: "16pt",
+ fontWeight: "bold"
+ }}
+ >
+ {/* The level is in stock units at the To
+ storage unit; unitOfMeasureCode is the
+ purchase unit, so MIN prints no unit. */}
+ MIN: {label.replenishmentLevel}
+ </Text>
+ )}
</View>
</View>
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index 5e561be7a8..6caedcc7f5 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -68,6 +68,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `send-push` | `carbon/send-push` (one per `pushSubscription` row, fanned out by `notify` for every notification, like in-app, when `isPushConfigured()`) | Send one Web Push with `web-push`; deletes the row on 404/410, logs a warning and keeps it on 401/403 (another VAPID key, or Apple refusing our token), retries 429/5xx, fails other 4xx (`pushDeliveryOutcome`) |
| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic |
| `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers |
+| `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls the `kanban-replenish` server function in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |
| `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |
| `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index cb4e113fae..45a9ab5ae5 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -5,7 +5,7 @@
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-12T23:12:49.551Z",
+ "exportedAt": "2026-10-13T00:04:42.459Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -2269,26 +2269,6 @@
"updatedBy"
]
},
- {
- "name": "stockTransfer",
- "rows": 0,
- "columns": [
- "id",
- "stockTransferId",
- "locationId",
- "status",
- "completedAt",
- "companyId",
- "createdAt",
- "createdBy",
- "updatedAt",
- "updatedBy",
- "notes",
- "assignee",
- "customFields",
- "tags"
- ]
- },
{
"name": "storageType",
"rows": 0,
@@ -5362,29 +5342,6 @@
"substitutionFactor"
]
},
- {
- "name": "stockTransferLine",
- "rows": 0,
- "columns": [
- "id",
- "stockTransferId",
- "jobId",
- "jobMaterialId",
- "itemId",
- "fromStorageUnitId",
- "toStorageUnitId",
- "quantity",
- "pickedQuantity",
- "trackedEntityId",
- "requiresBatchTracking",
- "requiresSerialTracking",
- "companyId",
- "createdAt",
- "createdBy",
- "updatedAt",
- "updatedBy"
- ]
- },
{
"name": "jobMaterialStep",
"rows": 0,
@@ -5703,7 +5660,52 @@
"autoStartJob",
"completedBarcodeOverride",
"jobId",
- "fromStorageUnitId"
+ "fromStorageUnitId",
+ "replenishmentLevel"
+ ]
+ },
+ {
+ "name": "stockTransfer",
+ "rows": 0,
+ "columns": [
+ "id",
+ "stockTransferId",
+ "locationId",
+ "status",
+ "completedAt",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy",
+ "notes",
+ "assignee",
+ "customFields",
+ "tags",
+ "kanbanId"
+ ]
+ },
+ {
+ "name": "stockTransferLine",
+ "rows": 0,
+ "columns": [
+ "id",
+ "stockTransferId",
+ "jobId",
+ "jobMaterialId",
+ "itemId",
+ "fromStorageUnitId",
+ "toStorageUnitId",
+ "quantity",
+ "pickedQuantity",
+ "trackedEntityId",
+ "requiresBatchTracking",
+ "requiresSerialTracking",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy"
]
},
{
diff --git a/packages/jobs/src/inngest/functions/tasks/index.ts b/packages/jobs/src/inngest/functions/tasks/index.ts
index 8882b069b7..0f4ea16af7 100644
--- a/packages/jobs/src/inngest/functions/tasks/index.ts
+++ b/packages/jobs/src/inngest/functions/tasks/index.ts
@@ -18,6 +18,7 @@ export {
companyTemplateRevertFunction
} from "./company-template";
export { invoiceAutomateFunction } from "./invoice-automate";
+export { kanbanLevelCheckFunction } from "./kanban-level-check";
export { modelCompactFunction } from "./model-compact";
export { modelOptimizeFunction } from "./model-optimize";
export { modelThumbnailFunction } from "./model-thumbnail";
diff --git a/packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts b/packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts
new file mode 100644
index 0000000000..335352252e
--- /dev/null
+++ b/packages/jobs/src/inngest/functions/tasks/kanban-level-check.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { serverFns } from "@carbon/server-functions";
+import { getJobDatabaseClient } from "../../../db";
+import { inngest } from "../../client";
+
+/**
+ * Replenishes Transfer kanbans whose To storage unit is below its
+ * replenishment level. Only the database sends the event: the `itemLedger`
+ * statement handler, the `kanban` interceptor and the hourly sweep
+ * (`util.sweep_kanban_levels`). `kanban-replenish` re-checks the level inside
+ * its own transaction, so a stale or duplicate event writes nothing.
+ *
+ * No `debounce`: the local Inngest dev server cannot run it.
+ */
+export const kanbanLevelCheckFunction = inngest.createFunction(
+ {
+ id: "kanban-level-check",
+ retries: 3,
+ concurrency: {
+ limit: 1,
+ scope: "env",
+ key: '"kanban-level:" + event.data.companyId'
+ }
+ },
+ { event: "carbon/kanban.level-check" },
+ async ({ event, step, logger }) => {
+ const { companyId, kanbanIds } = event.data;
+
+ const result = await step.run("replenish", () =>
+ serverFns
+ .system({ db: getJobDatabaseClient(), companyId, userId: "system" })
+ .invokeOrThrow("kanban-replenish", { mode: "level", kanbanIds })
+ );
+
+ for (const outcome of result.results) {
+ if (outcome.outcome === "created") {
+ logger.info("Kanban replenishment created", {
+ companyId,
+ kanbanId: outcome.kanbanId,
+ stockTransferId: outcome.stockTransferId
+ });
+ } else if (outcome.outcome === "invalid") {
+ logger.warn("Kanban not replenished", {
+ companyId,
+ kanbanId: outcome.kanbanId,
+ reason: outcome.reason
+ });
+ }
+ }
+
+ return result;
+ }
+);
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
index ff9848ac40..52fcd7e948 100644
--- a/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/renderers.tsx
@@ -232,6 +232,7 @@ async function renderKanbanCardPDF(
fromStorageUnitName: item.fromStorageUnitName,
supplierName: item.supplierName,
quantity: item.quantity,
+ replenishmentLevel: item.replenishmentLevel,
unitOfMeasureCode: item.unitOfMeasureCode,
thumbnail
}
diff --git a/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts
index 7848465124..414ad16994 100644
--- a/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts
+++ b/packages/jobs/src/inngest/functions/tasks/print-job/resolvers.ts
@@ -18,6 +18,7 @@ export type KanbanCardItem = {
fromStorageUnitName: string | null;
supplierName: string | null;
quantity: number;
+ replenishmentLevel: number | null;
unitOfMeasureCode: string | null;
thumbnailPath: string | null;
};
@@ -82,6 +83,7 @@ export async function resolveKanbanData(
fromStorageUnitName: kanban.fromStorageUnitName,
supplierName: kanban.supplierName,
quantity: kanban.quantity ?? 0,
+ replenishmentLevel: kanban.replenishmentLevel ?? null,
unitOfMeasureCode: kanban.purchaseUnitOfMeasureCode,
thumbnailPath: kanban.thumbnailPath
}
diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.ts
index 454362f1c1..a4a050a970 100644
--- a/packages/jobs/src/inngest/index.ts
+++ b/packages/jobs/src/inngest/index.ts
@@ -95,6 +95,7 @@ import {
companyTemplateFunction,
companyTemplateRevertFunction,
invoiceAutomateFunction,
+ kanbanLevelCheckFunction,
modelCompactFunction,
modelOptimizeFunction,
modelThumbnailFunction,
@@ -146,6 +147,7 @@ export const functions = [
companyTemplateFunction,
companyTemplateRevertFunction,
invoiceAutomateFunction,
+ kanbanLevelCheckFunction,
modelCompactFunction,
modelOptimizeFunction,
modelThumbnailFunction,
diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.ts
index ae312617b7..2bee576058 100644
--- a/packages/lib/src/events.ts
+++ b/packages/lib/src/events.ts
@@ -586,6 +586,12 @@ export type Events = {
"carbon/workflow-run-retention.process": {
data: Record<string, never>;
};
+ // Sent by the database (queue_kanban_level_checks, sync_kanban_level_check,
+ // util.sweep_kanban_levels), never by app code. Every id is a Transfer
+ // kanban whose projected quantity was below its replenishment level.
+ "carbon/kanban.level-check": {
+ data: { companyId: string; kanbanIds: string[] };
+ };
// Weekly tasks
"carbon/weekly": {
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 58fc6f83cd..598f9ca013 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Hinter Ziel um {daysBehindTarget} Tag(e)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Wird auslaufen — Nachfolger: <0>{0}</0>"
+msgid "Below level"
+msgstr "Unterhalb des Sollbestands"
+
msgid "Below safety stock"
msgstr "Unter Sicherheitsbestand"
@@ -12046,7 +12049,7 @@ msgstr "Nachname"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Letzte Übertragung {when} fehlgeschlagen: {0}"
+msgstr "Letzter Push {when} fehlgeschlagen: {0}"
msgid "Last push {when}:"
msgstr "Letzte Übertragung {when}:"
@@ -14984,6 +14987,9 @@ msgstr "An"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Bei einem Kontrollkonto eröffnet Carbon den Saldo aus seinen eigenen offenen Posten, Beständen und Anlagegütern. Die Rohbilanz muss zustimmen: Jede Differenz bleibt auf dem Migrations-Clearing, das sich auf Null summieren muss."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "Bei einer Umlagerungs-Kanban ist die Mindestmenge für die Ziel-Lagereinheit der Schwellwert. Wenn der verfügbare Bestand plus offene eingehende Umlagerungen darunter fällt, erstellt Carbon eine ausgelöste Umlagerung für die Kanban-Menge."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "Am Umstellungstag arbeiten Sie die Checkliste unten der Reihe nach ab. Akzeptanztests stammen aus Ihren im Umfang enthaltenen Anforderungen. Supportdetails finden Sie unten."
@@ -16804,6 +16810,9 @@ msgstr "Projektstart"
msgid "Projected"
msgstr "Prognostiziert"
+msgid "Projected (To)"
+msgstr "Geplant (Zu)"
+
msgid "Projected completion"
msgstr "Geplante Fertigstellung"
@@ -17134,6 +17143,9 @@ msgstr "GW der Zahlungen"
msgid "PV of Residual"
msgstr "GW des Restwerts"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR-Code zum Abschließen des aktuellen Arbeitsgangs für diesen Kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "QR-Code zum Erstellen eines {0} für diesen Kanban"
@@ -18193,6 +18205,9 @@ msgstr "Das Ersetzen der PDF entfernt alle Anmerkungsplatzierungen. Merkmalzeile
msgid "Replenishment"
msgstr "Nachschub"
+msgid "Replenishment Level"
+msgstr "Meldebestand"
+
msgid "Replenishment system"
msgstr "Beschaffungsart"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "Die Bestellung"
msgid "The push to Mount did not start. Try again."
-msgstr "Die Übertragung an Mount hat nicht begonnen. Versuchen Sie es erneut."
+msgstr "Der Push zu Mount konnte nicht gestartet werden. Versuchen Sie es erneut."
msgid "The push to Mount failed"
msgstr "Die Übertragung an Mount ist fehlgeschlagen"
@@ -22420,6 +22435,9 @@ msgstr "Die Übertragung an Mount ist abgeschlossen. Einige Datensätze benötig
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Die Mengenestaffeln, zu denen diese Position bewertet ist; jede Spalte hat seinen eigenen Stückpreis für Käufer–Lieferant-Verhandlungen und für die Umwandlung in nachgelagerte Dokumente."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "Die bei jedem Signal aus der Von-Lagereinheit verschobene Menge."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "Die Menge des Artikels, die bei der scan-basierten Nachbestellung neu bestellt werden soll."
@@ -25123,6 +25141,9 @@ msgstr "Wenn die Kanban-Karte gescannt wird, wird der Job automatisch aus dem En
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Wann der Mietvertrag beginnt und wie lange er läuft, einschließlich Verlängerungen, die mit angemessener Sicherheit erwartet werden."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Wenn die geplante Menge in der Zu-Lagereinheit unter diese Ebene fällt, wird eine ausgelöste Umlagerung für die Menge erstellt. Leer lassen nur zum Scannen."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Wann der Empfangsort die Ankunft des Bestandes erwartet; treibt die MRP-Verfügbarkeit am Bestimmungsort."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 7d7711d027..93a8127b4b 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Behind target by {daysBehindTarget} day(s)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Being phased out — successor: <0>{0}</0>"
+msgid "Below level"
+msgstr "Below level"
+
msgid "Below safety stock"
msgstr "Below safety stock"
@@ -14984,6 +14987,9 @@ msgstr "On {sentDate}"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
@@ -16804,6 +16810,9 @@ msgstr "Project start"
msgid "Projected"
msgstr "Projected"
+msgid "Projected (To)"
+msgstr "Projected (To)"
+
msgid "Projected completion"
msgstr "Projected completion"
@@ -17134,6 +17143,9 @@ msgstr "PV of Payments"
msgid "PV of Residual"
msgstr "PV of Residual"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code to complete the current operation for this kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "QR Code to create a {0} for this kanban"
@@ -18193,6 +18205,9 @@ msgstr "Replacing the PDF removes all balloon placements on this document. Chara
msgid "Replenishment"
msgstr "Replenishment"
+msgid "Replenishment Level"
+msgstr "Replenishment Level"
+
msgid "Replenishment system"
msgstr "Replenishment system"
@@ -22420,6 +22435,9 @@ msgstr "The push to Mount finished. Some records need attention"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "The quantity moved from the From storage unit on each signal."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "The quantity of the item to be reordered on scan-based replenishment."
@@ -25123,6 +25141,9 @@ msgstr "When the kanban card is scanned, the job is automatically moved out of d
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "When the lease starts and how long it runs, including renewals that are reasonably certain."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index e79629add8..5ebe54becc 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Atrás del objetivo por {daysBehindTarget} día(s)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Siendo descontinuado — sucesor: <0>{0}</0>"
+msgid "Below level"
+msgstr "Por debajo del nivel"
+
msgid "Below safety stock"
msgstr "Por debajo del stock de seguridad"
@@ -12046,7 +12049,7 @@ msgstr "Apellido"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Último envío {when} falló: {0}"
+msgstr "El último envío {when} falló: {0}"
msgid "Last push {when}:"
msgstr "Último envío {when}:"
@@ -14984,6 +14987,9 @@ msgstr "El {sentDate}"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "En una cuenta de control, Carbon abre el saldo de sus propios artículos abiertos, existencias y activos fijos. El balance de comprobación debe coincidir: toda diferencia permanece en Liquidación de migración, que debe totalizar cero."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "En un kanban de transferencia, la cantidad mínima para la unidad de almacenamiento de destino. Cuando las existencias disponibles más las transferencias entrantes abiertas caen por debajo de esto, Carbon crea una transferencia de existencias Liberada por la cantidad del kanban."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "En el día de la migración, trabaja la lista de verificación a continuación en orden. Las pruebas de aceptación provienen de tus requisitos dentro del alcance. Los detalles de soporte están en la parte inferior."
@@ -16804,6 +16810,9 @@ msgstr "Inicio del proyecto"
msgid "Projected"
msgstr "Proyectado"
+msgid "Projected (To)"
+msgstr "Proyectado (A)"
+
msgid "Projected completion"
msgstr "Finalización proyectada"
@@ -17134,6 +17143,9 @@ msgstr "VP de Pagos"
msgid "PV of Residual"
msgstr "VP de Residual"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code para completar la operación actual para este kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Código QR para crear un {0} para este kanban"
@@ -18193,6 +18205,9 @@ msgstr "Reemplazar el PDF elimina todas las ubicaciones de globos en este docume
msgid "Replenishment"
msgstr "Reabastecimiento"
+msgid "Replenishment Level"
+msgstr "Nivel de reabastecimiento"
+
msgid "Replenishment system"
msgstr "Sistema de reposición"
@@ -22420,6 +22435,9 @@ msgstr "El envío a Mount finalizó. Algunos registros necesitan atención"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Los puntos de ruptura de cantidad a los que se cotiza esta línea; cada columna lleva su propio precio por unidad para la negociación comprador-proveedor y para la conversión a documentos posteriores."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "La cantidad que se mueve desde la unidad de almacenamiento de origen en cada señal."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "La cantidad del artículo a ser reordenado en reabastecimiento basado en escaneo."
@@ -25123,6 +25141,9 @@ msgstr "Cuando se escanea la tarjeta kanban, el trabajo se mueve automáticament
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Cuándo comienza el arrendamiento y cuánto tiempo dura, incluidas las renovaciones que son razonablemente ciertas."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Cuando la cantidad proyectada en la unidad de almacenamiento de destino cae por debajo de este nivel, se crea una transferencia de existencias Liberada por la cantidad. Dejar en blanco para escaneo solamente."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Cuándo la ubicación de recepción espera que lleguen las existencias; impulsa la disponibilidad de MRP en el destino."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 7fa470d50c..36b63eeed0 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -3935,6 +3935,9 @@ msgstr "En retard de {daysBehindTarget} jour(s)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "En cours de suppression — successeur : <0>{0}</0>"
+msgid "Below level"
+msgstr "Sous le niveau"
+
msgid "Below safety stock"
msgstr "Sous stock de sécurité"
@@ -14984,6 +14987,9 @@ msgstr "Le {sentDate}"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Sur un compte de contrôle, Carbon établit le solde d'ouverture à partir de ses propres articles ouverts, stocks et immobilisations. La balance d'essai doit concorder : toute différence reste dans le compte de transition, qui doit totaliser zéro."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "Sur un kanban de transfert, la quantité minimale pour l'unité de stockage de destination. Lorsque le stock disponible plus les transferts entrants ouverts descend au-dessous, Carbon crée un transfert de stock lancé pour la quantité du kanban."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "Le jour du basculement, travaillez la liste de contrôle ci-dessous dans l'ordre. Les tests d'acceptation proviennent de vos exigences dans le périmètre. Les détails du support se trouvent en bas."
@@ -16804,6 +16810,9 @@ msgstr "Démarrage du projet"
msgid "Projected"
msgstr "Prévue"
+msgid "Projected (To)"
+msgstr "Projeté (Vers)"
+
msgid "Projected completion"
msgstr "Achèvement projeté"
@@ -17134,6 +17143,9 @@ msgstr "VA des paiements"
msgid "PV of Residual"
msgstr "VA de la valeur résiduelle"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code pour terminer l'opération en cours pour ce kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Code QR pour créer un {0} pour ce kanban"
@@ -18193,6 +18205,9 @@ msgstr "Le remplacement du PDF supprime tous les placements de bulles sur ce doc
msgid "Replenishment"
msgstr "Réapprovisionnement"
+msgid "Replenishment Level"
+msgstr "Niveau de réapprovisionnement"
+
msgid "Replenishment system"
msgstr "Mode d'approvisionnement"
@@ -22420,6 +22435,9 @@ msgstr "L'envoi vers Mount est terminé. Certains enregistrements nécessitent u
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Les points d'arrêt de quantité à laquelle cette ligne est tarifée; chaque colonne porte son propre prix par unité pour la négociation acheteur-fournisseur et la conversion en documents aval."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "La quantité déplacée de l'unité de stockage source à chaque signal."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "La quantité de l'article à réapprovisionner lors du réapprovisionnement basé sur la numérisation."
@@ -25123,6 +25141,9 @@ msgstr "Lorsque la carte kanban est scannée, le travail est automatiquement dé
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Quand le bail commence et combien de temps il s'exécute, y compris les renouvellements qui sont raisonnablement certains."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Lorsque la quantité projetée dans l'unité de stockage de destination descend au-dessous de ce niveau, un transfert de stock lancé pour la Quantité est créé. Laissez vide pour la numérisation uniquement."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Quand le site de réception s'attend à la réception du stock ; détermine la disponibilité du MRP à destination."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 020509ea50..b0b9ebb8cc 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -3935,6 +3935,9 @@ msgstr "लक्ष्य से {daysBehindTarget} दिन पीछे"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "चरणबद्ध रूप से बंद किया जा रहा है — उत्तराधिकारी: <0>{0}</0>"
+msgid "Below level"
+msgstr "स्तर से नीचे"
+
msgid "Below safety stock"
msgstr "सुरक्षा स्टॉक से नीचे"
@@ -14984,6 +14987,9 @@ msgstr "{sentDate} को"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "एक नियंत्रण खाते पर, कार्बन अपने खुली आइटम, इन्वेंटरी और अचल संपत्ति से शेष राशि खोलता है। ट्रायल बैलेंस सहमत होना चाहिए: हर अंतर माइग्रेशन साफी पर रहता है, जो शून्य होना चाहिए।"
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "एक स्थानांतरण कानबान पर, To भंडारण इकाई के लिए न्यूनतम मात्रा। जब हाथ पर प्लस खुली आने वाली स्थानांतरण इससे नीचे चली जाती है, तो Carbon कानबान मात्रा के लिए एक जारी स्टॉक स्थानांतरण बनाता है।"
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "कटओवर दिन पर, नीचे दी गई चेकलिस्ट को क्रम में काम करें। स्वीकृति परीक्षण आपकी स्कोप में शामिल आवश्यकताओं से आते हैं। समर्थन विवरण नीचे हैं।"
@@ -16804,6 +16810,9 @@ msgstr "प्रोजेक्ट शुरुआत"
msgid "Projected"
msgstr "अनुमानित"
+msgid "Projected (To)"
+msgstr "अनुमानित (To)"
+
msgid "Projected completion"
msgstr "अनुमानित पूर्णता"
@@ -17134,6 +17143,9 @@ msgstr "भुगतान का PV"
msgid "PV of Residual"
msgstr "अवशिष्ट का PV"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "इस कानबान के लिए वर्तमान ऑपरेशन पूर्ण करने के लिए QR कोड"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "इस कानबान के लिए एक {0} बनाने के लिए QR कोड"
@@ -18193,6 +18205,9 @@ msgstr "PDF को बदलने से इस दस्तावेज़ प
msgid "Replenishment"
msgstr "पुनःपूर्ति"
+msgid "Replenishment Level"
+msgstr "पुनर्पूरण स्तर"
+
msgid "Replenishment system"
msgstr "पुनःपूर्ति प्रणाली"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "क्रय आदेश"
msgid "The push to Mount did not start. Try again."
-msgstr "Mount को पुश शुरू नहीं हुआ। फिर से कोशिश करें।"
+msgstr "Mount को पुश शुरू नहीं हुआ। फिर से प्रयास करें।"
msgid "The push to Mount failed"
msgstr "Mount को पुश विफल"
@@ -22420,6 +22435,9 @@ msgstr "Mount को पुश समाप्त हुआ। कुछ रि
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "मात्रा विभाजन बिंदु जिन पर इस पंक्ति की कीमत है; प्रत्येक कॉलम क्रेता-आपूर्तिकर्ता बातचीत और डाउनस्ट्रीम दस्तावेजों में परिवर्तित करने के लिए अपनी स्वयं की प्रति-यूनिट कीमत रखता है।"
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "From भंडारण इकाई से प्रत्येक सिग्नल पर स्थानांतरित मात्रा।"
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "स्कैन-आधारित पुनःपूर्ति पर पुनः ऑर्डर किए जाने वाली वस्तु की मात्रा।"
@@ -25123,6 +25141,9 @@ msgstr "जब कानबान कार्ड को स्कैन कि
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "जब पट्टा शुरू होता है और यह कितने समय तक चलता है, उचित रूप से निश्चित नवीनीकरण सहित।"
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "जब To भंडारण इकाई में अनुमानित मात्रा इस स्तर से नीचे चली जाती है, तो मात्रा के लिए एक जारी स्टॉक स्थानांतरण बनाया जाता है। केवल स्कैन के लिए खाली छोड़ें।"
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "प्राप्ति स्थान को स्टॉक के आने की उम्मीद कब है; गंतव्य पर MRP उपलब्धता को संचालित करता है।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 874ac4635f..eb74c8c611 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -3935,6 +3935,9 @@ msgstr "In ritardo di {daysBehindTarget} giorno/i rispetto al target"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "In fase di eliminazione — successore: <0>{0}</0>"
+msgid "Below level"
+msgstr "Sotto il livello"
+
msgid "Below safety stock"
msgstr "Sotto la scorta di sicurezza"
@@ -12046,7 +12049,7 @@ msgstr "Cognome"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Ultimo push {when} non riuscito: {0}"
+msgstr "Ultimo invio {when} non riuscito: {0}"
msgid "Last push {when}:"
msgstr "Ultimo push {when}:"
@@ -14984,6 +14987,9 @@ msgstr "Acceso"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Su un conto di controllo, Carbon apre il saldo dai propri articoli aperti, magazzino e cespiti. Il bilancio di verifica deve corrispondere: ogni differenza rimane sulla compensazione della migrazione, che deve essere a zero."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "Su un kanban di trasferimento, la quantità minima per l'unità di stoccaggio di destinazione. Quando la giacenza più i trasferimenti in entrata aperti scendono al di sotto di essa, Carbon crea un trasferimento di giacenza Autorizzato per la quantità del kanban."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "Nel giorno del cutover, esegui la checklist sottostante in ordine. I test di accettazione provengono dai tuoi requisiti in ambito. I dettagli di supporto sono in fondo."
@@ -16804,6 +16810,9 @@ msgstr "Inizio progetto"
msgid "Projected"
msgstr "Proiettato"
+msgid "Projected (To)"
+msgstr "Previsto (A)"
+
msgid "Projected completion"
msgstr "Completamento previsto"
@@ -17134,6 +17143,9 @@ msgstr "VA dei pagamenti"
msgid "PV of Residual"
msgstr "VA residuale"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code per completare l'operazione corrente per questo kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Codice QR per creare un {0} per questo kanban"
@@ -18193,6 +18205,9 @@ msgstr "La sostituzione del PDF rimuove tutti i posizionamenti dei palloni su qu
msgid "Replenishment"
msgstr "Rifornimento"
+msgid "Replenishment Level"
+msgstr "Livello di rifornimento"
+
msgid "Replenishment system"
msgstr "Sistema di approvvigionamento"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "L'ordine di acquisto"
msgid "The push to Mount did not start. Try again."
-msgstr "Il push su Mount non è stato avviato. Riprova."
+msgstr "L'invio a Mount non è iniziato. Riprova."
msgid "The push to Mount failed"
msgstr "Il push su Mount non è riuscito"
@@ -22420,6 +22435,9 @@ msgstr "Il push su Mount è terminato. Alcuni record necessitano attenzione"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "I punti di rottura della quantità a cui questa riga è quotata; ogni colonna ha il proprio prezzo unitario per la negoziazione acquirente-fornitore e per la conversione a documenti a valle."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "La quantità trasferita dall'unità di stoccaggio di origine a ogni segnale."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "La quantità dell'articolo da riordinare sul rifornimento basato su scansione."
@@ -25123,6 +25141,9 @@ msgstr "Quando la carta kanban viene scansionata, il lavoro viene automaticament
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Quando inizia il contratto di locazione e per quanto tempo continua, comprese le rinnovazioni che sono ragionevolmente certe."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Quando la quantità prevista nell'unità di stoccaggio di destinazione scende al di sotto di questo livello, viene creato un trasferimento di giacenza Autorizzato per la Quantità. Lascia vuoto per sola scansione."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Quando l'ubicazione di ricevimento si aspetta l'arrivo della giacenza; determina la disponibilità MRP presso la destinazione."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 624d40d953..e4ca07c38f 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -3935,6 +3935,9 @@ msgstr "ターゲットから {daysBehindTarget} 日遅れています"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "段階的に廃止されます — 後継品目:<0>{0}</0>"
+msgid "Below level"
+msgstr "レベル以下"
+
msgid "Below safety stock"
msgstr "安全在庫以下"
@@ -14984,6 +14987,9 @@ msgstr "{sentDate}に送信"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "管理勘定では、Carbonが未決済品目、在庫、固定資産から残高を決定します。試算表は一致する必要があります。すべての差異はマイグレーションクリアリングに留まり、合計はゼロである必要があります。"
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "転送かんばんでは、宛先保管ユニットの最小数量です。手持ちプラス未処理の受信転送がそれ以下に落ちると、Carbon はかんばん数量のためにリリース済の在庫転送を作成します。"
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "カットオーバー日に、下のチェックリストを順番に作業してください。受け入れテストはあなたの対象要求事項から取得されます。サポートの詳細は下部にあります。"
@@ -16804,6 +16810,9 @@ msgstr "プロジェクト開始"
msgid "Projected"
msgstr "予測"
+msgid "Projected (To)"
+msgstr "予定 (To)"
+
msgid "Projected completion"
msgstr "予測完了"
@@ -17134,6 +17143,9 @@ msgstr "支払のPV"
msgid "PV of Residual"
msgstr "残存価値のPV"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "このかんばんの現在の工程を完了するためのQRコード"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "このかんばんの{0}を作成するためのQR Code"
@@ -18193,6 +18205,9 @@ msgstr "PDFを置き換えると、このドキュメント上のすべてのバ
msgid "Replenishment"
msgstr "補充"
+msgid "Replenishment Level"
+msgstr "補充レベル"
+
msgid "Replenishment system"
msgstr "調達方式"
@@ -22420,6 +22435,9 @@ msgstr "Mount へのプッシュが完了しました。いくつかのレコー
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "この明細が価格設定される数量ブレークポイント。各列は買い手と仕入先の交渉および下流文書への変換用に、独自の単価を持ちます。"
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "各シグナルで From 保管ユニットから移動される数量。"
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "スキャンベースの補充時に再注文される品目の数量。"
@@ -25123,6 +25141,9 @@ msgstr "かんばんカードがスキャンされると、製造指図は自動
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "リースが開始される時期と期間、および合理的に確実な更新を含みます。"
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "宛先保管ユニットの予定数量がこのレベル以下に落ちると、リリース済の在庫転送がかんばん数量で作成されます。スキャンのみの場合は空白のままにしてください。"
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "入荷拠点が在庫到着を予想する日時。目的地でのMRP在庫可用性を決定します。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 3c66848ee2..da92ac765d 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -3935,6 +3935,9 @@ msgstr "목표 대비 {daysBehindTarget}일 뒤떨어짐"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "단계적으로 폐기 중 — 후속 품목: <0>{0}</0>"
+msgid "Below level"
+msgstr "레벨 이하"
+
msgid "Below safety stock"
msgstr "안전 재고 아래"
@@ -14984,6 +14987,9 @@ msgstr "켬"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "제어 계정에서 Carbon은 자신의 미결 항목, 재고 및 고정자산에서 잔액을 개설합니다. 시산표가 일치해야 합니다. 모든 차이는 마이그레이션 정산에 유지되며, 이는 합계가 0이어야 합니다."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "이송 칸반에서 도착 보관 단위의 최소 수량입니다. 현재 재고와 미결 인바운드 이송의 합이 이 수준 아래로 내려가면, Carbon은 칸반 수량만큼의 릴리스됨 재고 이송을 생성합니다."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "전환일 당일에는 아래 체크리스트를 순서대로 진행하세요. 승인 테스트는 범위 내 요구사항을 기준으로 하며, 지원 관련 세부 정보는 하단에 있습니다."
@@ -16804,6 +16810,9 @@ msgstr "프로젝트 시작"
msgid "Projected"
msgstr "예상"
+msgid "Projected (To)"
+msgstr "예상 (도착)"
+
msgid "Projected completion"
msgstr "예상 완료"
@@ -17134,6 +17143,9 @@ msgstr "지불의 현재가치"
msgid "PV of Residual"
msgstr "잔존가치의 현재가치"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "이 칸반의 현재 공정을 완료 처리하기 위한 QR 코드"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "이 칸반에 대한 {0}을(를) 생성하는 QR 코드"
@@ -18193,6 +18205,9 @@ msgstr "PDF를 교체하면 이 문서의 모든 풍선 배치가 제거됩니
msgid "Replenishment"
msgstr "보충"
+msgid "Replenishment Level"
+msgstr "보충 레벨"
+
msgid "Replenishment system"
msgstr "조달 방식"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "발주서"
msgid "The push to Mount did not start. Try again."
-msgstr "Mount로의 푸시가 시작되지 않았습니다. 다시 시도하세요."
+msgstr "Mount으로의 푸시가 시작되지 않았습니다. 다시 시도하세요."
msgid "The push to Mount failed"
msgstr "Mount로의 푸시 실패"
@@ -22420,6 +22435,9 @@ msgstr "Mount로의 푸시 완료. 일부 기록에 주의가 필요합니다."
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "이 라인의 가격 책정 수량 구간점; 각 열은 구매자-공급업체 협상 및 다운스트림 문서로 변환하기 위한 자체 단가를 포함합니다."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "각 신호마다 출발 보관 단위에서 이송되는 수량입니다."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "스캔 기반 보충 시 재주문할 품목 수량입니다."
@@ -25123,6 +25141,9 @@ msgstr "칸반 카드를 스캔하면 작업이 자동으로 초안 상태에서
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "리스가 시작되는 시기 및 실행 기간(합리적으로 확실한 갱신 포함)"
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "도착 보관 단위의 예상 수량이 이 레벨 아래로 내려가면 수량만큼의 릴리스됨 재고 이송이 생성됩니다. 스캔 전용인 경우 비워두세요."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "입고 사업장이 재고가 도착할 것으로 예상할 때; 목적지의 MRP 가용성을 결정합니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 5245d79b90..77338ecc0b 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Opóźnienie o {daysBehindTarget} dzień(dni)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Wycofywane — następca: <0>{0}</0>"
+msgid "Below level"
+msgstr "Poniżej poziomu"
+
msgid "Below safety stock"
msgstr "Poniżej zapasu bezpieczeństwa"
@@ -12046,7 +12049,7 @@ msgstr "Nazwisko"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Ostatni push {when} nie powiódł się: {0}"
+msgstr "Ostatnie wysłanie {when} nie powiodło się: {0}"
msgid "Last push {when}:"
msgstr "Ostatni push {when}:"
@@ -14984,6 +14987,9 @@ msgstr "W dniu {sentDate}"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Na koncie kontrolnym Carbon otwiera saldo na podstawie własnych pozycji otwartych, zapasów i środków trwałych. Bilans próbny musi się zgadzać: każda różnica pozostaje na koncie Przejście Migracji, które musi sumować się do zera."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "W kanban transferu minimalna ilość dla jednostki magazynowej docelowej. Gdy zapas dostępny plus otwarte przychodzące przesunięcia spadną poniżej tej wartości, Carbon tworzy zwolnione przesunięcie zapasu dla ilości kanban."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "W dniu przejścia pracuj nad listą kontrolną poniżej w kolejności. Testy akceptacyjne pochodzą z Twoich wymagań objętych zakresem. Szczegóły dotyczące wsparcia znajdują się na dole."
@@ -16804,6 +16810,9 @@ msgstr "Początek projektu"
msgid "Projected"
msgstr "Prognozowane"
+msgid "Projected (To)"
+msgstr "Prognozowane (Do)"
+
msgid "Projected completion"
msgstr "Przewidywane zakończenie"
@@ -17134,6 +17143,9 @@ msgstr "WO płatności"
msgid "PV of Residual"
msgstr "WO wartości resztkowej"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code do zakończenia bieżącej operacji dla tego kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Kod QR do utworzenia {0} dla tego kanbanu"
@@ -18193,6 +18205,9 @@ msgstr "Zastąpienie PDF-a usuwa wszystkie umieszczenia balonów na tym dokumenc
msgid "Replenishment"
msgstr "Uzupełnianie"
+msgid "Replenishment Level"
+msgstr "Poziom uzupełnienia"
+
msgid "Replenishment system"
msgstr "System uzupełniania"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "Zamówienie zakupu"
msgid "The push to Mount did not start. Try again."
-msgstr "Push do Mount nie rozpoczął się. Spróbuj ponownie."
+msgstr "Wysłanie do Mount nie rozpoczęło się. Spróbuj ponownie."
msgid "The push to Mount failed"
msgstr "Push do Mount nie powiódł się"
@@ -22420,6 +22435,9 @@ msgstr "Push do Mount zakończył się. Niektóre rekordy wymagają uwagi"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Punkty graniczne ilości, przy których ta pozycja jest wyceniona; każda kolumna nosi własną cenę za sztukę do negocjacji kupiec–dostawca i do konwersji na dokumenty następujące."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "Ilość przeniesiona z jednostki magazynowej źródłowej na każdy sygnał."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "Ilość przedmiotu do ponownego zamówienia w ramach uzupełniania opartego na skanowaniu."
@@ -25123,6 +25141,9 @@ msgstr "Gdy karta kanban zostanie zeskanowana, zlecenie produkcyjne jest automat
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Kiedy dzierżawa się zaczyna i jak długo trwa, łącznie z odnowieniami, które są rozsądnie pewne."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Gdy prognozowana ilość w jednostce magazynowej docelowej spadnie poniżej tego poziomu, tworzone jest zwolnione przesunięcie zapasu dla ilości. Pozostaw puste dla tylko skanowania."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Gdy lokalizacja przyjęcia oczekuje na przybycie zapasu; napędza dostępność MRP w miejscu docelowym."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index b4c35b733a..ab5268763e 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Atrasado em relação ao alvo em {daysBehindTarget} dia(s)"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Sendo descontinuado — sucessor: <0>{0}</0>"
+msgid "Below level"
+msgstr "Abaixo do nível"
+
msgid "Below safety stock"
msgstr "Abaixo do estoque de segurança"
@@ -14984,6 +14987,9 @@ msgstr "Ligado"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Em uma conta de controle, o Carbon abre o saldo a partir de seus próprios itens abertos, estoque e ativos fixos. O balanço de verificação deve concordar: toda diferença fica na Limpeza de Migração, que deve totalizar zero."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "Em um kanban de transferência, a quantidade mínima para a unidade de armazenamento de destino. Quando o estoque em mão mais as transferências de entrada abertas caem abaixo disso, Carbon cria uma transferência de estoque confirmada para a quantidade do kanban."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "No dia de cutover, trabalhe a lista de verificação abaixo em ordem. Os testes de aceitação vêm dos seus requisitos no escopo. Os detalhes de suporte estão na parte inferior."
@@ -16804,6 +16810,9 @@ msgstr "Início do projeto"
msgid "Projected"
msgstr "Projetado"
+msgid "Projected (To)"
+msgstr "Projetado (Para)"
+
msgid "Projected completion"
msgstr "Conclusão projetada"
@@ -17134,6 +17143,9 @@ msgstr "VP de Pagamentos"
msgid "PV of Residual"
msgstr "VP de Residual"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR Code para concluir a operação atual para este kanban"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Código QR para criar um {0} para este kanban"
@@ -18193,6 +18205,9 @@ msgstr "Substituir o PDF remove todos os posicionamentos de balão neste documen
msgid "Replenishment"
msgstr "Reabastecimento"
+msgid "Replenishment Level"
+msgstr "Nível de Reabastecimento"
+
msgid "Replenishment system"
msgstr "Sistema de reposição"
@@ -22420,6 +22435,9 @@ msgstr "O envio para Mount foi concluído. Alguns registros precisam de atençã
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Os pontos de ruptura de quantidade em que essa linha é precificada; cada coluna possui seu próprio preço por unidade para negociação comprador-fornecedor e conversão para documentos posteriores."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "A quantidade movida da unidade de armazenamento de origem em cada sinal."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "A quantidade do item a ser reordenado no reabastecimento baseado em varredura."
@@ -25123,6 +25141,9 @@ msgstr "Quando o cartão kanban é escaneado, o trabalho é automaticamente reti
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Quando a locação inicia e sua duração, inclusive renovações que sejam razoavelmente certas."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Quando a quantidade projetada na unidade de armazenamento de destino cair abaixo deste nível, uma transferência de estoque confirmada para a Quantidade é criada. Deixe em branco apenas para verificação."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Quando o local de recebimento espera que o estoque chegue; determina a disponibilidade de MRP no destino."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index cf15f225ce..0e6de80c7b 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Отстает от целевого показателя на {daysBehi
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Снимается с производства — преемник: <0>{0}</0>"
+msgid "Below level"
+msgstr "Ниже уровня"
+
msgid "Below safety stock"
msgstr "Ниже страховой запас"
@@ -12046,7 +12049,7 @@ msgstr "Фамилия"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Последняя отправка {when} не удалась: {0}"
+msgstr "Последняя попытка отправки {when} не удалась: {0}"
msgid "Last push {when}:"
msgstr "Последняя отправка {when}:"
@@ -14984,6 +14987,9 @@ msgstr "На {sentDate}"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "На контрольном счете Carbon открывает остаток из собственных открытых позиций, запасов и основных средств. Пробный баланс должен совпадать: каждая разница остается на переводной разнице миграции, которая должна быть нулевой."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "На канбане перемещения минимальное количество для целевой единицы хранения. Когда наличие плюс открытые входящие перемещения упадут ниже этого значения, Carbon создает перемещение запаса в объеме канбана."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "В день переключения выполняйте контрольный список ниже по порядку. Тесты приемки основаны на ваших требованиях в области действия. Детали поддержки находятся внизу."
@@ -16804,6 +16810,9 @@ msgstr "Начало проекта"
msgid "Projected"
msgstr "Спрогнозировано"
+msgid "Projected (To)"
+msgstr "Спроецировано (целевое)"
+
msgid "Projected completion"
msgstr "Прогнозное завершение"
@@ -17134,6 +17143,9 @@ msgstr "ТС платежей"
msgid "PV of Residual"
msgstr "ТС остатка"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "QR-код для завершения текущей операции для этого канбана"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "QR-код для создания {0} для этого канбана"
@@ -18193,6 +18205,9 @@ msgstr "Замена PDF удаляет все размещения выносо
msgid "Replenishment"
msgstr "Пополнение"
+msgid "Replenishment Level"
+msgstr "Уровень пополнения"
+
msgid "Replenishment system"
msgstr "Способ пополнения"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "Заказ поставщику"
msgid "The push to Mount did not start. Try again."
-msgstr "Отправка на Mount не началась. Попробуйте еще раз."
+msgstr "Отправка в Mount не началась. Попробуйте снова."
msgid "The push to Mount failed"
msgstr "Отправка на Mount не удалась"
@@ -22420,6 +22435,9 @@ msgstr "Отправка на Mount завершена. Некоторые за
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Точки разрыва по количеству, при которых рассчитывается цена этой строки; каждый столбец содержит свою цену за единицу для переговоров между закупщиком и поставщиком и для преобразования в последующие документы."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "Количество, перемещаемое с исходной единицы хранения с каждым сигналом."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "Количество товара, которое будет переупорядочено при сканировании для пополнения запасов."
@@ -25123,6 +25141,9 @@ msgstr "Когда карточка канбана сканируется, за
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Когда начинается аренда и как долго она длится, включая продления, которые разумно ожидаемы."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "Когда спроецированное количество в целевой единице хранения упадет ниже этого уровня, создается перемещение запаса в объеме Количества. Оставьте пусто для режима только сканирования."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Когда Площадка приемки ожидает прибытия Запаса; определяет доступность MRP в пункте назначения."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b048b9a924..accfd452e2 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -3935,6 +3935,9 @@ msgstr "Hedef {daysBehindTarget} gün geride"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "Kademeli olarak kullanımdan kaldırılıyor — ardıl: <0>{0}</0>"
+msgid "Below level"
+msgstr "Seviyenin altında"
+
msgid "Below safety stock"
msgstr "Emniyet stokunun altında"
@@ -12046,7 +12049,7 @@ msgstr "Soyadı"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "Son gönderim {when} başarısız oldu: {0}"
+msgstr "Son itme {when} başarısız oldu: {0}"
msgid "Last push {when}:"
msgstr "Son gönderim {when}:"
@@ -14984,6 +14987,9 @@ msgstr "{sentDate} tarihinde"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "Bir kontrol hesabında, Carbon, açık kalemlerinin, envanterinin ve sabit kıymetlerinin bakiyesini açar. Deneme bakiyesi eşleşmelidir: her fark Geçiş Temizliğinde kalır, bu toplam sıfır olmalıdır."
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "Transfer kanban'ında To depolama birimi için minimum miktar. Eldeki + açık gelen transferler bunun altına düştüğünde, Carbon kanban miktarı için Serbest bırakıldı stok transferi oluşturur."
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "Geçiş gününde, aşağıdaki kontrol listesini sırayla çalışın. Kabul testleri kapsam içi gerekliliklerinizden gelir. Destek ayrıntıları altta yer alır."
@@ -16804,6 +16810,9 @@ msgstr "Proje başlangıcı"
msgid "Projected"
msgstr "Öngörülen"
+msgid "Projected (To)"
+msgstr "Tahmini (To)"
+
msgid "Projected completion"
msgstr "Öngörülen tamamlanma"
@@ -17134,6 +17143,9 @@ msgstr "Ödemelerin BDH"
msgid "PV of Residual"
msgstr "Kalıntıların BDH"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "Bu kanban için geçerli operasyonu tamamlamak için QR Kodu"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "Bu kanban için bir {0} oluşturmak için QR Kod"
@@ -18193,6 +18205,9 @@ msgstr "PDF'yi değiştirmek bu belgede tüm balon yerleştirmelerini kaldırır
msgid "Replenishment"
msgstr "Yenileştirme"
+msgid "Replenishment Level"
+msgstr "Yenileme Seviyesi"
+
msgid "Replenishment system"
msgstr "İkmal yöntemi"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "Satın alma siparişi"
msgid "The push to Mount did not start. Try again."
-msgstr "Mount'a gönderim başlamadı. Lütfen tekrar deneyin."
+msgstr "Mount'a itme başlamadı. Tekrar deneyin."
msgid "The push to Mount failed"
msgstr "Mount'a gönderim başarısız oldu"
@@ -22420,6 +22435,9 @@ msgstr "Mount'a gönderim tamamlandı. Bazı kayıtlar dikkat gerektiriyor"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "Bu Satırın fiyatlandırıldığı Miktar kırılım noktaları; her sütun Satın almacı–Tedarikçi müzakereleri ve aşağı yönlü belgelere dönüştürme için kendi birim başına Fiyatını taşır."
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "Her sinyalde From depolama biriminden taşınan miktar."
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "Tarama tabanlı yenileme ile yeniden sipariş edilecek ürün miktarı."
@@ -25123,6 +25141,9 @@ msgstr "Kanban kartı tarandığında, iş otomatik olarak taslaktan çıkarıl
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "Kiralama ne zaman başladığı ve ne kadar sürdüğü, makul ölçüde kesin olan yenilemeleri de kapsayarak."
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "To depolama birimindeki tahmini miktar bu seviyenin altına düştüğünde, kanban miktarı için Serbest bırakıldı stok transferi oluşturulur. Yalnızca tarama için boş bırakın."
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "Mal kabul lokasyonunun stokun teslim alınmasını beklediği zaman; varış yerinde MRP uygunluğunu belirler."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index eeff6a1765..1912985013 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -3935,6 +3935,9 @@ msgstr "落后目标 {daysBehindTarget} 天"
msgid "Being phased out — successor: <0>{0}</0>"
msgstr "正在逐步淘汰—后继物料:<0>{0}</0>"
+msgid "Below level"
+msgstr "低于水位线"
+
msgid "Below safety stock"
msgstr "低于安全库存"
@@ -12046,7 +12049,7 @@ msgstr "姓氏"
#. placeholder {0}: record.error
msgid "Last push {when} failed: {0}"
-msgstr "最后一次推送 {when} 失败:{0}"
+msgstr "上次推送 {when} 失败:{0}"
msgid "Last push {when}:"
msgstr "最后一次推送 {when}:"
@@ -14984,6 +14987,9 @@ msgstr "打开"
msgid "On a control account, Carbon opens the balance from its own open items, inventory and fixed assets. The trial balance must agree: every difference stays on Migration Clearing, which must total zero."
msgstr "在控制帐户上,Carbon从其自身的未结项目、库存和固定资产获取余额。试算平衡表必须一致:每项差异保留在迁差账户上,该账户必须合计为零。"
+msgid "On a transfer kanban, the minimum quantity for the To storage unit. When on-hand plus open inbound transfers drops below it, Carbon creates a Released stock transfer for the kanban quantity."
+msgstr "在转移看板上,指目标存储单元的最小数量。当现有库存加上未完成的入库调拨降至此水位以下时,Carbon 会创建一个已下达的库存调拨,调拨数量为看板数量。"
+
msgid "On cutover day, work the checklist below in order. Acceptance tests come from your in-scope requirements. Support details are at the bottom."
msgstr "在转换日,按顺序完成下列检查清单。验收测试来自您范围内的要求。支持详情见下方。"
@@ -16804,6 +16810,9 @@ msgstr "项目开始"
msgid "Projected"
msgstr "预测"
+msgid "Projected (To)"
+msgstr "预计(目标)"
+
msgid "Projected completion"
msgstr "预计完成"
@@ -17134,6 +17143,9 @@ msgstr "付款现值"
msgid "PV of Residual"
msgstr "残值现值"
+msgid "QR Code to complete the current operation for this kanban"
+msgstr "为此看板完成当前工序的QR代码"
+
#. placeholder {0}: getKanbanCreateNoun(row.original.replenishmentSystem)
msgid "QR Code to create a {0} for this kanban"
msgstr "二维码以为此看板创建{0}"
@@ -18193,6 +18205,9 @@ msgstr "替换PDF将移除此文件上的所有气泡位置。特性行及其值
msgid "Replenishment"
msgstr "补货"
+msgid "Replenishment Level"
+msgstr "补货水位"
+
msgid "Replenishment system"
msgstr "补货方式"
@@ -22406,7 +22421,7 @@ msgid "The purchase order"
msgstr "采购订单"
msgid "The push to Mount did not start. Try again."
-msgstr "推送至 Mount 未启动。请重试。"
+msgstr "推送到 Mount 未启动。请重试。"
msgid "The push to Mount failed"
msgstr "推送至 Mount 失败"
@@ -22420,6 +22435,9 @@ msgstr "推送至 Mount 已完成。某些记录需要关注"
msgid "The quantity breakpoints this line is priced at; each column carries its own per-unit price for buyer–supplier negotiation and for converting to downstream documents."
msgstr "此行定价的数量断点;每一列都有自己的单位价格,用于采购方–供应商谈判和转换为下游文件。"
+msgid "The quantity moved from the From storage unit on each signal."
+msgstr "每次触发时从源存储单元移动的数量。"
+
msgid "The quantity of the item to be reordered on scan-based replenishment."
msgstr "扫描补货时要重新订购的物品数量。"
@@ -25123,6 +25141,9 @@ msgstr "当扫描看板卡时,工单自动从草稿移出并已下达到工厂
msgid "When the lease starts and how long it runs, including renewals that are reasonably certain."
msgstr "租赁何时开始及其持续多久,包括有合理确定性的续约。"
+msgid "When the projected quantity in the To storage unit drops below this level, a Released stock transfer for Quantity is created. Leave blank for scan-only."
+msgstr "当目标存储单元中的预计数量降至此水位以下时,会创建一个已下达的库存调拨,调拨数量等于看板数量。留空表示仅扫描模式。"
+
msgid "When the receiving location expects the stock to arrive; drives MRP availability at the destination."
msgstr "当收货地点期望库存到达时;驱动目的地的 MRP 可用性。"
diff --git a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
index 42ab0e593c..49c5a07a58 100644
--- a/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
+++ b/packages/server-functions/src/__snapshots__/permissions-manifest.test.ts.snap
@@ -290,6 +290,15 @@ exports[`server function permissions > match the reviewed manifest 1`] = `
"journal-legacy-documents": {
"update": "accounting",
},
+ "kanban-replenish": {
+ "by": "mode",
+ "rules": {
+ "level": "system",
+ "scan": {
+ "create": "inventory",
+ },
+ },
+ },
"post-asset-transfer": {
"by": "type",
"rules": {
diff --git a/packages/server-functions/src/invoke.ts b/packages/server-functions/src/invoke.ts
index 1ecf91fb98..a03b65ea54 100644
--- a/packages/server-functions/src/invoke.ts
+++ b/packages/server-functions/src/invoke.ts
@@ -29,6 +29,7 @@ const registry = {
"import-csv": () => import("./import-csv"),
issue: () => import("./issue"),
"journal-legacy-documents": () => import("./journal-legacy-documents"),
+ "kanban-replenish": () => import("./kanban-replenish"),
"post-asset-transfer": () => import("./post-asset-transfer"),
"post-charge": () => import("./post-charge"),
"post-customer-contract": () => import("./post-customer-contract"),
diff --git a/packages/server-functions/src/kanban-replenish/index.ts b/packages/server-functions/src/kanban-replenish/index.ts
new file mode 100644
index 0000000000..743bdd562d
--- /dev/null
+++ b/packages/server-functions/src/kanban-replenish/index.ts
@@ -0,0 +1,367 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { KyselyDatabase } from "@carbon/database/client";
+import { toJson } from "@carbon/database/json";
+import { getNextSequence } from "@carbon/database/sequence";
+import {
+ expandSerialTrackedLines,
+ kanbanReplenishmentNote,
+ levelReplenishmentQuantity,
+ type StockTransferLineDraft
+} from "@carbon/database/stock-transfer";
+import { getLogger } from "@carbon/logger";
+import { type Insertable, sql } from "kysely";
+import { z } from "zod";
+import { defineServerFn } from "../define-server-fn";
+import { NotFoundError } from "../errors";
+
+const logger = getLogger("server-functions", "kanban-replenish");
+
+export const kanbanReplenishInput = z.discriminatedUnion("mode", [
+ z.object({ mode: z.literal("scan"), kanbanId: z.string().min(1) }),
+ z.object({
+ mode: z.literal("level"),
+ kanbanIds: z.array(z.string().min(1)).min(1)
+ })
+]);
+
+// The first three are the scan route's own error strings, kept exact.
+export const KANBAN_REPLENISH_REASONS = {
+ missingStorageUnit: "Kanban is missing a from or to storage unit",
+ foreignStorageUnit: "Storage unit does not belong to the kanban location",
+ missingItem: "Failed to get item",
+ notTransfer: "Kanban is not a transfer kanban",
+ notArmed: "Kanban has no replenishment level"
+} as const;
+
+type KanbanReplenishReason =
+ (typeof KANBAN_REPLENISH_REASONS)[keyof typeof KANBAN_REPLENISH_REASONS];
+
+export type KanbanReplenishOutcome =
+ | {
+ kanbanId: string;
+ outcome: "created";
+ id: string;
+ stockTransferId: string;
+ }
+ | { kanbanId: string; outcome: "at-level"; projectedQuantity: number }
+ | { kanbanId: string; outcome: "invalid"; reason: KanbanReplenishReason };
+
+export type KanbanReplenishResult = { results: KanbanReplenishOutcome[] };
+
+/**
+ * The only writer of a kanban replenishment: a Released stock transfer from a
+ * Transfer kanban's From storage unit to its To storage unit, marked with
+ * `kanbanId` and a "Kanban replenishment" note.
+ *
+ * - `scan` always creates (the operator asked for it).
+ * - `level` creates only while the projected quantity at the To storage unit
+ * (on-hand + open inbound transfers) is below `replenishmentLevel`, and then
+ * moves enough whole kanban quantities to reach the level, so a second
+ * signal for the same shortfall writes nothing.
+ *
+ * The kanban rows are locked `FOR UPDATE` in id order, so two signals for one
+ * kanban serialise and the second reads the first one's transfer as supply.
+ */
+const kanbanReplenish = defineServerFn({
+ name: "kanban-replenish",
+ input: kanbanReplenishInput,
+ // A scan writes a stock transfer as the person who scanned, so it needs the
+ // same permission the stock transfer's RLS rule asks for. The level path
+ // runs only from the job, with no user behind it. Every statement below is
+ // scoped by companyId.
+ permissions: {
+ by: "mode",
+ rules: { scan: { create: "inventory" }, level: "system" }
+ },
+ async run(ctx, input): Promise<KanbanReplenishResult> {
+ const { db, companyId, userId } = ctx;
+
+ const { results, created } = await db.transaction().execute(async (trx) => {
+ let kanbanQuery = trx
+ .selectFrom("kanban")
+ .select([
+ "id",
+ "itemId",
+ "locationId",
+ "replenishmentSystem",
+ "replenishmentLevel",
+ "quantity",
+ "fromStorageUnitId",
+ "storageUnitId"
+ ])
+ .where("companyId", "=", companyId);
+
+ kanbanQuery =
+ input.mode === "scan"
+ ? kanbanQuery.where("id", "=", input.kanbanId)
+ : kanbanQuery.where("id", "in", input.kanbanIds);
+
+ const kanbans = await kanbanQuery.orderBy("id").forUpdate().execute();
+
+ if (input.mode === "scan" && kanbans.length === 0) {
+ throw new NotFoundError("Kanban not found");
+ }
+
+ const outcomes = new Map<string, KanbanReplenishOutcome>();
+ const invalid = (kanbanId: string, reason: KanbanReplenishReason) =>
+ outcomes.set(kanbanId, { kanbanId, outcome: "invalid", reason });
+
+ let candidates = kanbans.filter((kanban) => {
+ if (kanban.replenishmentSystem !== "Transfer") {
+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.notTransfer);
+ return false;
+ }
+ if (!kanban.fromStorageUnitId || !kanban.storageUnitId) {
+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.missingStorageUnit);
+ return false;
+ }
+ if (input.mode === "level" && kanban.replenishmentLevel === null) {
+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.notArmed);
+ return false;
+ }
+ return true;
+ });
+
+ // CWE-639: both storage units must belong to this company and to the
+ // kanban's own location — never trust the stored ids.
+ const storageUnitIds = [
+ ...new Set(
+ candidates.flatMap((kanban) => [
+ kanban.fromStorageUnitId!,
+ kanban.storageUnitId!
+ ])
+ )
+ ];
+ const storageUnits =
+ storageUnitIds.length > 0
+ ? await trx
+ .selectFrom("storageUnit")
+ .select(["id", "name", "locationId"])
+ .where("companyId", "=", companyId)
+ .where("id", "in", storageUnitIds)
+ .execute()
+ : [];
+ const storageUnitById = new Map(storageUnits.map((su) => [su.id, su]));
+
+ candidates = candidates.filter((kanban) => {
+ const from = storageUnitById.get(kanban.fromStorageUnitId!);
+ const to = storageUnitById.get(kanban.storageUnitId!);
+ if (
+ !from ||
+ !to ||
+ from.locationId !== kanban.locationId ||
+ to.locationId !== kanban.locationId
+ ) {
+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.foreignStorageUnit);
+ return false;
+ }
+ return true;
+ });
+
+ // Drop a kanban whose item cannot be read before sizing any transfer, so
+ // the level loop below never counts supply for a transfer it will not write.
+ const itemIds = [...new Set(candidates.map((kanban) => kanban.itemId))];
+ const items =
+ itemIds.length > 0
+ ? await trx
+ .selectFrom("item")
+ .select([
+ "id",
+ "readableIdWithRevision",
+ "itemTrackingType",
+ "unitOfMeasureCode"
+ ])
+ .where("companyId", "=", companyId)
+ .where("id", "in", itemIds)
+ .execute()
+ : [];
+ const itemById = new Map(items.map((item) => [item.id, item]));
+
+ candidates = candidates.filter((kanban) => {
+ if (!itemById.has(kanban.itemId)) {
+ invalid(kanban.id, KANBAN_REPLENISH_REASONS.missingItem);
+ return false;
+ }
+ return true;
+ });
+
+ // Level mode moves enough whole kanban quantities to reach the level in
+ // one signal. Two kanbans can watch the same item at the same To storage
+ // unit; `addedInbound` carries what this call has already created there,
+ // so the second kanban sees the first one's transfer as supply.
+ const projectedByKanban = new Map<string, number>();
+ const transferQuantityByKanban = new Map<string, number>();
+ if (input.mode === "level" && candidates.length > 0) {
+ const projected = await sql<{
+ kanbanId: string;
+ replenishmentLevel: number;
+ projectedQuantity: number;
+ }>`
+ SELECT * FROM get_kanban_projected_quantities(
+ ${companyId},
+ ${candidates.map((kanban) => kanban.id)}::text[]
+ )
+ `.execute(trx);
+ const baseByKanban = new Map(
+ projected.rows.map((row) => [
+ row.kanbanId,
+ Number(row.projectedQuantity)
+ ])
+ );
+
+ const addedInbound = new Map<string, number>();
+ candidates = candidates.filter((kanban) => {
+ const key = `${kanban.itemId}:${kanban.storageUnitId}`;
+ const projectedQuantity =
+ (baseByKanban.get(kanban.id) ?? 0) + (addedInbound.get(key) ?? 0);
+ projectedByKanban.set(kanban.id, projectedQuantity);
+ const quantityToMove = levelReplenishmentQuantity(
+ projectedQuantity,
+ Number(kanban.replenishmentLevel),
+ kanban.quantity
+ );
+ if (quantityToMove <= 0) {
+ outcomes.set(kanban.id, {
+ kanbanId: kanban.id,
+ outcome: "at-level",
+ projectedQuantity
+ });
+ return false;
+ }
+ transferQuantityByKanban.set(kanban.id, quantityToMove);
+ addedInbound.set(key, (addedInbound.get(key) ?? 0) + quantityToMove);
+ return true;
+ });
+ }
+ // A scan always moves one kanban quantity.
+ const transferQuantity = (kanban: { id: string; quantity: number }) =>
+ transferQuantityByKanban.get(kanban.id) ?? kanban.quantity;
+
+ if (candidates.length === 0) {
+ return {
+ results: kanbans.map((kanban) => outcomes.get(kanban.id)!),
+ created: [] as KanbanReplenishOutcome[]
+ };
+ }
+
+ let scannerName = "unknown user";
+ if (input.mode === "scan") {
+ const user = await trx
+ .selectFrom("user")
+ .select("fullName")
+ .where("id", "=", userId)
+ .executeTakeFirst();
+ // A user with no last name has a fullName ending in a space.
+ scannerName = user?.fullName?.trim() || scannerName;
+ }
+
+ const headers: Insertable<KyselyDatabase["stockTransfer"]>[] = [];
+ for (const kanban of candidates) {
+ const item = itemById.get(kanban.itemId)!;
+ const stockTransferId = await getNextSequence(
+ trx,
+ "stockTransfer",
+ companyId
+ );
+ const note = kanbanReplenishmentNote({
+ itemReadableId: item.readableIdWithRevision ?? kanban.itemId,
+ fromStorageUnitName:
+ storageUnitById.get(kanban.fromStorageUnitId!)?.name ?? "",
+ toStorageUnitName:
+ storageUnitById.get(kanban.storageUnitId!)?.name ?? "",
+ quantity: transferQuantity(kanban),
+ unitOfMeasureCode: item.unitOfMeasureCode,
+ signal:
+ input.mode === "scan"
+ ? { type: "scan", userName: scannerName }
+ : {
+ type: "level",
+ replenishmentLevel: Number(kanban.replenishmentLevel),
+ projectedQuantity: projectedByKanban.get(kanban.id) ?? 0
+ }
+ });
+ headers.push({
+ stockTransferId,
+ locationId: kanban.locationId,
+ status: "Released" as const,
+ companyId,
+ kanbanId: kanban.id,
+ notes: toJson(note),
+ createdBy: userId
+ });
+ }
+
+ const inserted = await trx
+ .insertInto("stockTransfer")
+ .values(headers)
+ .returning(["id", "kanbanId", "stockTransferId"])
+ .execute();
+ const headerByKanban = new Map(
+ inserted.map((header) => [header.kanbanId!, header])
+ );
+
+ const lines = candidates.flatMap((kanban) => {
+ const item = itemById.get(kanban.itemId)!;
+ const header = headerByKanban.get(kanban.id)!;
+ const draft: StockTransferLineDraft = {
+ itemId: kanban.itemId,
+ fromStorageUnitId: kanban.fromStorageUnitId,
+ toStorageUnitId: kanban.storageUnitId,
+ quantity: transferQuantity(kanban),
+ requiresSerialTracking: item.itemTrackingType === "Serial",
+ requiresBatchTracking: item.itemTrackingType === "Batch"
+ };
+ return expandSerialTrackedLines([draft]).map((line) => ({
+ itemId: line.itemId,
+ fromStorageUnitId: line.fromStorageUnitId ?? null,
+ toStorageUnitId: line.toStorageUnitId ?? null,
+ quantity: line.quantity ?? 0,
+ requiresSerialTracking: line.requiresSerialTracking ?? false,
+ requiresBatchTracking: line.requiresBatchTracking ?? false,
+ stockTransferId: header.id,
+ companyId,
+ createdBy: userId
+ }));
+ });
+
+ if (lines.length > 0) {
+ await trx.insertInto("stockTransferLine").values(lines).execute();
+ }
+
+ const createdOutcomes: KanbanReplenishOutcome[] = [];
+ for (const kanban of candidates) {
+ const header = headerByKanban.get(kanban.id)!;
+ const outcome: KanbanReplenishOutcome = {
+ kanbanId: kanban.id,
+ outcome: "created",
+ id: header.id,
+ stockTransferId: header.stockTransferId
+ };
+ outcomes.set(kanban.id, outcome);
+ createdOutcomes.push(outcome);
+ }
+
+ return {
+ results: kanbans.map((kanban) => outcomes.get(kanban.id)!),
+ created: createdOutcomes
+ };
+ });
+
+ for (const outcome of created) {
+ if (outcome.outcome !== "created") continue;
+ logger.info("Kanban replenishment created", {
+ companyId,
+ kanbanId: outcome.kanbanId,
+ stockTransferId: outcome.stockTransferId,
+ mode: input.mode
+ });
+ }
+
+ return { results };
+ }
+});
+
+export default kanbanReplenish;
diff --git a/packages/server-functions/src/kanban-replenish/kanban-replenish.test.ts b/packages/server-functions/src/kanban-replenish/kanban-replenish.test.ts
new file mode 100644
index 0000000000..9e5733bef9
--- /dev/null
+++ b/packages/server-functions/src/kanban-replenish/kanban-replenish.test.ts
@@ -0,0 +1,373 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { KANBAN_REPLENISHMENT_NOTE_PREFIX } from "@carbon/database/stock-transfer";
+import { expect } from "vitest";
+import { serverFns } from "../invoke";
+import { databaseTest } from "../local-database-test-fixture";
+import { kanbanFixture } from "./kanban-test-fixture";
+
+type Fixture = Awaited<ReturnType<typeof kanbanFixture>>;
+
+function replenish(
+ f: Fixture,
+ input:
+ | { mode: "scan"; kanbanId: string }
+ | { mode: "level"; kanbanIds: string[] }
+) {
+ return serverFns
+ .system({ db: f.db, companyId: f.companyId, userId: "system" })
+ .invokeOrThrow("kanban-replenish", input);
+}
+
+function transfers(f: Fixture) {
+ return f.db
+ .selectFrom("stockTransfer")
+ .select(["id", "kanbanId", "status", "createdBy", "notes"])
+ .where("companyId", "=", f.companyId)
+ .orderBy("stockTransferId")
+ .execute();
+}
+
+function lines(f: Fixture, stockTransferId: string) {
+ return f.db
+ .selectFrom("stockTransferLine")
+ .select(["id", "fromStorageUnitId", "toStorageUnitId", "quantity"])
+ .where("companyId", "=", f.companyId)
+ .where("stockTransferId", "=", stockTransferId)
+ .execute();
+}
+
+function first<T>(rows: T[]): T {
+ const [row] = rows;
+ if (row === undefined) throw new Error("expected at least one row");
+ return row;
+}
+
+function noteText(notes: unknown): string {
+ const doc = (typeof notes === "string" ? JSON.parse(notes) : notes) as {
+ content: { content: { text: string }[] }[];
+ };
+ return first(first(doc.content).content).text;
+}
+
+databaseTest("level mode at or above the level writes nothing", async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(12);
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(results).toEqual([
+ { kanbanId: f.kanbanId, outcome: "at-level", projectedQuantity: 12 }
+ ]);
+ expect(await transfers(f)).toHaveLength(0);
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "level mode below the level creates one Released kanban transfer",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(9);
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(results).toHaveLength(1);
+ expect(first(results).outcome).toBe("created");
+
+ const all = await transfers(f);
+ expect(all).toHaveLength(1);
+ const transfer = first(all);
+ expect(transfer.kanbanId).toBe(f.kanbanId);
+ expect(transfer.status).toBe("Released");
+ expect(transfer.createdBy).toBe("system");
+ expect(noteText(transfer.notes)).toBe(
+ `${KANBAN_REPLENISHMENT_NOTE_PREFIX} — KB-TEST-ITEM, A → B, 5 EA. Signal: level 10 (projected 9).`
+ );
+
+ expect(await lines(f, transfer.id)).toEqual([
+ expect.objectContaining({
+ fromStorageUnitId: f.fromId,
+ toStorageUnitId: f.toId,
+ quantity: 5
+ })
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "an open transfer counts as supply, so a second signal writes nothing",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(9);
+ await replenish(f, { mode: "level", kanbanIds: [f.kanbanId] });
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(results).toEqual([
+ { kanbanId: f.kanbanId, outcome: "at-level", projectedQuantity: 14 }
+ ]);
+ expect(await transfers(f)).toHaveLength(1);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "picking the transfer in full does not re-fire, a further draw-down does",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(9);
+ await replenish(f, { mode: "level", kanbanIds: [f.kanbanId] });
+ const transfer = first(await transfers(f));
+ const line = first(await lines(f, transfer.id));
+
+ await f.db
+ .updateTable("stockTransferLine")
+ .set({ pickedQuantity: 5 })
+ .where("id", "=", line.id)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ await f.adjustFromBin(-5);
+ await f.adjustToBin(5);
+
+ const afterPick = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(afterPick.results).toEqual([
+ { kanbanId: f.kanbanId, outcome: "at-level", projectedQuantity: 14 }
+ ]);
+
+ await f.adjustToBin(-6);
+ const afterDrawDown = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(first(afterDrawDown.results).outcome).toBe("created");
+ expect(await transfers(f)).toHaveLength(2);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("scan mode creates a transfer even above the level", async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(12);
+ const { results } = await replenish(f, {
+ mode: "scan",
+ kanbanId: f.kanbanId
+ });
+ expect(first(results).outcome).toBe("created");
+
+ const transfer = first(await transfers(f));
+ expect(transfer.kanbanId).toBe(f.kanbanId);
+ expect(noteText(transfer.notes)).toContain("Signal: scan by");
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "the database refuses a Transfer kanban whose From equals its To",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await expect(
+ f.db
+ .updateTable("kanban")
+ .set({ fromStorageUnitId: f.toId })
+ .where("id", "=", f.kanbanId)
+ .where("companyId", "=", f.companyId)
+ .execute()
+ ).rejects.toThrow(/kanban_transfer_distinct_storage_units_check/);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a kanban id outside the company gets no outcome and no transfer",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: ["kb-not-in-this-company"]
+ });
+ expect(results).toEqual([]);
+ expect(await transfers(f)).toHaveLength(0);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a storage unit at another location is refused (CWE-639)",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.db
+ .insertInto("location")
+ .values({
+ id: `${f.companyId}-elsewhere`,
+ name: "Elsewhere",
+ addressLine1: "2 Test Way",
+ city: "Testville",
+ postalCode: "00000",
+ timezone: "America/New_York",
+ companyId: f.companyId,
+ createdBy: "system"
+ })
+ .execute();
+ await f.db
+ .updateTable("storageUnit")
+ .set({ locationId: `${f.companyId}-elsewhere` })
+ .where("id", "=", f.fromId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const { results } = await replenish(f, {
+ mode: "scan",
+ kanbanId: f.kanbanId
+ });
+ expect(results).toEqual([
+ {
+ kanbanId: f.kanbanId,
+ outcome: "invalid",
+ reason: "Storage unit does not belong to the kanban location"
+ }
+ ]);
+ expect(await transfers(f)).toHaveLength(0);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a level far above the quantity is reached in one signal",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.db
+ .updateTable("kanban")
+ .set({ replenishmentLevel: 20 })
+ .where("id", "=", f.kanbanId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const initial = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(first(initial.results).outcome).toBe("created");
+ const transfer = first(await transfers(f));
+ expect(await lines(f, transfer.id)).toEqual([
+ expect.objectContaining({ quantity: 20 })
+ ]);
+ expect(noteText(transfer.notes)).toContain(
+ "20 EA. Signal: level 20 (projected 0)."
+ );
+
+ const second = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(second.results).toEqual([
+ { kanbanId: f.kanbanId, outcome: "at-level", projectedQuantity: 20 }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "two kanbans on one item and To storage unit share the supply",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ const secondKanbanId = `${f.kanbanId}-2`;
+ await f.db
+ .insertInto("kanban")
+ .values({
+ id: secondKanbanId,
+ itemId: f.itemId,
+ replenishmentSystem: "Transfer",
+ quantity: 5,
+ replenishmentLevel: 10,
+ locationId: f.locationId,
+ fromStorageUnitId: f.fromId,
+ storageUnitId: f.toId,
+ companyId: f.companyId,
+ createdBy: "system"
+ })
+ .execute();
+
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId, secondKanbanId]
+ });
+ expect(results.map((r) => r.outcome).sort()).toEqual([
+ "at-level",
+ "created"
+ ]);
+ // One transfer covers both: two kanban quantities of 5 reach level 10.
+ const all = await transfers(f);
+ expect(all).toHaveLength(1);
+ expect(await lines(f, first(all).id)).toEqual([
+ expect.objectContaining({ quantity: 10 })
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "a kanban transfer reopened to Draft still counts as supply",
+ async () => {
+ const f = await kanbanFixture();
+ try {
+ await f.adjustToBin(9);
+ await replenish(f, { mode: "level", kanbanIds: [f.kanbanId] });
+ const transfer = first(await transfers(f));
+ await f.db
+ .updateTable("stockTransfer")
+ .set({ status: "Draft" })
+ .where("id", "=", transfer.id)
+ .where("companyId", "=", f.companyId)
+ .execute();
+
+ const { results } = await replenish(f, {
+ mode: "level",
+ kanbanIds: [f.kanbanId]
+ });
+ expect(results).toEqual([
+ { kanbanId: f.kanbanId, outcome: "at-level", projectedQuantity: 14 }
+ ]);
+ expect(await transfers(f)).toHaveLength(1);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
diff --git a/packages/server-functions/src/kanban-replenish/kanban-test-fixture.ts b/packages/server-functions/src/kanban-replenish/kanban-test-fixture.ts
new file mode 100644
index 0000000000..3d1bc9d39b
--- /dev/null
+++ b/packages/server-functions/src/kanban-replenish/kanban-test-fixture.ts
@@ -0,0 +1,166 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { sql } from "kysely";
+import { connectLocalTestDatabase } from "../local-database-test-fixture";
+
+/**
+ * A scratch company with one Transfer kanban: From storage unit A, To storage
+ * unit B, quantity 5, replenishment level 10, and no stock anywhere.
+ * `cleanup()` deletes the company (FK cascade) and closes the connection.
+ */
+export async function kanbanFixture() {
+ const db = await connectLocalTestDatabase();
+ const prefix = `kbtest-${crypto
+ .randomUUID()
+ .replaceAll("-", "")
+ .slice(0, 12)}`;
+ const companyId = `${prefix}-company`;
+ const groupId = `${prefix}-group`;
+ const locationId = `${prefix}-location`;
+ const fromId = `${prefix}-su-a`;
+ const toId = `${prefix}-su-b`;
+ const itemId = `${prefix}-item`;
+ const kanbanId = `${prefix}-kanban`;
+
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx
+ .insertInto("companyGroup")
+ .values({ id: groupId, name: prefix, createdBy: "system" })
+ .execute();
+ await trx
+ .insertInto("company")
+ .values({
+ id: companyId,
+ name: prefix,
+ companyGroupId: groupId,
+ baseCurrencyCode: "USD",
+ timezone: "America/New_York"
+ })
+ .execute();
+ await trx
+ .insertInto("location")
+ .values({
+ id: locationId,
+ name: "Plant",
+ addressLine1: "1 Test Way",
+ city: "Testville",
+ postalCode: "00000",
+ timezone: "America/New_York",
+ companyId,
+ createdBy: "system"
+ })
+ .execute();
+ await trx
+ .insertInto("storageUnit")
+ .values([
+ {
+ id: fromId,
+ name: "A",
+ locationId,
+ companyId,
+ createdBy: "system"
+ },
+ {
+ id: toId,
+ name: "B",
+ locationId,
+ companyId,
+ createdBy: "system"
+ }
+ ])
+ .execute();
+ await trx
+ .insertInto("unitOfMeasure")
+ .values({ code: "EA", name: "Each", companyId, createdBy: "system" })
+ .execute();
+ await trx
+ .insertInto("item")
+ .values({
+ id: itemId,
+ readableId: "KB-TEST-ITEM",
+ name: "Kanban test item",
+ type: "Part",
+ itemTrackingType: "Inventory",
+ unitOfMeasureCode: "EA",
+ companyId,
+ createdBy: "system"
+ })
+ .execute();
+ await trx
+ .insertInto("sequence")
+ .values({
+ table: "stockTransfer",
+ name: "Stock Transfer",
+ prefix: "ST",
+ next: 0,
+ size: 6,
+ step: 1,
+ companyId
+ })
+ .execute();
+ await trx
+ .insertInto("kanban")
+ .values({
+ id: kanbanId,
+ itemId,
+ replenishmentSystem: "Transfer",
+ quantity: 5,
+ replenishmentLevel: 10,
+ locationId,
+ fromStorageUnitId: fromId,
+ storageUnitId: toId,
+ companyId,
+ createdBy: "system"
+ })
+ .execute();
+ });
+
+ const postLedger = (storageUnitId: string, quantity: number) =>
+ db
+ .insertInto("itemLedger")
+ .values({
+ entryType: quantity >= 0 ? "Positive Adjmt." : "Negative Adjmt.",
+ documentType: "Inventory Receipt",
+ itemId,
+ locationId,
+ storageUnitId,
+ quantity,
+ companyId,
+ createdBy: "system"
+ })
+ .execute();
+
+ return {
+ db,
+ companyId,
+ locationId,
+ kanbanId,
+ fromId,
+ toId,
+ itemId,
+ /** One itemLedger row of `delta` at the To storage unit (B). */
+ adjustToBin: (delta: number) => postLedger(toId, delta),
+ /** One itemLedger row of `delta` at the From storage unit (A). */
+ adjustFromBin: (delta: number) => postLedger(fromId, delta),
+ async cleanup() {
+ await db.transaction().execute(async (trx) => {
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(trx);
+ await trx.deleteFrom("company").where("id", "=", companyId).execute();
+ await trx
+ .deleteFrom("companyGroup")
+ .where("id", "=", groupId)
+ .execute();
+ await sql`DROP TABLE IF EXISTS ${sql.id(`searchIndex_${companyId}`)}`.execute(
+ trx
+ );
+ await sql`DROP TABLE IF EXISTS ${sql.id(`auditLog_${companyId}`)}`.execute(
+ trx
+ );
+ });
+ await db.destroy();
+ }
+ };
+}