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.

Merge commit from fork

Sidc02a11cfc689
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 205162a1e3..e1f31d1dfa 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -2271,3 +2271,28 @@ roles when only the server writes them. Also check `pg_policies` for `qual = 'tr
**Applies to:** `packages/database/supabase/migrations/**` RLS on global tables (`user`,
`userPermission`, `group`), and any review of an RLS helper.
+
+---
+
+**Context:** A security report: with only the published anon key, a caller could reach 84+
+SECURITY DEFINER functions through `/rest/v1/rpc` — inventory valuation, claims, document
+sequences, the event interceptors — for any company, plus a SQL injection in
+`get_company_id_from_foreign_key`. Table RLS held on all 438 tables; the functions went around it.
+
+**Problem:** Every function in `public` is an RPC endpoint, and a SECURITY DEFINER one bypasses
+RLS. Guards were written inline as `IF NOT (has_role(...) OR ...)`, which is NULL — not true —
+when a lookup finds nothing, so they never raised. The obvious fix, `REVOKE EXECUTE`, segfaults
+this Postgres image on the next anon call (`20260924192316`); a first draft of the fix did exactly
+that and only a rule file caught it, because its test checked `has_function_privilege` instead of
+making the call.
+
+**Rule:** Never `REVOKE EXECUTE` on a public function. A SECURITY DEFINER function that takes a
+company id calls `assert_company_access` first; one that only servers call raises on
+`current_setting('role')`; everything internal (helpers, event interceptors) is SECURITY INVOKER.
+Never trust a user id parameter without relating it to `auth.uid()`. Test a guard by CALLING the
+function as `anon` and as another company's user, not by reading the catalog. Edge functions:
+`verify_jwt` accepts the anon key, so authorize in-function (`requirePermissions` / `requireCaller`).
+
+**Applies to:** every `CREATE FUNCTION` in `packages/database/supabase/migrations/**`,
+`packages/database/supabase/functions/*/index.ts`; enforced by the
+`public-definer-function-authorizes-caller` invariant and `supabase/tests/rpc-privileges.test.sql`.
diff --git a/.claude/rules/database-migration-patterns.md b/.claude/rules/database-migration-patterns.md
index 77ba927538..661183376a 100644
--- a/.claude/rules/database-migration-patterns.md
+++ b/.claude/rules/database-migration-patterns.md
@@ -152,17 +152,34 @@ unauthenticated one-request DoS. (A missing TABLE privilege is an ordinary error
`IF current_setting('role', true) IN ('anon','authenticated') THEN RAISE EXCEPTION … USING ERRCODE = 'insufficient_privilege'; END IF;`
PostgREST's `SET ROLE` stays visible inside SECURITY DEFINER, and service role / direct connections
(`none`) pass. Examples: `get_integration_secret`, `assert_audit_log_access(company, NULL)`.
-- **Tenant-scoped function** — raise unless `p_company_id = ANY(get_companies_with_employee_permission(…))`
- (`assert_audit_log_access`).
+- **Tenant-scoped function** (SECURITY DEFINER, takes a company id from the caller) — first
+ statement `PERFORM assert_company_access(company_id[, '<module>_<action>'])` (in a
+ `LANGUAGE sql` body: a leading `SELECT assert_company_access(company_id);`). It raises; never
+ write the check inline as `IF NOT (x = ANY(helper()) OR …)`: when a lookup finds nothing that
+ expression is NULL, `IF NOT NULL` does not raise, and the guard fails open. That is how
+ `get_next_sequence` and the storage-requirement RPCs let any caller through until
+ `20260925121735`. A user id from the caller needs the same care (`get_claims`,
+ `groups_for_user`).
- **Internal helper of a SECURITY DEFINER function** — the role GUC still says `authenticated` inside
the nested call, so the guard above would refuse legitimate callers. Make the helper
`SECURITY INVOKER`: from its SECURITY DEFINER caller it runs as the owner, and from the API it runs
under the caller's RLS (`terminal_job_operations`, `complete_job_remaining_quantities`). Or put it in
`util` (no API `USAGE`) — see `event-system.md`.
+- **Event interceptor** — SECURITY INVOKER. The dispatchers are SECURITY DEFINER, so it runs as
+ the owner on every write; called directly it runs under the caller's RLS (`event-system.md`).
+
+Every public table has RLS (including the per-company `searchIndex_*` / `auditLog_*` tables), so a
+SECURITY INVOKER function can do nothing through the API that REST could not. Default to it; reach
+for SECURITY DEFINER only when the function must see across RLS, and then guard it as above. The
+`public-definer-function-authorizes-caller` invariant (`pnpm --filter @carbon/checks invariants`)
+fails on any SECURITY DEFINER function with no recognized guard.
+
Migration `20260924192316_api-function-guards-not-revokes.sql` converted the six functions that used
-REVOKE. Test a new guard in a throwaway container (`docker run --rm supabase/postgres:<tag>`), never a
-shared database.
+REVOKE; `20260925121735_rpc-function-guards.sql` closed the other 98. Test a new guard in a
+throwaway container (`docker run --rm supabase/postgres:<tag>`), never a shared database — and call
+the function as `anon`, don't just check `has_function_privilege`: the segfault only shows on the
+call. `packages/database/supabase/tests/rpc-privileges.test.sql` is the tenant-isolation test.
## Enums
diff --git a/.claude/rules/event-system.md b/.claude/rules/event-system.md
index 990fee51af..2f62d5586d 100644
--- a/.claude/rules/event-system.md
+++ b/.claude/rules/event-system.md
@@ -45,6 +45,7 @@ The wake path (`20260721184852_event-queue-wake.sql`) — both helpers live in t
- `dispatch_event_batch()` — AFTER STATEMENT. Reads transition tables (`batched_new`/`batched_old`), filters by active subscriptions, builds payload, `pgmq.send_batch('event_system', ...)`. Captures `actorId := auth.uid()::TEXT` (added `20260212153753`; NULL for service-role) and `workflowRunId` from the `workflow_run_id` JWT claim (`20260810100000`). UPDATE pairs transition rows on the table's **full** primary key via `get_primary_key_columns()` (`20260717143448`, restored in `20260810100000` after `20260721184852` copied the older single-column pairing forward). Uses `clock_timestamp()` per event so batched events get unique microsecond timestamps (`20260427120000`).
- `dispatch_event_interceptors()` — BEFORE ROW. Runs named sync interceptor functions inline (data-integrity, not async).
- `dispatch_event_after_interceptors()` — AFTER ROW. Same but post-commit-of-row, safe for FK refs (added `20260410030406`).
+- Both dispatchers are SECURITY DEFINER (`20260925121735`), so interceptors run as the owner on every write. Write a new interceptor as **SECURITY INVOKER**: it still runs as the owner from the dispatcher, but a direct `/rpc/<interceptor>` call with a forged payload runs under the caller's RLS. A SECURITY DEFINER interceptor is callable by anyone with the anon key as the owner — `public-definer-function-authorizes-caller` fails on it.
- `attach_event_trigger(table, sync_functions[], after_sync_functions[])` — helper that wires the BEFORE SYNC / AFTER SYNC / ASYNC STATEMENT triggers on a table (3rd arg added `20260410030406`). **Two overloads are live** — `(TEXT,TEXT[])` and `(TEXT,TEXT[],TEXT[])` — because `CREATE OR REPLACE` with an added parameter creates a sibling rather than replacing. Adding a *defaulted* parameter to this function is therefore a trap: a 2-arg call then matches more than one candidate and fails with `function attach_event_trigger(unknown, text[]) is not unique`, breaking 62 call sites. Adding an argument means dropping both overloads first.
- `attach_statement_handler(table, handler_functions[])` (`20260812002453`) — the STATEMENT-level counterpart to the row-level interceptors. Attaches each function as `trg_event_statement_<fn>_{ins,upd,del}` with transition tables `batched_new` / `batched_old`; an empty array detaches. Does **not** register the table for PGMQ dispatch. Used by `itemLedger` to maintain the `itemStockQuantities` aggregate.
- Handlers are attached for all three operations, so each **must branch on `TG_OP`**: only `batched_new` exists on INSERT, only `batched_old` on DELETE. PL/pgSQL plans lazily, so a branch that doesn't run never resolves its missing transition table.
diff --git a/.claude/rules/user-employee-job-relationships.md b/.claude/rules/user-employee-job-relationships.md
index 2c4e33815b..490776ac90 100644
--- a/.claude/rules/user-employee-job-relationships.md
+++ b/.claude/rules/user-employee-job-relationships.md
@@ -48,9 +48,11 @@ is the separate `job` table from `20240909194622_jobs.sql`).
employee type can do per module/action, scoped to company IDs.
3. Flattened: those grants are materialized into `userPermission.permissions` (JSONB,
`<module>_<action>` → company-ID array).
-4. Claims: SQL `get_claims(uid, company)` (`20230123004206_claims.sql`) reads `role` from
+4. Claims: SQL `get_claims(uid, company)` (latest: `20260925121735_rpc-function-guards.sql`) reads `role` from
`userToCompany` and `permissions` from `userPermission`, then returns
- `(jsonb_build_object('role', role) || permissions)`. RLS helpers like `has_company_permission`,
+ `(jsonb_build_object('role', role) || permissions)`. Called through the API it answers only for
+ the caller's own `uid`, or for someone in a company where the caller holds `users_view` or
+ `users_update`; service role and direct connections are unrestricted. RLS helpers like `has_company_permission`,
`get_companies_with_employee_role()`, and `get_companies_with_employee_permission('<module>_<action>')`
enforce this in policies (helpers re-defined in later migrations — read the newest).
5. App layer (`packages/auth/src/services/`): `getUserClaims()` caches claims in Redis at
diff --git a/.claude/rules/workflow-edge-function.md b/.claude/rules/workflow-edge-function.md
index 1dada9c6cf..6082ad9e99 100644
--- a/.claude/rules/workflow-edge-function.md
+++ b/.claude/rules/workflow-edge-function.md
@@ -47,8 +47,17 @@ verify_jwt = true # JWT required (the common case)
# entrypoint = "./functions/<name>/index.ts" # optional; only if not default index.ts
```
-- `verify_jwt = true` — protected (almost all Carbon functions; the JWT/API-key is
- re-checked in-function anyway, see step 4).
+- `verify_jwt = true` — the gateway checks the JWT's signature, nothing more. The anon key
+ published in the apps' HTML IS a valid JWT, so this alone lets anyone in. The function must
+ still authorize in-function: `requirePermissions` when it acts on a company's data, or
+ `requireCaller` (`lib/supabase.ts` — service role, signed-in user, or valid API key) when it
+ touches none, or `requireServiceRole` when only servers call it (`thumbnail`). `embedding`,
+ `post-picking`, `post-stock-transfer`, `reschedule` and `thumbnail` all served the anon key
+ until they got one. The `edge-function-authorizes-caller` check (`@carbon/checks`) fails a
+ function that calls none of them. `embed`, `event-wake` and `trigger` are still open —
+ Postgres calls them with the anon key from the `config` table (`util.invoke_edge_function`,
+ `util.wake_event_queue`, `finish_job_operation`), so they cannot tell it from an anonymous
+ caller until Postgres sends a server credential.
- `verify_jwt = false` — only for genuinely public endpoints (`logo-resizer`).
Image processing for API/server callers is `process-image` (`verify_jwt = true`,
in-function `requirePermissions`); it runs the shared pipeline in
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
index f82070b5b3..2e22409ce1 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.line.quantity.tsx
@@ -1,5 +1,6 @@
import { assertIsPost, error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -93,8 +94,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Call the post-stock-transfer function for inventory items
+ // Service role: `userId` is the effective (console pin-in) user, not the
+ // token's subject, which the edge function's membership check compares.
const { data: transferResult, error: functionError } =
- await client.functions.invoke("post-stock-transfer", {
+ await getCarbonServiceRole().functions.invoke("post-stock-transfer", {
body: JSON.stringify({
type: type,
stockTransferId: stockTransferLine.data.stockTransferId,
diff --git a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
index f890b8a863..4c15ffaf4c 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/$id.scan.$lineId.tsx
@@ -1,6 +1,7 @@
import type { Result } from "@carbon/auth";
import { error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
import { trigger } from "@carbon/jobs";
import { getLogger } from "@carbon/logger";
@@ -196,8 +197,10 @@ export async function action({ request, params }: ActionFunctionArgs) {
companyId
};
+ // Service role: `userId` is the effective (console pin-in) user, not the
+ // token's subject, which the edge function's membership check compares.
const { data: transferResult, error: functionError } =
- await client.functions.invoke("post-stock-transfer", {
+ await getCarbonServiceRole().functions.invoke("post-stock-transfer", {
body: JSON.stringify(functionPayload)
});
diff --git a/packages/checks/AGENTS.md b/packages/checks/AGENTS.md
index 2a82f2862e..2981f0ef1e 100644
--- a/packages/checks/AGENTS.md
+++ b/packages/checks/AGENTS.md
@@ -6,7 +6,7 @@ Conformance checking, clobber detection, invariant queries, and module structure
- **Run checks against real migrations and module directories** — `collectFindings(root)` scans both SQL migrations and app module structure
- **Use `newViolations()` for CI** — filters findings against the baseline so only new violations fail the build
-- **Add new conformance rules to the array that matches the rule's SOURCE** — `CONFORMANCE_CHECKS` (SQL migrations), `SERVER_CHECKS` (server-only TS), `TS_CHECKS` (all app + shared-package TS, client and server), or `STRUCTURE_CHECKS` (module layout). Follow the `ConformanceCheck` / `StructureCheck` interface
+- **Add new conformance rules to the array that matches the rule's SOURCE** — `CONFORMANCE_CHECKS` (SQL migrations), `SERVER_CHECKS` (server-only TS), `TS_CHECKS` (all app + shared-package TS, client and server), `EDGE_FUNCTION_CHECKS` (one source per edge function, all of its `.ts` files joined — `sources/edge-functions.ts`), or `STRUCTURE_CHECKS` (module layout). Follow the `ConformanceCheck` / `StructureCheck` interface
- **Write invariants as `.sql` files** — each returns rows that VIOLATE the rule (empty = healthy); loaded from directory by `loadInvariants(dir)`
## Ask First
@@ -33,6 +33,7 @@ pnpm --filter @carbon/checks baseline # regenerate baseline (careful!)
- **Conformance checks**: `noNumericPrecision`, `noLegacyRls`, `noDerivedPercentColumn` — scan SQL migrations for anti-patterns (`noDerivedPercentColumn` flags a `*Percent`/`*Rate` column `GENERATED ALWAYS AS` an expression that divides — a percentage is an entered fact, never a lossy echo of a rounded amount); `noLocalTimezone` (in `SERVER_CHECKS`) scans server TS (`sources/server-files.ts`) for `getLocalTimeZone()`, UTC day-slicing, local date-parts of now (`new Date().getDay()` etc.), and `setHours(0,0,0,0)` midnights. Scanned files: MES services, `packages/jobs`, edge functions, ERP module `.service.ts`/`.server.ts`, **plus both apps' route trees** — route modules are server AND client in one file, so `maskClientCode` blanks the browser half (default export, `clientLoader`/`clientAction`, PascalCase/`use*` declarations) while keeping loaders, actions, and the module-level helpers they call
- **Numeric-precision checks** (in `TS_CHECKS`, over `sources/typescript.ts`): `noRawRounding` flags `Math.round/ceil/floor` and `.toFixed` on value-bearing numbers (use `round`/`scrapAllowance`/`applyRate`/`deriveRate` from `@carbon/utils`); `noInlineFractionDigits` flags `minimum`/`maximumFractionDigits` at a call site (pick a named kind from `@carbon/utils` `format.ts`, and `INPUT_FORMAT.*` for anything editable); `noUnroundedTrackedQuantity` flags inline unrounded arithmetic inside a `.updateTable("trackedEntity")` statement's `quantity:` set, and a raw `===`/`!==`/`<` compare against a `*[Ee]ntity*.quantity` read (use `round`/`settleQuantity` at the write, `isFullDraw` at a split gate — see `.claude/rules/traceability-model.md`). It is scoped to what one file can prove: a `quantity:` set from an already-rounded variable is unflaggable either way, and a compare of two locals is presumed rounded where they were defined. It has **no baseline entries** — the whole tree was fixed in the pass that added it, so any finding is new. `sources/typescript.ts` walks `apps/erp/app/{components,hooks,modules,routes}`, `apps/mes/app`, `packages/database/supabase/functions`, `packages/{ee,jobs}/src`, `packages/documents/src/{pdf,utils}` and the shared packages `packages/{utils,form,react,printing,workflows}/src` — tests and the image/logo resizers excluded. The shared packages matter: `@carbon/utils` is where the standard's own helpers live, and `form`/`react` own the number inputs whose `formatOptions` are part of the storage round-trip. See `.claude/rules/numeric-precision.md`
+- **Edge-function auth** (`EDGE_FUNCTION_CHECKS`): `edgeFunctionAuthorizesCaller` fails any function under `packages/database/supabase/functions/` that never calls `requirePermissions` / `requireCaller` / `requireServiceRole` / `getSupabaseServiceRole`, because `verify_jwt` accepts the published anon key. `ALLOWED` in the check holds the functions that are correct without one, each with its reason (`logo-resizer`, `transcription`). `embed`, `event-wake` and `trigger` are baselined, not allowed: Postgres calls them over pg_net with the anon key from `config`, so gating them needs a migration that makes Postgres send a server credential first
- **Structure checks**: `moduleShape` — validates ERP modules have `types.ts`, `ui/`, `index.ts`, `<name>.service.ts`, `<name>.models.ts`
- **Clobber detection**: `findClobbers(branch, main)` — identifies DB objects redefined on both sides
- **Baseline**: `src/baseline.ts` — grandfathered violations keyed by `checkId + file + line + snippet`
diff --git a/packages/checks/src/conformance/baseline.json b/packages/checks/src/conformance/baseline.json
index 003c94d41b..8a9ebed2f7 100644
--- a/packages/checks/src/conformance/baseline.json
+++ b/packages/checks/src/conformance/baseline.json
@@ -1,4 +1,7 @@
[
+ "edge-function-authorizes-caller::packages/database/supabase/functions/embed::embed",
+ "edge-function-authorizes-caller::packages/database/supabase/functions/event-wake::event-wake",
+ "edge-function-authorizes-caller::packages/database/supabase/functions/trigger::trigger",
"module-shape::settings::extra-service:backups.service.ts",
"module-shape::shared::extra-models:imports.models.ts",
"module-shape::shared::missing:ui",
diff --git a/packages/checks/src/conformance/edge-function-authorizes-caller.test.ts b/packages/checks/src/conformance/edge-function-authorizes-caller.test.ts
new file mode 100644
index 0000000000..98b7d22bd6
--- /dev/null
+++ b/packages/checks/src/conformance/edge-function-authorizes-caller.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from "vitest";
+import { edgeFunctionAuthorizesCaller } from "./edge-function-authorizes-caller";
+
+const DIR = "packages/database/supabase/functions";
+
+describe("edgeFunctionAuthorizesCaller", () => {
+ it("flags a function with no in-function auth", () => {
+ const ts =
+ 'serve(async (req) => jsonResponse(await db.selectFrom("job")));';
+ const v = edgeFunctionAuthorizesCaller.scan(`${DIR}/post-picking`, ts);
+ expect(v).toHaveLength(1);
+ expect(v[0]?.snippet).toBe("post-picking");
+ });
+
+ it.each([
+ "await requirePermissions(req, companyId, userId, {});",
+ "await requireCaller(req);",
+ "requireServiceRole(req);",
+ "const client = await getSupabaseServiceRole(auth, apiKey, companyId);"
+ ])("accepts %s", (ts) => {
+ expect(edgeFunctionAuthorizesCaller.scan(`${DIR}/x`, ts)).toHaveLength(0);
+ });
+
+ it("does not accept a bare import of a gate", () => {
+ const ts = 'import { requirePermissions } from "../lib/supabase.ts";';
+ expect(edgeFunctionAuthorizesCaller.scan(`${DIR}/x`, ts)).toHaveLength(1);
+ });
+
+ it("skips allowlisted functions", () => {
+ expect(
+ edgeFunctionAuthorizesCaller.scan(`${DIR}/logo-resizer`, "serve(f);")
+ ).toHaveLength(0);
+ });
+});
diff --git a/packages/checks/src/conformance/edge-function-authorizes-caller.ts b/packages/checks/src/conformance/edge-function-authorizes-caller.ts
new file mode 100644
index 0000000000..8c3f7c4124
--- /dev/null
+++ b/packages/checks/src/conformance/edge-function-authorizes-caller.ts
@@ -0,0 +1,47 @@
+import type { ConformanceCheck, Violation } from "../check";
+
+/**
+ * The shared gates in functions/lib/supabase.ts. Each one throws for the bare
+ * anon key, which verify_jwt alone lets through: it is a validly signed JWT,
+ * and the apps publish it in their HTML.
+ */
+const AUTH_CALL =
+ /\b(requirePermissions|requireCaller|requireServiceRole|getSupabaseServiceRole)\s*\(/;
+
+/**
+ * Functions that may skip the shared gates. Keep the reason with each entry.
+ * A function that SHOULD be gated but cannot be yet belongs in baseline.json,
+ * not here — this list is for "correct as it is".
+ */
+const ALLOWED = new Map<string, string>([
+ [
+ "logo-resizer",
+ "public by design (verify_jwt = false): resizes the company logo shown on unauthenticated pages"
+ ],
+ [
+ "transcription",
+ "verifies the bearer itself with auth.getUser(), which rejects the anon key; touches no company data"
+ ]
+]);
+
+export const edgeFunctionAuthorizesCaller: ConformanceCheck = {
+ id: "edge-function-authorizes-caller",
+ description:
+ "Every edge function authorizes its caller in-function (requirePermissions / requireCaller / requireServiceRole).",
+ provenance: {
+ deprecates: "relying on verify_jwt, which accepts the published anon key",
+ replacedBy: "requirePermissions / requireCaller / requireServiceRole"
+ },
+ scan(file, contents) {
+ const name = file.split("/").pop() ?? file;
+ if (ALLOWED.has(name) || AUTH_CALL.test(contents)) return [];
+ const violation: Violation = {
+ file,
+ line: 0,
+ snippet: name,
+ message:
+ "No in-function authorization: verify_jwt accepts the anon key. Call requirePermissions (company data), requireCaller (no company data) or requireServiceRole (servers only)."
+ };
+ return [violation];
+ }
+};
diff --git a/packages/checks/src/index.ts b/packages/checks/src/index.ts
index cd39f56931..563b5943a8 100644
--- a/packages/checks/src/index.ts
+++ b/packages/checks/src/index.ts
@@ -6,6 +6,7 @@ export type {
Violation
} from "./check";
export { findClobbers, objectRefs } from "./clobber";
+export { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";
export { moduleShape } from "./conformance/module-shape";
export { noDbClientInService } from "./conformance/no-db-client-in-service";
export { noDefaultOnEffects } from "./conformance/no-default-on-effects";
@@ -27,6 +28,7 @@ export {
export {
CONFORMANCE_CHECKS,
collectFindings,
+ EDGE_FUNCTION_CHECKS,
type Finding,
newViolations,
SERVER_CHECKS,
@@ -35,6 +37,7 @@ export {
scanModules,
TS_CHECKS
} from "./run";
+export { loadEdgeFunctions } from "./sources/edge-functions";
export { loadModules, modulesDir } from "./sources/modules";
export { loadServerFiles } from "./sources/server-files";
export { loadTypescriptFiles } from "./sources/typescript";
diff --git a/packages/checks/src/invariants/public-definer-function-authorizes-caller.sql b/packages/checks/src/invariants/public-definer-function-authorizes-caller.sql
new file mode 100644
index 0000000000..1b547364ae
--- /dev/null
+++ b/packages/checks/src/invariants/public-definer-function-authorizes-caller.sql
@@ -0,0 +1,36 @@
+-- invariant: every SECURITY DEFINER function in "public" authorizes its caller
+-- returns rows that VIOLATE the rule (none = healthy)
+--
+-- Every function in "public" is a PostgREST RPC, callable with the anon key the
+-- apps publish; API-key requests also arrive as anon. A SECURITY DEFINER
+-- function runs as the owner and bypasses RLS, so one that takes a company or
+-- user id from the caller without checking it is a cross-tenant read or write
+-- for anyone (20260925121735_rpc-function-guards).
+--
+-- REVOKE EXECUTE is NOT an escape hatch on this image: a call to a revoked
+-- function segfaults the backend (20260924192316). A SECURITY DEFINER function
+-- must instead do one of:
+-- - assert_company_access(company_id[, permission]) first thing, for a
+-- company id the caller supplies;
+-- - raise when current_setting('role') is anon/authenticated, for a function
+-- only service_role and direct connections may call;
+-- - be caller-scoped, answering only about auth.uid() or the request's own
+-- carbon-key (the RLS helpers).
+-- An internal helper called only from other SECURITY DEFINER functions, or an
+-- event interceptor, should simply be SECURITY INVOKER: from its SECURITY
+-- DEFINER caller it still runs as the owner, and through the API it runs under
+-- the caller's RLS.
+--
+-- Trigger functions are excluded: PostgREST cannot call them.
+-- get_company_id_from_foreign_key is excluded by name: 44 RLS policies resolve
+-- a child row's company through it and then check membership themselves, and
+-- it returns nothing but a company id.
+SELECT p.oid::regprocedure AS function
+FROM pg_proc p
+WHERE p.pronamespace = 'public'::regnamespace
+ AND p.prosecdef
+ AND p.prorettype <> 'trigger'::regtype
+ AND p.oid <> 'get_company_id_from_foreign_key(text,text)'::regprocedure
+ AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
+ AND p.prosrc !~* '(assert_company_access|assert_audit_log_access|can_manage_event_subscription|current_setting\(\s*''role''|auth\.uid\(|auth\.role\(|get_companies_with_[a-z_]+\(|get_company_id_from_api_key\(|request\.headers)'
+ORDER BY 1;
diff --git a/packages/checks/src/run.ts b/packages/checks/src/run.ts
index b1bf53b910..37f8011643 100644
--- a/packages/checks/src/run.ts
+++ b/packages/checks/src/run.ts
@@ -6,6 +6,7 @@ import type {
StructureCheck,
Violation
} from "./check";
+import { edgeFunctionAuthorizesCaller } from "./conformance/edge-function-authorizes-caller";
import { moduleShape } from "./conformance/module-shape";
import { noDbClientInService } from "./conformance/no-db-client-in-service";
import { noDefaultOnEffects } from "./conformance/no-default-on-effects";
@@ -18,6 +19,7 @@ import { noRawRounding } from "./conformance/no-raw-rounding";
import { noRequiredColumnWithoutDefault } from "./conformance/no-required-column-without-default";
import { noUnroundedTrackedQuantity } from "./conformance/no-unrounded-tracked-quantity";
import { noZeroConcurrency } from "./conformance/no-zero-concurrency";
+import { loadEdgeFunctions } from "./sources/edge-functions";
import { loadSqlFiles, migrationsDir, repoRoot } from "./sources/migrations";
import { loadModules, modulesDir } from "./sources/modules";
import { loadServerFiles } from "./sources/server-files";
@@ -45,6 +47,11 @@ export const TS_CHECKS: ConformanceCheck[] = [
noUnroundedTrackedQuantity
];
+/** Checks that run once per edge function, over all of its .ts files. */
+export const EDGE_FUNCTION_CHECKS: ConformanceCheck[] = [
+ edgeFunctionAuthorizesCaller
+];
+
export const STRUCTURE_CHECKS: StructureCheck[] = [moduleShape];
export type Finding = { checkId: string; violation: Violation };
@@ -79,13 +86,14 @@ export function scanModules(
return out;
}
-/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS under `root`. */
+/** Every finding across the real migrations (text) + modules (structure) + server TS + app TS + edge functions under `root`. */
export function collectFindings(root: string = repoRoot()): Finding[] {
return [
...scanAll(loadSqlFiles(migrationsDir(root))),
...scanModules(loadModules(modulesDir(root))),
...scanAll(loadServerFiles(root), SERVER_CHECKS),
- ...scanAll(loadTypescriptFiles(root), TS_CHECKS)
+ ...scanAll(loadTypescriptFiles(root), TS_CHECKS),
+ ...scanAll(loadEdgeFunctions(root), EDGE_FUNCTION_CHECKS)
];
}
diff --git a/packages/checks/src/sources/edge-functions.ts b/packages/checks/src/sources/edge-functions.ts
new file mode 100644
index 0000000000..246acc3395
--- /dev/null
+++ b/packages/checks/src/sources/edge-functions.ts
@@ -0,0 +1,47 @@
+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { join, relative } from "node:path";
+import type { SourceFile } from "../check";
+
+const FUNCTIONS_ROOT = "packages/database/supabase/functions";
+
+/** Shared code, not deployable functions. */
+const NOT_FUNCTIONS = new Set(["lib", "shared", "node_modules"]);
+
+function collectTs(dir: string, out: string[]): void {
+ for (const entry of readdirSync(dir)) {
+ const path = join(dir, entry);
+ if (statSync(path).isDirectory()) {
+ collectTs(path, out);
+ } else if (entry.endsWith(".ts") && !entry.endsWith(".test.ts")) {
+ out.push(path);
+ }
+ }
+}
+
+/**
+ * One SourceFile per deployable edge function: every directory with an
+ * index.ts deploys, config.toml entry or not. Its contents are all of the
+ * function's own .ts files joined, because a function's auth call can live
+ * beside index.ts (post-card-transaction/handler.ts).
+ */
+export function loadEdgeFunctions(root: string): SourceFile[] {
+ const base = join(root, FUNCTIONS_ROOT);
+ if (!existsSync(base)) return [];
+ return readdirSync(base)
+ .filter(
+ (name) =>
+ !NOT_FUNCTIONS.has(name) && existsSync(join(base, name, "index.ts"))
+ )
+ .sort()
+ .map((name) => {
+ const paths: string[] = [];
+ collectTs(join(base, name), paths);
+ return {
+ file: relative(root, join(base, name)),
+ contents: paths
+ .sort()
+ .map((path) => readFileSync(path, "utf8"))
+ .join("\n")
+ };
+ });
+}
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index e96581b2f5..b46f7711f1 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -32,6 +32,8 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti
- Specify decimal places in `NUMERIC` columns (use bare `NUMERIC`).
- Use `000000` for the HHMMSS portion of migration timestamps (causes cross-branch collisions).
- Use the deprecated `has_role` / `has_company_permission` RLS helpers.
+- Write a `SECURITY DEFINER` function that trusts a company id from its caller without `PERFORM assert_company_access(company_id)` first — every `public` function is an API endpoint (see `.claude/rules/database-migration-patterns.md`).
+- `REVOKE EXECUTE` on a `public` function: on this Postgres image calling it then segfaults the backend. Guard inside the function, or make it `SECURITY INVOKER`.
## Validation Commands
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 10fbbbbc42..b3b9408f2b 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -91731,9 +91731,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -91743,6 +91740,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -91940,9 +91940,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -91952,6 +91949,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -92103,9 +92103,6 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.returnPickedMaterialTiming"
},
- {
- $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
- },
{
$ref: "#/parameters/rowFilter.companySettings.showCurrencyTrailingZeros"
},
@@ -92115,6 +92112,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.allowLowercaseItemIds"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.salesRuleNotificationGroup"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.includeOperationsOnTraveler"
},
@@ -100153,6 +100153,74 @@ export default {
tags: ["(rpc) get_radan_v1"]
}
},
+ "/rpc/assert_company_access": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_company_id",
+ required: true,
+ type: "string"
+ },
+ {
+ format: "text",
+ in: "query",
+ name: "p_permission",
+ 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) assert_company_access"]
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string"
+ },
+ p_permission: {
+ format: "text",
+ type: "string"
+ }
+ },
+ required: ["p_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) assert_company_access"]
+ }
+ },
"/rpc/trialBalance": {
post: {
parameters: [
@@ -149488,10 +149556,10 @@ export default {
"incompletePickingListPolicy",
"includeMaterialsOnTraveler",
"returnPickedMaterialTiming",
- "salesRuleNotificationGroup",
"showCurrencyTrailingZeros",
"requireMfa",
"allowLowercaseItemIds",
+ "salesRuleNotificationGroup",
"includeOperationsOnTraveler"
],
properties: {
@@ -149739,13 +149807,6 @@ export default {
format: "text",
type: "string"
},
- salesRuleNotificationGroup: {
- format: "text[]",
- items: {
- type: "string"
- },
- type: "array"
- },
showCurrencyTrailingZeros: {
default: true,
format: "boolean",
@@ -149761,6 +149822,13 @@ export default {
format: "boolean",
type: "boolean"
},
+ salesRuleNotificationGroup: {
+ format: "text[]",
+ items: {
+ type: "string"
+ },
+ type: "array"
+ },
includeOperationsOnTraveler: {
default: true,
format: "boolean",
@@ -199199,12 +199267,6 @@ export default {
in: "query",
type: "string"
},
- "rowFilter.companySettings.salesRuleNotificationGroup": {
- name: "salesRuleNotificationGroup",
- required: false,
- in: "query",
- type: "string"
- },
"rowFilter.companySettings.showCurrencyTrailingZeros": {
name: "showCurrencyTrailingZeros",
required: false,
@@ -199223,6 +199285,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.salesRuleNotificationGroup": {
+ name: "salesRuleNotificationGroup",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.includeOperationsOnTraveler": {
name: "includeOperationsOnTraveler",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 5daef88a79..56a0f29b7f 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -81993,6 +81993,10 @@ export type Database = {
Args: { p_company_id: string; p_permission: string }
Returns: undefined
}
+ assert_company_access: {
+ Args: { p_company_id: string; p_permission?: string }
+ Returns: undefined
+ }
attach_audit_log_append_only: {
Args: { p_table_name: string }
Returns: undefined
diff --git a/packages/database/supabase/functions/embedding/index.ts b/packages/database/supabase/functions/embedding/index.ts
index 71275ace50..1015bbcd78 100644
--- a/packages/database/supabase/functions/embedding/index.ts
+++ b/packages/database/supabase/functions/embedding/index.ts
@@ -6,11 +6,18 @@
import "jsr:@supabase/functions-js/edge-runtime.d.ts";
import { generateEmbedding } from "../lib/ai/embedding.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requireCaller } from "../lib/supabase.ts";
Deno.serve(async (req) => {
const preflight = corsPreflight(req);
if (preflight) return preflight;
+ try {
+ await requireCaller(req);
+ } catch (err) {
+ return errorResponse(err, (err as { status?: number }).status ?? 401);
+ }
+
try {
const { text } = await req.json();
diff --git a/packages/database/supabase/functions/lib/supabase.ts b/packages/database/supabase/functions/lib/supabase.ts
index 4f611e20bf..e61a057779 100644
--- a/packages/database/supabase/functions/lib/supabase.ts
+++ b/packages/database/supabase/functions/lib/supabase.ts
@@ -254,6 +254,58 @@ function checkPermissions(
return true;
}
+/**
+ * For functions that touch no company's data, so requirePermissions has nothing
+ * to check, but that must still refuse the published anon key: accepts the
+ * service role, a signed-in user, or a valid, rate-limited API key. As in
+ * requirePermissions, the gateway (verify_jwt) has verified the signature.
+ * Throws; a rate-limited key's error carries `status: 429`, anything else is a 401.
+ */
+export async function requireCaller(req: Request): Promise<void> {
+ const authorizationHeader = req.headers.get("Authorization");
+ const apiKeyHeader = req.headers.get("carbon-key");
+
+ if (apiKeyHeader) {
+ const auth = await getAuthFromAPIKey(apiKeyHeader);
+ if (!auth) throw new Error("Invalid API key");
+ const serviceRole = createClient(
+ Deno.env.get("SUPABASE_URL") ?? "",
+ postgrestServiceKey(authorizationHeader),
+ { auth: { autoRefreshToken: false, persistSession: false } }
+ );
+ const rl = await checkApiKeyRateLimit(
+ serviceRole,
+ auth.apiKeyId,
+ auth.rateLimit,
+ auth.rateLimitWindow
+ );
+ if (!rl.success) {
+ throw Object.assign(new Error("Rate limit exceeded"), { status: 429 });
+ }
+ return;
+ }
+
+ if (isTrustedBearer(authorizationHeader)) return;
+
+ const token = authorizationHeader?.replace(/^Bearer\s+/i, "").trim() ?? "";
+ try {
+ const role = (JSON.parse(atob(token.split(".")[1] ?? "")) as {
+ role?: string;
+ }).role;
+ if (role === "authenticated") return;
+ } catch {
+ // fall through
+ }
+ throw new Error("Sign in or use an API key");
+}
+
+/** For functions only servers call (jobs, other edge functions): the service role key or nothing. */
+export function requireServiceRole(req: Request): void {
+ if (!isTrustedBearer(req.headers.get("Authorization"))) {
+ throw new Error("Service role only");
+ }
+}
+
export async function requirePermissions(
req: Request,
companyId: string,
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 5daef88a79..56a0f29b7f 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -81993,6 +81993,10 @@ export type Database = {
Args: { p_company_id: string; p_permission: string }
Returns: undefined
}
+ assert_company_access: {
+ Args: { p_company_id: string; p_permission?: string }
+ Returns: undefined
+ }
attach_audit_log_append_only: {
Args: { p_table_name: string }
Returns: undefined
diff --git a/packages/database/supabase/functions/post-picking/index.ts b/packages/database/supabase/functions/post-picking/index.ts
index 2693f76670..4edba98dfa 100644
--- a/packages/database/supabase/functions/post-picking/index.ts
+++ b/packages/database/supabase/functions/post-picking/index.ts
@@ -5,6 +5,7 @@ import { sql } from "kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { resolveTrackedEntityBin } from "../issue/resolve-tracked-entity-bin.ts";
import {
@@ -130,6 +131,14 @@ serve(async (req: Request) => {
try {
const payload = await req.json();
const validatedPayload = payloadValidator.parse(payload);
+
+ // Kysely below bypasses RLS: the caller must belong to the company it names.
+ try {
+ await requirePermissions(req, validatedPayload.companyId, validatedPayload.userId, {});
+ } catch (err) {
+ return errorResponse(err, 401);
+ }
+
const today = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId)).toString();
let splitEntityId: string | undefined;
diff --git a/packages/database/supabase/functions/post-stock-transfer/index.ts b/packages/database/supabase/functions/post-stock-transfer/index.ts
index 2d4fc6db3e..8961e75a6d 100644
--- a/packages/database/supabase/functions/post-stock-transfer/index.ts
+++ b/packages/database/supabase/functions/post-stock-transfer/index.ts
@@ -6,6 +6,7 @@ import { sql } from "kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { datetime, getCompanyTimeZone } from "../lib/datetime.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
import type { Database } from "../lib/types.ts";
import { buildBatchSplitRecords, isFullDraw } from "../shared/batch-split.ts";
import { round } from "../shared/precision.ts";
@@ -136,6 +137,14 @@ serve(async (req: Request) => {
try {
const validatedPayload = payloadValidator.parse(payload);
+
+ // Kysely below bypasses RLS: the caller must belong to the company it names.
+ try {
+ await requirePermissions(req, validatedPayload.companyId, validatedPayload.userId, {});
+ } catch (err) {
+ return errorResponse(err, 401);
+ }
+
const companyToday = datetime.today(await getCompanyTimeZone(db, validatedPayload.companyId));
const today = companyToday.toString();
let expiredWarning: string | undefined;
diff --git a/packages/database/supabase/functions/reschedule/index.ts b/packages/database/supabase/functions/reschedule/index.ts
index 59db4296ca..fa70e152f2 100644
--- a/packages/database/supabase/functions/reschedule/index.ts
+++ b/packages/database/supabase/functions/reschedule/index.ts
@@ -2,6 +2,7 @@ import { serve } from "https://deno.land/[email protected]/http/server.ts";
import type { Transaction } from "kysely";
import { getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import { corsPreflight, errorResponse, jsonResponse } from "../lib/response.ts";
+import { requirePermissions } from "../lib/supabase.ts";
import type { DB } from "../lib/types.ts";
const pool = getConnectionPool(1);
@@ -387,6 +388,20 @@ serve(async (req) => {
try {
const { jobId, companyId, userId } = await req.json();
+ try {
+ await requirePermissions(req, companyId, userId, { update: "production" });
+ } catch (err) {
+ return errorResponse(err, 401);
+ }
+
+ const owned = await db
+ .selectFrom("job")
+ .select("id")
+ .where("id", "=", jobId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!owned) return errorResponse("Job not found", 404);
+
console.info(`🔰 Starting reschedule for job ${jobId}`);
const result = await db.transaction().execute(async (trx) => {
diff --git a/packages/database/supabase/functions/thumbnail/index.ts b/packages/database/supabase/functions/thumbnail/index.ts
index 65551c65a7..4af8a47334 100644
--- a/packages/database/supabase/functions/thumbnail/index.ts
+++ b/packages/database/supabase/functions/thumbnail/index.ts
@@ -5,6 +5,7 @@ import { Buffer } from "node:buffer";
import { corsHeaders } from "../lib/headers.ts";
import { getFunctionLogger } from "../lib/logging.ts";
import { corsPreflight, errorResponse } from "../lib/response.ts";
+import { requireServiceRole } from "../lib/supabase.ts";
import {
decodeImage,
@@ -28,6 +29,13 @@ serve(async (req: Request) => {
const preflight = corsPreflight(req);
if (preflight) return preflight;
+ // It drives a browser to whatever URL it is handed: servers only.
+ try {
+ requireServiceRole(req);
+ } catch (err) {
+ return errorResponse(err, 401);
+ }
+
let browser;
try {
const payload = await req.json();
diff --git a/packages/database/supabase/migrations/20260925121735_rpc-function-guards.sql b/packages/database/supabase/migrations/20260925121735_rpc-function-guards.sql
new file mode 100644
index 0000000000..bbe6c40fd9
--- /dev/null
+++ b/packages/database/supabase/migrations/20260925121735_rpc-function-guards.sql
@@ -0,0 +1,2841 @@
+-- Close the API surface of `public` functions.
+--
+-- Every function in "public" is a PostgREST RPC, callable with the anon key
+-- published in the apps' HTML (API-key requests also arrive as anon, plus a
+-- `carbon-key` header). SECURITY DEFINER functions run as the owner and bypass
+-- RLS, so each one that trusted a caller-supplied company or user id, and each
+-- internal helper that was never meant to be called directly, was a
+-- cross-tenant read or write for anyone.
+--
+-- REVOKE EXECUTE is not the fix on this image: calling a revoked function as
+-- anon/authenticated segfaults the backend (20260924192316). Instead:
+--
+-- 1. A caller-facing SECURITY DEFINER function authorizes the company it was
+-- handed with assert_company_access, first thing.
+-- 2. An internal SECURITY DEFINER function becomes SECURITY INVOKER. From a
+-- SECURITY DEFINER caller (the event dispatchers, now SECURITY DEFINER
+-- themselves) it still runs as the owner; through the API it runs under
+-- the caller's RLS, so it can do nothing the REST API would not allow.
+-- 3. The RLS helpers return '{}' instead of NULL, so `x = ANY(helper())` is
+-- false rather than NULL and `IF NOT (...)` guards raise as intended.
+
+-- It raises rather than returns a boolean: `IF NOT (a OR b)` is NULL, not
+-- true, when a membership lookup finds nothing, and never raises — which is
+-- exactly how the older inline guards failed open.
+CREATE OR REPLACE FUNCTION assert_company_access(p_company_id text, p_permission text DEFAULT NULL)
+RETURNS void
+LANGUAGE plpgsql
+STABLE SECURITY DEFINER
+SET search_path = public
+AS $$
+BEGIN
+ -- service_role, and direct connections (jobs, Kysely, edge functions) are already trusted.
+ IF current_setting('role', true) NOT IN ('anon', 'authenticated') THEN
+ RETURN;
+ END IF;
+
+ IF p_company_id = ANY (
+ CASE WHEN p_permission IS NULL
+ THEN get_companies_with_employee_role()
+ ELSE get_companies_with_employee_permission(p_permission)
+ END
+ ) THEN
+ RETURN;
+ END IF;
+
+ RAISE EXCEPTION 'Not authorized for this company'
+ USING ERRCODE = 'insufficient_privilege';
+END;
+$$;
+
+CREATE OR REPLACE FUNCTION public.get_companies_with_any_role()
+ RETURNS text[]
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ user_companies text[];
+ api_key_company text;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ RETURN ARRAY[api_key_company];
+ END IF;
+
+ SELECT array_agg("companyId"::text)
+ INTO user_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text;
+
+ RETURN COALESCE(user_companies, '{}');
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_companies_with_employee_role()
+ RETURNS text[]
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ user_companies text[];
+ api_key_company text;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ RETURN ARRAY[api_key_company];
+ END IF;
+
+ SELECT array_agg("companyId"::text)
+ INTO user_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';
+
+ RETURN COALESCE(user_companies, '{}');
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_companies_with_employee_permission(permission text)
+ RETURNS text[]
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ permission_companies text[];
+ api_key_company text;
+ employee_companies text[];
+ api_key_scopes JSONB;
+BEGIN
+ api_key_company := get_company_id_from_api_key();
+
+ IF api_key_company IS NOT NULL THEN
+ api_key_scopes := get_api_key_scopes();
+ IF api_key_scopes IS NULL OR api_key_scopes = '{}'::jsonb THEN
+ RETURN '{}';
+ END IF;
+ IF (api_key_scopes ? permission)
+ AND api_key_company = ANY(jsonb_to_text_array(api_key_scopes->permission)) THEN
+ RETURN ARRAY[api_key_company];
+ ELSE
+ RETURN '{}';
+ END IF;
+ END IF;
+
+ SELECT array_agg("companyId"::text)
+ INTO employee_companies
+ FROM "userToCompany"
+ WHERE "userId" = auth.uid()::text AND "role" = 'employee';
+
+ SELECT jsonb_to_text_array(COALESCE(permissions->permission, '[]'))
+ INTO permission_companies
+ FROM public."userPermission"
+ WHERE id::text = auth.uid()::text;
+
+ IF permission_companies IS NOT NULL AND employee_companies IS NOT NULL THEN
+ SELECT array_agg(company)
+ INTO permission_companies
+ FROM unnest(permission_companies) company
+ WHERE company = ANY(employee_companies);
+ ELSE
+ permission_companies := '{}';
+ END IF;
+
+ RETURN COALESCE(permission_companies, '{}');
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.has_role(required_role text, company text)
+ RETURNS boolean
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+ DECLARE
+ user_role text;
+ BEGIN
+ SELECT role INTO user_role FROM public."userToCompany" WHERE "userId" = (SELECT auth.uid()::text) AND "companyId" = company;
+ RETURN COALESCE(user_role = required_role, false);
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_company_id_from_foreign_key(foreign_key text, tbl text)
+ RETURNS text
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+ DECLARE
+ company_id text;
+ BEGIN
+ EXECUTE format('SELECT "companyId" FROM %I WHERE id = $1', tbl) INTO company_id USING foreign_key;
+ RETURN company_id;
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_next_sequence(sequence_name text, company_id text)
+ RETURNS text
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_prefix text;
+ v_suffix text;
+ v_next_value integer;
+ v_size integer;
+ v_next_sequence text;
+ v_derived_prefix text;
+ v_derived_suffix text;
+ v_now timestamp;
+BEGIN
+ PERFORM assert_company_access(company_id);
+
+ UPDATE sequence
+ SET next = next + step,
+ "updatedBy" = 'system'
+ WHERE "table" = sequence_name
+ AND "companyId" = company_id
+ RETURNING next, prefix, suffix, size
+ INTO v_next_value, v_prefix, v_suffix, v_size;
+
+ IF NOT FOUND THEN
+ RAISE EXCEPTION 'Sequence not found for table % and company %', sequence_name, company_id;
+ END IF;
+
+ -- Format sequence number
+ v_next_sequence := lpad(v_next_value::text, COALESCE(v_size, 4), '0');
+
+ -- Wall-clock in the company's timezone: document prefixes must roll over at
+ -- the company's midnight, not the database's. Matches the TypeScript twin
+ -- interpolateSequenceDate(value, companyTimezone).
+ v_now := now() AT TIME ZONE COALESCE(
+ (SELECT "timezone" FROM "company" WHERE "id" = company_id),
+ 'UTC'
+ );
+
+ -- Interpolate date variables in prefix/suffix
+ v_derived_prefix := COALESCE(v_prefix, '');
+ v_derived_prefix := replace(v_derived_prefix, '%{yyyy}', to_char(v_now, 'YYYY'));
+ v_derived_prefix := replace(v_derived_prefix, '%{yy}', to_char(v_now, 'YY'));
+ v_derived_prefix := replace(v_derived_prefix, '%{mm}', to_char(v_now, 'MM'));
+ v_derived_prefix := replace(v_derived_prefix, '%{ww}', to_char(v_now, 'IW'));
+ v_derived_prefix := replace(v_derived_prefix, '%{dd}', to_char(v_now, 'DD'));
+ v_derived_prefix := replace(v_derived_prefix, '%{hh}', to_char(v_now, 'HH24'));
+ v_derived_prefix := replace(v_derived_prefix, '%{ss}', to_char(v_now, 'SS'));
+
+ v_derived_suffix := COALESCE(v_suffix, '');
+ v_derived_suffix := replace(v_derived_suffix, '%{yyyy}', to_char(v_now, 'YYYY'));
+ v_derived_suffix := replace(v_derived_suffix, '%{yy}', to_char(v_now, 'YY'));
+ v_derived_suffix := replace(v_derived_suffix, '%{mm}', to_char(v_now, 'MM'));
+ v_derived_suffix := replace(v_derived_suffix, '%{ww}', to_char(v_now, 'IW'));
+ v_derived_suffix := replace(v_derived_suffix, '%{dd}', to_char(v_now, 'DD'));
+ v_derived_suffix := replace(v_derived_suffix, '%{hh}', to_char(v_now, 'HH24'));
+ v_derived_suffix := replace(v_derived_suffix, '%{ss}', to_char(v_now, 'SS'));
+
+ RETURN v_derived_prefix || v_next_sequence || v_derived_suffix;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.complete_job_to_inventory(p_job_id text, p_quantity_complete numeric, p_storage_unit_id text DEFAULT NULL::text, p_location_id text DEFAULT NULL::text, p_company_id text DEFAULT NULL::text, p_user_id text DEFAULT NULL::text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_item_id TEXT;
+ v_item_tracking_type "itemTrackingType";
+ v_cogs_account TEXT;
+ v_sales_order_line_id TEXT;
+ v_line_quantity_complete NUMERIC;
+ v_job_company_id TEXT;
+ v_prior_quantity_received NUMERIC;
+ v_quantity_received_to_inventory NUMERIC;
+ v_job_id_readable TEXT;
+ v_job_make_method RECORD;
+ v_tracked_entity RECORD;
+ v_accounting_enabled BOOLEAN;
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_item_inventory_account TEXT;
+ v_item_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_labor_absorption_account TEXT;
+ v_overhead_absorption_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_dimension_cost_center TEXT;
+ v_dimension_employee TEXT;
+ v_event RECORD;
+ v_duration_hours NUMERIC;
+ v_rate NUMERIC;
+ v_labor_cost NUMERIC;
+ v_overhead_cost NUMERIC;
+ v_event_reference TEXT;
+ v_labor_journal_line_reference TEXT;
+ v_labor_accounting_period_id TEXT;
+ v_labor_journal_entry_id TEXT;
+ v_labor_journal_id TEXT;
+ v_labor_jl_id TEXT;
+ v_accumulated_wip_cost NUMERIC;
+ v_today DATE;
+ v_journal_line_reference TEXT;
+ v_accounting_period_id TEXT;
+ v_journal_entry_id TEXT;
+ v_journal_id TEXT;
+ v_jl_ids TEXT[];
+ v_new_per_unit_cost NUMERIC;
+ v_costing_method TEXT;
+ v_existing_unit_cost NUMERIC;
+ v_item_posting_group_id TEXT;
+ v_job_location_id TEXT;
+ v_total_qty_on_hand NUMERIC;
+ v_prior_qty NUMERIC;
+ v_prior_value NUMERIC;
+ v_new_unit_cost NUMERIC;
+ v_serial_unit_ids TEXT[];
+ v_company_today DATE := company_today(p_company_id);
+BEGIN
+ PERFORM assert_company_access(p_company_id);
+
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details. The row lock makes a concurrent completion wait and then
+ -- read this completion's cumulative quantity, so both cannot compute the same
+ -- receipt delta.
+ SELECT "itemId", "quantityReceivedToInventory", "jobId", "locationId", "salesOrderLineId", "companyId"
+ INTO STRICT v_item_id, v_prior_quantity_received, v_job_id_readable, v_job_location_id, v_sales_order_line_id, v_job_company_id
+ FROM "job"
+ WHERE id = p_job_id
+ FOR UPDATE;
+
+ -- SECURITY DEFINER bypasses RLS: bind the call to the job's own company so a
+ -- caller can never complete another tenant's job or post into a mismatched
+ -- company's ledger/journal.
+ IF p_company_id IS NULL OR v_job_company_id IS DISTINCT FROM p_company_id THEN
+ RAISE EXCEPTION 'Job % does not belong to company %', p_job_id, COALESCE(p_company_id, '<null>');
+ END IF;
+
+ -- Non-Inventory items (services) never enter inventory
+ SELECT "itemTrackingType"
+ INTO v_item_tracking_type
+ FROM "item"
+ WHERE id = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- A stocked item completed at zero marks the job Completed, receives nothing
+ -- and backflushes nothing. Refuse it at the one function every completion path
+ -- crosses (ERP complete route, API/MCP, sync_finish_job_operation).
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND COALESCE(p_quantity_complete, 0) <= 0 THEN
+ RAISE EXCEPTION 'Quantity completed must be greater than 0 for job %', v_job_id_readable;
+ END IF;
+
+ -- Delta for this completion: drives the itemLedger/costLedger quantities and
+ -- the WIP-discharge journal. The job column itself stores the CUMULATIVE
+ -- quantity (get_inventory_quantities computes on-production supply as
+ -- production + scrap - received - shipped, which requires cumulative).
+ v_quantity_received_to_inventory := p_quantity_complete - COALESCE(v_prior_quantity_received, 0);
+
+ -- Fetch jobMakeMethod for the top-level (no parentMaterialId)
+ SELECT *
+ INTO STRICT v_job_make_method
+ FROM "jobMakeMethod"
+ WHERE "jobId" = p_job_id
+ AND "parentMaterialId" IS NULL;
+
+ -- Serial units are received one tracked entity at a time, so a fractional
+ -- quantity cannot be honoured; it would be stored on the job and rounded by
+ -- the receipt.
+ IF v_job_make_method."requiresSerialTracking"
+ AND p_quantity_complete <> trunc(p_quantity_complete) THEN
+ RAISE EXCEPTION 'Quantity completed must be a whole number for serial-tracked job %', v_job_id_readable;
+ END IF;
+
+ -- The quantity is cumulative, so a stocked job cannot be completed at less than
+ -- it has already received: the negative delta would post a negative receipt,
+ -- cost layer and WIP journal. Received stock is corrected through inventory
+ -- adjustments, not by re-completing the job. Non-Inventory jobs never receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND p_quantity_complete < COALESCE(v_prior_quantity_received, 0) THEN
+ RAISE EXCEPTION 'Quantity completed cannot be lower than the % already received for job %',
+ COALESCE(v_prior_quantity_received, 0), v_job_id_readable;
+ END IF;
+
+ -- Update job status. quantityReceivedToInventory is CUMULATIVE (not the
+ -- delta): re-completions previously overwrote it with the delta, corrupting
+ -- get_inventory_quantities' on-production supply math. Non-Inventory items
+ -- never receive to inventory, so their value is left unchanged.
+ UPDATE "job"
+ SET status = 'Completed',
+ "completedDate" = NOW(),
+ "quantityComplete" = p_quantity_complete,
+ "quantityReceivedToInventory" = CASE
+ WHEN v_item_tracking_type = 'Non-Inventory' THEN v_prior_quantity_received
+ ELSE p_quantity_complete
+ END,
+ "updatedAt" = NOW(),
+ "updatedBy" = p_user_id
+ WHERE id = p_job_id;
+
+ -- Complete the quantities behind the status: raise the terminal operations so
+ -- the routing agrees with a Completed job, and refuse a serial job whose units
+ -- still need serial numbers.
+ --
+ -- AFTER the status flip, never before. Closing an operation fires
+ -- sync_finish_job_operation, which re-enters this function for a job in
+ -- Ready/In Progress/Paused. Being a BEFORE row trigger it runs mid-statement,
+ -- so it reads the operation's OLD quantityComplete (still 0 on a desk
+ -- completion), falls back to the job's planned quantity and receives a second
+ -- time — while this call's own receipt delta was computed further up, before
+ -- any of it happened. With the job already Completed the interceptor's status
+ -- gate returns early, so the operations close without a second receipt.
+ PERFORM complete_job_remaining_quantities(p_job_id, p_quantity_complete, p_user_id);
+
+ -- Services never ship, so job completion is the fulfillment event: advance
+ -- the linked sales-order line the way post-shipment does for physical lines.
+ -- Lives HERE (not in app code) because completion has multiple entry points —
+ -- the ERP complete route AND the sync_finish_job_operation interceptor that
+ -- auto-completes when the last operation finishes. Recomputed from ALL jobs
+ -- on the line, so it is idempotent and lot-split safe. Runs before the
+ -- accounting-enabled / zero-WIP early returns.
+ -- NARROWED: only genuine Service lines (salesOrderLineType = 'Service') fulfill
+ -- by completion. They never receive a shipment line (the `create` edge fn skips
+ -- salesOrderLineType='Service'), so completion is their only fulfillment event.
+ -- A Non-Inventory *Part* (or Material/Tool/etc.) still ships via post-shipment and
+ -- must NOT be auto-fulfilled here — that was marking SO lines "Shipped" with no shipment.
+ IF v_item_tracking_type = 'Non-Inventory' AND v_sales_order_line_id IS NOT NULL
+ AND EXISTS (
+ SELECT 1 FROM "salesOrderLine" sol
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id
+ AND sol."salesOrderLineType" = 'Service'
+ ) THEN
+ SELECT COALESCE(SUM("quantityComplete"), 0)
+ INTO v_line_quantity_complete
+ FROM "job"
+ WHERE "salesOrderLineId" = v_sales_order_line_id
+ AND "companyId" = p_company_id
+ AND status != 'Cancelled';
+
+ UPDATE "salesOrderLine" sol
+ SET "quantitySent" = v_line_quantity_complete,
+ "sentComplete" = (COALESCE(sol."saleQuantity", 0) > 0 AND v_line_quantity_complete >= sol."saleQuantity"),
+ "sentDate" = CASE
+ WHEN COALESCE(sol."saleQuantity", 0) > 0
+ AND v_line_quantity_complete >= sol."saleQuantity"
+ AND sol."sentDate" IS NULL
+ THEN v_company_today
+ ELSE sol."sentDate"
+ END,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE sol.id = v_sales_order_line_id
+ AND sol."companyId" = p_company_id;
+ END IF;
+
+ -- Insert itemLedger entries based on tracking type.
+ -- Non-Inventory items (services) never enter inventory, and a re-completion at
+ -- the quantity already received has nothing new to receive.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_quantity_received_to_inventory > 0 THEN
+ IF v_job_make_method."requiresBatchTracking" THEN
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity"
+ WHERE attributes->>'Job Make Method' = v_job_make_method.id
+ AND "companyId" = p_company_id
+ AND status != 'Consumed'
+ ORDER BY "createdAt" DESC
+ LIMIT 1;
+
+ -- The job's own lot can already be Consumed by a lot MERGE: the batch
+ -- completion prompt offers the merge before member jobs are received,
+ -- and the merge is identity-only (it moves no unreceived stock). This
+ -- job's receipt must then land on the merge's output lot — walk Merge
+ -- activities from the job's lot to the terminal, still-live output.
+ IF v_tracked_entity.id IS NULL THEN
+ WITH RECURSIVE merge_walk(id) AS (
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ UNION
+ SELECT tao."trackedEntityId"
+ FROM merge_walk
+ JOIN "trackedActivityInput" tai
+ ON tai."trackedEntityId" = merge_walk.id
+ AND tai."companyId" = p_company_id
+ JOIN "trackedActivity" ta
+ ON ta.id = tai."trackedActivityId"
+ AND ta."companyId" = p_company_id
+ AND ta.type = 'Merge'
+ JOIN "trackedActivityOutput" tao
+ ON tao."trackedActivityId" = ta.id
+ AND tao."companyId" = p_company_id
+ )
+ SELECT te.*
+ INTO v_tracked_entity
+ FROM merge_walk
+ JOIN "trackedEntity" te ON te.id = merge_walk.id
+ WHERE te.status != 'Consumed'
+ ORDER BY te."createdAt" DESC
+ LIMIT 1;
+ END IF;
+
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Tracked entity not found';
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ ELSIF v_job_make_method."requiresSerialTracking" THEN
+ -- Receive exactly the newly completed units: units finished on the shop floor
+ -- (Available) first, then by serial number. A unit this job already received
+ -- is never received again, so re-completion cannot double-count. Rejected
+ -- (failed inspection) and Scrapped units never enter stock. The candidates
+ -- are locked so a concurrent completion cannot take the same units.
+ v_serial_unit_ids := ARRAY(
+ SELECT te.id
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')
+ AND te.quantity = 1
+ AND NOT EXISTS (
+ SELECT 1
+ FROM "itemLedger" il
+ WHERE il."trackedEntityId" = te.id
+ AND il."documentType" = 'Job Receipt'
+ AND il."documentId" = p_job_id
+ )
+ ORDER BY
+ CASE te.status WHEN 'Available' THEN 0 WHEN 'Reserved' THEN 1 ELSE 2 END,
+ te."readableId" NULLS LAST,
+ te."createdAt",
+ te.id
+ FOR UPDATE OF te
+ );
+
+ IF COALESCE(array_length(v_serial_unit_ids, 1), 0) >= v_quantity_received_to_inventory THEN
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ )
+ SELECT
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, 1, p_location_id, p_storage_unit_id,
+ unit_id, p_user_id
+ FROM unnest(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]) AS unit_id;
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = ANY(v_serial_unit_ids[1:v_quantity_received_to_inventory::INTEGER]);
+
+ ELSE
+ -- An item with no serial sequence never reaches assign-serial-numbers, so
+ -- the job still holds ONE seed entity covering every unit and there is
+ -- nothing to receive one at a time. Receive the delta against that seed,
+ -- the way the batch branch does. Raising here instead would abort the
+ -- jobOperation UPDATE itself: completion also runs inside
+ -- sync_finish_job_operation, a BEFORE trigger interceptor.
+ SELECT *
+ INTO v_tracked_entity
+ FROM "trackedEntity" te
+ WHERE te.attributes->>'Job Make Method' = v_job_make_method.id
+ AND te."companyId" = p_company_id
+ AND te.status NOT IN ('Consumed', 'Rejected', 'Scrapped')
+ AND te.quantity > 1
+ ORDER BY te."createdAt"
+ LIMIT 1
+ FOR UPDATE;
+
+ -- Genuinely short of units (some scrapped, some already received) rather
+ -- than un-numbered: receiving fewer than completed would leave the job's
+ -- received quantity ahead of the ledger.
+ IF v_tracked_entity.id IS NULL THEN
+ RAISE EXCEPTION 'Job % has % serial unit(s) left to receive, fewer than the % being completed',
+ v_job_id_readable, COALESCE(array_length(v_serial_unit_ids, 1), 0), v_quantity_received_to_inventory;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId",
+ "trackedEntityId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ v_tracked_entity.id, p_user_id
+ );
+
+ UPDATE "trackedEntity"
+ SET status = 'Available'
+ WHERE id = v_tracked_entity.id;
+ END IF;
+
+ ELSE
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Assembly Output', 'Job Receipt', p_job_id, p_company_id,
+ v_item_id, v_quantity_received_to_inventory, p_location_id, p_storage_unit_id,
+ p_user_id
+ );
+ END IF;
+ END IF;
+
+ -- Update pickMethod defaultStorageUnitId if needed
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' AND p_storage_unit_id IS NOT NULL AND p_location_id IS NOT NULL THEN
+ IF NOT EXISTS (
+ SELECT 1 FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id
+ AND "storageUnitId" IS NOT NULL
+ AND "storageUnitId" != p_storage_unit_id
+ LIMIT 1
+ ) THEN
+ IF EXISTS (
+ SELECT 1 FROM "pickMethod"
+ WHERE "itemId" = v_item_id AND "locationId" = p_location_id
+ ) THEN
+ UPDATE "pickMethod"
+ SET "defaultStorageUnitId" = p_storage_unit_id,
+ "updatedBy" = p_user_id,
+ "updatedAt" = NOW()
+ WHERE "itemId" = v_item_id
+ AND "locationId" = p_location_id;
+ ELSE
+ INSERT INTO "pickMethod" (
+ "itemId", "locationId", "defaultStorageUnitId",
+ "companyId", "createdBy", "createdAt"
+ ) VALUES (
+ v_item_id, p_location_id, p_storage_unit_id,
+ p_company_id, p_user_id, NOW()
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ -- Backflush unissued materials (delegated to shared function)
+ PERFORM backflush_job_materials(p_job_id, p_quantity_complete, p_company_id, p_user_id);
+
+ -- Check if accounting is enabled
+ SELECT "accountingEnabled"
+ INTO v_accounting_enabled
+ FROM "companySettings"
+ WHERE id = p_company_id;
+
+ v_accounting_enabled := COALESCE(v_accounting_enabled, false);
+
+ IF NOT v_accounting_enabled THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount", "laborAbsorptionAccount", "overheadAbsorptionAccount", "costOfGoodsSoldAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account, v_labor_absorption_account, v_overhead_absorption_account, v_cogs_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Resolve Raw Materials vs Finished Goods from the produced item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_item_inventory_account, v_item_inventory_description
+ FROM "item" i
+ WHERE i."id" = v_item_id
+ AND i."companyId" = p_company_id;
+
+ -- Non-Inventory (Service): the produced output is never stocked, so completion
+ -- relieves WIP straight to Cost of Goods Sold (Epicor "Make Direct" pattern).
+ -- >>> REV-REC SEAM (spec .ai/specs/2026-07-04-revenue-recognition.md, issue #1048):
+ -- when revenue recognition lands, Percent-of-Completion elements will gate THIS
+ -- branch off and post COGS as-incurred in the recognition run instead. <<<
+ IF v_item_tracking_type = 'Non-Inventory' THEN
+ v_item_inventory_account := v_cogs_account;
+ v_item_inventory_description := 'Cost of Goods Sold';
+ END IF;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END),
+ MAX(CASE WHEN "entityType" = 'CostCenter' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Employee' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location,
+ v_dimension_cost_center, v_dimension_employee
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location', 'CostCenter', 'Employee');
+
+ -- Post unposted production events as labor/machine + overhead absorption JEs
+ -- (mirrors post-production-event; this is the catch-up path for events that
+ -- were never posted individually)
+ FOR v_event IN
+ SELECT
+ pe.id,
+ pe.duration,
+ pe.type,
+ pe."employeeId",
+ wc."laborRate",
+ wc."machineRate",
+ wc."overheadRate"
+ FROM "productionEvent" pe
+ INNER JOIN "jobOperation" jo ON jo.id = pe."jobOperationId"
+ INNER JOIN "workCenter" wc ON wc.id = pe."workCenterId"
+ WHERE jo."jobId" = p_job_id
+ AND pe."endTime" IS NOT NULL
+ AND pe."postedToGL" = false
+ AND pe.duration > 0
+ LOOP
+ v_duration_hours := v_event.duration::NUMERIC / 3600;
+ v_rate := CASE
+ WHEN v_event.type = 'Machine' THEN COALESCE(v_event."machineRate", 0)
+ ELSE COALESCE(v_event."laborRate", 0)
+ END;
+ v_labor_cost := v_duration_hours * v_rate;
+ v_overhead_cost := v_duration_hours * COALESCE(v_event."overheadRate", 0);
+ v_event_reference := 'production-event:' || v_event.id;
+
+ IF (v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL)
+ OR (v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL) THEN
+ v_labor_journal_line_reference := nanoid();
+
+ -- Get current accounting period
+ SELECT id INTO v_labor_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ RETURNING id INTO v_labor_accounting_period_id;
+
+ IF v_labor_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_company_today)::DATE,
+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_labor_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_labor_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_labor_journal_entry_id, v_labor_accounting_period_id,
+ v_event.type || ' Time — Job ' || v_job_id_readable,
+ v_company_today, p_company_id, 'Production Event', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_labor_journal_id;
+
+ IF v_labor_cost > 0 AND v_labor_absorption_account IS NOT NULL THEN
+ -- DR WIP (labor/machine)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account',
+ v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP line (the finished good this labor rolls into)
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Labor/Machine Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_labor_absorption_account, 'Labor/Machine Absorption',
+ -v_labor_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+
+ IF v_overhead_cost > 0 AND v_overhead_absorption_account IS NOT NULL THEN
+ -- DR WIP (overhead)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_wip_account, 'WIP Account (Overhead)',
+ v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on WIP overhead line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on WIP overhead line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ -- CR Overhead Absorption
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_labor_journal_id, v_overhead_absorption_account, 'Overhead Absorption',
+ -v_overhead_cost, 1,
+ 'Production Event', p_job_id, v_event_reference,
+ v_labor_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ -- Employee dimension on overhead absorption line
+ IF v_dimension_employee IS NOT NULL AND v_event."employeeId" IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_employee, v_event."employeeId", p_company_id
+ );
+ END IF;
+
+ -- Item dimension on overhead absorption line
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_labor_jl_id, v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+ END IF;
+ END IF;
+
+ UPDATE "productionEvent"
+ SET "postedToGL" = true
+ WHERE id = v_event.id;
+ END LOOP;
+
+ -- Calculate accumulated WIP cost for this job
+ SELECT COALESCE(ABS(SUM(jl.amount)), 0)
+ INTO v_accumulated_wip_cost
+ FROM "journalLine" jl
+ INNER JOIN journal j ON j.id = jl."journalId"
+ WHERE jl."accountId" = v_wip_account
+ AND jl."documentId" = p_job_id
+ AND j."companyId" = p_company_id;
+
+ IF v_accumulated_wip_cost <= 0 THEN
+ RETURN;
+ END IF;
+
+ -- A stocked re-completion at the quantity already received has no units to
+ -- carry this cost. The catch-up WIP above stays in WIP and is discharged with
+ -- the next receipt; the per-unit cost below would otherwise divide by zero.
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory'
+ AND v_quantity_received_to_inventory <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_today := v_company_today;
+ v_journal_line_reference := nanoid();
+
+ -- Get accounting period for WIP discharge
+ SELECT id INTO v_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_accounting_period_id IS NULL THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_today
+ AND "endDate" >= v_today
+ RETURNING id INTO v_accounting_period_id;
+
+ IF v_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_today)::DATE,
+ (date_trunc('month', v_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_accounting_period_id;
+ END IF;
+ END IF;
+
+ v_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_journal_entry_id, v_accounting_period_id,
+ 'Job Completion ' || v_job_id_readable,
+ v_today, p_company_id, 'Job Receipt', 'Posted',
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_journal_id;
+
+ -- DR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_item_inventory_account, v_item_inventory_description,
+ v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := ARRAY[v_labor_jl_id];
+
+ -- CR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_journal_id, v_wip_account, 'WIP Account',
+ -v_accumulated_wip_cost, v_quantity_received_to_inventory,
+ 'Job Receipt', p_job_id, 'job:' || p_job_id,
+ v_journal_line_reference, p_company_id
+ )
+ RETURNING id INTO v_labor_jl_id;
+
+ v_jl_ids := v_jl_ids || v_labor_jl_id;
+
+ -- Write costLedger entry for finished good (skipped for Non-Inventory: no
+ -- output layer exists for a service — its cost went straight to COGS above)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Output', 'Direct Cost', false,
+ 'Job Receipt', p_job_id, v_item_id,
+ v_quantity_received_to_inventory, v_accumulated_wip_cost,
+ v_quantity_received_to_inventory, p_company_id
+ );
+ END IF;
+
+ -- Update item cost
+ SELECT "costingMethod", "unitCost", "itemPostingGroupId"
+ INTO v_costing_method, v_existing_unit_cost, v_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ -- Update itemCost.unitCost (skipped for Non-Inventory: a service has no
+ -- stocked unit cost; the read above still feeds the dimension inserts below)
+ IF v_item_tracking_type IS DISTINCT FROM 'Non-Inventory' THEN
+ v_new_per_unit_cost := v_accumulated_wip_cost / v_quantity_received_to_inventory;
+
+ IF v_costing_method = 'Average' THEN
+ SELECT COALESCE(SUM(quantity), 0)
+ INTO v_total_qty_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+
+ v_prior_qty := v_total_qty_on_hand - v_quantity_received_to_inventory;
+ v_prior_value := v_prior_qty * COALESCE(v_existing_unit_cost, 0);
+
+ IF v_total_qty_on_hand > 0 THEN
+ v_new_unit_cost := (v_prior_value + v_accumulated_wip_cost) / v_total_qty_on_hand;
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ ELSIF v_costing_method IN ('FIFO', 'LIFO') THEN
+ UPDATE "itemCost"
+ SET "unitCost" = v_new_per_unit_cost
+ WHERE "itemId" = v_item_id
+ AND "companyId" = p_company_id;
+ END IF;
+ END IF;
+
+ -- Insert dimensions on WIP discharge journal lines
+ IF v_jl_ids IS NOT NULL AND array_length(v_jl_ids, 1) > 0 THEN
+ FOR i IN 1..array_length(v_jl_ids, 1)
+ LOOP
+ IF v_item_posting_group_id IS NOT NULL AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item_posting_group, v_item_posting_group_id, p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_item_id IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_item, v_item_id, p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_custom_field_unique_values(table_name text, field_key text, company_id text)
+ RETURNS TABLE(value jsonb)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM assert_company_access(company_id);
+
+ RETURN QUERY EXECUTE format(
+ 'SELECT DISTINCT jsonb_extract_path("customFields", $1) as value
+ FROM %I
+ WHERE "companyId" = $2
+ AND "customFields" ? $1
+ AND jsonb_extract_path("customFields", $1) IS NOT NULL',
+ table_name
+ ) USING field_key, company_id;
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_inventory_quantities(company_id text, location_id text, item_id text DEFAULT NULL::text)
+ RETURNS TABLE(id text, "readableId" text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "materialSubstanceId" text, "materialFormId" text, "dimensionId" text, dimension text, "finishId" text, finish text, "gradeId" text, grade text, "materialType" text, "materialTypeId" text, "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "maximumInventoryQuantity" numeric, "orderMultiple" integer, "quantityOnHand" numeric, "quantityOnHold" numeric, "quantityRejected" numeric, "quantityOnSalesOrder" numeric, "quantityOnPurchaseOrder" numeric, "quantityOnProductionOrder" numeric, "quantityOnProductionDemand" numeric, "demandForecast" numeric, "usageLast30Days" numeric, "usageLast90Days" numeric, "daysRemaining" numeric, "storageTypeIds" text[], "storageUnitIds" text[], tags text[])
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+ DECLARE
+ v_cutoff TIMESTAMPTZ;
+ BEGIN
+ PERFORM assert_company_access(company_id);
+
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+
+WITH
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId",
+ SUM(pol."quantityToReceive" * pol."conversionFactor") AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND (item_id IS NULL OR pol."itemId" = item_id)
+ GROUP BY pol."itemId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ AND (item_id IS NULL OR sol."itemId" = item_id)
+ GROUP BY sol."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR jm."itemId" = item_id)
+ GROUP BY jm."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ AND (item_id IS NULL OR j."itemId" = item_id)
+ GROUP BY j."itemId"
+ ),
+ -- Snapshot (immutable untracked rows) + live tracked rows + live untracked
+ -- rows past the snapshot cutoff. With no snapshot (v_cutoff NULL) the third
+ -- arm is the full untracked history — the pre-snapshot behavior.
+ item_ledgers AS (
+ SELECT
+ combined."itemId",
+ SUM(combined."quantityOnHand") AS "quantityOnHand",
+ SUM(combined."quantityOnHold") AS "quantityOnHold",
+ SUM(combined."quantityRejected") AS "quantityRejected",
+ SUM(combined."consumed30") / 30 AS "usageLast30Days",
+ SUM(combined."consumed90") / 90 AS "usageLast90Days"
+ FROM (
+ SELECT
+ s."itemId",
+ s."quantity" AS "quantityOnHand",
+ 0::NUMERIC AS "quantityOnHold",
+ 0::NUMERIC AS "quantityRejected",
+ s."consumed30",
+ s."consumed90"
+ FROM "itemLedgerSnapshot" s
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT
+ il."itemId",
+ CASE WHEN il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'On Hold'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected'
+ THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '30 days'
+ THEN -il."quantity" ELSE 0 END,
+ CASE WHEN il."entryType" IN ('Negative Adjmt.', 'Sale', 'Consumption', 'Assembly Consumption')
+ AND il."createdAt" >= CURRENT_DATE - INTERVAL '90 days'
+ THEN -il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) combined
+ GROUP BY combined."itemId"
+ ),
+ -- Distinct storage units the item is stocked in: snapshot arrays plus the
+ -- same live arms. NULL storageUnitId rows are excluded.
+ item_storage_units AS (
+ SELECT
+ u."itemId",
+ ARRAY_AGG(DISTINCT u."storageUnitId") AS "storageUnitIds"
+ FROM (
+ SELECT s."itemId", su_id AS "storageUnitId"
+ FROM "itemLedgerSnapshot" s
+ CROSS JOIN LATERAL unnest(s."storageUnitIds") AS su_id
+ WHERE s."companyId" = company_id
+ AND s."locationId" = location_id
+ AND (item_id IS NULL OR s."itemId" = item_id)
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NOT NULL
+
+ UNION ALL
+
+ SELECT il."itemId", il."storageUnitId"
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ AND il."storageUnitId" IS NOT NULL
+ AND (item_id IS NULL OR il."itemId" = item_id)
+ AND il."trackedEntityId" IS NULL
+ AND (v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ ) u
+ GROUP BY u."itemId"
+ ),
+ -- Distinct storage types, derived from the merged storage-unit ids.
+ item_storage_types AS (
+ SELECT
+ isu."itemId",
+ ARRAY_AGG(DISTINCT t) AS "storageTypeIds"
+ FROM item_storage_units isu
+ INNER JOIN "storageUnit" su
+ ON su."id" = ANY(isu."storageUnitIds")
+ AND su."companyId" = company_id
+ CROSS JOIN LATERAL unnest(su."storageTypeIds") AS t
+ GROUP BY isu."itemId"
+ ),
+ demand_forecast AS (
+ SELECT combined."itemId", SUM(qty) AS "demandForecast"
+ FROM (
+ SELECT da."itemId", da."actualQuantity" AS qty
+ FROM "demandActual" da
+ WHERE da."companyId" = company_id AND da."locationId" = location_id
+ AND (item_id IS NULL OR da."itemId" = item_id)
+ UNION ALL
+ SELECT df."itemId", df."forecastQuantity" AS qty
+ FROM "demandForecast" df
+ WHERE df."companyId" = company_id AND df."locationId" = location_id
+ AND (item_id IS NULL OR df."itemId" = item_id)
+ ) combined
+ GROUP BY combined."itemId"
+ )
+
+SELECT
+ i."id",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."dimensionId",
+ md."name" AS "dimension",
+ m."finishId",
+ mf."name" AS "finish",
+ m."gradeId",
+ mg."name" AS "grade",
+ mt."name" AS "materialType",
+ m."materialTypeId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."maximumInventoryQuantity",
+ ip."orderMultiple",
+ COALESCE(il."quantityOnHand", 0) AS "quantityOnHand",
+ COALESCE(il."quantityOnHold", 0) AS "quantityOnHold",
+ COALESCE(il."quantityRejected", 0) AS "quantityRejected",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(jo."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(jr."quantityOnProductionDemand", 0) AS "quantityOnProductionDemand",
+ COALESCE(df."demandForecast", 0) AS "demandForecast",
+ COALESCE(il."usageLast30Days", 0) AS "usageLast30Days",
+ COALESCE(il."usageLast90Days", 0) AS "usageLast90Days",
+ CASE
+ WHEN COALESCE(il."usageLast30Days", 0) > 0
+ THEN ROUND(COALESCE(il."quantityOnHand", 0) / il."usageLast30Days", 2)
+ ELSE NULL
+ END AS "daysRemaining",
+ COALESCE(ist."storageTypeIds", ARRAY[]::TEXT[]) AS "storageTypeIds",
+ COALESCE(isu."storageUnitIds", ARRAY[]::TEXT[]) AS "storageUnitIds",
+ COALESCE(m."tags", p."tags", t."tags", c."tags") AS "tags"
+FROM
+ "item" i
+ LEFT JOIN item_ledgers il ON i."id" = il."itemId"
+ LEFT JOIN item_storage_types ist ON i."id" = ist."itemId"
+ LEFT JOIN item_storage_units isu ON i."id" = isu."itemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."itemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."itemId"
+ LEFT JOIN open_jobs jo ON i."id" = jo."itemId"
+ LEFT JOIN open_job_requirements jr ON i."id" = jr."itemId"
+ LEFT JOIN demand_forecast df ON i."id" = df."itemId"
+ LEFT JOIN material m ON i."readableId" = m."id" AND m."companyId" = company_id
+ LEFT JOIN part p ON i."readableId" = p."id" AND p."companyId" = company_id
+ LEFT JOIN tool t ON i."readableId" = t."id" AND t."companyId" = company_id
+ LEFT JOIN consumable c ON i."readableId" = c."id" AND c."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mf ON m."finishId" = mf."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemReplenishment" ir ON i."id" = ir."itemId" AND ir."companyId" = company_id
+ LEFT JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+WHERE
+ i."itemTrackingType" <> 'Non-Inventory' AND i."companyId" = company_id
+ AND (item_id IS NULL OR i."id" = item_id);
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_inventory_tie_out(company_id text, as_of_date date DEFAULT NULL::date)
+ RETURNS TABLE("accountKind" text, "accountId" text, "accountName" text, "subledgerValue" numeric, "glBalance" numeric, variance numeric)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ v_as_of DATE := COALESCE(as_of_date, CURRENT_DATE);
+ v_rm_account TEXT;
+ v_fg_account TEXT;
+BEGIN
+ PERFORM assert_company_access(company_id);
+
+ SELECT ad."rawMaterialsAccount", ad."finishedGoodsAccount"
+ INTO v_rm_account, v_fg_account
+ FROM "accountDefault" ad
+ WHERE ad."companyId" = company_id;
+
+ IF v_rm_account IS NULL OR v_fg_account IS NULL THEN
+ RETURN; -- company has no account defaults (accounting never configured)
+ END IF;
+
+ RETURN QUERY
+ WITH subledger AS (
+ SELECT
+ CASE WHEN v."replenishmentSystem" IN ('Make', 'Buy and Make')
+ THEN 'finishedGoods' ELSE 'rawMaterials' END AS "kind",
+ SUM(v."totalValue") AS "value"
+ FROM get_inventory_valuation(company_id, as_of_date, NULL) v
+ GROUP BY 1
+ ),
+ gl AS (
+ SELECT jl."accountId" AS "account", SUM(jl."amount") AS "balance"
+ FROM "journal" j
+ INNER JOIN "journalLine" jl
+ ON jl."journalId" = j."id" AND jl."companyId" = j."companyId"
+ WHERE j."companyId" = company_id
+ AND j."status" <> 'Draft'
+ AND j."postingDate" <= v_as_of
+ AND jl."accountId" IN (v_rm_account, v_fg_account)
+ GROUP BY jl."accountId"
+ ),
+ accounts AS (
+ SELECT 'rawMaterials' AS "kind", v_rm_account AS "account"
+ UNION ALL
+ SELECT 'finishedGoods' AS "kind", v_fg_account AS "account"
+ )
+ SELECT
+ a."kind" AS "accountKind",
+ a."account" AS "accountId",
+ acc."name" AS "accountName",
+ COALESCE(s."value", 0) AS "subledgerValue",
+ COALESCE(g."balance", 0) AS "glBalance",
+ COALESCE(s."value", 0) - COALESCE(g."balance", 0) AS "variance"
+ -- account is companyGroup-scoped (no companyId); the ids come from the
+ -- company-scoped accountDefault row, so joining by id alone is correct.
+ FROM accounts a
+ LEFT JOIN "account" acc ON acc."id" = a."account"
+ LEFT JOIN subledger s ON s."kind" = a."kind"
+ LEFT JOIN gl g ON g."account" = a."account"
+ ORDER BY a."kind" DESC; -- rawMaterials first
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_inventory_valuation(company_id text, as_of_date date DEFAULT NULL::date, location_id text DEFAULT NULL::text)
+ RETURNS TABLE("locationId" text, "locationName" text, "itemId" text, "readableIdWithRevision" text, name text, "thumbnailPath" text, type "itemType", "replenishmentSystem" "itemReplenishmentSystem", "unitOfMeasureCode" text, "costingMethod" "itemCostingMethod", "quantityOnHand" numeric, "quantityOnHold" numeric, "quantityRejected" numeric, "unitCost" numeric, "totalValue" numeric)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+DECLARE
+ v_cutoff TIMESTAMPTZ;
+ v_dated BOOLEAN := as_of_date IS NOT NULL AND as_of_date < CURRENT_DATE;
+BEGIN
+ PERFORM assert_company_access(company_id);
+
+ SELECT MAX("snapshotCutoff") INTO v_cutoff
+ FROM "itemLedgerSnapshot"
+ WHERE "companyId" = company_id;
+
+ RETURN QUERY
+ WITH quantities AS (
+ SELECT
+ combined."itemId",
+ combined."locationId",
+ SUM(combined."quantity") AS "quantityOnHand",
+ SUM(combined."onHold") AS "quantityOnHold",
+ SUM(combined."rejected") AS "quantityRejected"
+ FROM (
+ -- Arm 1: snapshot (untracked, immutable). Skipped on dated queries —
+ -- the snapshot has no postingDate grain.
+ SELECT
+ s."itemId",
+ NULLIF(s."locationId", '') AS "locationId",
+ s."quantity",
+ 0::NUMERIC AS "onHold",
+ 0::NUMERIC AS "rejected"
+ FROM "itemLedgerSnapshot" s
+ WHERE NOT v_dated
+ AND s."companyId" = company_id
+ AND (location_id IS NULL OR s."locationId" = location_id)
+
+ UNION ALL
+
+ -- Arm 2: tracked rows, always live (status flips in place).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ CASE WHEN il."trackedEntityStatus" = 'On Hold' THEN il."quantity" ELSE 0 END,
+ CASE WHEN il."trackedEntityStatus" = 'Rejected' THEN il."quantity" ELSE 0 END
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NOT NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+
+ UNION ALL
+
+ -- Arm 3: untracked delta past the cutoff (current path) OR the full
+ -- untracked history filtered by postingDate (dated path / no snapshot).
+ SELECT
+ il."itemId",
+ il."locationId",
+ il."quantity",
+ 0::NUMERIC,
+ 0::NUMERIC
+ FROM "itemLedger" il
+ WHERE il."companyId" = company_id
+ AND il."trackedEntityId" IS NULL
+ AND (location_id IS NULL OR il."locationId" = location_id)
+ AND (v_dated OR v_cutoff IS NULL OR il."createdAt" >= v_cutoff)
+ AND (NOT v_dated OR il."postingDate" <= as_of_date)
+ ) combined
+ GROUP BY combined."itemId", combined."locationId"
+ HAVING SUM(combined."quantity") <> 0
+ ),
+ carrying AS (
+ -- Company-level effective unit cost per item, by costing method.
+ SELECT
+ ic."itemId",
+ ic."costingMethod",
+ CASE ic."costingMethod"
+ WHEN 'Standard' THEN ic."standardCost"
+ WHEN 'Average' THEN ic."unitCost"
+ ELSE COALESCE(layers."layerUnitCost", ic."unitCost")
+ END AS "unitCost"
+ FROM "itemCost" ic
+ LEFT JOIN LATERAL (
+ SELECT
+ SUM(
+ cl."remainingQuantity"
+ * (cl."cost" + COALESCE(adj."applied", 0))
+ / NULLIF(cl."quantity", 0)
+ ) / NULLIF(SUM(cl."remainingQuantity"), 0) AS "layerUnitCost"
+ FROM "costLedger" cl
+ LEFT JOIN LATERAL (
+ SELECT SUM(a."cost") AS "applied"
+ FROM "costLedger" a
+ WHERE a."appliesToCostLedgerId" = cl."id"
+ AND a."companyId" = cl."companyId"
+ ) adj ON TRUE
+ WHERE cl."itemId" = ic."itemId"
+ AND cl."companyId" = ic."companyId"
+ AND cl."remainingQuantity" > 0
+ ) layers ON ic."costingMethod" IN ('FIFO', 'LIFO')
+ WHERE ic."companyId" = company_id
+ )
+ SELECT
+ l."id" AS "locationId",
+ l."name" AS "locationName",
+ i."id" AS "itemId",
+ i."readableIdWithRevision",
+ i."name",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."type",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ c."costingMethod",
+ q."quantityOnHand",
+ q."quantityOnHold",
+ q."quantityRejected",
+ COALESCE(c."unitCost", 0) AS "unitCost",
+ q."quantityOnHand" * COALESCE(c."unitCost", 0) AS "totalValue"
+ FROM quantities q
+ INNER JOIN "item" i ON q."itemId" = i."id" AND i."companyId" = company_id
+ INNER JOIN "location" l ON q."locationId" = l."id" AND l."companyId" = company_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId" AND mu."companyId" = company_id
+ LEFT JOIN carrying c ON c."itemId" = q."itemId"
+ ORDER BY l."name", i."readableIdWithRevision";
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_item_quantities_by_tracking_id(item_id text, company_id text, location_id text)
+ RETURNS TABLE("itemId" text, "storageUnitId" text, "storageUnitName" text, "trackedEntityId" text, "readableId" text, quantity numeric)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM assert_company_access(company_id);
+
+ RETURN QUERY
+ SELECT
+ il."itemId",
+ il."storageUnitId",
+ s."name" AS "storageUnitName",
+ il."trackedEntityId",
+ te."readableId",
+ SUM(il."quantity") AS "quantity"
+ FROM
+ "itemLedger" il
+ LEFT JOIN
+ "storageUnit" s ON il."storageUnitId" = s."id"
+ LEFT JOIN
+ "trackedEntity" te ON il."trackedEntityId" = te."id"
+ WHERE
+ il."itemId" = item_id
+ AND il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY
+ il."itemId",
+ il."storageUnitId",
+ s."name",
+ il."trackedEntityId",
+ te."readableId";
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_job_quantity_on_hand(job_id text, company_id text, location_id text)
+ RETURNS TABLE(id text, "jobMaterialItemId" text, "jobMakeMethodId" text, "itemReadableId" text, name text, description text, "itemTrackingType" "itemTrackingType", "methodType" "methodType", type "itemType", "thumbnailPath" text, "unitOfMeasureCode" text, "quantityPerParent" numeric, "estimatedQuantity" numeric, "quantityIssued" numeric, "quantityOnHandInStorageUnit" numeric, "quantityOnHandNotInStorageUnit" numeric, "quantityOnSalesOrder" numeric, "quantityOnPurchaseOrder" numeric, "quantityOnProductionOrder" numeric, "quantityFromProductionOrderInStorageUnit" numeric, "quantityFromProductionOrderNotInStorageUnit" numeric, "quantityInTransitToStorageUnit" numeric, "storageUnitId" text, "storageUnitName" text, "itemScrapPercentage" numeric, "substitutedFromItemId" text)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public', 'pg_temp'
+AS $function$
+ BEGIN
+ PERFORM assert_company_access(company_id);
+
+ RETURN QUERY
+
+WITH
+ job_materials AS (
+ SELECT
+ jm."id",
+ jm."itemId",
+ jm."jobMakeMethodId",
+ jm."description",
+ jm."methodType",
+ jm."quantity",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ jm."storageUnitId",
+ jm."itemScrapPercentage",
+ jm."substitutedFromItemId"
+ FROM
+ "jobMaterial" jm
+ WHERE
+ jm."jobId" = job_id
+ -- SECURITY DEFINER bypasses RLS, so the caller's company must be checked
+ -- here: without it a valid job id from another tenant returns its rows.
+ AND jm."companyId" = company_id
+ ),
+ -- Distinct item / item+unit sets used to FILTER the aggregate CTEs below.
+ -- Joining the raw job_materials rows fans out (multiplies) the aggregates when
+ -- an item is on more than one BoM line — these dedupe so each item is counted
+ -- once.
+ job_material_items AS (
+ SELECT DISTINCT jm."itemId" FROM job_materials jm
+ ),
+ job_material_item_units AS (
+ SELECT DISTINCT jm."itemId", jm."storageUnitId" FROM job_materials jm
+ ),
+ open_purchase_orders AS (
+ SELECT
+ pol."itemId" AS "purchaseOrderItemId",
+ SUM(pol."quantityToReceive" * COALESCE(pol."conversionFactor", 1)) AS "quantityOnPurchaseOrder"
+ FROM
+ "purchaseOrder" po
+ INNER JOIN "purchaseOrderLine" pol
+ ON pol."purchaseOrderId" = po."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = pol."itemId"
+ WHERE
+ po."status" IN (
+ 'Planned',
+ 'Needs Approval',
+ 'To Review',
+ 'To Receive',
+ 'To Receive and Invoice'
+ )
+ AND po."companyId" = company_id
+ AND pol."locationId" = location_id
+ AND pol."receivedComplete" = false
+ GROUP BY pol."itemId"
+ ),
+ open_stock_transfers_to AS (
+ SELECT
+ stl."itemId",
+ stl."toStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferTo"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."toStorageUnitId"
+ ),
+ open_stock_transfers_from AS (
+ SELECT
+ stl."itemId",
+ stl."fromStorageUnitId" AS "storageUnitId",
+ SUM(stl."outstandingQuantity") AS "quantityOnStockTransferFrom"
+ FROM "stockTransferLine" stl
+ INNER JOIN "stockTransfer" st ON stl."stockTransferId" = st."id"
+ INNER JOIN job_material_items jm ON jm."itemId" = stl."itemId"
+ WHERE st."status" IN ('Released', 'In Progress')
+ AND st."companyId" = company_id
+ AND st."locationId" = location_id
+ GROUP BY stl."itemId", stl."fromStorageUnitId"
+ ),
+ stock_transfers_in_transit AS (
+ SELECT
+ COALESCE(stt."itemId", stf."itemId") AS "itemId",
+ COALESCE(stt."storageUnitId", stf."storageUnitId") AS "storageUnitId",
+ COALESCE(stt."quantityOnStockTransferTo", 0) - COALESCE(stf."quantityOnStockTransferFrom", 0) AS "quantityInTransit"
+ FROM open_stock_transfers_to stt
+ FULL OUTER JOIN open_stock_transfers_from stf ON stt."itemId" = stf."itemId" AND stt."storageUnitId" = stf."storageUnitId"
+ ),
+ open_sales_orders AS (
+ SELECT
+ sol."itemId" AS "salesOrderItemId",
+ SUM(sol."quantityToSend") AS "quantityOnSalesOrder"
+ FROM
+ "salesOrder" so
+ INNER JOIN "salesOrderLine" sol
+ ON sol."salesOrderId" = so."id"
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = sol."itemId"
+ WHERE
+ so."status" IN (
+ 'Confirmed',
+ 'To Ship and Invoice',
+ 'To Ship',
+ 'To Invoice',
+ 'In Progress'
+ )
+ AND so."companyId" = company_id
+ AND sol."locationId" = location_id
+ GROUP BY sol."itemId"
+ ),
+ open_jobs AS (
+ SELECT
+ j."itemId" AS "jobItemId",
+ SUM(j."productionQuantity" + j."scrapQuantity" - j."quantityReceivedToInventory" - j."quantityShipped") AS "quantityOnProductionOrder"
+ FROM job j
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY j."itemId"
+ ),
+ open_job_requirements AS (
+ SELECT
+ jm."itemId",
+ jm."storageUnitId",
+ SUM(jm."quantityToIssue") AS "quantityOnProductionDemand"
+ FROM "jobMaterial" jm
+ INNER JOIN "job" j ON jm."jobId" = j."id"
+ INNER JOIN job_material_items jmat
+ ON jmat."itemId" = jm."itemId"
+ WHERE j."status" IN (
+ 'Planned',
+ 'Ready',
+ 'In Progress',
+ 'Paused'
+ )
+ AND jm."methodType" != 'Make to Order'
+ AND j."companyId" = company_id
+ AND j."locationId" = location_id
+ GROUP BY jm."itemId", jm."storageUnitId"
+ ),
+ open_job_requirements_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND jm."storageUnitId" = ojr."storageUnitId"
+ GROUP BY ojr."itemId"
+ ),
+ open_job_requirements_not_in_storage_unit AS (
+ SELECT
+ ojr."itemId",
+ SUM(ojr."quantityOnProductionDemand") AS "quantityOnProductionDemandNotInStorageUnit"
+ FROM open_job_requirements ojr
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = ojr."itemId" AND (jm."storageUnitId" IS NULL OR ojr."storageUnitId" IS NULL OR jm."storageUnitId" != ojr."storageUnitId")
+ GROUP BY ojr."itemId"
+ ),
+ item_ledgers AS (
+ SELECT
+ il."itemId" AS "ledgerItemId",
+ il."storageUnitId",
+ -- quantityOnHand excludes only Rejected tracked entities. On Hold
+ -- units are still physically in the warehouse and count toward
+ -- on-hand. Rows with no tracked entity always count.
+ SUM(il."quantity") FILTER (
+ WHERE il."trackedEntityStatus" IS NULL
+ OR il."trackedEntityStatus" != 'Rejected'
+ ) AS "quantityOnHand"
+ FROM "itemLedger" il
+ INNER JOIN job_material_items jm
+ ON jm."itemId" = il."itemId"
+ WHERE il."companyId" = company_id
+ AND il."locationId" = location_id
+ GROUP BY il."itemId", il."storageUnitId"
+ ),
+ item_ledgers_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND jm."storageUnitId" = il."storageUnitId"
+ GROUP BY il."ledgerItemId"
+ ),
+ item_ledgers_not_in_storage_unit AS (
+ SELECT
+ il."ledgerItemId",
+ SUM(il."quantityOnHand") AS "quantityOnHandNotInStorageUnit"
+ FROM item_ledgers il
+ INNER JOIN job_material_item_units jm
+ ON jm."itemId" = il."ledgerItemId" AND (jm."storageUnitId" IS NULL OR il."storageUnitId" IS NULL OR jm."storageUnitId" != il."storageUnitId")
+ GROUP BY il."ledgerItemId"
+ )
+
+SELECT
+ jm."id",
+ jm."itemId" AS "jobMaterialItemId",
+ jm."jobMakeMethodId",
+ i."readableId" AS "itemReadableId",
+ i."name",
+ jm."description",
+ i."itemTrackingType",
+ jm."methodType",
+ i."type",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ jm."quantity" as "quantityPerParent",
+ jm."estimatedQuantity",
+ jm."quantityIssued",
+ COALESCE(ils."quantityOnHandInStorageUnit", 0) AS "quantityOnHandInStorageUnit",
+ COALESCE(ilns."quantityOnHandNotInStorageUnit", 0) AS "quantityOnHandNotInStorageUnit",
+ COALESCE(so."quantityOnSalesOrder", 0) AS "quantityOnSalesOrder",
+ COALESCE(po."quantityOnPurchaseOrder", 0) AS "quantityOnPurchaseOrder",
+ COALESCE(oj."quantityOnProductionOrder", 0) AS "quantityOnProductionOrder",
+ COALESCE(ojis."quantityOnProductionDemandInStorageUnit", 0) AS "quantityFromProductionOrderInStorageUnit",
+ COALESCE(ojns."quantityOnProductionDemandNotInStorageUnit", 0) AS "quantityFromProductionOrderNotInStorageUnit",
+ COALESCE(stit."quantityInTransit", 0) AS "quantityInTransitToStorageUnit",
+ jm."storageUnitId",
+ s."name" AS "storageUnitName",
+ jm."itemScrapPercentage",
+ jm."substitutedFromItemId"
+FROM
+ job_materials jm
+ INNER JOIN "item" i ON i."id" = jm."itemId"
+ LEFT JOIN "storageUnit" s ON s."id" = jm."storageUnitId"
+ LEFT JOIN item_ledgers_in_storage_unit ils ON i."id" = ils."ledgerItemId"
+ LEFT JOIN item_ledgers_not_in_storage_unit ilns ON i."id" = ilns."ledgerItemId"
+ LEFT JOIN open_sales_orders so ON i."id" = so."salesOrderItemId"
+ LEFT JOIN open_purchase_orders po ON i."id" = po."purchaseOrderItemId"
+ LEFT JOIN open_jobs oj ON i."id" = oj."jobItemId"
+ LEFT JOIN open_job_requirements_in_storage_unit ojis ON i."id" = ojis."itemId"
+ LEFT JOIN open_job_requirements_not_in_storage_unit ojns ON i."id" = ojns."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN stock_transfers_in_transit stit ON jm."itemId" = stit."itemId" AND jm."storageUnitId" = stit."storageUnitId";
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_training_assignment_status(p_company_id text, p_employee_id text DEFAULT NULL::text)
+ RETURNS TABLE("trainingAssignmentId" text, "trainingId" text, "trainingName" text, frequency "trainingFrequency", "trainingType" "trainingType", "employeeId" text, "employeeName" text, "avatarUrl" text, "employeeStartDate" date, "companyId" text, "currentPeriod" text, "completionId" integer, "completedAt" timestamp with time zone, status text)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM assert_company_access(p_company_id);
+
+ RETURN QUERY
+ WITH group_users AS (
+ -- Get distinct users from all training assignment groups for this company
+ SELECT DISTINCT
+ ta.id AS assignment_id,
+ jsonb_array_elements_text(users_for_groups(ta."groupIds")) AS user_id
+ FROM "trainingAssignment" ta
+ WHERE ta."companyId" = p_company_id
+ ),
+ assigned_employees AS (
+ SELECT DISTINCT
+ ta.id AS "trainingAssignmentId",
+ ta."trainingId" AS "trainingId",
+ t."name" AS "trainingName",
+ t."frequency",
+ t."type" AS "trainingType",
+ u.id AS "employeeId",
+ u."fullName" AS "employeeName",
+ u."avatarUrl" AS "avatarUrl",
+ ej."startDate" AS "employeeStartDate",
+ ta."companyId" AS "companyId"
+ FROM "trainingAssignment" ta
+ JOIN "training" t ON t.id = ta."trainingId" AND t."status" = 'Active'
+ JOIN group_users gu ON gu.assignment_id = ta.id
+ JOIN "user" u ON u.id = gu.user_id AND u.active = TRUE
+ JOIN "employee" e ON e.id = u.id AND e."companyId" = ta."companyId"
+ LEFT JOIN "employeeJob" ej ON ej.id = u.id AND ej."companyId" = ta."companyId"
+ WHERE ta."companyId" = p_company_id
+ AND (p_employee_id IS NULL OR u.id = p_employee_id)
+ ),
+ with_period AS (
+ SELECT ae.*, get_current_training_period(ae."frequency") AS "currentPeriod"
+ FROM assigned_employees ae
+ )
+ SELECT
+ wp."trainingAssignmentId",
+ wp."trainingId",
+ wp."trainingName",
+ wp."frequency",
+ wp."trainingType",
+ wp."employeeId",
+ wp."employeeName",
+ wp."avatarUrl",
+ wp."employeeStartDate",
+ wp."companyId",
+ wp."currentPeriod",
+ tc.id AS "completionId",
+ tc."completedAt" AS "completedAt",
+ CASE
+ WHEN wp."frequency" = 'Once' THEN
+ CASE WHEN tc.id IS NOT NULL THEN 'Completed' ELSE 'Pending' END
+ WHEN tc.id IS NOT NULL THEN 'Completed'
+ WHEN NOT employee_requires_period(wp."employeeStartDate", wp."currentPeriod") THEN 'Not Required'
+ WHEN get_period_end_date(wp."currentPeriod") < CURRENT_DATE THEN 'Overdue'
+ ELSE 'Pending'
+ END AS status
+ FROM with_period wp
+ LEFT JOIN "trainingCompletion" tc ON
+ tc."trainingAssignmentId" = wp."trainingAssignmentId"
+ AND tc."employeeId" = wp."employeeId"
+ AND ((wp."frequency" = 'Once' AND tc."period" IS NULL) OR tc."period" = wp."currentPeriod");
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_training_assignment_summary(p_company_id text)
+ RETURNS TABLE("trainingId" text, "trainingName" text, frequency "trainingFrequency", "currentPeriod" text, "totalAssigned" bigint, completed bigint, pending bigint, overdue bigint, "completionPercent" numeric)
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+AS $function$
+BEGIN
+ PERFORM assert_company_access(p_company_id);
+
+ RETURN QUERY
+ SELECT
+ tas."trainingId",
+ tas."trainingName",
+ tas.frequency,
+ tas."currentPeriod",
+ COUNT(*) FILTER (WHERE tas.status != 'Not Required'),
+ COUNT(*) FILTER (WHERE tas.status = 'Completed'),
+ COUNT(*) FILTER (WHERE tas.status = 'Pending'),
+ COUNT(*) FILTER (WHERE tas.status = 'Overdue'),
+ CASE
+ WHEN COUNT(*) FILTER (WHERE tas.status != 'Not Required') = 0 THEN 100
+ ELSE ROUND(COUNT(*) FILTER (WHERE tas.status = 'Completed')::NUMERIC * 100 /
+ NULLIF(COUNT(*) FILTER (WHERE tas.status != 'Not Required'), 0), 1)
+ END
+ FROM get_training_assignment_status(p_company_id) tas
+ GROUP BY tas."trainingId", tas."trainingName", tas.frequency, tas."currentPeriod";
+END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_production_projections(company_id text, location_id text, periods text[])
+ RETURNS TABLE(id text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "manufacturingBlocked" boolean, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "orderMultiple" integer, "quantityOnHand" numeric, "maximumInventoryQuantity" numeric, week1 numeric, week2 numeric, week3 numeric, week4 numeric, week5 numeric, week6 numeric, week7 numeric, week8 numeric, week9 numeric, week10 numeric, week11 numeric, week12 numeric, week13 numeric, week14 numeric, week15 numeric, week16 numeric, week17 numeric, week18 numeric, week19 numeric, week20 numeric, week21 numeric, week22 numeric, week23 numeric, week24 numeric, week25 numeric, week26 numeric, week27 numeric, week28 numeric, week29 numeric, week30 numeric, week31 numeric, week32 numeric, week33 numeric, week34 numeric, week35 numeric, week36 numeric, week37 numeric, week38 numeric, week39 numeric, week40 numeric, week41 numeric, week42 numeric, week43 numeric, week44 numeric, week45 numeric, week46 numeric, week47 numeric, week48 numeric, week49 numeric, week50 numeric, week51 numeric, week52 numeric)
+ LANGUAGE sql
+ SECURITY DEFINER
+AS $function$
+ SELECT assert_company_access(company_id);
+ SELECT
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."manufacturingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand",
+ ip."maximumInventoryQuantity",
+ MAX(CASE WHEN df."periodId" = periods[1] THEN df."forecastQuantity" END) AS "week1",
+ MAX(CASE WHEN df."periodId" = periods[2] THEN df."forecastQuantity" END) AS "week2",
+ MAX(CASE WHEN df."periodId" = periods[3] THEN df."forecastQuantity" END) AS "week3",
+ MAX(CASE WHEN df."periodId" = periods[4] THEN df."forecastQuantity" END) AS "week4",
+ MAX(CASE WHEN df."periodId" = periods[5] THEN df."forecastQuantity" END) AS "week5",
+ MAX(CASE WHEN df."periodId" = periods[6] THEN df."forecastQuantity" END) AS "week6",
+ MAX(CASE WHEN df."periodId" = periods[7] THEN df."forecastQuantity" END) AS "week7",
+ MAX(CASE WHEN df."periodId" = periods[8] THEN df."forecastQuantity" END) AS "week8",
+ MAX(CASE WHEN df."periodId" = periods[9] THEN df."forecastQuantity" END) AS "week9",
+ MAX(CASE WHEN df."periodId" = periods[10] THEN df."forecastQuantity" END) AS "week10",
+ MAX(CASE WHEN df."periodId" = periods[11] THEN df."forecastQuantity" END) AS "week11",
+ MAX(CASE WHEN df."periodId" = periods[12] THEN df."forecastQuantity" END) AS "week12",
+ MAX(CASE WHEN df."periodId" = periods[13] THEN df."forecastQuantity" END) AS "week13",
+ MAX(CASE WHEN df."periodId" = periods[14] THEN df."forecastQuantity" END) AS "week14",
+ MAX(CASE WHEN df."periodId" = periods[15] THEN df."forecastQuantity" END) AS "week15",
+ MAX(CASE WHEN df."periodId" = periods[16] THEN df."forecastQuantity" END) AS "week16",
+ MAX(CASE WHEN df."periodId" = periods[17] THEN df."forecastQuantity" END) AS "week17",
+ MAX(CASE WHEN df."periodId" = periods[18] THEN df."forecastQuantity" END) AS "week18",
+ MAX(CASE WHEN df."periodId" = periods[19] THEN df."forecastQuantity" END) AS "week19",
+ MAX(CASE WHEN df."periodId" = periods[20] THEN df."forecastQuantity" END) AS "week20",
+ MAX(CASE WHEN df."periodId" = periods[21] THEN df."forecastQuantity" END) AS "week21",
+ MAX(CASE WHEN df."periodId" = periods[22] THEN df."forecastQuantity" END) AS "week22",
+ MAX(CASE WHEN df."periodId" = periods[23] THEN df."forecastQuantity" END) AS "week23",
+ MAX(CASE WHEN df."periodId" = periods[24] THEN df."forecastQuantity" END) AS "week24",
+ MAX(CASE WHEN df."periodId" = periods[25] THEN df."forecastQuantity" END) AS "week25",
+ MAX(CASE WHEN df."periodId" = periods[26] THEN df."forecastQuantity" END) AS "week26",
+ MAX(CASE WHEN df."periodId" = periods[27] THEN df."forecastQuantity" END) AS "week27",
+ MAX(CASE WHEN df."periodId" = periods[28] THEN df."forecastQuantity" END) AS "week28",
+ MAX(CASE WHEN df."periodId" = periods[29] THEN df."forecastQuantity" END) AS "week29",
+ MAX(CASE WHEN df."periodId" = periods[30] THEN df."forecastQuantity" END) AS "week30",
+ MAX(CASE WHEN df."periodId" = periods[31] THEN df."forecastQuantity" END) AS "week31",
+ MAX(CASE WHEN df."periodId" = periods[32] THEN df."forecastQuantity" END) AS "week32",
+ MAX(CASE WHEN df."periodId" = periods[33] THEN df."forecastQuantity" END) AS "week33",
+ MAX(CASE WHEN df."periodId" = periods[34] THEN df."forecastQuantity" END) AS "week34",
+ MAX(CASE WHEN df."periodId" = periods[35] THEN df."forecastQuantity" END) AS "week35",
+ MAX(CASE WHEN df."periodId" = periods[36] THEN df."forecastQuantity" END) AS "week36",
+ MAX(CASE WHEN df."periodId" = periods[37] THEN df."forecastQuantity" END) AS "week37",
+ MAX(CASE WHEN df."periodId" = periods[38] THEN df."forecastQuantity" END) AS "week38",
+ MAX(CASE WHEN df."periodId" = periods[39] THEN df."forecastQuantity" END) AS "week39",
+ MAX(CASE WHEN df."periodId" = periods[40] THEN df."forecastQuantity" END) AS "week40",
+ MAX(CASE WHEN df."periodId" = periods[41] THEN df."forecastQuantity" END) AS "week41",
+ MAX(CASE WHEN df."periodId" = periods[42] THEN df."forecastQuantity" END) AS "week42",
+ MAX(CASE WHEN df."periodId" = periods[43] THEN df."forecastQuantity" END) AS "week43",
+ MAX(CASE WHEN df."periodId" = periods[44] THEN df."forecastQuantity" END) AS "week44",
+ MAX(CASE WHEN df."periodId" = periods[45] THEN df."forecastQuantity" END) AS "week45",
+ MAX(CASE WHEN df."periodId" = periods[46] THEN df."forecastQuantity" END) AS "week46",
+ MAX(CASE WHEN df."periodId" = periods[47] THEN df."forecastQuantity" END) AS "week47",
+ MAX(CASE WHEN df."periodId" = periods[48] THEN df."forecastQuantity" END) AS "week48",
+ MAX(CASE WHEN df."periodId" = periods[49] THEN df."forecastQuantity" END) AS "week49",
+ MAX(CASE WHEN df."periodId" = periods[50] THEN df."forecastQuantity" END) AS "week50",
+ MAX(CASE WHEN df."periodId" = periods[51] THEN df."forecastQuantity" END) AS "week51",
+ MAX(CASE WHEN df."periodId" = periods[52] THEN df."forecastQuantity" END) AS "week52"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ INNER JOIN "demandProjection" df ON df."itemId" = i."id"
+ AND df."companyId" = company_id
+ AND df."locationId" = location_id
+ AND df."periodId" = ANY(periods)
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" = 'Make'
+ AND i."itemTrackingType" != 'Non-Inventory'
+ AND i."active" = TRUE
+ GROUP BY
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ i."thumbnailPath",
+ mu."thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."manufacturingBlocked",
+ ir."lotSize",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity";
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_purchasing_planning(company_id text, location_id text, periods text[])
+ RETURNS TABLE(id text, "readableIdWithRevision" text, name text, active boolean, type "itemType", "itemTrackingType" "itemTrackingType", "replenishmentSystem" "itemReplenishmentSystem", "thumbnailPath" text, "unitOfMeasureCode" text, "leadTime" integer, "purchasingBlocked" boolean, "lotSize" integer, "reorderingPolicy" "itemReorderingPolicy", "demandAccumulationPeriod" integer, "demandAccumulationSafetyStock" numeric, "reorderPoint" integer, "reorderQuantity" integer, "minimumOrderQuantity" integer, "maximumOrderQuantity" integer, "orderMultiple" integer, "quantityOnHand" numeric, "maximumInventoryQuantity" numeric, suppliers jsonb, "preferredSupplierId" text, "purchasingUnitOfMeasureCode" text, "conversionFactor" numeric, "quantityToOrder" numeric, "supersessionMode" text, "minimumReserveQuantity" numeric, week1 numeric, week2 numeric, week3 numeric, week4 numeric, week5 numeric, week6 numeric, week7 numeric, week8 numeric, week9 numeric, week10 numeric, week11 numeric, week12 numeric, week13 numeric, week14 numeric, week15 numeric, week16 numeric, week17 numeric, week18 numeric, week19 numeric, week20 numeric, week21 numeric, week22 numeric, week23 numeric, week24 numeric, week25 numeric, week26 numeric, week27 numeric, week28 numeric, week29 numeric, week30 numeric, week31 numeric, week32 numeric, week33 numeric, week34 numeric, week35 numeric, week36 numeric, week37 numeric, week38 numeric, week39 numeric, week40 numeric, week41 numeric, week42 numeric, week43 numeric, week44 numeric, week45 numeric, week46 numeric, week47 numeric, week48 numeric, week49 numeric, week50 numeric, week51 numeric, week52 numeric)
+ LANGUAGE sql
+ SECURITY DEFINER
+AS $function$
+ SELECT assert_company_access(company_id);
+ WITH RECURSIVE
+ supply_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "supply"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "supplyActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "supplyForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ demand_data AS (
+ SELECT
+ "itemId",
+ "periodId",
+ SUM(COALESCE("actualQuantity", 0) + COALESCE("forecastQuantity", 0)) AS "demand"
+ FROM (
+ SELECT "itemId", "periodId", "actualQuantity", NULL as "forecastQuantity"
+ FROM "demandActual"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "demandForecast"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ UNION ALL
+ -- Top-level manual projections. The "Demand Forecast" drawer writes the
+ -- demandProjection table; MRP explodes these into child demand
+ -- (demandForecast) but the projected item's OWN demand lives only here —
+ -- without this arm a purchased item whose only demand is a projection never
+ -- appears in purchasing planning and never drives a suggested order.
+ SELECT "itemId", "periodId", NULL as "actualQuantity", "forecastQuantity"
+ FROM "demandProjection"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "periodId" = ANY(periods)
+ ) combined
+ GROUP BY "itemId", "periodId"
+ ),
+ base_items AS (
+ SELECT DISTINCT ON (i."id")
+ i."id",
+ i."readableIdWithRevision",
+ i."name",
+ i."active",
+ i."type",
+ i."itemTrackingType",
+ i."replenishmentSystem",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END AS "thumbnailPath",
+ i."unitOfMeasureCode",
+ ir."leadTime",
+ ir."purchasingBlocked",
+ ir."lotSize",
+ ir."preferredSupplierId",
+ ir."purchasingUnitOfMeasureCode",
+ ir."conversionFactor",
+ ip."reorderingPolicy",
+ ip."demandAccumulationPeriod",
+ ip."demandAccumulationSafetyStock",
+ ip."reorderPoint",
+ ip."reorderQuantity",
+ ip."minimumOrderQuantity",
+ ip."maximumOrderQuantity",
+ ip."orderMultiple",
+ ip."maximumInventoryQuantity",
+ COALESCE(ps."suppliers", '[]'::jsonb) as "suppliers",
+ COALESCE((
+ SELECT SUM("quantity")
+ FROM "itemLedger"
+ WHERE "companyId" = company_id
+ AND "locationId" = location_id
+ AND "itemId" = i."id"
+ ), 0) AS "quantityOnHand"
+ FROM "item" i
+ INNER JOIN "itemReplenishment" ir ON i."id" = ir."itemId"
+ INNER JOIN "itemPlanning" ip ON i."id" = ip."itemId" AND ip."locationId" = location_id
+ LEFT JOIN "modelUpload" mu ON mu."id" = i."modelUploadId"
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ jsonb_agg(
+ jsonb_build_object(
+ 'id', ps."id",
+ 'minimumOrderQuantity', ps."minimumOrderQuantity",
+ 'supplierUnitOfMeasureCode', ps."supplierUnitOfMeasureCode",
+ 'conversionFactor', ps."conversionFactor",
+ 'unitPrice', ps."unitPrice",
+ 'supplierId', ps."supplierId",
+ 'supplierPartId', ps."supplierPartId"
+ )
+ ) AS "suppliers"
+ FROM "supplierPart" ps
+ WHERE ps."companyId" = company_id
+ AND ps.active = true
+ GROUP BY ps."itemId"
+ ) ps ON ps."itemId" = i."id"
+ WHERE i."companyId" = company_id
+ AND i."replenishmentSystem" != 'Make'
+ AND i."itemTrackingType" != 'Non-Inventory'
+ AND i."active" = TRUE
+ -- Supersession: drop obsolete items and items past their discontinuation
+ -- date so no new orders are suggested.
+ AND NOT EXISTS (
+ SELECT 1 FROM "itemSupersession" ss
+ WHERE ss."itemId" = i."id"
+ AND (
+ ss."supersessionMode" = 'No Stock'
+ OR (
+ -- date-based suppression applies only to the phase-out modes; Stock
+ -- Only keeps replenishing to its reserve floor regardless of date.
+ ss."supersessionMode" IN ('Consume First', 'Prefer New')
+ AND ss."discontinuationDate" IS NOT NULL
+ AND ss."discontinuationDate" <= CURRENT_DATE
+ )
+ )
+ )
+ AND (
+ EXISTS (
+ SELECT 1 FROM demand_data d
+ WHERE d."itemId" = i."id"
+ )
+ OR (
+ ip."reorderPoint" > 0
+ AND ip."reorderingPolicy" IN ('Fixed Reorder Quantity', 'Maximum Quantity')
+ )
+ )
+ ),
+ projections AS (
+ SELECT
+ bi.*,
+ periods[1] as "periodId",
+ bi."quantityOnHand" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ 1 as period_index
+ FROM base_items bi
+ LEFT JOIN supply_data s ON bi."id" = s."itemId" AND s."periodId" = periods[1]
+ LEFT JOIN demand_data d ON bi."id" = d."itemId" AND d."periodId" = periods[1]
+
+ UNION ALL
+
+ SELECT
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."quantityOnHand",
+ periods[p.period_index + 1] as "periodId",
+ p."projection" + COALESCE(s."supply", 0) - COALESCE(d."demand", 0) AS "projection",
+ p.period_index + 1 as period_index
+ FROM projections p
+ LEFT JOIN supply_data s ON p."id" = s."itemId" AND s."periodId" = periods[p.period_index + 1]
+ LEFT JOIN demand_data d ON p."id" = d."itemId" AND d."periodId" = periods[p.period_index + 1]
+ WHERE p.period_index < array_length(periods, 1)
+ ),
+ order_quantities AS (
+ SELECT
+ p."id",
+ calculate_quantity_to_order(
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ array_agg(p."projection" ORDER BY p.period_index)
+ ) AS "quantityToOrder"
+ FROM projections p
+ GROUP BY
+ p."id",
+ p."reorderingPolicy",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."lotSize",
+ p."maximumInventoryQuantity",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock"
+ )
+ SELECT DISTINCT ON (p."id")
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ CASE
+ WHEN ss."supersessionMode" = 'Stock Only'
+ THEN GREATEST(
+ 0,
+ COALESCE(rsv."minimumReserveQuantity", 0)
+ - p."quantityOnHand"
+ - COALESCE(sup."incomingSupply", 0)
+ )
+ ELSE COALESCE(oq."quantityToOrder", 0)
+ END AS "quantityToOrder",
+ ss."supersessionMode" AS "supersessionMode",
+ COALESCE(rsv."minimumReserveQuantity", 0) AS "minimumReserveQuantity",
+ MAX(CASE WHEN p."periodId" = periods[1] THEN p."projection" END) AS "week1",
+ MAX(CASE WHEN p."periodId" = periods[2] THEN p."projection" END) AS "week2",
+ MAX(CASE WHEN p."periodId" = periods[3] THEN p."projection" END) AS "week3",
+ MAX(CASE WHEN p."periodId" = periods[4] THEN p."projection" END) AS "week4",
+ MAX(CASE WHEN p."periodId" = periods[5] THEN p."projection" END) AS "week5",
+ MAX(CASE WHEN p."periodId" = periods[6] THEN p."projection" END) AS "week6",
+ MAX(CASE WHEN p."periodId" = periods[7] THEN p."projection" END) AS "week7",
+ MAX(CASE WHEN p."periodId" = periods[8] THEN p."projection" END) AS "week8",
+ MAX(CASE WHEN p."periodId" = periods[9] THEN p."projection" END) AS "week9",
+ MAX(CASE WHEN p."periodId" = periods[10] THEN p."projection" END) AS "week10",
+ MAX(CASE WHEN p."periodId" = periods[11] THEN p."projection" END) AS "week11",
+ MAX(CASE WHEN p."periodId" = periods[12] THEN p."projection" END) AS "week12",
+ MAX(CASE WHEN p."periodId" = periods[13] THEN p."projection" END) AS "week13",
+ MAX(CASE WHEN p."periodId" = periods[14] THEN p."projection" END) AS "week14",
+ MAX(CASE WHEN p."periodId" = periods[15] THEN p."projection" END) AS "week15",
+ MAX(CASE WHEN p."periodId" = periods[16] THEN p."projection" END) AS "week16",
+ MAX(CASE WHEN p."periodId" = periods[17] THEN p."projection" END) AS "week17",
+ MAX(CASE WHEN p."periodId" = periods[18] THEN p."projection" END) AS "week18",
+ MAX(CASE WHEN p."periodId" = periods[19] THEN p."projection" END) AS "week19",
+ MAX(CASE WHEN p."periodId" = periods[20] THEN p."projection" END) AS "week20",
+ MAX(CASE WHEN p."periodId" = periods[21] THEN p."projection" END) AS "week21",
+ MAX(CASE WHEN p."periodId" = periods[22] THEN p."projection" END) AS "week22",
+ MAX(CASE WHEN p."periodId" = periods[23] THEN p."projection" END) AS "week23",
+ MAX(CASE WHEN p."periodId" = periods[24] THEN p."projection" END) AS "week24",
+ MAX(CASE WHEN p."periodId" = periods[25] THEN p."projection" END) AS "week25",
+ MAX(CASE WHEN p."periodId" = periods[26] THEN p."projection" END) AS "week26",
+ MAX(CASE WHEN p."periodId" = periods[27] THEN p."projection" END) AS "week27",
+ MAX(CASE WHEN p."periodId" = periods[28] THEN p."projection" END) AS "week28",
+ MAX(CASE WHEN p."periodId" = periods[29] THEN p."projection" END) AS "week29",
+ MAX(CASE WHEN p."periodId" = periods[30] THEN p."projection" END) AS "week30",
+ MAX(CASE WHEN p."periodId" = periods[31] THEN p."projection" END) AS "week31",
+ MAX(CASE WHEN p."periodId" = periods[32] THEN p."projection" END) AS "week32",
+ MAX(CASE WHEN p."periodId" = periods[33] THEN p."projection" END) AS "week33",
+ MAX(CASE WHEN p."periodId" = periods[34] THEN p."projection" END) AS "week34",
+ MAX(CASE WHEN p."periodId" = periods[35] THEN p."projection" END) AS "week35",
+ MAX(CASE WHEN p."periodId" = periods[36] THEN p."projection" END) AS "week36",
+ MAX(CASE WHEN p."periodId" = periods[37] THEN p."projection" END) AS "week37",
+ MAX(CASE WHEN p."periodId" = periods[38] THEN p."projection" END) AS "week38",
+ MAX(CASE WHEN p."periodId" = periods[39] THEN p."projection" END) AS "week39",
+ MAX(CASE WHEN p."periodId" = periods[40] THEN p."projection" END) AS "week40",
+ MAX(CASE WHEN p."periodId" = periods[41] THEN p."projection" END) AS "week41",
+ MAX(CASE WHEN p."periodId" = periods[42] THEN p."projection" END) AS "week42",
+ MAX(CASE WHEN p."periodId" = periods[43] THEN p."projection" END) AS "week43",
+ MAX(CASE WHEN p."periodId" = periods[44] THEN p."projection" END) AS "week44",
+ MAX(CASE WHEN p."periodId" = periods[45] THEN p."projection" END) AS "week45",
+ MAX(CASE WHEN p."periodId" = periods[46] THEN p."projection" END) AS "week46",
+ MAX(CASE WHEN p."periodId" = periods[47] THEN p."projection" END) AS "week47",
+ MAX(CASE WHEN p."periodId" = periods[48] THEN p."projection" END) AS "week48",
+ MAX(CASE WHEN p."periodId" = periods[49] THEN p."projection" END) AS "week49",
+ MAX(CASE WHEN p."periodId" = periods[50] THEN p."projection" END) AS "week50",
+ MAX(CASE WHEN p."periodId" = periods[51] THEN p."projection" END) AS "week51",
+ MAX(CASE WHEN p."periodId" = periods[52] THEN p."projection" END) AS "week52"
+ FROM projections p
+ LEFT JOIN order_quantities oq ON p."id" = oq."id"
+ LEFT JOIN "itemSupersession" ss ON ss."itemId" = p."id"
+ LEFT JOIN "itemPlanning" rsv ON rsv."itemId" = p."id" AND rsv."locationId" = location_id
+ LEFT JOIN (
+ SELECT "itemId", SUM("supply") AS "incomingSupply"
+ FROM supply_data GROUP BY "itemId"
+ ) sup ON sup."itemId" = p."id"
+ GROUP BY
+ p."id",
+ p."readableIdWithRevision",
+ p."name",
+ p."active",
+ p."type",
+ p."itemTrackingType",
+ p."replenishmentSystem",
+ p."thumbnailPath",
+ p."unitOfMeasureCode",
+ p."leadTime",
+ p."purchasingBlocked",
+ p."lotSize",
+ p."reorderingPolicy",
+ p."demandAccumulationPeriod",
+ p."demandAccumulationSafetyStock",
+ p."reorderPoint",
+ p."reorderQuantity",
+ p."minimumOrderQuantity",
+ p."maximumOrderQuantity",
+ p."orderMultiple",
+ p."quantityOnHand",
+ p."maximumInventoryQuantity",
+ p."suppliers",
+ p."preferredSupplierId",
+ p."purchasingUnitOfMeasureCode",
+ p."conversionFactor",
+ oq."quantityToOrder",
+ ss."supersessionMode",
+ rsv."minimumReserveQuantity",
+ sup."incomingSupply";
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_returnable_receipt_lines(company_id text, supplier_id text, purchase_order_id text DEFAULT NULL::text, search text DEFAULT NULL::text, limit_count integer DEFAULT 5, offset_count integer DEFAULT 0)
+ RETURNS TABLE("receiptLineId" text, "receiptReadableId" text, "purchaseOrderReadableId" text, "purchaseOrderLineId" text, "itemId" text, "itemReadableId" text, "itemName" text, "itemTrackingType" text, "receivedQuantity" numeric, "alreadyReturned" numeric, "returnableQuantity" numeric, "unitPrice" numeric, "unitOfMeasureCode" text, "totalCount" bigint)
+ LANGUAGE sql
+ SECURITY DEFINER
+AS $function$
+ SELECT assert_company_access(company_id);
+ WITH candidate AS (
+ SELECT
+ rl.id AS receipt_line_id,
+ r."receiptId" AS receipt_readable_id,
+ r."sourceDocumentReadableId" AS po_readable_id,
+ rl."lineId" AS po_line_id,
+ rl."itemId" AS item_id,
+ i."readableIdWithRevision" AS item_readable_id,
+ i."name" AS item_name,
+ i."itemTrackingType"::text AS item_tracking_type,
+ rl."receivedQuantity" AS received_quantity,
+ rl."unitOfMeasure" AS unit_of_measure_code,
+ r."postingDate" AS posting_date,
+ r."createdAt" AS created_at,
+ -- supplierUnitPrice is per purchase unit; the return order + credit memo
+ -- are in inventory units, so divide by the conversion factor.
+ COALESCE(pol."supplierUnitPrice", 0)
+ / NULLIF(COALESCE(pol."conversionFactor", 1), 0) AS unit_price,
+ COALESCE(auth.total_authorized, 0) AS already_returned
+ FROM "receiptLine" rl
+ JOIN "receipt" r
+ ON r.id = rl."receiptId" AND r."companyId" = rl."companyId"
+ JOIN "item" i
+ ON i.id = rl."itemId"
+ LEFT JOIN "purchaseOrderLine" pol
+ ON pol.id = rl."lineId" AND pol."companyId" = rl."companyId"
+ LEFT JOIN (
+ SELECT prol."receiptLineId", SUM(prol."quantity") AS total_authorized
+ FROM "purchaseReturnOrderLine" prol
+ JOIN "purchaseReturnOrder" pro
+ ON pro.id = prol."purchaseReturnOrderId"
+ AND pro."companyId" = prol."companyId"
+ WHERE prol."companyId" = company_id
+ AND prol."receiptLineId" IS NOT NULL
+ AND pro."status" <> 'Cancelled'
+ GROUP BY prol."receiptLineId"
+ ) auth ON auth."receiptLineId" = rl.id
+ WHERE rl."companyId" = company_id
+ AND r."supplierId" = supplier_id
+ AND r."sourceDocument" = 'Purchase Order'
+ AND r."status" = 'Posted'
+ AND (purchase_order_id IS NULL OR r."sourceDocumentId" = purchase_order_id)
+ AND (
+ search IS NULL OR search = '' OR
+ r."receiptId" ILIKE '%' || search || '%' OR
+ r."sourceDocumentReadableId" ILIKE '%' || search || '%' OR
+ i."readableIdWithRevision" ILIKE '%' || search || '%' OR
+ i."name" ILIKE '%' || search || '%'
+ )
+ ),
+ returnable AS (
+ SELECT *, (received_quantity - already_returned) AS returnable_quantity
+ FROM candidate
+ WHERE (received_quantity - already_returned) > 0.000001
+ )
+ SELECT
+ receipt_line_id,
+ receipt_readable_id,
+ po_readable_id,
+ po_line_id,
+ item_id,
+ item_readable_id,
+ item_name,
+ item_tracking_type,
+ received_quantity,
+ already_returned,
+ returnable_quantity,
+ unit_price,
+ unit_of_measure_code,
+ COUNT(*) OVER () AS total_count
+ FROM returnable
+ ORDER BY posting_date DESC NULLS LAST, created_at DESC, receipt_line_id
+ LIMIT limit_count OFFSET offset_count;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_returnable_shipment_lines(company_id text, customer_id text, sales_order_id text DEFAULT NULL::text, search text DEFAULT NULL::text, limit_count integer DEFAULT 5, offset_count integer DEFAULT 0)
+ RETURNS TABLE("shipmentLineId" text, "shipmentReadableId" text, "salesOrderReadableId" text, "salesOrderLineId" text, "itemId" text, "itemReadableId" text, "itemName" text, "itemTrackingType" text, "shippedQuantity" numeric, "alreadyReturned" numeric, "returnableQuantity" numeric, "unitPrice" numeric, "unitOfMeasureCode" text, "totalCount" bigint)
+ LANGUAGE sql
+ SECURITY DEFINER
+AS $function$
+ SELECT assert_company_access(company_id);
+ WITH candidate AS (
+ SELECT
+ sl.id AS shipment_line_id,
+ s."shipmentId" AS shipment_readable_id,
+ s."sourceDocumentReadableId" AS so_readable_id,
+ sl."lineId" AS so_line_id,
+ sl."itemId" AS item_id,
+ i."readableIdWithRevision" AS item_readable_id,
+ i."name" AS item_name,
+ i."itemTrackingType"::text AS item_tracking_type,
+ sl."shippedQuantity" AS shipped_quantity,
+ COALESCE(sol."unitOfMeasureCode", sl."unitOfMeasure") AS unit_of_measure_code,
+ s."postingDate" AS posting_date,
+ s."createdAt" AS created_at,
+ COALESCE(sol."unitPrice", 0) AS unit_price,
+ COALESCE(auth.total_authorized, 0) AS already_returned
+ FROM "shipmentLine" sl
+ JOIN "shipment" s
+ ON s.id = sl."shipmentId" AND s."companyId" = sl."companyId"
+ JOIN "item" i
+ ON i.id = sl."itemId"
+ LEFT JOIN "salesOrderLine" sol
+ ON sol.id = sl."lineId" AND sol."companyId" = sl."companyId"
+ LEFT JOIN (
+ SELECT srol."shipmentLineId", SUM(srol."quantity") AS total_authorized
+ FROM "salesReturnOrderLine" srol
+ JOIN "salesReturnOrder" sro
+ ON sro.id = srol."salesReturnOrderId"
+ AND sro."companyId" = srol."companyId"
+ WHERE srol."companyId" = company_id
+ AND srol."shipmentLineId" IS NOT NULL
+ AND sro."status" <> 'Cancelled'
+ GROUP BY srol."shipmentLineId"
+ ) auth ON auth."shipmentLineId" = sl.id
+ WHERE sl."companyId" = company_id
+ AND s."customerId" = customer_id
+ AND s."sourceDocument" = 'Sales Order'
+ AND s."status" = 'Posted'
+ AND (sales_order_id IS NULL OR s."sourceDocumentId" = sales_order_id)
+ AND (
+ search IS NULL OR search = '' OR
+ s."shipmentId" ILIKE '%' || search || '%' OR
+ s."sourceDocumentReadableId" ILIKE '%' || search || '%' OR
+ i."readableIdWithRevision" ILIKE '%' || search || '%' OR
+ i."name" ILIKE '%' || search || '%'
+ )
+ ),
+ returnable AS (
+ SELECT *, (shipped_quantity - already_returned) AS returnable_quantity
+ FROM candidate
+ WHERE (shipped_quantity - already_returned) > 0.000001
+ )
+ SELECT
+ shipment_line_id,
+ shipment_readable_id,
+ so_readable_id,
+ so_line_id,
+ item_id,
+ item_readable_id,
+ item_name,
+ item_tracking_type,
+ shipped_quantity,
+ already_returned,
+ returnable_quantity,
+ unit_price,
+ unit_of_measure_code,
+ COUNT(*) OVER () AS total_count
+ FROM returnable
+ ORDER BY posting_date DESC NULLS LAST, created_at DESC, shipment_line_id
+ LIMIT limit_count OFFSET offset_count;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.get_claims(uid text, company text)
+ RETURNS jsonb
+ LANGUAGE plpgsql
+ STABLE SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+ DECLARE company_role text;
+ DECLARE role_object jsonb;
+ DECLARE perms jsonb;
+ BEGIN
+ -- Your own claims, or those of someone in a company where you may view or
+ -- update users (the permission editor reads them with users_update alone).
+ IF current_setting('role', true) IN ('anon', 'authenticated')
+ AND uid IS DISTINCT FROM auth.uid()::text
+ AND NOT EXISTS (
+ SELECT 1 FROM "userToCompany" utc
+ WHERE utc."userId" = uid
+ AND utc."companyId" = ANY (
+ get_companies_with_employee_permission('users_view')
+ || get_companies_with_employee_permission('users_update')
+ )
+ ) THEN
+ RAISE EXCEPTION 'Not authorized to read claims for this user'
+ USING ERRCODE = 'insufficient_privilege';
+ END IF;
+
+ select role from "userToCompany" into company_role where "userId" = uid AND "companyId" = company;
+ select permissions from "userPermission" into perms where id = uid;
+ role_object := jsonb_build_object('role', company_role);
+
+
+ return (role_object || perms)::jsonb;
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.groups_for_user(uid text)
+ RETURNS text[]
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+ DECLARE retval TEXT[];
+ BEGIN
+ WITH RECURSIVE "groupsForUser" AS (
+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
+ WHERE "memberUserId" = uid::text
+ UNION
+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
+ INNER JOIN "groupsForUser" g2 ON g2."groupId" = g1."memberGroupId"
+ ) SELECT COALESCE(array_agg("groupId"), '{}') INTO retval FROM "groupsForUser";
+
+ -- Someone else's groups: only those in a company the caller belongs to.
+ IF current_setting('role', true) IN ('anon', 'authenticated')
+ AND uid IS DISTINCT FROM auth.uid()::text THEN
+ SELECT COALESCE(array_agg(g.id), '{}') INTO retval
+ FROM "group" g
+ WHERE g.id = ANY (retval)
+ AND g."companyId" = ANY (get_companies_with_employee_role());
+ END IF;
+
+ RETURN retval;
+ END;
+$function$;
+
+CREATE OR REPLACE FUNCTION public.users_for_groups(groups text[])
+ RETURNS jsonb
+ LANGUAGE plpgsql
+ SECURITY DEFINER
+ SET search_path TO 'public'
+AS $function$
+ DECLARE retval jsonb;
+ BEGIN
+ IF current_setting('role', true) IN ('anon', 'authenticated') THEN
+ groups := ARRAY(
+ SELECT g.id FROM "group" g
+ WHERE g.id = ANY (groups)
+ AND g."companyId" = ANY (get_companies_with_employee_role())
+ );
+ END IF;
+
+ WITH RECURSIVE "usersForGroups" AS (
+ SELECT "groupId", "memberGroupId", "memberUserId" FROM "membership"
+ WHERE "groupId" = ANY(groups)
+ UNION
+ SELECT g1."groupId", g1."memberGroupId", g1."memberUserId" FROM "membership" g1
+ INNER JOIN "usersForGroups" g2 ON g2."memberGroupId" = g1."groupId"
+ ) SELECT coalesce(jsonb_agg("memberUserId"), '[]') AS groups INTO retval FROM "usersForGroups" WHERE "memberUserId" IS NOT NULL;
+ RETURN retval;
+ END;
+$function$;
+
+-- The event-system dispatchers call interceptors by name through dynamic SQL.
+-- Run them as the owner so the interceptors below can be SECURITY INVOKER and
+-- still behave exactly as before on every write. 59 of the 63 interceptors were
+-- SECURITY DEFINER already; the other four only refuse deletes of posted
+-- invoices or bump the parent's "updatedAt".
+ALTER FUNCTION dispatch_event_interceptors() SECURITY DEFINER SET search_path = public;
+ALTER FUNCTION dispatch_event_after_interceptors() SECURITY DEFINER SET search_path = public;
+
+-- Internal SECURITY DEFINER functions, from the live catalog: every one that is
+-- not a trigger, not called by the apps with a user or API-key client, not an
+-- RLS helper, and not already guarded by current_setting('role'). They are
+-- event interceptors, helpers called only from other SECURITY DEFINER
+-- functions, or called only by service_role and direct connections. All tables
+-- in "public", including the per-company searchIndex/auditLog tables, have RLS.
+ALTER FUNCTION backflush_job_materials(text,numeric,text,text) SECURITY INVOKER;
+ALTER FUNCTION check_api_key_rate_limit(text,integer,text) SECURITY INVOKER;
+ALTER FUNCTION check_operation_dependencies(text) SECURITY INVOKER;
+ALTER FUNCTION create_rfq_from_models_v1(text,text,text,json[]) SECURITY INVOKER;
+ALTER FUNCTION create_rfq_from_models_v2(text,text,text,json[]) SECURITY INVOKER;
+ALTER FUNCTION create_rfq_from_model_v1(text,text,text,text,text,text,json) SECURITY INVOKER;
+ALTER FUNCTION delete_from_search_index(text,text,text) SECURITY INVOKER;
+ALTER FUNCTION get_inventory_value_by_location(text) SECURITY INVOKER;
+ALTER FUNCTION get_training_assignments_by_user(text) SECURITY INVOKER;
+ALTER FUNCTION increment_webhook_error(text) SECURITY INVOKER;
+ALTER FUNCTION increment_webhook_success(text) SECURITY INVOKER;
+ALTER FUNCTION is_last_job_operation(text) SECURITY INVOKER;
+ALTER FUNCTION items_search(vector,double precision,integer,text) SECURITY INVOKER;
+ALTER FUNCTION populate_company_search_index(text) SECURITY INVOKER;
+ALTER FUNCTION populate_sales_search_results(text) SECURITY INVOKER;
+ALTER FUNCTION recompute_service_line_fulfillment(text,text,text) SECURITY INVOKER;
+ALTER FUNCTION reconcile_item_stock_quantities() SECURITY INVOKER;
+ALTER FUNCTION set_shelf_life_for_operation(text,"shelfLifeTriggerTiming") SECURITY INVOKER;
+ALTER FUNCTION set_shelf_life_on_operation_done(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION set_shelf_life_on_operation_started(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION "snapshotAccountingPeriodBalances"(text,text,text) SECURITY INVOKER;
+ALTER FUNCTION storage_unit_block_location_change_with_children(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION storage_unit_enforce_no_cycle(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION storage_unit_enforce_same_location(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION suppliers_search(vector,double precision,integer,text) SECURITY INVOKER;
+ALTER FUNCTION sync_add_customer_account_to_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_add_employee_to_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_add_supplier_account_to_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_archive_other_procedures(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_archive_other_quality_documents(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_check_job_material_self_reference(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_check_method_material_self_reference(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_customer_entries(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_customer_org_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_customer_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_employee_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_item_related_records(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_location_related_records(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_make_method_related_records(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_nc_external_link(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_supplier_entries(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_supplier_org_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_supplier_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_create_user_identity_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_delete_tracked_entity_on_job_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_delete_user_identity_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_edit_document_transaction(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_finish_job_operation(jsonb,jsonb,text) SECURITY INVOKER;
+ALTER FUNCTION sync_finish_job_operation(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_insert_company_related_records(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_insert_job_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_insert_job_material_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_insert_quote_line_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_insert_quote_material_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_job_complete_or_canceled(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_job_recompute_service_line(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_on_maintenance_dispatch_complete(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_propagate_item_readable_id_to_tracked_entity(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_protect_system_required_actions(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_purchase_invoice_line_price_change(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_set_initial_dependency_status(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_set_job_operation_in_progress(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_customer_type_group_name(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_customer_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_employee_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_employee_type_membership(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_job_material_make_method_item_id(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_job_operation_quantities(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_quote_exchange_rate(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_quote_line_make_method_item_id(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_quote_material_make_method_item_id(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_sales_order_exchange_rate(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_stock_transfer_status(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_supplier_type_group_name(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_supplier_type_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_tracked_entity_on_job_make_method(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_update_user_identity_group(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_upload_document_transaction(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_verify_integration(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION sync_webhook_subscription(text,text,jsonb,jsonb) SECURITY INVOKER;
+ALTER FUNCTION upsert_to_search_index(text,text,text,text,text,text,text[],jsonb) SECURITY INVOKER;
diff --git a/packages/database/supabase/tests/rpc-privileges.test.sql b/packages/database/supabase/tests/rpc-privileges.test.sql
new file mode 100644
index 0000000000..58d98a8bb5
--- /dev/null
+++ b/packages/database/supabase/tests/rpc-privileges.test.sql
@@ -0,0 +1,209 @@
+-- Tenant isolation for functions reachable at /rest/v1/rpc (20260925121735_rpc-function-guards).
+-- Run from the repository root against an existing local database:
+-- pnpm exec tsx scripts/run-local-accounting-check.ts psql -X -v ON_ERROR_STOP=1 -f packages/database/supabase/tests/rpc-privileges.test.sql
+-- All fixtures and role changes are confined to the rolled-back transaction.
+\set ON_ERROR_STOP on
+BEGIN;
+SET LOCAL statement_timeout = '30s';
+SET LOCAL "app.sync_in_progress" = 'true';
+
+DO $fixtures$
+DECLARE
+ group_id text;
+ company_a text;
+ company_b text;
+ user_a text := gen_random_uuid()::text;
+ user_b text := gen_random_uuid()::text;
+ user_c text := gen_random_uuid()::text;
+ group_b text := gen_random_uuid()::text;
+ raw_key text := 'crbn_rpc_privileges_' || gen_random_uuid()::text;
+ perms jsonb;
+BEGIN
+ INSERT INTO "companyGroup" (name, "createdBy") VALUES ('RPC privileges ' || id(), 'system') RETURNING id INTO group_id;
+ INSERT INTO "company" (name, "companyGroupId", "baseCurrencyCode") VALUES ('RPC A ' || id(), group_id, 'USD') RETURNING id INTO company_a;
+ INSERT INTO "company" (name, "companyGroupId", "baseCurrencyCode") VALUES ('RPC B ' || id(), group_id, 'USD') RETURNING id INTO company_b;
+ INSERT INTO "user" (id, email) VALUES
+ (user_a, user_a || '@rpc-privileges.invalid'),
+ (user_b, user_b || '@rpc-privileges.invalid'),
+ (user_c, user_c || '@rpc-privileges.invalid');
+ INSERT INTO "userToCompany" ("userId", "companyId", role) VALUES
+ (user_a, company_a, 'employee'), (user_b, company_b, 'employee'), (user_c, company_a, 'employee');
+ SELECT jsonb_object_agg(p, jsonb_build_array(company_a)) INTO perms
+ FROM unnest(ARRAY['sales_view', 'sales_create', 'inventory_view', 'users_view']) p;
+ -- user_c can edit users but not view them: the permission editor's shape.
+ INSERT INTO "userPermission" (id, permissions) VALUES
+ (user_a, perms), (user_b, '{}'::jsonb),
+ (user_c, jsonb_build_object('users_update', jsonb_build_array(company_a)));
+ INSERT INTO "group" (id, name, "companyId") VALUES (group_b, 'RPC privileges B', company_b);
+ INSERT INTO "membership" ("groupId", "memberUserId") VALUES (group_b, user_b);
+ INSERT INTO "apiKey" (name, "companyId", "createdBy", "keyHash", scopes)
+ VALUES ('RPC privileges', company_a, user_a, encode(digest(raw_key::bytea, 'sha256'), 'hex'),
+ jsonb_build_object('inventory_view', jsonb_build_array(company_a)));
+
+ PERFORM set_config('test.company_a', company_a, true);
+ PERFORM set_config('test.company_b', company_b, true);
+ PERFORM set_config('test.user_a', user_a, true);
+ PERFORM set_config('test.user_b', user_b, true);
+ PERFORM set_config('test.user_c', user_c, true);
+ PERFORM set_config('test.group_b', group_b, true);
+ PERFORM set_config('test.raw_key', raw_key, true);
+END;
+$fixtures$;
+
+-- Never REVOKE EXECUTE here: on this image a call to a revoked function
+-- segfaults the backend (20260924192316). Internal functions are SECURITY
+-- INVOKER instead, and only the dispatchers that call them run as the owner.
+DO $$
+DECLARE
+ definer_interceptors text;
+BEGIN
+ SELECT string_agg(DISTINCT p.proname, ', ') INTO definer_interceptors
+ FROM pg_trigger t
+ JOIN pg_proc d ON d.oid = t.tgfoid AND d.proname LIKE 'dispatch_event%'
+ CROSS JOIN LATERAL unnest(string_to_array(encode(t.tgargs, 'escape'), E'\\000')) a(fname)
+ JOIN pg_proc p ON p.proname = a.fname AND p.pronamespace = 'public'::regnamespace
+ WHERE p.prosecdef AND p.prosrc !~* 'current_setting\(\s*''role''';
+ IF definer_interceptors IS NOT NULL THEN
+ RAISE EXCEPTION 'FAIL: event interceptors callable through the API as the owner: %', definer_interceptors;
+ END IF;
+
+ IF (SELECT prosecdef FROM pg_proc WHERE oid = 'create_rfq_from_model_v1(text,text,text,text,text,text,json)'::regprocedure)
+ OR (SELECT prosecdef FROM pg_proc WHERE oid = 'backflush_job_materials(text,numeric,text,text)'::regprocedure)
+ OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_interceptors()'::regprocedure)
+ OR NOT (SELECT prosecdef FROM pg_proc WHERE oid = 'dispatch_event_after_interceptors()'::regprocedure) THEN
+ RAISE EXCEPTION 'FAIL: internal functions or dispatchers have the wrong security mode';
+ END IF;
+END;
+$$;
+
+-- Anonymous: no access to any company, and no injection through the table name.
+SET LOCAL ROLE anon;
+DO $$
+DECLARE
+ leaked text;
+BEGIN
+ BEGIN
+ PERFORM get_inventory_valuation(current_setting('test.company_b'));
+ RAISE EXCEPTION 'FAIL: anon read another company''s inventory valuation';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ PERFORM * FROM get_production_projections(current_setting('test.company_b'), 'x', ARRAY[]::text[]);
+ RAISE EXCEPTION 'FAIL: anon read another company''s production projections';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ PERFORM get_next_sequence('customer', current_setting('test.company_b'));
+ RAISE EXCEPTION 'FAIL: anon advanced another company''s sequence';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ PERFORM get_claims(current_setting('test.user_a'), current_setting('test.company_a'));
+ RAISE EXCEPTION 'FAIL: anon read a user''s claims';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ -- An inline `IF NOT (x = ANY(helper()))` guard: failed open while the helper returned NULL.
+ BEGIN
+ PERFORM get_item_storage_unit_requirements_by_location(current_setting('test.company_b'), 'x');
+ RAISE EXCEPTION 'FAIL: anon read another company''s storage requirements';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ BEGIN
+ leaked := get_company_id_from_foreign_key('x', 'customer" WHERE 1=0 UNION SELECT (''X'')::text -- ');
+ RAISE EXCEPTION 'FAIL: get_company_id_from_foreign_key returned % for an injected table name', leaked;
+ EXCEPTION WHEN undefined_table THEN NULL;
+ END;
+END;
+$$;
+RESET ROLE;
+
+-- An API key reads its own company, and only its own.
+SELECT set_config('request.headers', jsonb_build_object('carbon-key', current_setting('test.raw_key'))::text, true);
+SET LOCAL ROLE anon;
+DO $$
+BEGIN
+ PERFORM get_inventory_valuation(current_setting('test.company_a'));
+ BEGIN
+ PERFORM get_inventory_valuation(current_setting('test.company_b'));
+ RAISE EXCEPTION 'FAIL: an API key read another company''s inventory valuation';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+END;
+$$;
+RESET ROLE;
+SELECT set_config('request.headers', '{}', true);
+
+-- A signed-in employee of company A.
+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_a'), 'role', 'authenticated')::text, true);
+SET LOCAL ROLE authenticated;
+DO $$
+DECLARE
+ claims jsonb;
+BEGIN
+ PERFORM get_inventory_valuation(current_setting('test.company_a'));
+ BEGIN
+ PERFORM get_inventory_valuation(current_setting('test.company_b'));
+ RAISE EXCEPTION 'FAIL: an employee of A read B''s inventory valuation';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ claims := get_claims(current_setting('test.user_a'), current_setting('test.company_a'));
+ IF claims->>'role' IS DISTINCT FROM 'employee' THEN
+ RAISE EXCEPTION 'FAIL: a user cannot read their own claims (%)', claims;
+ END IF;
+ BEGIN
+ PERFORM get_claims(current_setting('test.user_b'), current_setting('test.company_b'));
+ RAISE EXCEPTION 'FAIL: an employee of A read the claims of a user only in B';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+
+ IF cardinality(groups_for_user(current_setting('test.user_b'))) <> 0 THEN
+ RAISE EXCEPTION 'FAIL: an employee of A saw the groups of a user only in B';
+ END IF;
+
+ IF users_for_groups(ARRAY[current_setting('test.group_b')]) <> '[]'::jsonb THEN
+ RAISE EXCEPTION 'FAIL: an employee of A listed the members of a group in B';
+ END IF;
+
+ -- An interceptor called directly with a forged payload runs under RLS.
+ BEGIN
+ PERFORM sync_create_customer_type_group('customerType', 'INSERT',
+ jsonb_build_object('id', 'rpc-privileges-forged', 'name', 'forged', 'companyId', current_setting('test.company_b')), NULL);
+ RAISE EXCEPTION 'FAIL: an employee of A wrote a group into B through an interceptor';
+ EXCEPTION WHEN insufficient_privilege THEN NULL;
+ END;
+END;
+$$;
+
+-- Ordinary writes still work as the user: id() defaults, RLS helpers and the
+-- event-system dispatchers (now SECURITY DEFINER) all run.
+SET LOCAL "app.sync_in_progress" = 'false';
+INSERT INTO "customer" (name, "readableId", "companyId") VALUES ('RPC privileges customer', 'RPC-TEST', current_setting('test.company_a'));
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM "customer" WHERE name = 'RPC privileges customer') THEN
+ RAISE EXCEPTION 'FAIL: the employee cannot read back their own customer';
+ END IF;
+END;
+$$;
+RESET ROLE;
+
+-- The permission editor reads a colleague's claims holding users_update alone.
+SELECT set_config('request.jwt.claims', jsonb_build_object('sub', current_setting('test.user_c'), 'role', 'authenticated')::text, true);
+SET LOCAL ROLE authenticated;
+DO $$
+BEGIN
+ IF get_claims(current_setting('test.user_a'), current_setting('test.company_a'))->>'role' IS DISTINCT FROM 'employee' THEN
+ RAISE EXCEPTION 'FAIL: a users_update holder cannot read a colleague''s claims';
+ END IF;
+END;
+$$;
+RESET ROLE;
+
+SELECT 'rpc-privileges: all checks passed' AS result;
+ROLLBACK;
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 6844343be6..85e34aac2a 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260923134421",
+ "schemaVersion": "20260925121735",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-24T08:19:28.605Z",
+ "exportedAt": "2026-09-25T14:21:00.020Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -14,107 +14,107 @@
"name": "account",
"rows": 0,
"columns": [
- "tags",
- "companyGroupId",
- "createdAt",
- "name",
- "isSystem",
- "parentId",
- "class",
- "accountType",
- "customFields",
- "isGroup",
- "updatedBy",
- "number",
- "createdBy",
- "updatedAt",
"incomeBalance",
- "active",
+ "updatedAt",
+ "createdBy",
+ "number",
+ "consolidatedRate",
"id",
- "consolidatedRate"
+ "active",
+ "isSystem",
+ "name",
+ "createdAt",
+ "companyGroupId",
+ "tags",
+ "updatedBy",
+ "isGroup",
+ "customFields",
+ "accountType",
+ "class",
+ "parentId"
]
},
{
"name": "accountDefault",
"rows": 0,
"columns": [
- "bankLocalCurrencyAccount",
- "payablesAccount",
- "accumulatedDepreciationAccount",
- "intercompanyReceivablesAccount",
- "receivablesAccount",
- "customerPaymentDiscountAccount",
- "currencyTranslationAccount",
- "supplierPaymentDiscountAccount",
- "reverseChargeSalesTaxPayableAccount",
- "assetDepreciationExpenseAccount",
- "salesDiscountAccount",
- "costOfGoodsSoldAccount",
- "assetGainOnDisposalAccount",
- "customerWriteOffAccount",
- "assetAquisitionCostAccount",
- "supplierPrepaymentAccount",
- "interestAccount",
- "lotSizeVarianceAccount",
- "intercompanyPayablesAccount",
- "indirectCostAccount",
- "bankCashAccount",
- "roundingAccount",
- "scrapAccount",
- "subcontractingVarianceAccount",
- "assetAquisitionCostOnDisposalAccount",
- "accumulatedDepreciationOnDisposalAccount",
- "realizedExchangeGainAccount",
+ "laborAbsorptionAccount",
+ "updatedBy",
+ "salesReturnsAccount",
+ "laborAndMachineVarianceAccount",
+ "rawMaterialsAccount",
+ "workInProgressAccount",
+ "overheadAbsorptionAccount",
+ "purchaseTaxPayableAccount",
+ "salesTaxPayableAccount",
+ "deferredTaxLiabilityAccountId",
+ "inventoryAdjustmentVarianceAccount",
+ "deferredTaxExpenseAccountId",
+ "companyId",
+ "finishedGoodsAccount",
+ "assetLossOnDisposalAccount",
"materialVarianceAccount",
"bankForeignCurrencyAccount",
+ "accumulatedDepreciationOnDisposalAccount",
+ "realizedExchangeGainAccount",
+ "purchaseVarianceAccount",
"salesShippingRevenueAccount",
"overheadVarianceAccount",
"realizedExchangeLossAccount",
- "purchaseVarianceAccount",
+ "prepaymentAccount",
+ "salesAccount",
"maintenanceAccount",
"retainedEarningsAccount",
- "salesAccount",
- "prepaymentAccount",
- "serviceChargeAccount",
"goodsReceivedNotInvoicedAccount",
"supplierWriteOffAccount",
- "laborAbsorptionAccount",
- "updatedBy",
- "overheadAbsorptionAccount",
- "purchaseTaxPayableAccount",
- "salesTaxPayableAccount",
- "salesReturnsAccount",
- "rawMaterialsAccount",
- "laborAndMachineVarianceAccount",
- "workInProgressAccount",
- "inventoryAdjustmentVarianceAccount",
- "assetLossOnDisposalAccount",
- "finishedGoodsAccount",
- "companyId",
- "deferredTaxExpenseAccountId",
- "deferredTaxLiabilityAccountId"
+ "serviceChargeAccount",
+ "interestAccount",
+ "assetAquisitionCostAccount",
+ "supplierPrepaymentAccount",
+ "intercompanyPayablesAccount",
+ "lotSizeVarianceAccount",
+ "indirectCostAccount",
+ "bankCashAccount",
+ "roundingAccount",
+ "scrapAccount",
+ "assetAquisitionCostOnDisposalAccount",
+ "subcontractingVarianceAccount",
+ "bankLocalCurrencyAccount",
+ "receivablesAccount",
+ "payablesAccount",
+ "intercompanyReceivablesAccount",
+ "accumulatedDepreciationAccount",
+ "supplierPaymentDiscountAccount",
+ "reverseChargeSalesTaxPayableAccount",
+ "customerPaymentDiscountAccount",
+ "currencyTranslationAccount",
+ "assetGainOnDisposalAccount",
+ "customerWriteOffAccount",
+ "salesDiscountAccount",
+ "assetDepreciationExpenseAccount",
+ "costOfGoodsSoldAccount"
]
},
{
"name": "accountingPeriod",
"rows": 0,
"columns": [
- "lockedAt",
- "companyId",
- "closeStatus",
- "closedBy",
+ "status",
"periodNumber",
"endDate",
- "status",
- "closedAt",
- "createdAt",
- "id",
- "updatedAt",
- "createdBy",
- "updatedBy",
- "lockedBy",
+ "closedBy",
+ "closeStatus",
+ "companyId",
+ "lockedAt",
+ "startDate",
"fiscalYear",
- "startDate"
+ "lockedBy",
+ "updatedBy",
+ "createdBy",
+ "updatedAt",
+ "id",
+ "createdAt",
+ "closedAt"
]
},
{
@@ -122,47 +122,56 @@
"rows": 0,
"columns": [
"endingBalance",
- "createdBy",
"accountingPeriodId",
"accountId",
- "endingBalanceDate",
+ "createdBy",
"updatedBy",
"id",
- "createdAt",
+ "endingBalanceDate",
+ "companyId",
"updatedAt",
- "companyId"
+ "createdAt"
]
},
{
"name": "accountingSyncOperation",
"rows": 0,
"columns": [
- "trigger",
+ "completedAt",
+ "updatedAt",
+ "entityId",
+ "createdBy",
+ "externalId",
"integration",
"errorMessage",
"entityType",
- "updatedBy",
"createdAt",
- "externalId",
- "createdBy",
- "entityId",
- "completedAt",
- "updatedAt",
- "status",
- "attemptCount",
- "metadata",
- "errorCode",
- "companyId",
- "direction",
+ "updatedBy",
+ "trigger",
"idempotencyKey",
"id",
- "lastAttemptAt"
+ "lastAttemptAt",
+ "direction",
+ "metadata",
+ "companyId",
+ "errorCode",
+ "status",
+ "attemptCount"
]
},
{
"name": "accountingSyncTieOut",
"rows": 0,
"columns": [
+ "docBackedAmount",
+ "pendingAmount",
+ "createdBy",
+ "internalDelta",
+ "companyId",
+ "carbonPostedAmount",
+ "excludedAmount",
+ "id",
+ "blockedAmount",
"syncedAmount",
"integration",
"externalDelta",
@@ -172,32 +181,23 @@
"computedAt",
"createdAt",
"accountId",
- "providerAmount",
- "docBackedAmount",
- "pendingAmount",
- "createdBy",
- "internalDelta",
- "companyId",
- "carbonPostedAmount",
- "excludedAmount",
- "id",
- "blockedAmount"
+ "providerAmount"
]
},
{
"name": "address",
"rows": 0,
"columns": [
- "stateProvince",
- "countryCode",
"addressLine2",
"city",
- "postalCode",
+ "countryCode",
+ "stateProvince",
+ "addressLine1",
+ "companyId",
+ "phone",
"fax",
"id",
- "phone",
- "companyId",
- "addressLine1"
+ "postalCode"
]
},
{
@@ -220,44 +220,44 @@
"name": "agentMessage",
"rows": 0,
"columns": [
- "feedback",
- "createdBy",
- "id",
- "inputTokens",
"outputTokens",
"finishReason",
"updatedBy",
"threadId",
- "context",
- "createdAt",
+ "feedback",
+ "createdBy",
+ "id",
+ "inputTokens",
"feedbackNote",
"role",
"companyId",
- "updatedAt"
+ "updatedAt",
+ "context",
+ "createdAt"
]
},
{
"name": "agentMessagePart",
"rows": 0,
"columns": [
- "toolOutput",
- "id",
- "toolCallId",
- "textContent",
+ "toolName",
+ "updatedAt",
+ "errorMessage",
+ "companyId",
+ "orderIndex",
+ "updatedBy",
+ "createdBy",
+ "toolState",
+ "type",
+ "toolInput",
+ "toolClassification",
"messageId",
"toolDurationMs",
"createdAt",
- "toolInput",
- "toolClassification",
- "toolState",
- "type",
- "updatedBy",
- "createdBy",
- "updatedAt",
- "orderIndex",
- "companyId",
- "errorMessage",
- "toolName"
+ "textContent",
+ "toolOutput",
+ "toolCallId",
+ "id"
]
},
{
@@ -269,62 +269,62 @@
"createdAt",
"status",
"updatedBy",
- "companyId",
"amount",
+ "companyId",
"decisionAt",
- "updatedAt",
- "documentType",
"createdBy",
+ "documentType",
+ "updatedAt",
"requestedBy",
+ "decisionNotes",
"decisionBy",
- "id",
- "decisionNotes"
+ "id"
]
},
{
"name": "approvalRule",
"rows": 0,
"columns": [
- "documentType",
- "createdAt",
- "companyId",
+ "lowerBoundAmount",
"updatedBy",
- "id",
"createdBy",
- "lowerBoundAmount",
- "approverGroupIds",
- "enabled",
- "escalationDays",
+ "id",
+ "createdAt",
+ "companyId",
+ "documentType",
"defaultApproverId",
- "updatedAt"
+ "updatedAt",
+ "escalationDays",
+ "enabled",
+ "approverGroupIds"
]
},
{
"name": "auditLogArchive",
"rows": 0,
"columns": [
- "companyId",
- "createdAt",
"id",
"rowCount",
+ "companyId",
+ "createdAt",
+ "endDate",
"startDate",
"archivePath",
- "sizeBytes",
- "endDate"
+ "sizeBytes"
]
},
{
"name": "changeOrderRequiredAction",
"rows": 0,
"columns": [
- "updatedAt",
"companyId",
- "createdAt",
+ "updatedAt",
"id",
"customFields",
- "updatedBy",
+ "createdAt",
"active",
"name",
+ "updatedBy",
"createdBy"
]
},
@@ -332,107 +332,107 @@
"name": "changeOrderType",
"rows": 0,
"columns": [
- "createdBy",
- "createdAt",
"companyId",
+ "createdAt",
"updatedBy",
+ "createdBy",
+ "name",
"id",
- "updatedAt",
- "name"
+ "updatedAt"
]
},
{
"name": "companyAccountsPayableBillingAddress",
"rows": 0,
"columns": [
- "updatedAt",
- "city",
- "addressLine1",
- "addressLine2",
- "postalCode",
+ "fax",
+ "countryCode",
+ "updatedBy",
+ "name",
+ "state",
"email",
"phone",
"id",
- "state",
- "name",
- "updatedBy",
- "fax",
- "countryCode"
+ "postalCode",
+ "addressLine1",
+ "addressLine2",
+ "city",
+ "updatedAt"
]
},
{
"name": "companyAccountsReceivableBillingAddress",
"rows": 0,
"columns": [
- "updatedAt",
- "city",
"postalCode",
"addressLine2",
"addressLine1",
+ "city",
+ "updatedAt",
+ "countryCode",
+ "fax",
+ "updatedBy",
+ "name",
"state",
- "email",
"id",
"phone",
- "fax",
- "countryCode",
- "name",
- "updatedBy"
+ "email"
]
},
{
"name": "companySettings",
"rows": 0,
"columns": [
- "inventoryShelfLife",
- "incompletePickingListPolicy",
- "gaugeCalibrationExpiredNotificationGroup",
- "consoleEnabled",
- "digitalQuoteEnabled",
- "returnPickedMaterialTiming",
- "accountingEnabled",
- "inventoryJobCompletedNotificationGroup",
- "accountsReceivableAddress",
- "accountsPayableAddress",
- "includeMaterialsOnTraveler",
- "materialGeneratedIds",
- "qualityIssueTarget",
- "id",
- "includeOperationsOnTraveler",
+ "productLabelSize",
+ "showCustomerReadableId",
"plmReleaseControl",
+ "includeOperationsOnTraveler",
+ "id",
"salesJobCompletedNotificationGroup",
"autoStartOperationTimer",
"enforceInspectionFourEyes",
- "showCurrencyTrailingZeros",
+ "requireMfa",
"updateLeadTimesOnReceipt",
"accountsPayableEmail",
+ "salesRuleNotificationGroup",
"useMetric",
+ "returnPickedMaterialTiming",
+ "accountingEnabled",
+ "accountsReceivableAddress",
+ "inventoryJobCompletedNotificationGroup",
+ "accountsPayableAddress",
+ "includeMaterialsOnTraveler",
+ "materialGeneratedIds",
+ "qualityIssueTarget",
+ "inventoryShelfLife",
+ "incompletePickingListPolicy",
+ "gaugeCalibrationExpiredNotificationGroup",
+ "digitalQuoteEnabled",
+ "consoleEnabled",
+ "assetTaxDepreciationEnabled",
+ "otherDispatchNotificationGroup",
"allowLowercaseItemIds",
- "productLabelSize",
- "showCustomerReadableId",
+ "supplierQuoteNotificationGroup",
+ "assetTaxRate",
+ "defaultSupplierCc",
+ "rfqReadyNotificationGroup",
+ "operationsDispatchNotificationGroup",
+ "kanbanOutput",
+ "quoteLineCategoryMarkups",
+ "defaultCustomerCc",
+ "printing",
+ "showCurrencyTrailingZeros",
+ "shelfLabelSize",
+ "timeCardEnabled",
+ "accountsReceivableEmail",
"digitalQuoteIncludesPurchaseOrders",
- "digitalQuoteNotificationGroup",
"purchasePriceUpdateTiming",
+ "digitalQuoteNotificationGroup",
"autoSelectMaterialWithoutPickingList",
"showSupplierReadableId",
"qualityDispatchNotificationGroup",
"maintenanceDispatchNotificationGroup",
- "samplingStandard",
- "salesRuleNotificationGroup",
- "printing",
- "defaultCustomerCc",
- "shelfLabelSize",
- "timeCardEnabled",
- "accountsReceivableEmail",
- "defaultSupplierCc",
- "assetTaxRate",
- "rfqReadyNotificationGroup",
- "operationsDispatchNotificationGroup",
- "kanbanOutput",
- "quoteLineCategoryMarkups",
- "assetTaxDepreciationEnabled",
- "otherDispatchNotificationGroup",
- "supplierQuoteNotificationGroup",
- "requireMfa"
+ "samplingStandard"
]
},
{
@@ -453,103 +453,103 @@
"name": "consumable",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "id",
- "createdAt",
- "updatedAt",
"customFields",
"tags",
- "createdBy",
"approved",
- "approvedBy"
+ "approvedBy",
+ "createdBy",
+ "updatedBy",
+ "id",
+ "companyId",
+ "updatedAt",
+ "createdAt"
]
},
{
"name": "contact",
"rows": 0,
"columns": [
- "firstName",
- "homePhone",
- "fax",
- "id",
- "workPhone",
- "title",
+ "isCustomer",
+ "email",
"lastName",
- "notes",
"companyId",
+ "notes",
"mobilePhone",
- "isCustomer",
- "email"
+ "workPhone",
+ "id",
+ "title",
+ "firstName",
+ "homePhone",
+ "fax"
]
},
{
"name": "costCenter",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "parentCostCenterId",
- "companyId",
- "createdAt",
"customFields",
"id",
+ "createdAt",
+ "name",
"ownerId",
"updatedAt",
- "name"
+ "createdBy",
+ "parentCostCenterId",
+ "companyId",
+ "updatedBy"
]
},
{
"name": "currency",
"rows": 0,
"columns": [
- "updatedBy",
- "tags",
- "historicalExchangeRate",
- "customFields",
- "code",
- "id",
- "createdAt",
- "decimalPlaces",
- "companyGroupId",
"updatedAt",
+ "companyGroupId",
+ "createdBy",
"active",
- "createdBy"
+ "createdAt",
+ "id",
+ "decimalPlaces",
+ "code",
+ "customFields",
+ "updatedBy",
+ "historicalExchangeRate",
+ "tags"
]
},
{
"name": "customField",
"rows": 0,
"columns": [
- "required",
- "sortOrder",
- "table",
- "active",
"updatedBy",
"dataTypeId",
- "name",
- "tags",
- "createdBy",
- "companyId",
- "updatedAt",
+ "active",
+ "sortOrder",
+ "required",
+ "table",
+ "listOptions",
"createdAt",
"id",
- "listOptions"
+ "updatedAt",
+ "companyId",
+ "createdBy",
+ "name",
+ "tags"
]
},
{
"name": "customerStatus",
"rows": 0,
"columns": [
+ "createdBy",
+ "updatedAt",
+ "createdAt",
+ "companyId",
"updatedBy",
"id",
"tags",
"customFields",
- "name",
- "createdBy",
- "updatedAt",
- "createdAt",
- "companyId"
+ "name"
]
},
{
@@ -573,31 +573,31 @@
"rows": 0,
"columns": [
"createdBy",
- "parentDepartmentId",
- "companyId",
"updatedBy",
- "customFields",
- "id",
+ "companyId",
+ "parentDepartmentId",
"createdAt",
- "name",
+ "id",
+ "customFields",
"tags",
- "updatedAt"
+ "updatedAt",
+ "name"
]
},
{
"name": "depreciationRun",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "postedBy",
- "depreciationRunId",
- "updatedBy",
- "createdAt",
- "postedAt",
- "periodEnd",
+ "companyId",
"status",
- "companyId"
+ "periodEnd",
+ "postedAt",
+ "createdAt",
+ "updatedBy",
+ "depreciationRunId",
+ "postedBy",
+ "id",
+ "createdBy"
]
},
{
@@ -605,71 +605,71 @@
"rows": 0,
"columns": [
"active",
- "companyGroupId",
- "entityType",
"createdBy",
- "id",
- "updatedBy",
+ "entityType",
+ "companyGroupId",
"required",
- "name",
+ "updatedBy",
+ "id",
+ "updatedAt",
"createdAt",
- "updatedAt"
+ "name"
]
},
{
"name": "dimensionValue",
"rows": 0,
"columns": [
- "id",
- "createdAt",
- "dimensionId",
- "updatedAt",
- "createdBy",
- "name",
+ "updatedBy",
"companyGroupId",
- "updatedBy"
+ "name",
+ "createdBy",
+ "updatedAt",
+ "dimensionId",
+ "createdAt",
+ "id"
]
},
{
"name": "document",
"rows": 0,
"columns": [
+ "description",
+ "name",
+ "updatedBy",
+ "type",
"createdBy",
"size",
"sourceDocumentId",
"updatedAt",
- "name",
- "updatedBy",
- "description",
- "type",
- "companyId",
- "writeGroups",
- "id",
+ "sourceDocument",
"path",
"createdAt",
- "sourceDocument",
+ "readGroups",
"active",
- "readGroups"
+ "id",
+ "writeGroups",
+ "companyId"
]
},
{
"name": "documentExtraction",
"rows": 0,
"columns": [
- "createdAt",
"storagePath",
- "status",
- "sourceDocumentId",
- "updatedAt",
+ "createdAt",
"sourceDocument",
- "documentType",
- "createdBy",
- "id",
+ "updatedAt",
+ "sourceDocumentId",
+ "status",
"filteredData",
- "error",
- "extractedData",
+ "id",
+ "createdBy",
+ "documentType",
+ "updatedBy",
"companyId",
- "updatedBy"
+ "extractedData",
+ "error"
]
},
{
@@ -680,7 +680,7 @@
{
"name": "documentLabel",
"rows": 0,
- "columns": ["label", "companyId", "documentId", "userId"]
+ "columns": ["userId", "documentId", "companyId", "label"]
},
{
"name": "documentSection",
@@ -702,139 +702,139 @@
"name": "documentTemplate",
"rows": 0,
"columns": [
- "createdBy",
- "headerSectionId",
+ "formatVersion",
+ "documentType",
+ "settings",
+ "updatedBy",
+ "blocks",
"companyId",
"updatedAt",
- "theme",
- "createdAt",
+ "headerSectionId",
+ "createdBy",
"id",
"footerSectionId",
- "settings",
- "formatVersion",
- "documentType",
- "updatedBy",
- "blocks"
+ "createdAt",
+ "theme"
]
},
{
"name": "documentTransaction",
"rows": 0,
"columns": [
- "createdAt",
- "type",
- "userId",
- "companyId",
+ "documentId",
"id",
- "documentId"
+ "companyId",
+ "userId",
+ "type",
+ "createdAt"
]
},
{
"name": "employeeType",
"rows": 0,
"columns": [
- "updatedAt",
- "id",
- "name",
"createdAt",
- "systemType",
+ "companyId",
"protected",
- "companyId"
+ "systemType",
+ "id",
+ "updatedAt",
+ "name"
]
},
{
"name": "employee",
"rows": 0,
- "columns": ["pin", "employeeTypeId", "active", "id", "companyId"]
+ "columns": ["id", "companyId", "pin", "active", "employeeTypeId"]
},
{
"name": "employeeTypePermission",
"rows": 0,
"columns": [
- "employeeTypeId",
- "view",
- "module",
- "updatedAt",
"update",
"create",
"delete",
- "createdAt"
+ "createdAt",
+ "employeeTypeId",
+ "view",
+ "module",
+ "updatedAt"
]
},
{
"name": "enforcementRule",
"rows": 0,
"columns": [
- "description",
+ "message",
+ "appliesToAll",
+ "id",
+ "surfaces",
+ "targetType",
+ "conditionAst",
+ "companyId",
+ "filteredItemGroupIds",
+ "createdBy",
+ "createdAt",
+ "active",
"customFields",
"filteredItemTypes",
- "active",
- "createdAt",
+ "description",
+ "severity",
+ "updatedBy",
+ "updatedAt",
"name",
"family",
- "filteredItemMatchAll",
- "updatedAt",
- "updatedBy",
- "severity",
- "id",
- "surfaces",
- "appliesToAll",
- "message",
- "createdBy",
- "filteredItemGroupIds",
- "companyId",
- "conditionAst",
- "targetType"
+ "filteredItemMatchAll"
]
},
{
"name": "enforcementRuleAcknowledgment",
"rows": 0,
"columns": [
- "ruleName",
- "updatedBy",
- "ruleId",
- "documentLineId",
"createdBy",
"documentType",
- "companyId",
- "createdAt",
- "outcome",
- "itemId",
- "message",
+ "documentLineId",
+ "ruleName",
+ "ruleId",
+ "updatedBy",
+ "documentId",
"id",
"severity",
- "documentId"
+ "message",
+ "itemId",
+ "outcome",
+ "companyId",
+ "createdAt"
]
},
{
"name": "eventSystemSubscription",
"rows": 0,
"columns": [
- "id",
- "createdAt",
- "filter",
- "name",
- "config",
- "active",
- "operations",
+ "handlerType",
"table",
"companyId",
- "handlerType"
+ "operations",
+ "active",
+ "config",
+ "name",
+ "filter",
+ "createdAt",
+ "id"
]
},
{
"name": "exchangeRateOverride",
"rows": 0,
"columns": [
- "companyId",
- "updatedAt",
- "id",
- "createdAt",
"rate",
"currencyCode",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "companyId",
+ "updatedAt",
+ "id",
+ "createdAt"
]
},
{
@@ -845,99 +845,99 @@
"updatedBy",
"integration",
"metadata",
- "createdBy",
"externalId",
- "entityType",
+ "createdBy",
"companyId",
- "lastSyncedAt",
+ "entityType",
"createdAt",
+ "lastSyncedAt",
+ "updatedAt",
"remoteUpdatedAt",
"id",
- "updatedAt",
"allowDuplicateExternalId"
]
},
{
"name": "fiscalYearSettings",
"rows": 0,
- "columns": ["startMonth", "companyId", "updatedBy", "taxStartMonth"]
+ "columns": ["startMonth", "companyId", "taxStartMonth", "updatedBy"]
},
{
"name": "fixedAssetClass",
"rows": 0,
"columns": [
- "name",
- "taxDepreciationMethod",
- "macrsPropertyClass",
- "writeOffAccountId",
- "customFields",
- "accumulatedDepreciationAccountId",
- "writeDownAccountId",
- "depreciationExpenseAccountId",
- "id",
- "gainOnDisposalAccountId",
- "residualValuePercent",
- "bonusDepreciationPercent",
- "companyId",
- "description",
+ "updatedAt",
+ "usefulLifeMonths",
+ "lossOnDisposalAccountId",
+ "createdAt",
+ "taxResidualValuePercent",
+ "createdBy",
+ "macrsConvention",
"taxUsefulLifeMonths",
+ "description",
"depreciationMethod",
+ "companyId",
+ "bonusDepreciationPercent",
"assetAccountId",
"updatedBy",
- "lossOnDisposalAccountId",
- "createdAt",
- "usefulLifeMonths",
- "updatedAt",
- "macrsConvention",
- "createdBy",
- "taxResidualValuePercent"
+ "depreciationExpenseAccountId",
+ "id",
+ "writeDownAccountId",
+ "residualValuePercent",
+ "gainOnDisposalAccountId",
+ "macrsPropertyClass",
+ "taxDepreciationMethod",
+ "name",
+ "accumulatedDepreciationAccountId",
+ "customFields",
+ "writeOffAccountId"
]
},
{
"name": "gaugeType",
"rows": 0,
"columns": [
- "id",
- "createdBy",
- "name",
- "updatedBy",
- "createdAt",
"customFields",
"companyId",
- "updatedAt"
+ "updatedAt",
+ "createdAt",
+ "name",
+ "updatedBy",
+ "id",
+ "createdBy"
]
},
{
"name": "group",
"rows": 0,
"columns": [
- "companyId",
- "isIdentityGroup",
- "isCustomerTypeGroup",
- "isEmployeeTypeGroup",
- "name",
- "createdAt",
- "isSupplierTypeGroup",
+ "isCustomerOrgGroup",
"updatedAt",
- "isSupplierOrgGroup",
"id",
- "isCustomerOrgGroup"
+ "isSupplierOrgGroup",
+ "createdAt",
+ "isSupplierTypeGroup",
+ "name",
+ "isEmployeeTypeGroup",
+ "isCustomerTypeGroup",
+ "isIdentityGroup",
+ "companyId"
]
},
{
"name": "holiday",
"rows": 0,
"columns": [
- "companyId",
- "date",
"createdAt",
- "updatedAt",
- "id",
- "tags",
- "createdBy",
- "name",
- "updatedBy",
- "customFields"
+ "date",
+ "companyId",
+ "customFields",
+ "updatedBy",
+ "name",
+ "createdBy",
+ "tags",
+ "id",
+ "updatedAt"
]
},
{
@@ -959,183 +959,183 @@
"name": "implementationFieldValue",
"rows": 0,
"columns": [
- "createdBy",
- "value",
- "fieldKey",
- "updatedBy",
- "id",
"createdAt",
+ "id",
+ "updatedAt",
"companyId",
- "updatedAt"
+ "createdBy",
+ "updatedBy",
+ "value",
+ "fieldKey"
]
},
{
"name": "implementationRow",
"rows": 0,
"columns": [
+ "sortOrder",
+ "createdAt",
+ "collection",
+ "payload",
"createdBy",
"updatedAt",
"id",
"updatedBy",
- "companyId",
- "sortOrder",
- "createdAt",
- "collection",
- "payload"
+ "companyId"
]
},
{
"name": "invite",
"rows": 0,
"columns": [
- "code",
- "attestedAt",
"revokedAt",
"createdAt",
+ "attestedAt",
+ "code",
+ "companyId",
"updatedBy",
"id",
"acceptedAt",
- "companyId",
+ "createdBy",
"permissions",
"email",
- "createdBy",
- "attestedBy",
- "role"
+ "role",
+ "attestedBy"
]
},
{
"name": "itarCertification",
"rows": 0,
"columns": [
- "createdBy",
- "type",
- "userId",
- "fullLegalName",
"docVersion",
"userAgent",
"createdAt",
"updatedAt",
+ "userId",
+ "type",
+ "createdBy",
+ "fullLegalName",
+ "id",
+ "complianceContact",
+ "ipAddress",
+ "docHash",
+ "updatedBy",
"expiresAt",
"companyId",
- "updatedBy",
- "certifiedAt",
"title",
- "ipAddress",
- "complianceContact",
- "id",
- "docHash"
+ "certifiedAt"
]
},
{
"name": "itemPostingGroup",
"rows": 0,
"columns": [
- "name",
- "updatedBy",
- "customFields",
+ "companyId",
+ "description",
+ "active",
+ "createdAt",
"updatedAt",
"id",
"tags",
"createdBy",
- "description",
- "active",
- "createdAt",
- "companyId"
+ "name",
+ "updatedBy",
+ "customFields"
]
},
{
"name": "itemStockQuantities",
"rows": 0,
- "columns": ["quantityOnHand", "locationId", "itemId", "companyId"]
+ "columns": ["locationId", "quantityOnHand", "itemId", "companyId"]
},
{
"name": "journal",
"rows": 0,
"columns": [
- "customFields",
- "updatedBy",
+ "postingDate",
+ "reversalOfId",
+ "postedBy",
+ "updatedAt",
"eliminationKind",
- "companyId",
+ "updatedBy",
"postedAt",
"accountingPeriodId",
- "updatedAt",
- "postedBy",
- "reversalOfId",
- "postingDate",
- "status",
- "tags",
- "description",
- "reversedById",
- "createdBy",
- "createdAt",
+ "companyId",
+ "customFields",
"sourceType",
+ "journalEntryId",
"id",
- "journalEntryId"
+ "createdAt",
+ "reversedById",
+ "description",
+ "createdBy",
+ "status",
+ "tags"
]
},
{
"name": "journalLine",
"rows": 0,
"columns": [
- "journalLineReference",
"documentId",
+ "journalLineReference",
+ "tags",
"companyId",
"journalId",
- "tags",
"quantity",
- "documentLineReference",
- "externalDocumentId",
"id",
+ "externalDocumentId",
+ "documentLineReference",
"documentType",
+ "description",
+ "createdAt",
"updatedBy",
"updatedAt",
- "createdAt",
- "description",
"createdBy",
"customFields",
"accountId",
"amount",
- "accrual",
- "intercompanyPartnerId"
+ "intercompanyPartnerId",
+ "accrual"
]
},
{
"name": "intercompanyTransaction",
"rows": 0,
"columns": [
- "updatedAt",
"status",
"sourceJournalLineId",
- "amount",
+ "updatedAt",
+ "targetCompanyId",
"sourceCompanyId",
"createdAt",
- "targetCompanyId",
- "targetJournalLineId",
- "description",
+ "amount",
"id",
+ "description",
"documentId",
- "currencyCode",
- "documentType",
+ "targetJournalLineId",
"companyGroupId",
- "eliminationJournalId"
+ "eliminationJournalId",
+ "currencyCode",
+ "documentType"
]
},
{
"name": "intercompanyEliminationLine",
"rows": 0,
"columns": [
- "createdAt",
- "quantity",
"id",
+ "quantity",
+ "createdAt",
"accountId",
- "updatedAt",
"companyId",
- "createdBy",
+ "updatedAt",
"itemId",
- "journalLineId",
+ "createdBy",
"updatedBy",
- "intercompanyTransactionId",
+ "journalLineId",
"role",
+ "intercompanyTransactionId",
"amount"
]
},
@@ -1143,108 +1143,108 @@
"name": "journalLineDimension",
"rows": 0,
"columns": [
- "journalLineId",
- "id",
"createdAt",
- "valueId",
+ "id",
+ "journalLineId",
+ "companyId",
"dimensionId",
- "companyId"
+ "valueId"
]
},
{
"name": "location",
"rows": 0,
"columns": [
- "countryCode",
- "latitude",
"updatedAt",
"name",
"createdBy",
- "stateProvince",
+ "countryCode",
+ "latitude",
"timezone",
"id",
"longitude",
- "postalCode",
- "createdAt",
+ "stateProvince",
"addressLine1",
+ "createdAt",
"addressLine2",
"tags",
"code",
- "customFields",
- "updatedBy",
+ "postalCode",
"companyId",
"requiresStaffing",
- "city"
+ "city",
+ "customFields",
+ "updatedBy"
]
},
{
"name": "fixedAsset",
"rows": 0,
"columns": [
- "depreciationMethod",
- "updatedAt",
- "createdBy",
- "customFields",
- "residualValuePercent",
- "disposalDate",
- "bonusDepreciationPercent",
- "fixedAssetId",
- "taxResidualValuePercent",
- "serialNumber",
"disposalMethod",
- "id",
- "usefulLifeMonths",
+ "serialNumber",
"companyId",
"taxDepreciationMethod",
- "createdAt",
- "locationId",
- "status",
- "notes",
- "name",
- "fixedAssetClassId",
- "macrsPropertyClass",
- "acquisitionDate",
- "depreciationStartDate",
- "saleProceeds",
- "acquisitionCost",
+ "id",
+ "usefulLifeMonths",
+ "disposalDate",
+ "customFields",
+ "residualValuePercent",
+ "updatedAt",
+ "depreciationMethod",
+ "createdBy",
+ "taxResidualValuePercent",
+ "fixedAssetId",
+ "bonusDepreciationPercent",
"macrsConvention",
"accumulatedTaxDepreciation",
- "assetLifetimeUsage",
+ "saleProceeds",
+ "acquisitionCost",
+ "description",
"accumulatedDepreciation",
"updatedBy",
"taxUsefulLifeMonths",
- "description"
+ "assetLifetimeUsage",
+ "notes",
+ "locationId",
+ "status",
+ "createdAt",
+ "depreciationStartDate",
+ "acquisitionDate",
+ "name",
+ "macrsPropertyClass",
+ "fixedAssetClassId"
]
},
{
"name": "depreciationRunLine",
"rows": 0,
"columns": [
+ "journalId",
+ "id",
+ "depreciationRunId",
+ "taxAmount",
"companyId",
"fixedAssetId",
- "amount",
- "taxAmount",
- "depreciationRunId",
- "journalId",
- "id"
+ "amount"
]
},
{
"name": "fixedAssetDisposal",
"rows": 0,
"columns": [
- "netBookValueAtDisposal",
- "companyId",
- "id",
- "createdBy",
+ "gainLoss",
+ "disposalDate",
+ "disposalMethod",
+ "updatedBy",
+ "saleProceeds",
"journalId",
"createdAt",
"fixedAssetId",
- "saleProceeds",
- "updatedBy",
- "gainLoss",
- "disposalMethod",
- "disposalDate"
+ "netBookValueAtDisposal",
+ "id",
+ "companyId",
+ "createdBy"
]
},
{
@@ -1252,131 +1252,131 @@
"rows": 0,
"columns": [
"createdAt",
- "periodEnd",
"periodStart",
+ "periodEnd",
"unitsProduced",
"createdBy",
"fixedAssetId",
"companyId",
- "id",
- "updatedBy"
+ "updatedBy",
+ "id"
]
},
{
"name": "inventoryCount",
"rows": 0,
"columns": [
- "isBlind",
+ "locationId",
+ "updatedBy",
+ "inventoryCountId",
+ "scope",
+ "createdBy",
+ "status",
+ "updatedAt",
+ "companyId",
+ "createdAt",
+ "customFields",
+ "postedBy",
+ "snapshotAt",
"postedAt",
"id",
"notes",
- "postedBy",
- "snapshotAt",
- "createdAt",
- "companyId",
- "customFields",
- "updatedAt",
- "status",
- "createdBy",
- "scope",
- "locationId",
- "inventoryCountId",
- "updatedBy"
+ "isBlind"
]
},
{
"name": "maintenanceFailureMode",
"rows": 0,
"columns": [
- "id",
"updatedBy",
- "name",
+ "id",
"type",
+ "name",
"createdAt",
+ "updatedAt",
"createdBy",
- "companyId",
- "updatedAt"
+ "companyId"
]
},
{
"name": "materialForm",
"rows": 0,
"columns": [
- "createdAt",
- "id",
- "tags",
+ "updatedBy",
+ "customFields",
+ "companyId",
+ "createdBy",
"code",
"updatedAt",
"name",
- "createdBy",
- "updatedBy",
- "customFields",
- "companyId"
+ "createdAt",
+ "id",
+ "tags"
]
},
{
"name": "materialDimension",
"rows": 0,
- "columns": ["name", "isMetric", "companyId", "materialFormId", "id"]
+ "columns": ["isMetric", "name", "companyId", "materialFormId", "id"]
},
{
"name": "materialSubstance",
"rows": 0,
"columns": [
+ "updatedBy",
"customFields",
"companyId",
- "updatedBy",
"createdBy",
- "name",
- "updatedAt",
"code",
+ "updatedAt",
+ "name",
+ "createdAt",
"id",
- "tags",
- "createdAt"
+ "tags"
]
},
{
"name": "materialFinish",
"rows": 0,
- "columns": ["companyId", "materialSubstanceId", "name", "id"]
+ "columns": ["companyId", "materialSubstanceId", "id", "name"]
},
{
"name": "materialGrade",
"rows": 0,
- "columns": ["companyId", "name", "id", "materialSubstanceId"]
+ "columns": ["id", "materialSubstanceId", "companyId", "name"]
},
{
"name": "materialType",
"rows": 0,
"columns": [
- "code",
- "materialSubstanceId",
- "materialFormId",
- "name",
"id",
- "companyId"
+ "companyId",
+ "name",
+ "materialFormId",
+ "code",
+ "materialSubstanceId"
]
},
{
"name": "material",
"rows": 0,
"columns": [
+ "companyId",
+ "approvedBy",
+ "id",
"createdAt",
- "approved",
"customFields",
- "id",
- "approvedBy",
- "companyId",
- "materialSubstanceId",
- "updatedBy",
- "materialFormId",
- "dimensionId",
- "finishId",
- "gradeId",
+ "approved",
"createdBy",
+ "gradeId",
"tags",
"updatedAt",
- "materialTypeId"
+ "materialTypeId",
+ "dimensionId",
+ "finishId",
+ "materialFormId",
+ "updatedBy",
+ "materialSubstanceId"
]
},
{
@@ -1388,61 +1388,61 @@
"name": "modelUpload",
"rows": 0,
"columns": [
- "originalSize",
- "updatedBy",
- "createdBy",
- "id",
- "updatedAt",
- "optimizedSize",
- "createdAt",
- "name",
- "thumbnailPath",
- "glbPath",
- "graphPath",
- "originalPath",
- "optimizeStatus",
"processingError",
- "optimizedModelPath",
- "autodeskUrn",
+ "optimizeStatus",
+ "originalPath",
+ "graphPath",
"optimizeError",
- "companyId",
+ "autodeskUrn",
+ "optimizedModelPath",
"optimizedAt",
- "componentCount",
- "processedAt",
+ "companyId",
+ "modelPath",
"size",
"processingStatus",
- "modelPath"
+ "processedAt",
+ "componentCount",
+ "originalSize",
+ "id",
+ "createdBy",
+ "updatedBy",
+ "createdAt",
+ "optimizedSize",
+ "updatedAt",
+ "glbPath",
+ "thumbnailPath",
+ "name"
]
},
{
"name": "assemblyPlanJob",
"rows": 0,
"columns": [
- "planPath",
- "error",
- "status",
- "kind",
- "stats",
+ "modelUploadId",
+ "createdAt",
+ "companyId",
+ "updatedAt",
"id",
"createdBy",
- "updatedAt",
- "companyId",
- "createdAt",
- "modelUploadId"
+ "stats",
+ "status",
+ "kind",
+ "error",
+ "planPath"
]
},
{
"name": "noQuoteReason",
"rows": 0,
"columns": [
- "updatedBy",
- "id",
- "customFields",
- "name",
"createdBy",
- "updatedAt",
"createdAt",
- "companyId"
+ "companyId",
+ "updatedAt",
+ "id",
+ "updatedBy",
+ "name",
+ "customFields"
]
},
{
@@ -1450,271 +1450,271 @@
"rows": 0,
"columns": [
"createdAt",
- "active",
- "name",
"updatedAt",
- "id",
- "systemType",
+ "name",
+ "active",
"createdBy",
- "companyId",
- "updatedBy"
+ "systemType",
+ "id",
+ "updatedBy",
+ "companyId"
]
},
{
"name": "nonConformanceType",
"rows": 0,
"columns": [
- "name",
- "customFields",
"id",
"updatedAt",
+ "name",
+ "customFields",
+ "createdBy",
"createdAt",
"companyId",
- "updatedBy",
- "createdBy"
+ "updatedBy"
]
},
{
"name": "nonConformanceWorkflow",
"rows": 0,
"columns": [
- "createdBy",
- "description",
- "content",
- "requiredActionIds",
"priority",
"companyId",
"updatedAt",
+ "content",
+ "description",
+ "createdBy",
+ "requiredActionIds",
+ "id",
+ "approvalRequirements",
+ "tags",
+ "source",
"updatedBy",
"createdAt",
"name",
- "active",
- "approvalRequirements",
- "id",
- "tags",
- "source"
+ "active"
]
},
{
"name": "nonConformance",
"rows": 0,
"columns": [
- "locationId",
- "nonConformanceId",
- "dueDate",
- "createdAt",
- "approvalRequirements",
- "requiredActionIds",
+ "assignee",
+ "content",
+ "source",
+ "tags",
+ "updatedAt",
+ "closeDate",
+ "customFields",
+ "openDate",
+ "quantity",
+ "description",
+ "nonConformanceTypeId",
+ "name",
+ "companyId",
+ "priority",
"updatedBy",
"nonConformanceWorkflowId",
"id",
"createdBy",
"status",
- "quantity",
- "description",
+ "nonConformanceId",
+ "locationId",
+ "dueDate",
+ "approvalRequirements",
+ "createdAt",
+ "requiredActionIds"
+ ]
+ },
+ {
+ "name": "changeOrder",
+ "rows": 0,
+ "columns": [
+ "reasonForChange",
"name",
- "nonConformanceTypeId",
+ "approvalRequirements",
+ "customFields",
+ "tags",
+ "updatedAt",
+ "status",
+ "createdBy",
"companyId",
- "priority",
- "source",
+ "dueDate",
+ "description",
"assignee",
- "content",
- "tags",
+ "createdAt",
+ "sourceType",
+ "sourceId",
+ "changeOrderId",
+ "requiredActionIds",
+ "priority",
+ "nonConformanceId",
+ "updatedBy",
+ "id",
+ "changeOrderTypeId",
"openDate",
- "customFields",
- "updatedAt",
- "closeDate"
+ "type"
]
},
{
- "name": "changeOrder",
+ "name": "changeOrderActionTask",
"rows": 0,
"columns": [
- "type",
- "changeOrderTypeId",
+ "completedDate",
+ "companyId",
"id",
- "openDate",
- "priority",
- "nonConformanceId",
- "updatedBy",
- "sourceId",
- "changeOrderId",
- "requiredActionIds",
- "assignee",
- "sourceType",
- "createdAt",
+ "sortOrder",
+ "tags",
+ "notes",
"createdBy",
+ "changeOrderId",
+ "actionTypeId",
+ "updatedBy",
"dueDate",
- "companyId",
- "description",
+ "createdAt",
+ "assignee",
"status",
"updatedAt",
- "approvalRequirements",
- "name",
- "reasonForChange",
- "customFields",
- "tags"
+ "name"
]
},
{
- "name": "changeOrderActionTask",
+ "name": "nonConformanceApprovalTask",
"rows": 0,
"columns": [
+ "status",
+ "updatedAt",
+ "approvalType",
+ "assignee",
"createdAt",
"dueDate",
"updatedBy",
- "updatedAt",
- "name",
- "status",
- "assignee",
- "companyId",
- "sortOrder",
- "id",
- "completedDate",
- "changeOrderId",
+ "nonConformanceId",
"createdBy",
- "actionTypeId",
"tags",
- "notes"
- ]
- },
- {
- "name": "nonConformanceApprovalTask",
- "rows": 0,
- "columns": [
- "updatedBy",
- "dueDate",
- "createdAt",
- "assignee",
- "status",
- "updatedAt",
- "approvalType",
- "completedDate",
+ "notes",
+ "companyId",
"id",
"sortOrder",
- "companyId",
- "notes",
- "tags",
- "createdBy",
- "nonConformanceId"
+ "completedDate"
]
},
{
"name": "nonConformanceReviewer",
"rows": 0,
"columns": [
- "status",
- "nonConformanceId",
- "companyId",
- "completedDate",
- "notes",
"title",
"createdAt",
"updatedAt",
"createdBy",
"id",
"updatedBy",
- "assignee"
+ "assignee",
+ "status",
+ "nonConformanceId",
+ "companyId",
+ "notes",
+ "completedDate"
]
},
{
"name": "note",
"rows": 0,
"columns": [
- "active",
- "createdAt",
- "noteRichText",
- "note",
- "companyId",
- "id",
- "updatedAt",
+ "documentId",
"updatedBy",
"createdBy",
- "documentId"
+ "updatedAt",
+ "id",
+ "companyId",
+ "note",
+ "noteRichText",
+ "createdAt",
+ "active"
]
},
{
"name": "notification",
"rows": 0,
"columns": [
- "description",
+ "documentType",
+ "id",
+ "payload",
+ "title",
+ "seenAt",
+ "userId",
+ "from",
+ "documentId",
+ "event",
+ "readAt",
+ "createdAt",
"digestedInto",
"companyId",
"topic",
- "createdAt",
- "readAt",
- "event",
- "from",
- "documentId",
- "userId",
- "seenAt",
- "title",
- "documentType",
- "id",
- "payload"
+ "description"
]
},
{
"name": "notificationDelivery",
"rows": 0,
"columns": [
- "lastDeliveryId",
- "userId",
- "event",
"documentId",
- "lastDeliveredAt",
- "companyId",
- "successCount",
+ "event",
+ "userId",
+ "lastDeliveryId",
+ "id",
"createdAt",
- "id"
+ "successCount",
+ "companyId",
+ "lastDeliveredAt"
]
},
{
"name": "notificationPreference",
"rows": 0,
"columns": [
- "enabled",
- "id",
- "userId",
- "topic",
"updatedAt",
"companyId",
- "channel"
+ "channel",
+ "topic",
+ "userId",
+ "enabled",
+ "id"
]
},
{
"name": "oauthCode",
"rows": 0,
"columns": [
- "scope",
- "codeChallenge",
- "id",
"redirectUri",
- "code",
- "codeChallengeMethod",
+ "id",
+ "codeChallenge",
+ "scope",
"expiresAt",
+ "codeChallengeMethod",
+ "code",
"companyId",
- "clientId",
+ "createdAt",
"userId",
- "createdAt"
+ "clientId"
]
},
{
"name": "part",
"rows": 0,
"columns": [
- "tags",
- "updatedAt",
- "fromDate",
- "approvedBy",
- "approved",
+ "companyId",
+ "createdAt",
+ "customFields",
"toDate",
"id",
"createdBy",
"updatedBy",
- "companyId",
- "createdAt",
- "customFields"
+ "approvedBy",
+ "approved",
+ "tags",
+ "fromDate",
+ "updatedAt"
]
},
{
@@ -1722,18 +1722,18 @@
"rows": 0,
"columns": [
"active",
- "daysDiscount",
"tags",
"daysDue",
- "discountPercentage",
+ "daysDiscount",
"updatedBy",
+ "discountPercentage",
"companyId",
"createdBy",
- "customFields",
"name",
+ "customFields",
"calculationMethod",
- "id",
"createdAt",
+ "id",
"updatedAt"
]
},
@@ -1741,409 +1741,409 @@
"name": "periodCloseTaskDefinition",
"rows": 0,
"columns": [
- "taskType",
- "updatedBy",
- "name",
- "required",
- "autoCheckKey",
- "createdBy",
- "updatedAt",
- "customFields",
- "createdAt",
- "companyId",
"severity",
"isSystem",
+ "customFields",
+ "companyId",
+ "createdAt",
+ "sortOrder",
"id",
"active",
"defaultAssigneeId",
- "sortOrder"
+ "required",
+ "taskType",
+ "name",
+ "updatedBy",
+ "updatedAt",
+ "createdBy",
+ "autoCheckKey"
]
},
{
"name": "periodCloseTask",
"rows": 0,
"columns": [
+ "taskType",
"status",
"required",
"id",
- "taskType",
+ "severity",
+ "sortOrder",
"completedBy",
"companyId",
"evidenceJournalId",
- "severity",
- "sortOrder",
- "name",
- "assigneeId",
- "updatedBy",
"updatedAt",
"skippedReason",
"notes",
+ "name",
+ "assigneeId",
+ "updatedBy",
+ "autoCheckKey",
"createdAt",
"createdBy",
"completedAt",
"accountingPeriodId",
- "definitionId",
- "autoCheckKey"
+ "definitionId"
]
},
{
"name": "pickingList",
"rows": 0,
"columns": [
- "notes",
- "locationId",
- "status",
- "assignee",
- "updatedAt",
- "companyId",
"createdAt",
+ "companyId",
"customFields",
"pickingListId",
"dueDate",
+ "updatedBy",
"id",
"createdBy",
- "updatedBy"
+ "notes",
+ "locationId",
+ "status",
+ "assignee",
+ "updatedAt"
]
},
{
"name": "pricingRule",
"rows": 0,
"columns": [
+ "itemIds",
+ "customerIds",
+ "id",
+ "priority",
+ "validFrom",
+ "name",
+ "customerTypeIds",
+ "maxQuantity",
+ "amount",
"itemPostingGroupId",
"createdAt",
- "amount",
"updatedAt",
- "active",
"updatedBy",
- "companyId",
+ "active",
"createdBy",
- "ruleType",
+ "companyId",
"validTo",
+ "ruleType",
"amountType",
- "minQuantity",
- "itemIds",
- "customerIds",
- "id",
- "priority",
- "name",
- "validFrom",
- "customerTypeIds",
- "maxQuantity"
+ "minQuantity"
]
},
{
"name": "printJob",
"rows": 0,
"columns": [
- "sourceDocumentId",
- "description",
- "updatedAt",
- "companyId",
"attempts",
- "printerUrl",
- "id",
- "sourceDocumentReadableId",
+ "companyId",
+ "updatedAt",
+ "description",
+ "sourceDocumentId",
"origin",
- "sourceDocument",
- "contentType",
+ "sourceDocumentReadableId",
+ "id",
+ "printerUrl",
+ "completedAt",
"status",
"createdBy",
- "completedAt",
- "updatedBy",
- "createdAt",
+ "contentType",
+ "sourceDocument",
+ "content",
"error",
- "content"
+ "createdAt",
+ "updatedBy"
]
},
{
"name": "printerRoute",
"rows": 0,
"columns": [
+ "name",
+ "locationId",
+ "printerUrl",
+ "format",
+ "companyId",
"updatedAt",
"apiKey",
- "companyId",
- "mediaSizeId",
"templateId",
- "createdAt",
"id",
- "printerUrl",
- "locationId",
- "name",
- "format"
+ "createdAt",
+ "mediaSizeId"
]
},
{
"name": "process",
"rows": 0,
"columns": [
- "createdBy",
- "tags",
- "id",
- "updatedAt",
- "processType",
- "updatedBy",
- "name",
"active",
+ "name",
"batchType",
- "batchRules",
- "batchable",
- "completeAllOnScan",
- "customFields",
- "createdAt",
- "companyId",
- "requiresAbility",
- "defaultStandardFactor"
- ]
- },
+ "processType",
+ "updatedBy",
+ "tags",
+ "updatedAt",
+ "id",
+ "createdBy",
+ "defaultStandardFactor",
+ "requiresAbility",
+ "companyId",
+ "createdAt",
+ "customFields",
+ "completeAllOnScan",
+ "batchable",
+ "batchRules"
+ ]
+ },
{
"name": "ability",
"rows": 0,
"columns": [
- "processId",
- "id",
- "updatedAt",
- "companyId",
- "updatedBy",
- "createdBy",
"active",
"recertifyEveryDays",
- "shadowWeeks",
+ "createdAt",
"curve",
- "createdAt"
+ "shadowWeeks",
+ "companyId",
+ "updatedAt",
+ "id",
+ "processId",
+ "createdBy",
+ "updatedBy"
]
},
{
"name": "employeeAbility",
"rows": 0,
"columns": [
- "expiresAt",
- "id",
"companyId",
"employeeId",
- "lastTrainingDate",
- "abilityId"
+ "id",
+ "expiresAt",
+ "abilityId",
+ "lastTrainingDate"
]
},
{
"name": "procedure",
"rows": 0,
"columns": [
- "id",
- "companyId",
- "createdBy",
- "status",
- "name",
- "updatedBy",
- "assignee",
- "createdAt",
- "updatedAt",
- "version",
- "description",
"processId",
"tags",
- "content"
+ "description",
+ "content",
+ "version",
+ "updatedAt",
+ "updatedBy",
+ "name",
+ "createdAt",
+ "assignee",
+ "createdBy",
+ "companyId",
+ "id",
+ "status"
]
},
{
"name": "procedureParameter",
"rows": 0,
"columns": [
+ "createdAt",
"id",
"updatedBy",
- "createdAt",
- "procedureId",
"updatedAt",
+ "procedureId",
"companyId",
+ "createdBy",
"value",
- "key",
- "createdBy"
+ "key"
]
},
{
"name": "project",
"rows": 0,
"columns": [
- "updatedBy",
- "companyId",
- "createdBy",
- "updatedAt",
- "id",
- "createdAt",
- "name",
+ "active",
"description",
- "active"
+ "name",
+ "createdAt",
+ "id",
+ "updatedAt",
+ "createdBy",
+ "companyId",
+ "updatedBy"
]
},
{
"name": "purchasingRfq",
"rows": 0,
"columns": [
- "notes",
- "id",
- "assignee",
- "rfqDate",
- "updatedAt",
- "customFields",
- "rfqId",
- "internalNotes",
- "locationId",
- "employeeId",
- "companyId",
"createdBy",
"updatedBy",
+ "employeeId",
+ "companyId",
+ "expirationDate",
+ "status",
"revisionId",
"createdAt",
- "status",
- "expirationDate"
+ "rfqDate",
+ "assignee",
+ "id",
+ "notes",
+ "locationId",
+ "internalNotes",
+ "customFields",
+ "rfqId",
+ "updatedAt"
]
},
{
"name": "purchasingRfqFavorite",
"rows": 0,
- "columns": ["rfqId", "userId"]
+ "columns": ["userId", "rfqId"]
},
{
"name": "qualityDocument",
"rows": 0,
"columns": [
- "updatedBy",
"status",
- "description",
- "version",
+ "updatedBy",
"assignee",
- "createdAt",
- "id",
- "updatedAt",
+ "version",
+ "description",
"content",
- "name",
- "tags",
+ "updatedAt",
+ "id",
+ "createdAt",
+ "createdBy",
"companyId",
- "createdBy"
+ "tags",
+ "name"
]
},
{
"name": "reportPin",
"rows": 0,
"columns": [
- "updatedBy",
- "pinned",
"companyId",
+ "pinned",
+ "updatedBy",
"createdBy",
- "updatedAt",
"userId",
- "createdAt",
- "reportKey"
+ "updatedAt",
+ "reportKey",
+ "createdAt"
]
},
{
"name": "reportView",
"rows": 0,
"columns": [
- "visibility",
"id",
"updatedBy",
- "createdAt",
- "updatedAt",
+ "visibility",
"companyId",
+ "updatedAt",
+ "createdAt",
"config",
- "createdBy",
"name",
- "reportKey"
+ "reportKey",
+ "createdBy"
]
},
{
"name": "returnReason",
"rows": 0,
"columns": [
- "inventoryValueZero",
- "companyId",
- "updatedBy",
- "createdBy",
- "name",
- "updatedAt",
+ "createdAt",
"customFields",
"id",
- "createdAt"
+ "updatedAt",
+ "name",
+ "createdBy",
+ "updatedBy",
+ "inventoryValueZero",
+ "companyId"
]
},
{
"name": "scrapReason",
"rows": 0,
"columns": [
- "createdBy",
+ "updatedAt",
"companyId",
"createdAt",
- "updatedAt",
- "id",
- "updatedBy",
+ "createdBy",
+ "customFields",
"name",
- "customFields"
+ "updatedBy",
+ "id"
]
},
{
"name": "searchIndexRegistry",
"rows": 0,
- "columns": ["companyId", "createdAt", "lastRebuiltAt"]
+ "columns": ["lastRebuiltAt", "createdAt", "companyId"]
},
{
"name": "sequence",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "next",
- "table",
- "step",
- "updatedAt",
"suffix",
- "prefix",
+ "size",
"name",
- "size"
+ "prefix",
+ "next",
+ "updatedBy",
+ "companyId",
+ "updatedAt",
+ "step",
+ "table"
]
},
{
"name": "service",
"rows": 0,
"columns": [
+ "approvedBy",
+ "createdAt",
+ "tags",
"serviceType",
"updatedAt",
"approved",
"toDate",
- "approvedBy",
- "createdAt",
- "tags",
- "updatedBy",
- "companyId",
+ "createdBy",
"customFields",
"id",
- "createdBy",
- "fromDate"
+ "fromDate",
+ "updatedBy",
+ "companyId"
]
},
{
"name": "shift",
"rows": 0,
"columns": [
- "sunday",
- "wednesday",
"id",
+ "wednesday",
"friday",
- "tuesday",
- "thursday",
+ "sunday",
"createdAt",
"name",
"active",
- "updatedBy",
- "createdBy",
- "saturday",
+ "tuesday",
+ "thursday",
"tags",
+ "saturday",
"locationId",
- "monday",
+ "updatedBy",
+ "createdBy",
+ "endTime",
"companyId",
"startTime",
- "endTime",
"updatedAt",
- "customFields"
+ "customFields",
+ "monday"
]
},
{
@@ -2151,34 +2151,34 @@
"rows": 0,
"columns": [
"title",
- "shiftId",
- "managerId",
"companyId",
+ "managerId",
+ "shiftId",
+ "startDate",
"departmentId",
- "updatedBy",
"id",
- "startDate",
- "tags",
- "locationId",
+ "updatedBy",
"customFields",
- "updatedAt"
+ "updatedAt",
+ "locationId",
+ "tags"
]
},
{
"name": "employeeShift",
"rows": 0,
- "columns": ["employeeId", "id", "companyId", "shiftId"]
+ "columns": ["shiftId", "companyId", "employeeId", "id"]
},
{
"name": "peopleAbsence",
"rows": 0,
"columns": [
"shiftId",
- "date",
"employeeId",
+ "date",
"createdBy",
- "id",
"updatedBy",
+ "id",
"note",
"companyId",
"createdAt",
@@ -2189,34 +2189,34 @@
"name": "shippingMethod",
"rows": 0,
"columns": [
- "active",
- "id",
- "createdBy",
- "updatedBy",
"createdAt",
"updatedAt",
- "tags",
"name",
- "trackingUrl",
- "customFields",
+ "tags",
+ "active",
+ "createdBy",
+ "id",
+ "updatedBy",
"companyId",
+ "carrier",
"carrierAccountId",
- "carrier"
+ "customFields",
+ "trackingUrl"
]
},
{
"name": "shippingTerm",
"rows": 0,
"columns": [
+ "createdAt",
+ "updatedAt",
+ "companyId",
+ "active",
"createdBy",
"id",
"tags",
"updatedBy",
- "name",
- "createdAt",
- "updatedAt",
- "companyId",
- "active"
+ "name"
]
},
{
@@ -2227,8 +2227,8 @@
"documentType",
"documentId",
"channelId",
- "updatedBy",
"createdBy",
+ "updatedBy",
"companyId",
"threadTs",
"updatedAt",
@@ -2239,83 +2239,83 @@
"name": "ssoConnection",
"rows": 0,
"columns": [
+ "metadataUrl",
+ "providerId",
+ "requireSso",
+ "metadataXml",
+ "companyId",
"createdBy",
"updatedBy",
- "companyId",
- "active",
"id",
"createdAt",
"updatedAt",
- "requireSso",
- "metadataUrl",
- "providerId",
- "metadataXml"
+ "active"
]
},
{
"name": "ssoDomain",
"rows": 0,
"columns": [
- "status",
- "updatedAt",
- "createdAt",
- "id",
- "updatedBy",
- "createdBy",
- "companyId",
- "verificationToken",
"verifiedAt",
+ "domain",
"connectionId",
- "domain"
+ "verificationToken",
+ "createdBy",
+ "updatedBy",
+ "companyId",
+ "status",
+ "id",
+ "createdAt",
+ "updatedAt"
]
},
{
"name": "stockTransfer",
"rows": 0,
"columns": [
- "notes",
- "updatedAt",
- "id",
- "companyId",
- "customFields",
- "stockTransferId",
- "updatedBy",
- "createdBy",
- "completedAt",
- "assignee",
+ "createdAt",
+ "status",
"tags",
"locationId",
- "status",
- "createdAt"
+ "completedAt",
+ "assignee",
+ "updatedBy",
+ "createdBy",
+ "customFields",
+ "stockTransferId",
+ "companyId",
+ "notes",
+ "id",
+ "updatedAt"
]
},
{
"name": "storageType",
"rows": 0,
"columns": [
+ "updatedAt",
"createdBy",
"companyId",
- "updatedAt",
"createdAt",
- "name",
"customFields",
- "id",
- "updatedBy"
+ "name",
+ "updatedBy",
+ "id"
]
},
{
"name": "suggestion",
"rows": 0,
"columns": [
- "createdAt",
- "id",
- "tags",
"suggestion",
"companyId",
- "attachmentPath",
- "emoji",
+ "id",
+ "createdAt",
+ "tags",
"path",
- "userId"
+ "emoji",
+ "userId",
+ "attachmentPath"
]
},
{
@@ -2329,8 +2329,8 @@
"createdBy",
"id",
"customFields",
- "tags",
"updatedAt",
+ "tags",
"name"
]
},
@@ -2338,157 +2338,157 @@
"name": "tableView",
"rows": 0,
"columns": [
+ "sortOrder",
+ "columnVisibility",
+ "id",
+ "sorts",
+ "columnPinning",
+ "filters",
+ "createdAt",
+ "name",
"updatedBy",
"type",
"companyId",
"columnOrder",
"table",
"createdBy",
- "description",
- "sortOrder",
- "sorts",
- "columnVisibility",
- "id",
- "filters",
- "columnPinning",
- "createdAt",
- "name"
+ "description"
]
},
{
"name": "tag",
"rows": 0,
"columns": [
- "table",
- "name",
- "updatedBy",
- "companyId",
+ "createdBy",
"createdAt",
- "createdBy"
+ "companyId",
+ "updatedBy",
+ "name",
+ "table"
]
},
{
"name": "terms",
"rows": 0,
"columns": [
+ "id",
+ "purchasingTerms",
"updatedBy",
- "updatedAt",
"salesTerms",
- "id",
- "purchasingTerms"
+ "updatedAt"
]
},
{
"name": "timeCardEntry",
"rows": 0,
"columns": [
- "clockOut",
- "autoCloseShiftId",
- "clockIn",
- "companyId",
- "note",
- "id",
"createdAt",
+ "id",
"updatedAt",
+ "note",
+ "employeeId",
"createdBy",
"updatedBy",
- "employeeId"
+ "clockOut",
+ "companyId",
+ "clockIn",
+ "autoCloseShiftId"
]
},
{
"name": "tool",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "updatedBy",
- "updatedAt",
- "createdAt",
"customFields",
"tags",
- "createdBy",
"approvedBy",
- "approved"
+ "approved",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "companyId",
+ "createdAt",
+ "updatedAt"
]
},
{
"name": "trackedActivity",
"rows": 0,
"columns": [
- "companyId",
+ "id",
+ "createdBy",
+ "attributes",
+ "type",
+ "createdAt",
+ "updatedBy",
+ "sourceDocumentReadableId",
"sourceDocumentId",
"sourceDocument",
- "sourceDocumentReadableId",
- "updatedBy",
- "createdAt",
- "type",
- "attributes",
- "id",
- "createdBy"
+ "companyId"
]
},
{
"name": "training",
"rows": 0,
"columns": [
- "name",
- "companyId",
- "updatedAt",
- "estimatedDuration",
- "type",
- "tags",
"id",
"content",
+ "tags",
"status",
- "grantsAbilityId",
- "version",
- "description",
- "createdAt",
- "frequency",
+ "updatedAt",
+ "name",
+ "companyId",
+ "type",
+ "estimatedDuration",
"assignee",
"processId",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "version",
+ "createdAt",
+ "description",
+ "grantsAbilityId",
+ "frequency"
]
},
{
"name": "trainingAssignment",
"rows": 0,
"columns": [
- "companyId",
- "groupIds",
- "updatedAt",
- "createdAt",
+ "id",
+ "createdBy",
"trainingId",
"updatedBy",
- "id",
- "createdBy"
+ "createdAt",
+ "groupIds",
+ "companyId",
+ "updatedAt"
]
},
{
"name": "trainingCompletion",
"rows": 0,
"columns": [
+ "employeeId",
+ "companyId",
+ "createdAt",
+ "completedAt",
"trainingAssignmentId",
- "createdBy",
"updatedBy",
- "id",
- "updatedAt",
+ "createdBy",
"period",
- "completedBy",
- "companyId",
- "employeeId",
- "createdAt",
- "completedAt"
+ "updatedAt",
+ "id",
+ "completedBy"
]
},
{
"name": "trainingQuestion",
"rows": 0,
"columns": [
+ "type",
"question",
"createdAt",
- "type",
"options",
"sortOrder",
"tolerance",
@@ -2500,8 +2500,8 @@
"matchingPairs",
"correctAnswers",
"correctNumber",
- "correctBoolean",
"id",
+ "correctBoolean",
"required"
]
},
@@ -2513,11 +2513,11 @@
"customFields",
"updatedBy",
"tags",
- "updatedAt",
"id",
+ "updatedAt",
"createdBy",
- "name",
"active",
+ "name",
"createdAt",
"companyId"
]
@@ -2526,159 +2526,159 @@
"name": "item",
"rows": 0,
"columns": [
- "readableId",
- "companyId",
- "updatedBy",
- "active",
- "trackingMethod",
- "sourcingType",
- "mpn",
- "itemTrackingType",
- "unitOfMeasureCode",
- "id",
- "embedding",
- "replenishmentSystem",
- "assignee",
- "createdBy",
- "name",
- "description",
- "changeOrderId",
- "defaultMethodType",
"notes",
- "revisionStatus",
- "modelUploadId",
- "type",
- "thumbnailPath",
- "updatedAt",
+ "defaultMethodType",
+ "changeOrderId",
+ "description",
+ "name",
+ "createdBy",
+ "assignee",
+ "createdAt",
"revision",
- "createdAt"
+ "updatedAt",
+ "thumbnailPath",
+ "type",
+ "modelUploadId",
+ "revisionStatus",
+ "itemTrackingType",
+ "mpn",
+ "sourcingType",
+ "trackingMethod",
+ "active",
+ "updatedBy",
+ "companyId",
+ "readableId",
+ "replenishmentSystem",
+ "embedding",
+ "id",
+ "unitOfMeasureCode"
]
},
{
"name": "assemblyComponentMapping",
"rows": 0,
"columns": [
- "updatedBy",
+ "confidence",
+ "itemId",
+ "geometryHash",
+ "createdBy",
"id",
+ "updatedBy",
"companyId",
"modelUploadId",
"updatedAt",
- "createdAt",
- "confidence",
- "geometryHash",
- "itemId",
- "createdBy"
+ "createdAt"
]
},
{
"name": "assemblyInstruction",
"rows": 0,
"columns": [
- "status",
- "customFields",
- "settings",
- "id",
"companyId",
"publishedAt",
- "name",
"createdBy",
+ "name",
"updatedAt",
- "rootInstructionId",
- "updatedBy",
- "tags",
- "assemblyPlanJobId",
+ "status",
+ "customFields",
+ "id",
+ "settings",
"version",
+ "itemId",
"modelUploadId",
"createdAt",
- "itemId"
+ "updatedBy",
+ "rootInstructionId",
+ "assemblyPlanJobId",
+ "tags"
]
},
{
"name": "assemblyInstructionStep",
"rows": 0,
"columns": [
- "sortOrder",
- "parentStepId",
- "fileTypes",
- "camera",
- "explode",
- "updatedAt",
- "durationSeconds",
- "description",
- "planConfidence",
- "fastener",
- "rootStepId",
- "maxValue",
- "title",
- "createdAt",
"motion",
- "notes",
+ "createdAt",
"warnings",
- "componentNodeIds",
- "assemblyInstructionId",
- "listValues",
- "instructionText",
- "buildWave",
- "status",
+ "notes",
+ "maxValue",
+ "rootStepId",
+ "fastener",
+ "title",
+ "planConfidence",
+ "updatedAt",
+ "description",
+ "durationSeconds",
+ "camera",
+ "explode",
+ "fileTypes",
+ "parentStepId",
+ "sortOrder",
+ "createdBy",
+ "type",
+ "minValue",
+ "updatedBy",
+ "required",
+ "id",
"unitOfMeasureCode",
"companyId",
- "id",
- "required",
- "updatedBy",
- "minValue",
- "type",
- "createdBy"
+ "status",
+ "buildWave",
+ "instructionText",
+ "assemblyInstructionId",
+ "listValues",
+ "componentNodeIds"
]
},
{
"name": "assemblyInstructionStepMaterial",
"rows": 0,
"columns": [
- "id",
- "updatedBy",
+ "sortOrder",
+ "createdBy",
+ "itemId",
+ "quantity",
"companyId",
- "stepId",
+ "updatedBy",
+ "id",
"createdAt",
"updatedAt",
- "sortOrder",
- "quantity",
- "itemId",
- "createdBy"
+ "stepId"
]
},
{
"name": "assemblyInstructionStepSlide",
"rows": 0,
"columns": [
- "stepId",
"updatedAt",
- "createdBy",
+ "stepId",
"annotations",
- "createdAt",
+ "createdBy",
"id",
"companyId",
+ "createdAt",
"sortOrder",
"modelUploadId",
"imagePath",
"size",
- "updatedBy",
- "caption"
+ "caption",
+ "updatedBy"
]
},
{
"name": "assemblyInstructionStepTool",
"rows": 0,
"columns": [
- "stepId",
+ "createdBy",
+ "itemId",
+ "quantity",
+ "sortOrder",
"createdAt",
"updatedAt",
- "id",
- "updatedBy",
+ "stepId",
"companyId",
- "quantity",
- "itemId",
- "createdBy",
- "sortOrder"
+ "updatedBy",
+ "id"
]
},
{
@@ -2702,35 +2702,35 @@
"name": "batchProperty",
"rows": 0,
"columns": [
- "updatedBy",
- "id",
- "createdBy",
- "sortOrder",
- "itemId",
- "updatedAt",
"createdAt",
- "listOptions",
- "dataType",
+ "updatedAt",
+ "itemId",
+ "sortOrder",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "companyId",
"label",
- "companyId"
+ "dataType",
+ "listOptions"
]
},
{
"name": "changeOrderSupersession",
"rows": 0,
"columns": [
- "changeOrderId",
- "companyId",
"createdBy",
+ "companyId",
+ "changeOrderId",
+ "discontinuationDate",
+ "updatedAt",
"id",
"createdAt",
- "updatedAt",
- "discontinuationDate",
+ "successorEffectivityDate",
"successorItemId",
"predecessorItemId",
- "successorEffectivityDate",
- "updatedBy",
- "supersessionMode"
+ "supersessionMode",
+ "updatedBy"
]
},
{
@@ -2740,8 +2740,8 @@
"itemId",
"id",
"companyId",
- "sortOrder",
"name",
+ "sortOrder",
"isUngrouped"
]
},
@@ -2749,240 +2749,240 @@
"name": "configurationParameter",
"rows": 0,
"columns": [
- "updatedAt",
- "dataType",
"label",
"materialFormFilterId",
"key",
"configurationParameterGroupId",
- "createdBy",
- "companyId",
- "id",
- "listOptions",
+ "updatedAt",
+ "dataType",
"itemId",
"updatedBy",
+ "sortOrder",
"createdAt",
- "sortOrder"
+ "companyId",
+ "id",
+ "createdBy",
+ "listOptions"
]
},
{
"name": "configurationRule",
"rows": 0,
"columns": [
- "field",
"updatedBy",
"itemId",
+ "field",
+ "updatedAt",
"companyId",
- "code",
- "updatedAt"
+ "code"
]
},
{
"name": "demandForecast",
"rows": 0,
"columns": [
- "updatedBy",
- "forecastMethod",
- "periodId",
- "forecastQuantity",
- "notes",
+ "confidence",
"createdBy",
"itemId",
"updatedAt",
- "confidence",
- "locationId",
"companyId",
- "createdAt"
+ "createdAt",
+ "locationId",
+ "updatedBy",
+ "forecastMethod",
+ "notes",
+ "periodId",
+ "forecastQuantity"
]
},
{
"name": "demandProjection",
"rows": 0,
"columns": [
- "confidence",
- "itemId",
- "createdBy",
- "updatedAt",
+ "notes",
+ "forecastQuantity",
+ "periodId",
+ "forecastMethod",
+ "updatedBy",
"companyId",
"createdAt",
"id",
"locationId",
- "forecastMethod",
- "updatedBy",
- "notes",
- "forecastQuantity",
- "periodId"
+ "confidence",
+ "itemId",
+ "createdBy",
+ "updatedAt"
]
},
{
"name": "enforcementRuleItemAssignment",
"rows": 0,
"columns": [
- "createdAt",
"createdBy",
"companyId",
- "itemId",
+ "createdAt",
+ "ruleId",
"updatedBy",
- "ruleId"
+ "itemId"
]
},
{
"name": "inspectionDocument",
"rows": 0,
"columns": [
- "drawingNumber",
- "updatedBy",
- "partId",
- "samplingPercentage",
- "samplingAql",
- "fileName",
- "samplingInspectionLevel",
- "createdBy",
- "version",
"samplingSampleSize",
- "updatedAt",
"samplingSeverity",
- "samplingPlanType",
+ "updatedAt",
+ "createdBy",
+ "samplingInspectionLevel",
+ "version",
+ "fileName",
+ "samplingPercentage",
+ "samplingAql",
+ "updatedBy",
+ "partId",
+ "drawingNumber",
+ "storagePath",
+ "uploadedBy",
+ "defaultPageWidth",
+ "id",
+ "defaultPageHeight",
+ "pageCount",
"companyId",
"createdAt",
- "pageCount",
- "defaultPageHeight",
- "id",
- "defaultPageWidth",
- "uploadedBy",
- "storagePath"
+ "samplingPlanType"
]
},
{
"name": "inspectionFeature",
"rows": 0,
"columns": [
- "description",
- "toleranceMinus",
- "id",
- "createdBy",
- "tolerancePlus",
- "unit",
- "samplingPlanType",
- "updatedBy",
- "inspectionDocumentId",
"type",
"samplingSeverity",
"samplingSampleSize",
"label",
- "createdAt",
"samplingInspectionLevel",
+ "createdAt",
"nominalValue",
+ "samplingAql",
+ "samplingPercentage",
+ "pageNumber",
"updatedAt",
"companyId",
- "pageNumber",
- "samplingAql",
- "samplingPercentage"
+ "description",
+ "createdBy",
+ "id",
+ "toleranceMinus",
+ "unit",
+ "tolerancePlus",
+ "updatedBy",
+ "inspectionDocumentId",
+ "samplingPlanType"
]
},
{
"name": "balloon",
"rows": 0,
"columns": [
- "regionY",
- "companyId",
- "updatedBy",
- "inspectionFeatureId",
- "updatedAt",
- "createdBy",
- "pageNumber",
+ "regionX",
+ "regionHeight",
+ "id",
+ "yCoordinate",
"regionWidth",
"xCoordinate",
"inspectionDocumentId",
"createdAt",
- "regionX",
- "regionHeight",
- "id",
- "yCoordinate"
+ "updatedAt",
+ "createdBy",
+ "pageNumber",
+ "regionY",
+ "updatedBy",
+ "companyId",
+ "inspectionFeatureId"
]
},
{
"name": "inventoryCountLine",
"rows": 0,
"columns": [
- "storageUnitId",
- "systemQuantity",
"id",
- "countedQuantity",
- "readableId",
- "countedAt",
- "companyId",
+ "systemQuantity",
+ "storageUnitId",
"createdAt",
- "createdBy",
- "updatedBy",
- "locationId",
+ "companyId",
+ "countedAt",
+ "readableId",
+ "countedQuantity",
"countedBy",
- "trackedEntityId",
- "customFields",
- "updatedAt",
+ "locationId",
+ "updatedBy",
+ "createdBy",
+ "itemId",
"inventoryCountId",
"postedItemLedgerId",
- "itemId"
+ "updatedAt",
+ "customFields",
+ "trackedEntityId"
]
},
{
"name": "itemCost",
"rows": 0,
"columns": [
- "companyId",
- "standardCost",
- "costingMethod",
- "customFields",
- "unitCost",
+ "costIsAdjusted",
+ "updatedAt",
+ "itemId",
+ "createdAt",
"updatedBy",
"createdBy",
"itemPostingGroupId",
"tags",
- "costIsAdjusted",
- "updatedAt",
- "itemId",
- "createdAt"
+ "customFields",
+ "unitCost",
+ "companyId",
+ "standardCost",
+ "costingMethod"
]
},
{
"name": "itemInspectionDocumentAssignment",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
"inspectionDocumentId",
"companyId",
- "createdAt",
- "itemId",
+ "updatedBy",
+ "createdBy",
+ "usage",
"updatedAt",
- "usage"
+ "itemId",
+ "createdAt"
]
},
{
"name": "itemPlanning",
"rows": 0,
"columns": [
- "tags",
- "updatedAt",
- "customFields",
- "orderMultiple",
- "createdBy",
+ "companyId",
+ "locationId",
+ "minimumOrderQuantity",
+ "reorderPoint",
+ "demandAccumulationSafetyStock",
+ "demandAccumulationIncludesInventory",
+ "itemId",
+ "reorderQuantity",
+ "minimumReserveQuantity",
"maximumOrderQuantity",
"reorderingPolicy",
"critical",
- "updatedBy",
"createdAt",
+ "updatedBy",
"demandAccumulationPeriod",
"maximumInventoryQuantity",
- "demandAccumulationIncludesInventory",
- "itemId",
- "reorderQuantity",
- "minimumReserveQuantity",
- "companyId",
- "minimumOrderQuantity",
- "locationId",
- "demandAccumulationSafetyStock",
- "reorderPoint"
+ "tags",
+ "updatedAt",
+ "createdBy",
+ "orderMultiple",
+ "customFields"
]
},
{
@@ -2991,104 +2991,95 @@
"columns": [
"updatedAt",
"suffix",
+ "size",
"itemId",
"prefix",
- "size",
+ "next",
+ "updatedBy",
"createdBy",
"id",
- "updatedBy",
- "next",
- "companyId",
+ "createdAt",
"step",
- "createdAt"
+ "companyId"
]
},
{
"name": "itemShelfLife",
"rows": 0,
"columns": [
- "createdBy",
- "triggerProcessId",
- "days",
- "calculateFromBom",
"triggerTiming",
- "updatedAt",
- "createdAt",
- "mode",
- "companyId",
- "customFields",
+ "calculateFromBom",
+ "days",
+ "triggerProcessId",
+ "createdBy",
+ "updatedBy",
"itemId",
- "updatedBy"
+ "customFields",
+ "companyId",
+ "mode",
+ "createdAt",
+ "updatedAt"
]
},
{
"name": "itemSupersession",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "createdBy",
- "updatedAt",
+ "successorEffectivityDate",
"createdAt",
"itemId",
- "successorEffectivityDate",
- "supersessionMode",
- "successorItemId",
+ "updatedAt",
+ "createdBy",
+ "updatedBy",
+ "companyId",
+ "discontinuationDate",
"conversionFactor",
- "discontinuationDate"
+ "supersessionMode",
+ "successorItemId"
]
},
{
"name": "itemUnitSalePrice",
"rows": 0,
"columns": [
- "customFields",
- "unitSalePrice",
- "companyId",
- "createdAt",
- "itemId",
- "createdBy",
- "updatedBy",
- "priceIncludesTax",
- "salesUnitOfMeasureCode",
+ "allowInvoiceDiscount",
"tags",
"currencyCode",
- "allowInvoiceDiscount",
+ "salesUnitOfMeasureCode",
"salesBlocked",
- "updatedAt"
+ "updatedAt",
+ "companyId",
+ "createdAt",
+ "customFields",
+ "unitSalePrice",
+ "priceIncludesTax",
+ "createdBy",
+ "itemId",
+ "updatedBy"
]
},
{
"name": "makeMethod",
"rows": 0,
"columns": [
- "changeOrderId",
- "createdBy",
- "companyId",
- "createdAt",
"updatedBy",
- "tags",
- "id",
- "status",
- "updatedAt",
- "itemId",
+ "createdAt",
+ "companyId",
+ "createdBy",
+ "changeOrderId",
"customFields",
- "version"
+ "version",
+ "itemId",
+ "updatedAt",
+ "id",
+ "tags",
+ "status"
]
},
{
"name": "changeOrderAffectedItem",
"rows": 0,
"columns": [
- "updatedAt",
- "changeOrderId",
- "companyId",
- "supersessionMode",
- "successorEffectivityDate",
- "discontinuationDate",
- "id",
- "newItemId",
- "draftMakeMethodId",
"itemId",
"createdAt",
"sortOrder",
@@ -3096,151 +3087,160 @@
"changeSummary",
"changeType",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "changeOrderId",
+ "companyId",
+ "updatedAt",
+ "successorEffectivityDate",
+ "supersessionMode",
+ "newItemId",
+ "discontinuationDate",
+ "id",
+ "draftMakeMethodId"
]
},
{
"name": "nonConformanceItem",
"rows": 0,
"columns": [
- "createdAt",
+ "updatedAt",
"companyId",
"itemId",
- "updatedAt",
- "id",
- "disposition",
- "createdBy",
- "nonConformanceId",
+ "createdAt",
+ "updatedBy",
"quantity",
- "updatedBy"
+ "nonConformanceId",
+ "createdBy",
+ "id",
+ "disposition"
]
},
{
"name": "procedureStep",
"rows": 0,
"columns": [
- "fileTypes",
- "required",
- "updatedBy",
- "createdBy",
- "createdAt",
- "name",
- "description",
- "type",
+ "maxValue",
+ "unitOfMeasureCode",
+ "companyId",
+ "procedureId",
+ "updatedAt",
+ "sortOrder",
+ "listValues",
"minValue",
"id",
- "listValues",
- "sortOrder",
- "updatedAt",
- "procedureId",
- "companyId",
- "unitOfMeasureCode",
- "maxValue"
+ "type",
+ "description",
+ "name",
+ "createdAt",
+ "createdBy",
+ "updatedBy",
+ "required",
+ "fileTypes"
]
},
{
"name": "purchasingRfqLine",
"rows": 0,
"columns": [
+ "order",
+ "id",
+ "externalNotes",
+ "purchaseUnitOfMeasureCode",
"updatedAt",
"purchasingRfqId",
"customFields",
"conversionFactor",
"internalNotes",
- "id",
- "order",
- "externalNotes",
- "purchaseUnitOfMeasureCode",
- "description",
- "createdAt",
- "itemId",
- "inventoryUnitOfMeasureCode",
"companyId",
"quantity",
"updatedBy",
- "createdBy"
+ "createdBy",
+ "createdAt",
+ "itemId",
+ "description",
+ "inventoryUnitOfMeasureCode"
]
},
{
"name": "qualityDocumentStep",
"rows": 0,
"columns": [
- "fileTypes",
- "required",
- "updatedBy",
- "createdBy",
+ "type",
"description",
"createdAt",
"name",
- "type",
- "listValues",
- "id",
- "minValue",
- "sortOrder",
+ "updatedBy",
+ "createdBy",
+ "fileTypes",
+ "required",
+ "unitOfMeasureCode",
+ "maxValue",
+ "updatedAt",
"qualityDocumentId",
"companyId",
- "updatedAt",
- "maxValue",
- "unitOfMeasureCode"
+ "sortOrder",
+ "id",
+ "minValue",
+ "listValues"
]
},
{
"name": "riskRegister",
"rows": 0,
"columns": [
- "description",
- "updatedAt",
- "title",
- "severity",
- "createdBy",
- "source",
- "updatedBy",
- "notes",
- "companyId",
"createdAt",
+ "companyId",
"type",
"status",
"likelihood",
"assignee",
"id",
"itemId",
- "sourceId"
+ "sourceId",
+ "description",
+ "updatedAt",
+ "title",
+ "severity",
+ "source",
+ "createdBy",
+ "notes",
+ "updatedBy"
]
},
{
"name": "trackedEntity",
"rows": 0,
"columns": [
- "status",
+ "attributes",
"updatedBy",
+ "status",
"sourceDocument",
- "attributes",
"itemId",
"sourceDocumentId",
- "quantity",
- "expirationDate",
"createdBy",
"companyId",
+ "quantity",
+ "expirationDate",
+ "sourceDocumentReadableId",
"readableId",
"createdAt",
- "id",
- "sourceDocumentReadableId"
+ "id"
]
},
{
"name": "nonConformanceItemTrackedEntity",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "nonConformanceItemId",
"companyId",
- "id",
"updatedAt",
+ "id",
+ "updatedBy",
+ "createdBy",
+ "nonConformanceItemId",
+ "quantity",
"createdAt",
- "trackedEntityId",
"nonConformanceId",
- "quantity"
+ "trackedEntityId"
]
},
{
@@ -3252,8 +3252,8 @@
"createdBy",
"id",
"updatedAt",
- "trackedEntityId",
"companyId",
+ "trackedEntityId",
"createdAt"
]
},
@@ -3261,200 +3261,200 @@
"name": "trackedActivityInput",
"rows": 0,
"columns": [
- "updatedBy",
- "trackedEntityId",
- "createdAt",
- "trackedActivityId",
- "createdBy",
+ "companyId",
"quantity",
- "companyId"
+ "createdBy",
+ "trackedActivityId",
+ "createdAt",
+ "trackedEntityId",
+ "updatedBy"
]
},
{
"name": "trackedActivityOutput",
"rows": 0,
"columns": [
- "createdAt",
- "quantity",
- "companyId",
- "updatedBy",
- "trackedActivityId",
+ "trackedEntityId",
"createdBy",
- "trackedEntityId"
+ "trackedActivityId",
+ "updatedBy",
+ "companyId",
+ "quantity",
+ "createdAt"
]
},
{
"name": "userAttributeCategory",
"rows": 0,
"columns": [
- "name",
- "updatedBy",
- "createdBy",
- "emoji",
- "updatedAt",
- "id",
- "active",
+ "companyId",
"public",
"protected",
"createdAt",
- "companyId"
+ "updatedAt",
+ "id",
+ "emoji",
+ "active",
+ "name",
+ "createdBy",
+ "updatedBy"
]
},
{
"name": "userAttribute",
"rows": 0,
"columns": [
- "id",
- "createdAt",
- "updatedAt",
- "listOptions",
- "name",
- "active",
- "createdBy",
"updatedBy",
"attributeDataTypeId",
- "userAttributeCategoryId",
+ "canSelfManage",
"sortOrder",
- "canSelfManage"
+ "userAttributeCategoryId",
+ "listOptions",
+ "updatedAt",
+ "createdAt",
+ "id",
+ "createdBy",
+ "active",
+ "name"
]
},
{
"name": "userAttributeValue",
"rows": 0,
"columns": [
- "updatedBy",
- "valueDate",
- "valueText",
- "userId",
"valueBoolean",
- "valueNumeric",
- "createdAt",
- "id",
- "updatedAt",
+ "userId",
+ "valueText",
+ "valueDate",
+ "updatedBy",
+ "valueFile",
+ "userAttributeId",
"valueUser",
"createdBy",
- "userAttributeId",
- "valueFile"
+ "id",
+ "createdAt",
+ "updatedAt",
+ "valueNumeric"
]
},
{
"name": "userModulePreference",
"rows": 0,
"columns": [
- "companyId",
- "module",
- "updatedAt",
- "position",
- "userId",
"id",
- "hidden"
+ "hidden",
+ "userId",
+ "position",
+ "module",
+ "companyId",
+ "updatedAt"
]
},
{
"name": "userToCompany",
"rows": 0,
- "columns": ["role", "userId", "companyId"]
+ "columns": ["userId", "companyId", "role"]
},
{
"name": "warehouse",
"rows": 0,
"columns": [
- "requiresPutAway",
- "createdAt",
- "updatedAt",
- "locationId",
- "requiresPick",
- "requiresReceive",
- "active",
- "id",
"createdBy",
+ "id",
+ "active",
"requiresBin",
"updatedBy",
"name",
+ "companyId",
"requiresShipment",
- "companyId"
+ "requiresPutAway",
+ "createdAt",
+ "requiresPick",
+ "updatedAt",
+ "locationId",
+ "requiresReceive"
]
},
{
"name": "warehouseTransfer",
"rows": 0,
"columns": [
- "tags",
- "transferId",
- "updatedBy",
- "notes",
- "companyId",
+ "transferDate",
+ "createdBy",
"id",
"reference",
- "createdBy",
- "transferDate",
+ "companyId",
+ "notes",
+ "updatedBy",
+ "transferId",
+ "tags",
+ "customFields",
+ "status",
+ "createdAt",
+ "expectedReceiptDate",
"toLocationId",
"fromLocationId",
- "updatedAt",
- "expectedReceiptDate",
- "createdAt",
- "status",
- "customFields"
+ "updatedAt"
]
},
{
"name": "workCenter",
"rows": 0,
"columns": [
+ "companyId",
"requiredAbilityId",
"id",
- "companyId",
- "locationId",
"active",
- "updatedAt",
- "name",
+ "locationId",
"createdBy",
- "machineRate",
- "updatedBy",
+ "name",
+ "updatedAt",
"alwaysOn",
- "batchCapacity",
+ "updatedBy",
+ "machineRate",
+ "laborRate",
"customFields",
"departmentId",
- "laborRate",
+ "batchCapacity",
"defaultStandardFactor",
"minimumBatchQuantity",
- "createdAt",
- "description",
+ "tags",
"overheadRate",
- "tags"
+ "description",
+ "createdAt"
]
},
{
"name": "enforcementRuleWorkCenterAssignment",
"rows": 0,
"columns": [
- "createdAt",
"createdBy",
"companyId",
- "workCenterId",
+ "createdAt",
+ "ruleId",
"updatedBy",
- "ruleId"
+ "workCenterId"
]
},
{
"name": "jobOperationBatch",
"rows": 0,
"columns": [
- "status",
- "processId",
- "companyId",
- "mergeOutput",
- "outputLotNumber",
- "workCenterId",
- "updatedBy",
- "notes",
- "createdBy",
"updatedAt",
"readableId",
- "locationId",
+ "createdBy",
+ "notes",
+ "createdAt",
"id",
"customFields",
- "createdAt"
+ "locationId",
+ "processId",
+ "mergeOutput",
+ "companyId",
+ "status",
+ "workCenterId",
+ "updatedBy",
+ "outputLotNumber"
]
},
{
@@ -3472,8 +3472,8 @@
"frequency",
"createdBy",
"friday",
- "updatedAt",
"saturday",
+ "updatedAt",
"tuesday",
"takesWorkCenterOffline",
"monday",
@@ -3493,33 +3493,33 @@
"name": "maintenanceDispatch",
"rows": 0,
"columns": [
- "actualEndTime",
- "createdBy",
- "nonConformanceId",
- "createdAt",
+ "assignee",
+ "completedAt",
+ "status",
+ "content",
+ "actualStartTime",
+ "updatedBy",
+ "locationId",
"priority",
"companyId",
"plannedStartTime",
- "updatedBy",
- "locationId",
- "status",
- "actualStartTime",
- "content",
- "assignee",
- "completedAt",
- "source",
- "oeeImpact",
- "id",
- "maintenanceScheduleId",
- "severity",
- "actualFailureModeId",
- "takesWorkCenterOffline",
- "workCenterId",
- "procedureId",
+ "createdAt",
+ "actualEndTime",
+ "createdBy",
+ "nonConformanceId",
+ "plannedEndTime",
+ "maintenanceDispatchId",
"updatedAt",
"suspectedFailureModeId",
- "plannedEndTime",
- "maintenanceDispatchId"
+ "workCenterId",
+ "takesWorkCenterOffline",
+ "procedureId",
+ "severity",
+ "actualFailureModeId",
+ "id",
+ "maintenanceScheduleId",
+ "oeeImpact",
+ "source"
]
},
{
@@ -3527,8 +3527,8 @@
"rows": 0,
"columns": [
"updatedBy",
- "companyId",
"comment",
+ "companyId",
"createdBy",
"updatedAt",
"maintenanceDispatchId",
@@ -3540,35 +3540,35 @@
"name": "maintenanceDispatchEvent",
"rows": 0,
"columns": [
- "maintenanceDispatchId",
- "updatedAt",
"createdBy",
+ "updatedAt",
+ "maintenanceDispatchId",
+ "endTime",
"createdAt",
"companyId",
"id",
- "endTime",
+ "notes",
"employeeId",
"workCenterId",
- "notes",
- "updatedBy",
- "startTime"
+ "startTime",
+ "updatedBy"
]
},
{
"name": "maintenanceDispatchItem",
"rows": 0,
"columns": [
- "itemId",
- "quantity",
- "unitOfMeasureCode",
- "updatedAt",
- "createdAt",
- "companyId",
- "maintenanceDispatchId",
- "unitCost",
"updatedBy",
+ "id",
"createdBy",
- "id"
+ "unitCost",
+ "maintenanceDispatchId",
+ "createdAt",
+ "companyId",
+ "updatedAt",
+ "unitOfMeasureCode",
+ "quantity",
+ "itemId"
]
},
{
@@ -3576,86 +3576,86 @@
"rows": 0,
"columns": [
"companyId",
- "createdAt",
- "quantity",
"trackedEntityId",
- "createdBy",
- "id",
+ "quantity",
+ "createdAt",
"updatedAt",
- "updatedBy",
- "maintenanceDispatchItemId"
+ "id",
+ "createdBy",
+ "maintenanceDispatchItemId",
+ "updatedBy"
]
},
{
"name": "maintenanceDispatchWorkCenter",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
"companyId",
"workCenterId",
- "createdAt",
- "id",
+ "updatedBy",
+ "createdBy",
+ "maintenanceDispatchId",
"updatedAt",
- "maintenanceDispatchId"
+ "id",
+ "createdAt"
]
},
{
"name": "maintenanceScheduleItem",
"rows": 0,
"columns": [
- "quantity",
- "itemId",
- "createdBy",
- "unitOfMeasureCode",
"maintenanceScheduleId",
- "updatedAt",
"createdAt",
- "id",
+ "updatedAt",
"updatedBy",
- "companyId"
+ "id",
+ "companyId",
+ "itemId",
+ "quantity",
+ "createdBy",
+ "unitOfMeasureCode"
]
},
{
"name": "peopleAssignment",
"rows": 0,
"columns": [
- "employeeId",
- "updatedAt",
"shiftId",
"workCenterId",
"hours",
"locationId",
+ "updatedAt",
+ "employeeId",
+ "note",
+ "createdAt",
+ "companyId",
+ "overtimeHours",
"date",
- "updatedBy",
"id",
"createdBy",
- "createdAt",
- "note",
- "overtimeHours",
- "companyId"
+ "updatedBy"
]
},
{
"name": "storageUnit",
"rows": 0,
"columns": [
- "createdBy",
- "name",
- "id",
- "updatedAt",
- "customFields",
- "updatedBy",
- "locationId",
- "parentId",
- "isWorkCenterDefault",
- "workCenterId",
- "tags",
- "companyId",
"createdAt",
- "active",
"warehouseId",
- "storageTypeIds"
+ "storageTypeIds",
+ "active",
+ "workCenterId",
+ "companyId",
+ "tags",
+ "updatedBy",
+ "customFields",
+ "isWorkCenterDefault",
+ "parentId",
+ "locationId",
+ "createdBy",
+ "updatedAt",
+ "id",
+ "name"
]
},
{
@@ -3663,26 +3663,26 @@
"rows": 0,
"columns": [
"documentId",
- "storageUnitId",
"id",
- "locationId",
- "scrapReasonId",
+ "storageUnitId",
"itemId",
- "entryNumber",
- "companyId",
+ "scrapReasonId",
+ "locationId",
"documentLineId",
+ "companyId",
+ "entryNumber",
"createdBy",
"trackedEntityStatus",
+ "updatedBy",
+ "documentType",
"comment",
"quantity",
- "documentType",
- "updatedBy",
"correctionOfItemLedgerId",
"externalDocumentId",
- "trackedEntityId",
"entryType",
"createdAt",
- "postingDate"
+ "postingDate",
+ "trackedEntityId"
]
},
{
@@ -3692,11 +3692,11 @@
"locationId",
"updatedAt",
"sortMethod",
- "itemId",
"customFields",
+ "itemId",
"createdAt",
- "companyId",
"defaultStorageUnitId",
+ "companyId",
"updatedBy",
"createdBy"
]
@@ -3705,121 +3705,121 @@
"name": "warehouseTransferLine",
"rows": 0,
"columns": [
- "toStorageUnitId",
- "fromStorageUnitId",
- "companyId",
- "transferId",
- "updatedBy",
- "receivedQuantity",
- "unitOfMeasureCode",
- "id",
- "toLocationId",
- "fromLocationId",
- "customFields",
"quantity",
- "createdBy",
"itemId",
- "createdAt",
- "updatedAt",
+ "createdBy",
+ "customFields",
+ "fromLocationId",
+ "notes",
"shippedQuantity",
- "notes"
+ "updatedAt",
+ "createdAt",
+ "updatedBy",
+ "transferId",
+ "companyId",
+ "fromStorageUnitId",
+ "toStorageUnitId",
+ "id",
+ "toLocationId",
+ "unitOfMeasureCode",
+ "receivedQuantity"
]
},
{
"name": "workCenterProcess",
"rows": 0,
"columns": [
+ "workCenterId",
+ "updatedBy",
+ "processId",
"createdAt",
- "updatedAt",
"companyId",
"createdBy",
- "updatedBy",
- "workCenterId",
- "processId"
+ "updatedAt"
]
},
{
"name": "workCenterReplacementPart",
"rows": 0,
"columns": [
- "createdBy",
+ "unitOfMeasureCode",
"itemId",
"quantity",
- "unitOfMeasureCode",
- "updatedAt",
- "createdAt",
- "workCenterId",
- "companyId",
+ "createdBy",
"updatedBy",
- "id"
- ]
- },
- {
- "name": "workCenterShift",
- "rows": 0,
- "columns": [
- "updatedAt",
- "companyId",
- "createdAt",
"id",
- "updatedBy",
+ "companyId",
"workCenterId",
- "shiftId",
- "createdBy"
+ "createdAt",
+ "updatedAt"
]
},
{
- "name": "cardTransaction",
+ "name": "workCenterShift",
"rows": 0,
"columns": [
- "supplierId",
+ "createdBy",
+ "shiftId",
+ "workCenterId",
+ "updatedBy",
"id",
- "cardHolderName",
- "updatedAt",
- "integration",
"createdAt",
- "currencyCode",
- "memo",
"companyId",
- "offsetAccountId",
- "createdBy",
- "merchantName",
- "voidedAt",
- "status",
- "cardLast4",
- "postedAt",
- "postingDate",
- "postedBy",
- "exchangeRate",
- "updatedBy",
- "transactionDate",
- "cardTransactionId",
- "type",
- "journalId",
- "amount",
- "cardAccountId",
- "voidedBy",
- "customFields"
+ "updatedAt"
]
},
{
- "name": "cardTransactionLine",
+ "name": "cardTransaction",
"rows": 0,
"columns": [
- "createdBy",
- "id",
- "updatedBy",
- "description",
- "customFields",
- "companyId",
- "sequence",
"createdAt",
- "costCenterId",
+ "integration",
"updatedAt",
- "cardTransactionId",
- "projectId",
- "accountId",
- "amount"
+ "cardHolderName",
+ "id",
+ "supplierId",
+ "merchantName",
+ "createdBy",
+ "offsetAccountId",
+ "companyId",
+ "memo",
+ "currencyCode",
+ "updatedBy",
+ "exchangeRate",
+ "postedBy",
+ "postingDate",
+ "postedAt",
+ "cardLast4",
+ "status",
+ "voidedAt",
+ "customFields",
+ "voidedBy",
+ "cardAccountId",
+ "amount",
+ "journalId",
+ "type",
+ "cardTransactionId",
+ "transactionDate"
+ ]
+ },
+ {
+ "name": "cardTransactionLine",
+ "rows": 0,
+ "columns": [
+ "createdBy",
+ "id",
+ "updatedBy",
+ "description",
+ "customFields",
+ "companyId",
+ "sequence",
+ "createdAt",
+ "costCenterId",
+ "updatedAt",
+ "projectId",
+ "cardTransactionId",
+ "accountId",
+ "amount"
]
},
{
@@ -3830,8 +3830,8 @@
"id",
"createdAt",
"hoursPerWeek",
- "tags",
"updatedAt",
+ "tags",
"createdBy",
"active",
"companyId",
@@ -3843,8 +3843,8 @@
"rows": 0,
"columns": [
"companyId",
- "createdAt",
"createdBy",
+ "createdAt",
"contractorId",
"updatedBy",
"abilityId"
@@ -3854,135 +3854,135 @@
"name": "costLedger",
"rows": 0,
"columns": [
- "remainingQuantity",
- "appliesToCostLedgerId",
+ "companyId",
+ "supplierId",
+ "costLedgerType",
+ "quantity",
+ "documentType",
"postingDate",
"nominalCost",
"itemLedgerType",
- "documentType",
- "quantity",
- "costLedgerType",
- "supplierId",
- "companyId",
- "entryNumber",
- "cost",
- "createdAt",
- "itemId",
- "documentId",
+ "appliesToCostLedgerId",
+ "remainingQuantity",
+ "adjustment",
"externalDocumentId",
"id",
- "adjustment"
+ "documentId",
+ "itemId",
+ "createdAt",
+ "cost",
+ "entryNumber"
]
},
{
"name": "customer",
"rows": 0,
"columns": [
- "fax",
- "currencyCode",
- "tags",
- "updatedAt",
- "taxPercent",
- "embedding",
- "logo",
- "salesContactId",
- "website",
- "customerTypeId",
- "customFields",
- "customerStatusId",
- "defaultCc",
- "accountManagerId",
- "createdBy",
- "intercompanyCompanyId",
- "companyId",
- "id",
+ "updatedBy",
+ "name",
+ "phone",
"createdAt",
- "readableId",
"assignee",
- "name",
- "updatedBy",
- "phone"
+ "readableId",
+ "intercompanyCompanyId",
+ "createdBy",
+ "id",
+ "companyId",
+ "defaultCc",
+ "accountManagerId",
+ "website",
+ "customerStatusId",
+ "customFields",
+ "customerTypeId",
+ "salesContactId",
+ "logo",
+ "taxPercent",
+ "updatedAt",
+ "embedding",
+ "currencyCode",
+ "tags",
+ "fax"
]
},
{
"name": "customerAccount",
"rows": 0,
- "columns": ["id", "customerId", "companyId", "active"]
+ "columns": ["active", "companyId", "customerId", "id"]
},
{
"name": "customerBankAccount",
"rows": 0,
"columns": [
- "customFields",
- "swiftBic",
- "accountHolderName",
+ "bankName",
+ "bankCode",
+ "currencyCode",
+ "id",
+ "accountNumber",
+ "countryCode",
+ "companyId",
+ "isPrimary",
+ "createdBy",
"createdAt",
- "tags",
"notes",
- "name",
- "active",
- "customerId",
+ "tags",
+ "swiftBic",
+ "customFields",
+ "accountHolderName",
+ "bankAddress",
"updatedBy",
"updatedAt",
- "bankAddress",
- "id",
- "currencyCode",
- "bankCode",
- "bankName",
- "createdBy",
- "companyId",
- "isPrimary",
- "countryCode",
- "accountNumber"
+ "active",
+ "customerId",
+ "name"
]
},
{
"name": "customerItemPriceOverride",
"rows": 0,
"columns": [
- "active",
- "companyId",
- "customerId",
- "updatedBy",
- "validFrom",
- "applyRulesOnTop",
- "id",
- "createdBy",
"validTo",
+ "itemId",
"updatedAt",
"customerTypeId",
- "itemId",
+ "notes",
"createdAt",
- "notes"
+ "companyId",
+ "active",
+ "updatedBy",
+ "customerId",
+ "validFrom",
+ "createdBy",
+ "id",
+ "applyRulesOnTop"
]
},
{
"name": "customerItemPriceOverrideBreak",
"rows": 0,
"columns": [
- "createdBy",
- "quantity",
- "overridePrice",
- "active",
+ "companyId",
+ "id",
+ "updatedBy",
"createdAt",
"updatedAt",
"customerItemPriceOverrideId",
- "companyId",
- "updatedBy",
- "id"
+ "active",
+ "createdBy",
+ "overridePrice",
+ "quantity"
]
},
{
"name": "customerLocation",
"rows": 0,
"columns": [
- "tags",
- "id",
- "companyId",
- "customerId",
"name",
"addressId",
- "customFields"
+ "customFields",
+ "id",
+ "tags",
+ "customerId",
+ "companyId"
]
},
{
@@ -4015,14 +4015,14 @@
"name": "customerPayment",
"rows": 0,
"columns": [
- "updatedBy",
- "customerId",
- "updatedAt",
"invoiceCustomerId",
- "paymentTermId",
- "companyId",
+ "updatedAt",
+ "customerId",
+ "updatedBy",
+ "invoiceCustomerContactId",
"invoiceCustomerLocationId",
- "invoiceCustomerContactId"
+ "companyId",
+ "paymentTermId"
]
},
{
@@ -4046,15 +4046,15 @@
"name": "customerTax",
"rows": 0,
"columns": [
- "eori",
"vatNumber",
+ "eori",
"taxExemptionCertificateNumber",
"taxExempt",
"taxId",
"taxExemptionCertificatePath",
"updatedAt",
- "customerId",
"companyId",
+ "customerId",
"updatedBy",
"taxExemptionReason"
]
@@ -4063,78 +4063,78 @@
"name": "fixture",
"rows": 0,
"columns": [
- "approvedBy",
- "companyId",
- "approved",
- "customerId",
- "customFields",
- "updatedAt",
- "id",
- "createdAt",
- "updatedBy",
"createdBy",
+ "updatedBy",
"tags",
- "itemId"
+ "itemId",
+ "customFields",
+ "createdAt",
+ "id",
+ "updatedAt",
+ "companyId",
+ "customerId",
+ "approved",
+ "approvedBy"
]
},
{
"name": "nonConformanceCustomer",
"rows": 0,
"columns": [
- "customerId",
- "companyId",
"updatedAt",
+ "companyId",
+ "customerId",
"createdAt",
- "nonConformanceId",
"updatedBy",
- "id",
- "createdBy"
+ "nonConformanceId",
+ "createdBy",
+ "id"
]
},
{
"name": "opportunity",
"rows": 0,
"columns": [
+ "requestForQuoteDocumentPath",
+ "companyId",
"customerId",
"id",
- "purchaseOrderDocumentPath",
- "companyId",
- "requestForQuoteDocumentPath"
+ "purchaseOrderDocumentPath"
]
},
{
"name": "salesOrder",
"rows": 0,
"columns": [
- "exchangeRateUpdatedAt",
- "currencyCode",
- "opportunityId",
- "status",
- "revisionId",
- "closedAt",
- "updatedAt",
- "createdBy",
- "locationId",
- "closedBy",
- "salesPersonId",
- "createdAt",
- "exchangeRate",
- "orderDate",
- "updatedBy",
- "assignee",
- "customerId",
- "customerEngineeringContactId",
- "completedDate",
- "externalNotes",
- "customerContactId",
"customFields",
"companyId",
"salesOrderId",
- "internalNotes",
- "id",
+ "completedDate",
+ "customerEngineeringContactId",
+ "customerId",
+ "externalNotes",
+ "customerContactId",
"customerLocationId",
+ "id",
+ "customerReference",
"sentCompleteDate",
- "customerReference"
+ "internalNotes",
+ "closedAt",
+ "revisionId",
+ "status",
+ "updatedAt",
+ "createdBy",
+ "currencyCode",
+ "exchangeRateUpdatedAt",
+ "opportunityId",
+ "exchangeRate",
+ "orderDate",
+ "assignee",
+ "updatedBy",
+ "locationId",
+ "closedBy",
+ "createdAt",
+ "salesPersonId"
]
},
{
@@ -4146,129 +4146,129 @@
"name": "salesOrderLine",
"rows": 0,
"columns": [
+ "taxPercent",
+ "priceTrace",
+ "quantitySent",
+ "customFields",
+ "saleQuantity",
+ "id",
+ "sortOrder",
+ "updatedAt",
+ "externalNotes",
+ "quantityInvoiced",
+ "salesOrderId",
+ "locationId",
"sentDate",
"createdBy",
"exchangeRate",
"accountId",
+ "modelUploadId",
"promisedDate",
"description",
- "modelUploadId",
- "externalNotes",
- "quantityInvoiced",
- "salesOrderId",
- "locationId",
- "updatedAt",
- "taxPercent",
- "customFields",
- "priceTrace",
- "quantitySent",
- "sortOrder",
- "id",
- "saleQuantity",
- "methodType",
- "createdAt",
- "shippingCost",
- "nonTaxableAddOnCost",
- "assetId",
- "status",
+ "addOnCost",
+ "invoicedComplete",
+ "companyId",
+ "unitOfMeasureCode",
+ "pricingRuleId",
+ "storageUnitId",
+ "updatedBy",
"sentComplete",
"internalNotes",
"setupPrice",
- "itemId",
"unitPrice",
"salesOrderLineType",
- "pricingRuleId",
- "unitOfMeasureCode",
- "updatedBy",
- "storageUnitId",
- "invoicedComplete",
- "addOnCost",
- "companyId"
+ "itemId",
+ "methodType",
+ "assetId",
+ "shippingCost",
+ "createdAt",
+ "nonTaxableAddOnCost",
+ "status"
]
},
{
"name": "nonConformanceSalesOrderLine",
"rows": 0,
"columns": [
- "salesOrderReadableId",
- "createdAt",
- "salesOrderId",
- "salesOrderLineId",
"companyId",
- "id",
"updatedAt",
+ "id",
"createdBy",
"updatedBy",
- "nonConformanceId"
+ "nonConformanceId",
+ "salesOrderReadableId",
+ "createdAt",
+ "salesOrderLineId",
+ "salesOrderId"
]
},
{
"name": "salesOrderPayment",
"rows": 0,
"columns": [
- "updatedAt",
- "id",
- "customFields",
- "paymentComplete",
"invoiceCustomerId",
- "companyId",
"updatedBy",
- "paymentTermId",
+ "companyId",
+ "customFields",
+ "id",
+ "updatedAt",
+ "paymentComplete",
+ "invoiceCustomerContactId",
"invoiceCustomerLocationId",
- "invoiceCustomerContactId"
+ "paymentTermId"
]
},
{
"name": "salesOrderShipment",
"rows": 0,
"columns": [
- "trackingNumber",
- "id",
- "customerId",
- "receiptPromisedDate",
- "updatedBy",
- "supplierId",
- "locationId",
- "notes",
- "dropShipment",
- "incotermLocation",
- "receiptRequestedDate",
- "customerLocationId",
- "shippingCost",
- "incoterm",
- "companyId",
- "updatedAt",
+ "deliveryDate",
+ "shippingTermId",
"shippingMethodId",
"supplierLocationId",
- "shippingTermId",
"assignee",
"customFields",
- "deliveryDate"
+ "companyId",
+ "incoterm",
+ "updatedAt",
+ "incotermLocation",
+ "receiptRequestedDate",
+ "shippingCost",
+ "customerLocationId",
+ "notes",
+ "dropShipment",
+ "updatedBy",
+ "supplierId",
+ "locationId",
+ "receiptPromisedDate",
+ "id",
+ "trackingNumber",
+ "customerId"
]
},
{
"name": "salesOrderStatusHistory",
"rows": 0,
"columns": [
+ "salesOrderId",
+ "id",
+ "companyId",
"status",
"createdAt",
"updatedBy",
- "createdBy",
- "salesOrderId",
- "id",
- "companyId"
+ "createdBy"
]
},
{
"name": "salesOrderTransaction",
"rows": 0,
"columns": [
- "userId",
- "type",
"createdAt",
- "salesOrderId",
+ "type",
+ "userId",
+ "companyId",
"id",
- "companyId"
+ "salesOrderId"
]
},
{
@@ -4276,8 +4276,8 @@
"rows": 0,
"columns": [
"externalNotes",
- "orderDate",
"salesReturnOrderId",
+ "orderDate",
"locationId",
"replacementSalesOrderId",
"id",
@@ -4287,80 +4287,80 @@
"customerId",
"expirationDate",
"status",
- "createdBy",
"companyId",
+ "createdBy",
"customFields",
"customerReference",
"updatedAt",
- "customerLocationId",
"createdAt",
"exchangeRate",
- "updatedBy",
+ "customerLocationId",
+ "assignee",
"internalNotes",
- "assignee"
+ "updatedBy"
]
},
{
"name": "salesRfq",
"rows": 0,
"columns": [
- "rfqId",
- "locationId",
- "customFields",
- "expirationDate",
- "internalNotes",
"customerEngineeringContactId",
"customerReference",
"completedDate",
- "noQuoteReasonId",
+ "internalNotes",
+ "expirationDate",
+ "customFields",
+ "locationId",
+ "rfqId",
+ "customerId",
+ "salesPersonId",
"id",
"rfqDate",
- "salesPersonId",
- "customerId",
- "createdBy",
- "updatedAt",
+ "noQuoteReasonId",
+ "externalNotes",
+ "customerContactId",
+ "opportunityId",
"status",
"assignee",
"revisionId",
- "opportunityId",
- "externalNotes",
- "customerContactId",
- "updatedBy",
- "employeeId",
+ "updatedAt",
+ "createdBy",
+ "companyId",
+ "customerLocationId",
"tags",
"createdAt",
- "companyId",
- "customerLocationId"
+ "employeeId",
+ "updatedBy"
]
},
{
"name": "salesRfqFavorite",
"rows": 0,
- "columns": ["userId", "rfqId"]
+ "columns": ["rfqId", "userId"]
},
{
"name": "salesRfqLine",
"rows": 0,
"columns": [
+ "unitOfMeasureCode",
+ "internalNotes",
+ "updatedAt",
+ "salesRfqId",
+ "customFields",
+ "description",
+ "id",
+ "order",
+ "externalNotes",
"quantity",
+ "createdAt",
"modelUploadId",
"customerPartId",
- "createdAt",
"updatedBy",
"tags",
"createdBy",
"customerPartRevision",
"companyId",
- "itemId",
- "internalNotes",
- "unitOfMeasureCode",
- "salesRfqId",
- "customFields",
- "updatedAt",
- "description",
- "externalNotes",
- "id",
- "order"
+ "itemId"
]
},
{
@@ -4369,8 +4369,8 @@
"columns": [
"createdAt",
"companyId",
- "documentId",
"customerId",
+ "documentId",
"expiresAt",
"id",
"supplierId",
@@ -4381,100 +4381,100 @@
"name": "quote",
"rows": 0,
"columns": [
- "digitalQuoteRejectedBy",
- "externalLinkId",
- "completedDate",
- "status",
- "customerEngineeringContactId",
- "externalNotes",
- "companyId",
- "createdAt",
- "revisionId",
- "customerReference",
- "customFields",
- "exchangeRate",
- "locationId",
- "updatedAt",
- "tags",
- "customerLocationId",
- "createdBy",
- "dueDate",
- "updatedBy",
+ "customerId",
+ "exchangeRateUpdatedAt",
+ "salesPersonId",
+ "id",
+ "currencyCode",
+ "expirationDate",
+ "quoteId",
+ "opportunityId",
+ "customerContactId",
+ "assignee",
"digitalQuoteRejectedByEmail",
"estimatorId",
"internalNotes",
"digitalQuoteAcceptedBy",
"digitalQuoteAcceptedByEmail",
- "opportunityId",
- "quoteId",
- "customerContactId",
- "assignee",
- "currencyCode",
- "expirationDate",
- "customerId",
- "exchangeRateUpdatedAt",
- "salesPersonId",
- "id"
+ "tags",
+ "customerLocationId",
+ "createdBy",
+ "dueDate",
+ "updatedBy",
+ "customFields",
+ "exchangeRate",
+ "locationId",
+ "updatedAt",
+ "companyId",
+ "createdAt",
+ "customerReference",
+ "revisionId",
+ "digitalQuoteRejectedBy",
+ "externalLinkId",
+ "completedDate",
+ "status",
+ "customerEngineeringContactId",
+ "externalNotes"
]
},
{
"name": "job",
"rows": 0,
"columns": [
- "quantityComplete",
- "scheduleOutdatedReason",
- "jobId",
- "actualTime",
- "salesOrderId",
- "companyId",
- "quantity",
- "estimatedTime",
- "configuration",
- "dueDate",
- "tags",
- "priority",
- "storageUnitId",
- "updatedAt",
- "scrapQuantity",
- "id",
- "deadlineType",
- "createdAt",
- "scheduleOutdatedAt",
- "locationId",
- "quoteLineId",
- "quoteId",
- "projectedCompletionAt",
- "unitOfMeasureCode",
- "quantityShipped",
- "itemId",
- "completedDate",
+ "createdBy",
+ "salesOrderLineId",
+ "notes",
+ "quantityReceivedToInventory",
+ "assignee",
+ "modelUploadId",
+ "releasedDate",
+ "customerId",
+ "updatedBy",
"startDate",
"customFields",
"status",
- "updatedBy",
- "customerId",
- "modelUploadId",
- "releasedDate",
- "assignee",
- "notes",
- "quantityReceivedToInventory",
- "createdBy",
- "salesOrderLineId"
+ "completedDate",
+ "unitOfMeasureCode",
+ "itemId",
+ "quantityShipped",
+ "quoteId",
+ "projectedCompletionAt",
+ "quoteLineId",
+ "scheduleOutdatedAt",
+ "locationId",
+ "createdAt",
+ "id",
+ "deadlineType",
+ "updatedAt",
+ "scrapQuantity",
+ "priority",
+ "storageUnitId",
+ "dueDate",
+ "configuration",
+ "tags",
+ "quantity",
+ "estimatedTime",
+ "companyId",
+ "salesOrderId",
+ "actualTime",
+ "jobId",
+ "quantityComplete",
+ "scheduleOutdatedReason"
]
},
{
"name": "fulfillment",
"rows": 0,
"columns": [
- "companyId",
- "updatedBy",
- "id",
- "createdBy",
"salesOrderLineId",
- "jobId",
- "createdAt",
+ "createdBy",
+ "id",
+ "updatedBy",
+ "companyId",
+ "quantity",
"type",
- "quantity"
+ "createdAt",
+ "jobId"
]
},
{
@@ -4491,72 +4491,72 @@
"name": "quoteLine",
"rows": 0,
"columns": [
- "tags",
- "updatedAt",
+ "taxPercent",
+ "itemId",
+ "unitPricePrecision",
+ "customerPartRevision",
+ "id",
+ "description",
+ "noQuoteReason",
+ "customerPartId",
+ "itemType",
+ "pricingRuleId",
+ "configuration",
+ "unitOfMeasureCode",
+ "quoteId",
+ "createdBy",
"quantity",
"companyId",
+ "tags",
+ "updatedAt",
+ "estimatorId",
"modelUploadId",
"methodType",
"priceTrace",
- "estimatorId",
"additionalCharges",
"sortOrder",
- "externalNotes",
"locationId",
- "updatedBy",
+ "externalNotes",
"customFields",
+ "updatedBy",
"status",
- "internalNotes",
"quoteRevisionId",
- "taxPercent",
- "itemId",
- "unitPricePrecision",
- "customerPartRevision",
- "id",
- "description",
- "customerPartId",
- "noQuoteReason",
- "pricingRuleId",
- "itemType",
- "configuration",
- "quoteId",
- "unitOfMeasureCode",
- "createdBy"
+ "internalNotes"
]
},
{
"name": "quoteLinePrice",
"rows": 0,
"columns": [
+ "priceSource",
+ "createdAt",
+ "companyId",
+ "updatedBy",
+ "quoteId",
+ "categoryMarkups",
+ "leadTime",
+ "createdBy",
"discountPercent",
+ "quantity",
"unitPrice",
"quoteLineId",
- "quantity",
- "exchangeRate",
"shippingCost",
- "updatedAt",
- "createdAt",
- "priceSource",
- "quoteId",
- "updatedBy",
- "companyId",
- "leadTime",
- "categoryMarkups",
- "createdBy"
+ "exchangeRate",
+ "updatedAt"
]
},
{
"name": "quotePayment",
"rows": 0,
"columns": [
- "invoiceCustomerId",
- "customFields",
"updatedAt",
+ "customFields",
+ "invoiceCustomerId",
"id",
"updatedBy",
+ "companyId",
"invoiceCustomerContactId",
"invoiceCustomerLocationId",
- "companyId",
"paymentTermId"
]
},
@@ -4564,185 +4564,185 @@
"name": "quoteShipment",
"rows": 0,
"columns": [
- "shippingMethodId",
- "shippingTermId",
"updatedBy",
- "receiptRequestedDate",
+ "shippingTermId",
+ "shippingMethodId",
"incotermLocation",
- "locationId",
+ "receiptRequestedDate",
"updatedAt",
+ "locationId",
+ "companyId",
"incoterm",
- "shippingCost",
"id",
- "companyId"
+ "shippingCost"
]
},
{
"name": "capacityReservation",
"rows": 0,
"columns": [
- "endAt",
- "createdBy",
- "workHours",
"updatedAt",
"companyId",
- "jobId",
- "id",
- "scenarioId",
+ "workHours",
+ "createdBy",
+ "endAt",
"createdAt",
- "startAt",
- "resourceId",
- "resourceKind",
- "earliestStartAt",
+ "scenarioId",
+ "id",
+ "jobId",
"jobOperationBatchId",
- "scheduleNote",
- "isPlaceholder",
+ "earliestStartAt",
+ "resourceKind",
+ "resourceId",
+ "startAt",
"operationId",
- "updatedBy"
+ "updatedBy",
+ "scheduleNote",
+ "isPlaceholder"
]
},
{
"name": "gauge",
"rows": 0,
"columns": [
- "updatedBy",
+ "gaugeRole",
+ "gaugeCalibrationStatus",
+ "id",
+ "description",
+ "lastCalibrationDate",
+ "gaugeId",
+ "storageUnitId",
+ "gaugeStatus",
+ "gaugeTypeId",
"serialNumber",
"calibrationIntervalInMonths",
"createdBy",
- "locationId",
+ "updatedBy",
"updatedAt",
+ "locationId",
"companyId",
- "supplierId",
- "nextCalibrationDate",
- "modelNumber",
"createdAt",
"customFields",
+ "nextCalibrationDate",
+ "supplierId",
+ "modelNumber",
"dateAcquired",
- "lastCalibrationStatus",
- "gaugeCalibrationStatus",
- "id",
- "gaugeRole",
- "description",
- "storageUnitId",
- "lastCalibrationDate",
- "gaugeId",
- "gaugeTypeId",
- "gaugeStatus"
+ "lastCalibrationStatus"
]
},
{
"name": "gaugeCalibrationRecord",
"rows": 0,
"columns": [
- "customFields",
+ "calibrationAttempts",
+ "createdBy",
+ "requiresAction",
+ "humidity",
+ "supplierId",
+ "inspectionStatus",
+ "updatedBy",
+ "dateCalibrated",
+ "approvedBy",
+ "measurementStandard",
+ "requiresRepair",
"id",
+ "customFields",
"createdAt",
"requiresAdjustment",
"temperature",
- "updatedAt",
"gaugeId",
+ "updatedAt",
"notes",
- "companyId",
- "requiresAction",
- "createdBy",
- "calibrationAttempts",
- "supplierId",
- "humidity",
- "dateCalibrated",
- "updatedBy",
- "inspectionStatus",
- "measurementStandard",
- "approvedBy",
- "requiresRepair"
+ "companyId"
]
},
{
"name": "inspection",
"rows": 0,
"columns": [
- "companyId",
- "acceptanceNumber",
- "sourceDocumentReadableId",
- "dispositionedBy",
- "itemId",
+ "updatedAt",
+ "itemReadableId",
+ "sampleSize",
+ "inspectionDocumentId",
+ "samplingStandard",
+ "id",
+ "samplingPlanType",
+ "createdBy",
+ "sourceDocumentId",
+ "lotSize",
+ "sourceDocumentLineId",
+ "inspectionId",
+ "rejectionNumber",
+ "severity",
"codeLetter",
"updatedBy",
- "dispositionedAt",
"inspectionLevel",
- "aql",
- "status",
- "notes",
+ "dispositionedAt",
+ "sourceDocumentReadableId",
+ "acceptanceNumber",
+ "dispositionedBy",
+ "itemId",
+ "companyId",
"sourceDocument",
"supplierId",
"createdAt",
- "samplingStandard",
- "id",
- "sampleSize",
- "inspectionDocumentId",
- "itemReadableId",
- "updatedAt",
- "severity",
- "inspectionId",
- "rejectionNumber",
- "sourceDocumentId",
- "lotSize",
- "sourceDocumentLineId",
- "samplingPlanType",
- "createdBy"
+ "status",
+ "notes",
+ "aql"
]
},
{
"name": "inspectionSample",
"rows": 0,
"columns": [
+ "notes",
+ "updatedBy",
+ "inspectedAt",
+ "status",
+ "trackedEntityId",
"inspectedBy",
"updatedAt",
- "createdAt",
"id",
+ "createdAt",
"createdBy",
"companyId",
- "inspectionId",
- "notes",
- "updatedBy",
- "inspectedAt",
- "trackedEntityId",
- "status"
+ "inspectionId"
]
},
{
"name": "inspectionMeasurement",
"rows": 0,
"columns": [
- "value",
"createdAt",
- "notes",
+ "value",
"inspectionFeatureId",
"inspectionSampleId",
"updatedAt",
- "status",
+ "notes",
"createdBy",
"id",
"inspectedAt",
- "companyId",
- "inspectedBy",
+ "status",
+ "inspectionId",
"updatedBy",
- "inspectionId"
+ "companyId",
+ "inspectedBy"
]
},
{
"name": "inspectionSamplingPlan",
"rows": 0,
"columns": [
- "createdAt",
"companyId",
+ "createdAt",
"inspectionId",
"rejectionNumber",
- "updatedBy",
- "id",
"createdBy",
+ "id",
+ "updatedBy",
"codeLetter",
- "sampleSize",
"inspectionFeatureId",
+ "sampleSize",
"acceptanceNumber",
"updatedAt"
]
@@ -4751,41 +4751,49 @@
"name": "nonConformanceInspection",
"rows": 0,
"columns": [
+ "createdBy",
+ "id",
+ "nonConformanceId",
"createdAt",
- "companyId",
- "inspectionId",
"updatedBy",
- "id",
- "createdBy",
- "nonConformanceId"
+ "companyId",
+ "inspectionId"
]
},
{
"name": "inspectionHistory",
"rows": 0,
"columns": [
- "inspectionId",
- "companyId",
- "updatedBy",
- "sampleSize",
- "aql",
- "defectsFound",
- "lotSize",
- "id",
"severity",
- "createdAt",
- "itemId",
- "supplierId",
- "inspectionLevel",
- "outcome",
+ "id",
+ "lotSize",
+ "defectsFound",
+ "aql",
+ "sampleSize",
+ "updatedBy",
+ "companyId",
+ "inspectionId",
+ "createdBy",
"samplingStandard",
- "createdBy"
+ "outcome",
+ "inspectionLevel",
+ "supplierId",
+ "createdAt",
+ "itemId"
]
},
{
"name": "itemReplenishment",
"rows": 0,
"columns": [
+ "purchasingUnitOfMeasureCode",
+ "updatedBy",
+ "tags",
+ "leadTime",
+ "scrapPercentage",
+ "updatedAt",
+ "createdBy",
+ "conversionFactor",
"manufacturingBlocked",
"lotSize",
"customFields",
@@ -4794,443 +4802,435 @@
"purchasingBlocked",
"itemId",
"requiresConfiguration",
- "companyId",
- "purchasingUnitOfMeasureCode",
- "updatedBy",
- "tags",
- "leadTime",
- "scrapPercentage",
- "updatedAt",
- "createdBy",
- "conversionFactor"
+ "companyId"
]
},
{
"name": "jobMakeMethod",
"rows": 0,
"columns": [
- "requiresSerialTracking",
- "jobId",
- "itemScrapPercentage",
- "updatedBy",
- "createdBy",
- "customFields",
- "id",
- "updatedAt",
- "companyId",
+ "version",
+ "trackedEntityId",
+ "quantityPerParent",
+ "createdAt",
"itemId",
"parentMaterialId",
"requiresBatchTracking",
- "createdAt",
- "quantityPerParent",
- "trackedEntityId",
- "version"
+ "companyId",
+ "id",
+ "updatedAt",
+ "customFields",
+ "createdBy",
+ "updatedBy",
+ "itemScrapPercentage",
+ "jobId",
+ "requiresSerialTracking"
]
},
{
"name": "jobMaterial",
"rows": 0,
"columns": [
- "unitCost",
- "jobId",
- "createdBy",
- "storageUnitId",
- "substitutionFactor",
- "scrapQuantity",
- "description",
- "kit",
- "requiresBatchTracking",
- "id",
- "quantity",
- "quantityIssued",
- "methodType",
- "customFields",
- "updatedBy",
- "itemId",
- "companyId",
- "substitutedFromItemId",
- "defaultStorageUnit",
- "order",
- "requiresSerialTracking",
- "itemType",
- "jobMakeMethodId",
+ "estimatedQuantity",
"itemScrapPercentage",
"unitOfMeasureCode",
- "estimatedQuantity",
+ "jobMakeMethodId",
+ "itemType",
+ "updatedAt",
"createdAt",
"jobOperationId",
- "updatedAt"
+ "companyId",
+ "itemId",
+ "updatedBy",
+ "customFields",
+ "requiresSerialTracking",
+ "order",
+ "defaultStorageUnit",
+ "substitutedFromItemId",
+ "quantity",
+ "id",
+ "methodType",
+ "quantityIssued",
+ "createdBy",
+ "jobId",
+ "unitCost",
+ "requiresBatchTracking",
+ "kit",
+ "description",
+ "substitutionFactor",
+ "scrapQuantity",
+ "storageUnitId"
]
},
{
"name": "stockTransferLine",
"rows": 0,
"columns": [
- "stockTransferId",
- "requiresSerialTracking",
- "createdBy",
- "quantity",
"trackedEntityId",
- "id",
"pickedQuantity",
+ "id",
"fromStorageUnitId",
- "updatedBy",
- "jobMaterialId",
- "companyId",
- "jobId",
- "toStorageUnitId",
- "requiresBatchTracking",
+ "requiresSerialTracking",
+ "stockTransferId",
+ "createdBy",
+ "quantity",
"itemId",
+ "requiresBatchTracking",
+ "createdAt",
"updatedAt",
- "createdAt"
- ]
- },
- {
- "name": "jobMaterialStep",
- "rows": 0,
- "columns": ["quantity", "jobOperationStepId", "jobMaterialId"]
- },
- {
- "name": "jobOperation",
- "rows": 0,
- "columns": [
- "companyId",
- "laborTime",
- "quantityReworked",
- "targetQuantity",
- "operationQuantity",
- "setupTime",
- "customFields",
- "machineUnit",
- "dueDate",
+ "updatedBy",
"jobId",
- "status",
- "overheadRate",
- "conflictReason",
- "readyAt",
- "createdAt",
- "workCenterId",
+ "companyId",
+ "jobMaterialId",
+ "toStorageUnitId"
+ ]
+ },
+ {
+ "name": "jobMaterialStep",
+ "rows": 0,
+ "columns": ["quantity", "jobMaterialId", "jobOperationStepId"]
+ },
+ {
+ "name": "jobOperation",
+ "rows": 0,
+ "columns": [
"hasConflict",
- "procedureId",
- "tags",
- "updatedAt",
- "laborUnit",
+ "workCenterId",
+ "createdAt",
+ "readyAt",
+ "inspectionDocumentId",
"id",
"projectedCompletionAt",
"setupUnit",
- "inspectionDocumentId",
- "quantityScrapped",
+ "updatedAt",
+ "laborUnit",
+ "tags",
+ "procedureId",
+ "setupTime",
+ "operationQuantity",
+ "customFields",
+ "targetQuantity",
+ "quantityReworked",
+ "laborTime",
+ "companyId",
+ "conflictReason",
+ "overheadRate",
+ "status",
+ "jobId",
+ "dueDate",
+ "machineUnit",
+ "manuallyScheduled",
+ "createdBy",
+ "machineRate",
+ "laborRate",
+ "operationUnitCost",
+ "operationSupplierProcessId",
+ "reworkId",
+ "operationLeadTime",
+ "quantityComplete",
+ "machineTime",
+ "processId",
+ "updatedBy",
"assignee",
"workInstruction",
- "description",
"priority",
- "updatedBy",
- "assemblyInstructionId",
- "operationMinimumCost",
- "operationType",
- "startDate",
+ "description",
+ "quantityScrapped",
+ "jobOperationBatchId",
"order",
- "operationOrder",
"jobMakeMethodId",
- "jobOperationBatchId",
- "operationUnitCost",
- "laborRate",
- "createdBy",
- "machineRate",
- "manuallyScheduled",
- "processId",
- "operationLeadTime",
- "machineTime",
- "quantityComplete",
- "reworkId",
- "operationSupplierProcessId"
+ "operationOrder",
+ "startDate",
+ "operationType",
+ "assemblyInstructionId",
+ "operationMinimumCost"
]
},
{
"name": "jobOperationDependency",
"rows": 0,
"columns": [
- "createdAt",
+ "dependsOnId",
+ "operationId",
"jobId",
"companyId",
- "operationId",
- "dependsOnId"
+ "createdAt"
]
},
{
"name": "jobOperationParameter",
"rows": 0,
"columns": [
- "operationId",
- "value",
- "createdBy",
- "companyId",
+ "updatedBy",
+ "id",
+ "createdAt",
"key",
"updatedAt",
- "id",
- "updatedBy",
- "createdAt"
+ "companyId",
+ "value",
+ "operationId",
+ "createdBy"
]
},
{
"name": "jobOperationTool",
"rows": 0,
"columns": [
- "updatedAt",
- "operationId",
- "createdAt",
"updatedBy",
"id",
- "createdBy",
+ "createdAt",
+ "operationId",
+ "updatedAt",
+ "companyId",
"toolId",
"quantity",
- "companyId"
+ "createdBy"
]
},
{
"name": "nonConformanceJobOperation",
"rows": 0,
"columns": [
- "createdAt",
- "jobOperationId",
- "jobId",
"jobReadableId",
- "updatedBy",
- "createdBy",
- "nonConformanceId",
- "companyId",
+ "jobId",
+ "jobOperationId",
+ "createdAt",
+ "id",
"updatedAt",
- "id"
+ "companyId",
+ "nonConformanceId",
+ "createdBy",
+ "updatedBy"
]
},
{
"name": "pickingListLine",
"rows": 0,
"columns": [
- "id",
- "toStorageUnitId",
- "itemId",
- "updatedBy",
- "pickingListId",
- "companyId",
- "quantityPicked",
- "storageUnitId",
- "status",
"jobOperationId",
- "updatedAt",
+ "status",
"createdAt",
+ "updatedAt",
+ "quantityReturned",
+ "customFields",
"jobId",
"createdBy",
"jobMaterialId",
- "customFields",
- "quantityReturned",
- "quantityToPick"
+ "quantityToPick",
+ "toStorageUnitId",
+ "id",
+ "itemId",
+ "companyId",
+ "pickingListId",
+ "updatedBy",
+ "storageUnitId",
+ "quantityPicked"
]
},
{
"name": "pickingListLineTrackedEntity",
"rows": 0,
"columns": [
- "trackedEntityId",
"pickingListLineId",
- "quantity",
+ "trackedEntityId",
+ "companyId",
"quantityPicked",
- "companyId"
+ "quantity"
]
},
{
"name": "productionEvent",
"rows": 0,
"columns": [
- "startTime",
- "type",
- "employeeId",
- "endTime",
- "updatedAt",
- "notes",
- "jobOperationBatchId",
+ "createdAt",
+ "workCenterId",
"updatedBy",
"jobOperationId",
"postedToGL",
- "createdAt",
- "workCenterId",
"createdBy",
+ "companyId",
"id",
- "companyId"
+ "employeeId",
+ "type",
+ "startTime",
+ "notes",
+ "jobOperationBatchId",
+ "endTime",
+ "updatedAt"
]
},
{
"name": "productionQuantity",
"rows": 0,
"columns": [
+ "quantity",
+ "scrapReasonId",
+ "type",
+ "machineProductionEventId",
+ "updatedAt",
+ "setupProductionEventId",
+ "inspectionId",
"inspectionSampleId",
- "updatedBy",
"jobOperationId",
+ "updatedBy",
"notes",
"createdAt",
- "companyId",
"id",
+ "companyId",
"createdBy",
- "laborProductionEventId",
- "scrapReasonId",
- "type",
- "quantity",
- "machineProductionEventId",
- "setupProductionEventId",
- "updatedAt",
- "inspectionId"
+ "laborProductionEventId"
]
},
{
"name": "jobOperationNote",
"rows": 0,
"columns": [
- "createdAt",
- "updatedBy",
- "note",
"companyId",
- "createdBy",
- "productionQuantityId",
- "id",
+ "note",
+ "updatedBy",
+ "createdAt",
+ "jobOperationId",
"updatedAt",
- "jobOperationId"
+ "id",
+ "productionQuantityId",
+ "createdBy"
]
},
{
"name": "rework",
"rows": 0,
"columns": [
- "reason",
- "updatedAt",
"targetJobOperationId",
"triggeredAtJobOperationId",
+ "updatedAt",
+ "reason",
+ "companyId",
+ "requestedById",
+ "jobId",
"quantity",
"createdAt",
"id",
- "completedAt",
- "companyId",
- "requestedById",
- "jobId"
+ "completedAt"
]
},
{
"name": "jobOperationStep",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
- "name",
- "minValue",
- "listValues",
- "id",
- "maxValue",
- "fileTypes",
- "type",
- "required",
- "createdAt",
- "nonConformanceActionId",
- "description",
- "unitOfMeasureCode",
- "sortOrder",
"nonConformanceInvestigationId",
"operationId",
+ "sortOrder",
+ "updatedBy",
"assemblyInstructionStepId",
"createdBy",
- "updatedBy"
+ "description",
+ "nonConformanceActionId",
+ "required",
+ "createdAt",
+ "unitOfMeasureCode",
+ "fileTypes",
+ "id",
+ "maxValue",
+ "type",
+ "name",
+ "companyId",
+ "updatedAt",
+ "listValues",
+ "minValue"
]
},
{
"name": "jobOperationStepRecord",
"rows": 0,
"columns": [
- "userValue",
- "index",
- "booleanValue",
- "numericValue",
- "createdAt",
- "jobOperationStepId",
- "updatedAt",
- "id",
- "companyId",
- "value",
"createdBy",
- "updatedBy"
+ "updatedBy",
+ "value",
+ "companyId",
+ "updatedAt",
+ "jobOperationStepId",
+ "id",
+ "createdAt",
+ "numericValue",
+ "booleanValue",
+ "userValue",
+ "index"
]
},
{
"name": "jobOperationStepSlide",
"rows": 0,
"columns": [
- "size",
- "updatedBy",
- "id",
- "companyId",
+ "caption",
+ "imagePath",
+ "createdBy",
+ "sortOrder",
+ "annotations",
"modelUploadId",
"stepId",
"updatedAt",
"createdAt",
- "sortOrder",
- "annotations",
- "imagePath",
- "caption",
- "createdBy"
+ "size",
+ "id",
+ "updatedBy",
+ "companyId"
]
},
{
"name": "jobOperationToolStep",
"rows": 0,
- "columns": ["jobOperationToolId", "jobOperationStepId"]
+ "columns": ["jobOperationStepId", "jobOperationToolId"]
},
{
"name": "kanban",
"rows": 0,
"columns": [
- "updatedBy",
- "completedBarcodeOverride",
- "locationId",
- "createdAt",
- "supplierId",
- "fromStorageUnitId",
- "jobId",
- "replenishmentSystem",
- "updatedAt",
- "quantity",
- "storageUnitId",
"companyId",
- "conversionFactor",
"id",
+ "conversionFactor",
+ "storageUnitId",
+ "itemId",
+ "createdBy",
+ "autoStartJob",
"autoRelease",
"purchaseUnitOfMeasureCode",
- "createdBy",
- "itemId",
- "autoStartJob"
+ "createdAt",
+ "locationId",
+ "completedBarcodeOverride",
+ "updatedBy",
+ "jobId",
+ "fromStorageUnitId",
+ "quantity",
+ "updatedAt",
+ "replenishmentSystem",
+ "supplierId"
]
},
{
"name": "methodMaterial",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "createdBy",
- "itemId",
- "sourcingType",
- "updatedBy",
- "makeMethodId",
- "unitOfMeasureCode",
- "storageUnitIds",
- "createdAt",
- "itemType",
- "updatedAt",
- "tags",
- "order",
+ "kit",
+ "quantity",
+ "methodOperationId",
+ "scrapQuantity",
+ "materialMakeMethodId",
"methodType",
"customFields",
- "materialMakeMethodId",
- "scrapQuantity",
- "methodOperationId",
- "quantity",
- "kit"
+ "order",
+ "tags",
+ "updatedAt",
+ "itemType",
+ "createdAt",
+ "storageUnitIds",
+ "unitOfMeasureCode",
+ "makeMethodId",
+ "updatedBy",
+ "sourcingType",
+ "itemId",
+ "createdBy",
+ "id",
+ "companyId"
]
},
{
@@ -5242,108 +5242,108 @@
"name": "methodOperation",
"rows": 0,
"columns": [
+ "customFields",
+ "createdBy",
+ "inspectionDocumentId",
+ "makeMethodId",
"operationMinimumCost",
"procedureId",
"machineUnit",
"assemblyInstructionId",
- "customFields",
- "createdBy",
- "makeMethodId",
- "inspectionDocumentId",
- "operationType",
"id",
"workInstruction",
"companyId",
- "machineTime",
- "description",
- "tags",
- "operationUnitCost",
+ "operationType",
"operationOrder",
- "updatedAt",
"order",
+ "updatedAt",
"setupTime",
"workCenterId",
- "laborTime",
- "updatedBy",
- "operationSupplierProcessId",
- "processId",
+ "machineTime",
+ "description",
+ "tags",
+ "operationUnitCost",
"laborUnit",
"setupUnit",
"createdAt",
- "operationLeadTime"
+ "operationLeadTime",
+ "laborTime",
+ "updatedBy",
+ "operationSupplierProcessId",
+ "processId"
]
},
{
"name": "methodOperationParameter",
"rows": 0,
"columns": [
- "value",
- "operationId",
- "createdBy",
- "companyId",
"key",
"updatedAt",
- "updatedBy",
"id",
- "createdAt"
+ "updatedBy",
+ "createdAt",
+ "operationId",
+ "value",
+ "createdBy",
+ "companyId"
]
},
{
"name": "methodOperationStep",
"rows": 0,
"columns": [
- "sortOrder",
- "operationId",
- "createdBy",
- "updatedBy",
"assemblyInstructionStepId",
"description",
"createdAt",
"required",
"unitOfMeasureCode",
- "fileTypes",
- "maxValue",
- "id",
- "type",
+ "sortOrder",
+ "operationId",
+ "createdBy",
+ "updatedBy",
"companyId",
"name",
"updatedAt",
"listValues",
- "minValue"
+ "minValue",
+ "fileTypes",
+ "maxValue",
+ "id",
+ "type"
]
},
{
"name": "methodOperationStepSlide",
"rows": 0,
"columns": [
- "sortOrder",
- "annotations",
- "caption",
- "imagePath",
"createdBy",
- "id",
- "updatedBy",
- "size",
- "companyId",
- "modelUploadId",
- "stepId",
+ "imagePath",
+ "caption",
+ "annotations",
+ "sortOrder",
+ "updatedAt",
"createdAt",
- "updatedAt"
+ "stepId",
+ "modelUploadId",
+ "companyId",
+ "size",
+ "updatedBy",
+ "id"
]
},
{
"name": "methodOperationTool",
"rows": 0,
"columns": [
+ "createdBy",
+ "quantity",
+ "toolId",
+ "companyId",
"updatedAt",
"operationId",
"createdAt",
- "updatedBy",
"id",
- "createdBy",
- "toolId",
- "quantity",
- "companyId"
+ "updatedBy"
]
},
{
@@ -5357,8 +5357,8 @@
"columns": [
"createdAt",
"updatedAt",
- "companyId",
"processId",
+ "companyId",
"createdBy",
"id",
"updatedBy",
@@ -5370,8 +5370,8 @@
"rows": 0,
"columns": [
"assignee",
- "status",
"updatedAt",
+ "status",
"supplierId",
"updatedBy",
"createdAt",
@@ -5383,41 +5383,41 @@
"actionTypeId",
"completedDate",
"companyId",
- "id",
- "sortOrder"
+ "sortOrder",
+ "id"
]
},
{
"name": "nonConformancePurchaseReturnOrderLine",
"rows": 0,
"columns": [
- "purchaseReturnOrderReadableId",
- "companyId",
- "purchaseReturnOrderId",
- "purchaseReturnOrderLineId",
- "quantity",
- "updatedBy",
"id",
"createdBy",
- "updatedAt",
+ "updatedBy",
+ "quantity",
+ "nonConformanceId",
"createdAt",
- "nonConformanceId"
+ "updatedAt",
+ "purchaseReturnOrderReadableId",
+ "purchaseReturnOrderId",
+ "purchaseReturnOrderLineId",
+ "companyId"
]
},
{
"name": "nonConformanceSalesReturnOrderLine",
"rows": 0,
"columns": [
- "updatedBy",
- "createdBy",
- "nonConformanceId",
- "companyId",
"id",
"updatedAt",
- "createdAt",
+ "companyId",
+ "nonConformanceId",
+ "updatedBy",
+ "createdBy",
+ "salesReturnOrderReadableId",
"salesReturnOrderId",
"salesReturnOrderLineId",
- "salesReturnOrderReadableId"
+ "createdAt"
]
},
{
@@ -5439,150 +5439,150 @@
"name": "partner",
"rows": 0,
"columns": [
- "tags",
- "updatedAt",
- "id",
- "createdBy",
- "hoursPerWeek",
- "customFields",
- "updatedBy",
"companyId",
+ "createdAt",
"abilityId",
"active",
- "createdAt"
+ "createdBy",
+ "updatedAt",
+ "id",
+ "tags",
+ "updatedBy",
+ "customFields",
+ "hoursPerWeek"
]
},
{
"name": "payment",
"rows": 0,
"columns": [
- "postedAt",
- "reference",
- "paymentId",
"postingDate",
- "updatedAt",
"exchangeRate",
- "id",
- "currencyCode",
- "totalAmount",
+ "updatedAt",
+ "postedAt",
+ "paymentId",
+ "reference",
"supplierId",
"customFields",
- "status",
+ "currencyCode",
+ "id",
+ "totalAmount",
+ "paymentDate",
+ "updatedBy",
"memo",
"paymentType",
- "voidedBy",
+ "status",
"voidedAt",
- "updatedBy",
- "paymentDate",
+ "voidedBy",
+ "postedBy",
+ "journalId",
+ "createdBy",
"createdAt",
- "customerId",
- "companyId",
"bankAccount",
- "createdBy",
- "journalId",
- "postedBy"
+ "companyId",
+ "customerId"
]
},
{
"name": "purchaseInvoiceDelivery",
"rows": 0,
"columns": [
- "updatedBy",
- "shippingTermId",
- "shippingMethodId",
- "supplierShippingCost",
- "incoterm",
- "updatedAt",
- "locationId",
- "companyId",
- "incotermLocation",
+ "customFields",
"id",
- "customFields"
+ "incotermLocation",
+ "companyId",
+ "locationId",
+ "updatedAt",
+ "incoterm",
+ "supplierShippingCost",
+ "shippingMethodId",
+ "shippingTermId",
+ "updatedBy"
]
},
{
"name": "purchaseInvoiceStatusHistory",
"rows": 0,
- "columns": ["status", "id", "invoiceId", "companyId", "createdAt"]
+ "columns": ["createdAt", "companyId", "invoiceId", "id", "status"]
},
{
"name": "purchaseOrderDelivery",
"rows": 0,
"columns": [
+ "updatedAt",
+ "tags",
+ "receiptRequestedDate",
+ "customerLocationId",
+ "incotermLocation",
+ "deliveryDate",
"incoterm",
"supplierShippingCost",
- "shippingTermId",
"updatedBy",
"shippingMethodId",
- "deliveryDate",
- "receiptRequestedDate",
- "incotermLocation",
- "customerLocationId",
- "updatedAt",
- "tags",
- "companyId",
- "locationId",
- "customFields",
- "dropShipment",
- "notes",
+ "shippingTermId",
+ "receiptPromisedDate",
"customerId",
- "id",
"trackingNumber",
- "receiptPromisedDate"
+ "id",
+ "dropShipment",
+ "notes",
+ "companyId",
+ "locationId",
+ "customFields"
]
},
{
"name": "purchaseOrderFavorite",
"rows": 0,
- "columns": ["purchaseOrderId", "userId"]
+ "columns": ["userId", "purchaseOrderId"]
},
{
"name": "purchaseOrderLine",
"rows": 0,
"columns": [
- "createdBy",
- "requiredDate",
- "accountId",
- "supplierTaxAmount",
- "supplierPartId",
- "supplierShippingCost",
- "quantityReceived",
- "updatedBy",
- "purchaseQuantity",
- "id",
- "createdAt",
- "externalNotes",
- "receivedDate",
"conversionFactor",
- "description",
+ "receivedDate",
"tags",
+ "description",
+ "externalNotes",
+ "createdAt",
+ "purchaseUnitOfMeasureCode",
+ "purchaseOrderId",
+ "exchangeRate",
+ "jobId",
"ownerId",
- "modelUploadId",
"quantityInvoiced",
- "jobId",
- "exchangeRate",
- "purchaseOrderId",
- "purchaseUnitOfMeasureCode",
- "taxPercent",
- "quantityShipped",
- "inventoryUnitOfMeasureCode",
- "costCenterId",
- "invoicedComplete",
- "locationId",
- "updatedAt",
- "receivedComplete",
- "jobOperationId",
- "internalNotes",
- "assetId",
- "companyId",
+ "modelUploadId",
+ "supplierTaxAmount",
+ "accountId",
+ "supplierPartId",
+ "requiredDate",
+ "createdBy",
+ "purchaseQuantity",
+ "id",
+ "quantityReceived",
+ "updatedBy",
+ "supplierShippingCost",
"sortOrder",
"customFields",
- "setupPrice",
- "storageUnitId",
- "purchaseOrderLineType",
+ "assetId",
+ "companyId",
+ "internalNotes",
+ "promisedDate",
"supplierUnitPrice",
+ "purchaseOrderLineType",
"itemId",
- "promisedDate"
+ "storageUnitId",
+ "setupPrice",
+ "locationId",
+ "updatedAt",
+ "quantityShipped",
+ "taxPercent",
+ "invoicedComplete",
+ "costCenterId",
+ "inventoryUnitOfMeasureCode",
+ "jobOperationId",
+ "receivedComplete"
]
},
{
@@ -5590,54 +5590,54 @@
"rows": 0,
"columns": [
"companyId",
- "id",
"updatedAt",
- "createdBy",
+ "id",
"updatedBy",
+ "createdBy",
"nonConformanceId",
"purchaseOrderReadableId",
"createdAt",
- "purchaseOrderId",
- "purchaseOrderLineId"
+ "purchaseOrderLineId",
+ "purchaseOrderId"
]
},
{
"name": "purchaseOrderStatusHistory",
"rows": 0,
"columns": [
- "purchaseOrderId",
- "companyId",
- "id",
- "updatedBy",
+ "createdBy",
"createdAt",
"status",
- "createdBy"
+ "updatedBy",
+ "id",
+ "companyId",
+ "purchaseOrderId"
]
},
{
"name": "purchaseOrderTransaction",
"rows": 0,
"columns": [
- "purchaseOrderId",
"id",
"companyId",
+ "purchaseOrderId",
+ "createdAt",
"userId",
- "type",
- "createdAt"
+ "type"
]
},
{
"name": "purchaseReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "purchaseReturnOrderLineId",
"createdAt",
- "trackedEntityId",
+ "purchaseReturnOrderLineId",
"updatedAt",
+ "trackedEntityId",
"createdBy",
- "companyId",
+ "updatedBy",
"quantity",
- "updatedBy"
+ "companyId"
]
},
{
@@ -5656,17 +5656,23 @@
{
"name": "purchasingRfqToPurchaseOrder",
"rows": 0,
- "columns": ["companyId", "purchasingRfqId", "purchaseOrderId"]
+ "columns": ["purchasingRfqId", "purchaseOrderId", "companyId"]
},
{
"name": "purchasingRfqToSupplierQuote",
"rows": 0,
- "columns": ["companyId", "purchasingRfqId", "supplierQuoteId"]
+ "columns": ["purchasingRfqId", "supplierQuoteId", "companyId"]
},
{
"name": "quoteMakeMethod",
"rows": 0,
"columns": [
+ "parentMaterialId",
+ "quoteLineId",
+ "version",
+ "companyId",
+ "itemId",
+ "customFields",
"tags",
"quoteId",
"createdAt",
@@ -5674,159 +5680,153 @@
"id",
"createdBy",
"updatedBy",
- "quantityPerParent",
- "parentMaterialId",
- "quoteLineId",
- "version",
- "companyId",
- "itemId",
- "customFields"
+ "quantityPerParent"
]
},
{
"name": "quoteMaterial",
"rows": 0,
"columns": [
- "description",
- "id",
- "unitOfMeasureCode",
- "itemType",
- "kit",
- "updatedAt",
- "companyId",
- "quoteId",
- "order",
- "quantity",
- "unitCost",
- "quoteOperationId",
- "scrapQuantity",
- "createdBy",
- "updatedBy",
- "storageUnitId",
"quoteLineId",
"createdAt",
"itemId",
- "quoteMakeMethodId",
"customFields",
+ "quoteMakeMethodId",
+ "unitCostSource",
"methodType",
"tags",
- "unitCostSource"
+ "unitCost",
+ "quoteOperationId",
+ "updatedBy",
+ "storageUnitId",
+ "scrapQuantity",
+ "createdBy",
+ "updatedAt",
+ "quoteId",
+ "companyId",
+ "order",
+ "quantity",
+ "description",
+ "id",
+ "unitOfMeasureCode",
+ "itemType",
+ "kit"
]
},
{
"name": "quoteMaterialStep",
"rows": 0,
- "columns": ["quantity", "quoteOperationStepId", "quoteMaterialId"]
+ "columns": ["quoteMaterialId", "quoteOperationStepId", "quantity"]
},
{
"name": "quoteOperation",
"rows": 0,
"columns": [
- "setupUnit",
- "procedureId",
- "tags",
- "laborUnit",
- "id",
- "setupTime",
- "operationLeadTime",
- "machineRate",
- "description",
- "machineUnit",
- "inspectionDocumentId",
- "quoteId",
- "operationUnitCost",
- "companyId",
- "customFields",
- "overheadRate",
- "laborTime",
- "createdAt",
- "order",
- "updatedBy",
- "operationOrder",
- "operationType",
- "processId",
- "operationMinimumCost",
- "workInstruction",
- "workCenterId",
- "operationSupplierProcessId",
- "machineTime",
- "updatedAt",
- "createdBy",
- "assemblyInstructionId",
"quoteMakeMethodId",
+ "quoteLineId",
"laborRate",
- "quoteLineId"
+ "assemblyInstructionId",
+ "createdBy",
+ "updatedAt",
+ "machineTime",
+ "workCenterId",
+ "workInstruction",
+ "operationSupplierProcessId",
+ "operationMinimumCost",
+ "processId",
+ "updatedBy",
+ "operationType",
+ "operationOrder",
+ "order",
+ "laborTime",
+ "createdAt",
+ "overheadRate",
+ "customFields",
+ "companyId",
+ "operationUnitCost",
+ "quoteId",
+ "inspectionDocumentId",
+ "description",
+ "machineRate",
+ "machineUnit",
+ "operationLeadTime",
+ "setupTime",
+ "id",
+ "laborUnit",
+ "tags",
+ "procedureId",
+ "setupUnit"
]
},
{
"name": "quoteOperationParameter",
"rows": 0,
"columns": [
- "updatedAt",
- "key",
"createdAt",
- "id",
"updatedBy",
+ "id",
+ "updatedAt",
+ "key",
+ "companyId",
"createdBy",
- "operationId",
"value",
- "companyId"
+ "operationId"
]
},
{
"name": "quoteOperationStep",
"rows": 0,
"columns": [
- "unitOfMeasureCode",
- "description",
- "required",
- "createdAt",
- "updatedBy",
- "createdBy",
- "operationId",
- "sortOrder",
+ "type",
+ "fileTypes",
+ "id",
+ "maxValue",
"listValues",
"minValue",
"name",
"companyId",
"updatedAt",
- "type",
- "fileTypes",
- "id",
- "maxValue"
+ "updatedBy",
+ "createdBy",
+ "operationId",
+ "sortOrder",
+ "unitOfMeasureCode",
+ "description",
+ "required",
+ "createdAt"
]
},
{
"name": "quoteOperationStepSlide",
"rows": 0,
"columns": [
- "imagePath",
- "caption",
"createdBy",
+ "caption",
+ "imagePath",
"annotations",
"sortOrder",
- "stepId",
- "modelUploadId",
"updatedAt",
"createdAt",
+ "stepId",
+ "modelUploadId",
+ "companyId",
"size",
- "updatedBy",
"id",
- "companyId"
+ "updatedBy"
]
},
{
"name": "quoteOperationTool",
"rows": 0,
"columns": [
- "updatedAt",
"operationId",
- "createdAt",
+ "updatedAt",
"id",
"updatedBy",
- "createdBy",
+ "createdAt",
"quantity",
"toolId",
+ "createdBy",
"companyId"
]
},
@@ -5839,318 +5839,309 @@
"name": "receiptFixedAssetLine",
"rows": 0,
"columns": [
- "updatedAt",
- "id",
"companyId",
- "receiptId",
+ "id",
+ "updatedAt",
"createdAt",
"updatedBy",
+ "receiptId",
"serialNumber",
- "purchaseOrderLineId",
+ "createdBy",
"received",
- "createdBy"
+ "purchaseOrderLineId"
]
},
{
"name": "receiptLine",
"rows": 0,
"columns": [
+ "receiptId",
+ "companyId",
+ "updatedAt",
+ "storageUnitId",
+ "receivedQuantity",
+ "unitOfMeasure",
"id",
"locationId",
- "unitOfMeasure",
"orderQuantity",
- "updatedAt",
- "companyId",
- "receiptId",
- "receivedQuantity",
- "storageUnitId",
- "requiresBatchTracking",
- "unitPrice",
- "createdBy",
- "updatedBy",
+ "conversionFactor",
+ "requiresSerialTracking",
"itemId",
"createdAt",
"lineId",
- "requiresSerialTracking",
- "conversionFactor",
- "outstandingQuantity"
+ "outstandingQuantity",
+ "requiresBatchTracking",
+ "unitPrice",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "nonConformanceReceiptLine",
"rows": 0,
"columns": [
- "createdAt",
"receiptLineId",
"receiptId",
+ "createdAt",
"receiptReadableId",
- "createdBy",
- "updatedBy",
"nonConformanceId",
- "companyId",
+ "updatedBy",
+ "createdBy",
"updatedAt",
- "id"
+ "id",
+ "companyId"
]
},
{
"name": "salesInvoice",
"rows": 0,
"columns": [
+ "currencyCode",
+ "exchangeRate",
+ "companyId",
+ "totalDiscount",
+ "exchangeRateUpdatedAt",
+ "customerReference",
+ "createdAt",
+ "dateDue",
+ "opportunityId",
+ "invoiceCustomerLocationId",
+ "internalNotes",
+ "createdBy",
+ "customerId",
"locationId",
"status",
- "customerId",
"totalTax",
"totalAmount",
- "invoiceCustomerLocationId",
- "opportunityId",
- "internalNotes",
- "createdBy",
- "exchangeRateUpdatedAt",
- "customerReference",
- "dateDue",
- "createdAt",
- "exchangeRate",
- "currencyCode",
- "totalDiscount",
- "companyId",
- "subtotal",
- "datePaid",
- "invoiceId",
- "updatedBy",
- "externalNotes",
+ "invoiceCustomerId",
+ "assignee",
+ "id",
+ "paymentTermId",
+ "customFields",
+ "dateIssued",
"tags",
"invoiceCustomerContactId",
+ "externalNotes",
"shipmentId",
- "postingDate",
"updatedAt",
- "paymentTermId",
- "id",
- "dateIssued",
- "customFields",
- "invoiceCustomerId",
- "assignee"
+ "postingDate",
+ "subtotal",
+ "datePaid",
+ "invoiceId",
+ "updatedBy"
]
},
{
"name": "salesInvoiceLine",
"rows": 0,
"columns": [
- "methodType",
- "internalNotes",
- "id",
- "assetId",
+ "nonTaxableAddOnCost",
"opportunityId",
"unitOfMeasureCode",
- "nonTaxableAddOnCost",
- "customFields",
- "salesOrderLineId",
- "quantity",
- "createdBy",
- "externalNotes",
- "setupPrice",
+ "id",
+ "assetId",
+ "internalNotes",
+ "methodType",
+ "storageUnitId",
"updatedAt",
"invoiceId",
- "storageUnitId",
+ "setupPrice",
+ "externalNotes",
+ "createdBy",
+ "quantity",
+ "customFields",
+ "salesOrderLineId",
+ "itemId",
+ "companyId",
+ "locationId",
+ "unitPrice",
"modelUploadId",
"addOnCost",
- "unitPrice",
- "locationId",
- "companyId",
- "itemId",
- "salesOrderId",
- "accountId",
- "updatedBy",
- "createdAt",
+ "taxPercent",
+ "sortOrder",
+ "shippingCost",
"description",
"invoiceLineType",
"exchangeRate",
- "shippingCost",
- "sortOrder",
- "taxPercent"
+ "createdAt",
+ "accountId",
+ "updatedBy",
+ "salesOrderId"
]
},
{
"name": "salesInvoiceShipment",
"rows": 0,
"columns": [
- "companyId",
- "locationId",
- "shippingMethodId",
- "incoterm",
- "shippingTermId",
- "createdAt",
- "updatedAt",
"shippingCost",
"incotermLocation",
- "customFields",
+ "createdAt",
+ "updatedAt",
"createdBy",
"id",
- "updatedBy"
+ "updatedBy",
+ "customFields",
+ "locationId",
+ "shippingMethodId",
+ "companyId",
+ "incoterm",
+ "shippingTermId"
]
},
{
"name": "salesReturnOrderLine",
"rows": 0,
"columns": [
- "unitPrice",
- "returnReasonId",
- "companyId",
- "salesInvoiceLineId",
- "salesReturnOrderId",
- "quantityReceived",
- "restockFeePercent",
- "id",
- "salesOrderLineId",
"unitOfMeasureCode",
- "lineNumber",
- "disposition",
- "itemId",
- "updatedBy",
"createdAt",
+ "updatedBy",
+ "itemId",
+ "disposition",
+ "lineNumber",
+ "createdBy",
"customFields",
"closedComplete",
- "createdBy",
- "quantity",
+ "updatedAt",
"shipmentLineId",
- "updatedAt"
+ "quantity",
+ "returnReasonId",
+ "unitPrice",
+ "salesReturnOrderId",
+ "salesInvoiceLineId",
+ "companyId",
+ "quantityReceived",
+ "salesOrderLineId",
+ "id",
+ "restockFeePercent"
]
},
{
"name": "salesReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "updatedBy",
- "companyId",
"quantity",
+ "companyId",
+ "updatedBy",
"createdBy",
- "updatedAt",
"trackedEntityId",
- "createdAt",
- "salesReturnOrderLineId"
+ "updatedAt",
+ "salesReturnOrderLineId",
+ "createdAt"
]
},
{
"name": "salesReturnOrderCreditLine",
"rows": 0,
"columns": [
- "updatedBy",
- "createdBy",
- "memoId",
- "restockFee",
- "updatedAt",
- "id",
- "createdAt",
- "companyId",
- "quantity",
+ "unitPrice",
"salesReturnOrderLineId",
- "unitPrice"
+ "quantity",
+ "companyId",
+ "updatedAt",
+ "createdAt",
+ "id",
+ "restockFee",
+ "memoId",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "shipmentFixedAssetLine",
"rows": 0,
"columns": [
- "serialNumber",
"createdBy",
"salesOrderLineId",
"shipped",
+ "serialNumber",
+ "updatedBy",
+ "createdAt",
+ "shipmentId",
"companyId",
"updatedAt",
- "id",
- "createdAt",
- "updatedBy",
- "shipmentId"
+ "id"
]
},
{
"name": "shipmentLine",
"rows": 0,
"columns": [
- "shippedQuantity",
- "storageUnitId",
- "createdAt",
- "requiresSerialTracking",
- "shipmentId",
- "orderQuantity",
- "locationId",
- "id",
- "unitOfMeasure",
- "outstandingQuantity",
+ "fulfillmentId",
+ "unitPrice",
+ "companyId",
+ "createdBy",
+ "itemId",
"requiresBatchTracking",
"lineId",
- "itemId",
"updatedBy",
"updatedAt",
- "companyId",
- "createdBy",
- "unitPrice",
- "fulfillmentId"
+ "outstandingQuantity",
+ "id",
+ "locationId",
+ "unitOfMeasure",
+ "orderQuantity",
+ "createdAt",
+ "requiresSerialTracking",
+ "shipmentId",
+ "shippedQuantity",
+ "storageUnitId"
]
},
{
"name": "nonConformanceShipmentLine",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "nonConformanceId",
- "companyId",
- "id",
- "updatedAt",
- "createdAt",
- "shipmentId",
+ "shipmentReadableId",
"shipmentLineId",
- "shipmentReadableId"
+ "shipmentId",
+ "createdAt",
+ "updatedAt",
+ "id",
+ "companyId",
+ "nonConformanceId",
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "supplier",
"rows": 0,
"columns": [
- "embedding",
- "updatedAt",
+ "website",
+ "supplierTypeId",
+ "customFields",
+ "intercompanyCompanyId",
+ "purchasingContactId",
+ "logo",
"tags",
+ "updatedAt",
+ "embedding",
"fax",
"taxPercent",
"currencyCode",
- "customFields",
- "supplierTypeId",
- "website",
- "intercompanyCompanyId",
- "logo",
- "purchasingContactId",
- "companyId",
- "id",
- "createdBy",
- "supplierStatus",
- "accountManagerId",
- "defaultCc",
- "phone",
"name",
"updatedBy",
- "readableId",
+ "phone",
+ "createdAt",
"assignee",
- "createdAt"
+ "readableId",
+ "supplierStatus",
+ "createdBy",
+ "id",
+ "companyId",
+ "defaultCc",
+ "accountManagerId"
]
},
{
"name": "supplierAccount",
"rows": 0,
- "columns": ["supplierId", "id", "active", "companyId"]
+ "columns": ["active", "companyId", "id", "supplierId"]
},
{
"name": "supplierBankAccount",
"rows": 0,
"columns": [
- "id",
- "currencyCode",
- "bankCode",
- "bankName",
- "createdBy",
- "companyId",
- "isPrimary",
- "countryCode",
- "accountNumber",
"customFields",
"swiftBic",
"accountHolderName",
@@ -6162,208 +6153,202 @@
"supplierId",
"updatedBy",
"updatedAt",
- "bankAddress"
+ "bankAddress",
+ "id",
+ "currencyCode",
+ "bankCode",
+ "bankName",
+ "createdBy",
+ "companyId",
+ "isPrimary",
+ "countryCode",
+ "accountNumber"
]
},
{
"name": "supplierInteraction",
"rows": 0,
- "columns": ["companyId", "id", "supplierId"]
+ "columns": ["supplierId", "id", "companyId"]
},
{
"name": "receipt",
"rows": 0,
"columns": [
- "sourceDocument",
+ "supplierId",
+ "postingDate",
+ "updatedAt",
+ "companyId",
+ "receiptId",
+ "sourceDocumentReadableId",
+ "status",
+ "id",
+ "invoiced",
+ "externalDocumentId",
"createdAt",
"locationId",
+ "sourceDocument",
"tags",
"customFields",
- "externalDocumentId",
+ "createdBy",
+ "supplierInteractionId",
+ "updatedBy",
"postedBy",
"sourceDocumentId",
- "internalNotes",
"assignee",
- "supplierInteractionId",
- "createdBy",
- "updatedBy",
- "updatedAt",
- "companyId",
- "receiptId",
- "supplierId",
- "postingDate",
- "id",
- "status",
- "invoiced",
- "sourceDocumentReadableId"
+ "internalNotes"
]
},
{
"name": "shipment",
"rows": 0,
"columns": [
- "customerId",
- "id",
- "postingDate",
- "externalDocumentId",
- "sourceDocumentReadableId",
- "supplierId",
- "externalNotes",
- "invoiced",
- "shipmentId",
- "trackingNumber",
- "customFields",
- "status",
- "updatedBy",
- "sourceDocumentId",
- "postedBy",
- "createdBy",
- "internalNotes",
- "updatedAt",
- "opportunityId",
- "supplierInteractionId",
+ "shippingMethodId",
+ "tags",
"locationId",
"assignee",
"sourceDocument",
- "createdAt",
"companyId",
- "shippingMethodId",
- "tags"
+ "createdAt",
+ "opportunityId",
+ "supplierInteractionId",
+ "internalNotes",
+ "updatedAt",
+ "updatedBy",
+ "postedBy",
+ "createdBy",
+ "sourceDocumentId",
+ "trackingNumber",
+ "status",
+ "customFields",
+ "externalNotes",
+ "shipmentId",
+ "invoiced",
+ "sourceDocumentReadableId",
+ "supplierId",
+ "customerId",
+ "id",
+ "postingDate",
+ "externalDocumentId"
]
},
{
"name": "supplierLedger",
"rows": 0,
"columns": [
- "supplierId",
- "documentType",
- "postingDate",
"documentId",
- "amount",
- "createdAt",
- "entryNumber",
- "externalDocumentId",
+ "postingDate",
+ "documentType",
+ "supplierId",
+ "companyId",
"id",
- "companyId"
+ "externalDocumentId",
+ "entryNumber",
+ "amount",
+ "createdAt"
]
},
{
"name": "supplierLocation",
"rows": 0,
"columns": [
+ "name",
"customFields",
"addressId",
- "name",
- "companyId",
- "supplierId",
"tags",
- "id"
+ "id",
+ "companyId",
+ "supplierId"
]
},
{
"name": "supplierContact",
"rows": 0,
"columns": [
- "customFields",
"id",
- "companyId",
+ "customFields",
"supplierId",
+ "companyId",
"userId",
- "tags",
+ "supplierLocationId",
"contactId",
- "supplierLocationId"
+ "tags"
]
},
{
"name": "purchaseInvoice",
"rows": 0,
"columns": [
- "locationId",
- "customFields",
- "invoiceSupplierLocationId",
- "tags",
- "totalTax",
- "totalAmount",
- "supplierId",
- "dateDue",
- "assignee",
- "datePaid",
- "updatedBy",
- "totalDiscount",
- "supplierReference",
- "postingDate",
- "exchangeRateUpdatedAt",
- "companyId",
- "createdBy",
- "currencyCode",
- "internalNotes",
"invoiceSupplierContactId",
+ "internalNotes",
"supplierInteractionId",
+ "createdBy",
+ "currencyCode",
+ "subtotal",
"dateIssued",
- "invoiceId",
"status",
- "subtotal",
- "createdAt",
+ "invoiceId",
"invoiceSupplierId",
+ "createdAt",
+ "id",
+ "paymentTermId",
"updatedAt",
"exchangeRate",
- "id",
- "paymentTermId"
+ "customFields",
+ "invoiceSupplierLocationId",
+ "tags",
+ "locationId",
+ "supplierId",
+ "dateDue",
+ "totalTax",
+ "totalAmount",
+ "datePaid",
+ "assignee",
+ "updatedBy",
+ "totalDiscount",
+ "companyId",
+ "supplierReference",
+ "exchangeRateUpdatedAt",
+ "postingDate"
]
},
{
"name": "purchaseOrder",
"rows": 0,
"columns": [
- "status",
- "updatedBy",
- "assignee",
- "exchangeRate",
"currencyCode",
"closedBy",
- "externalNotes",
"createdAt",
+ "externalNotes",
+ "status",
+ "assignee",
+ "updatedBy",
+ "exchangeRate",
+ "exchangeRateUpdatedAt",
+ "purchaseOrderType",
"updatedAt",
"createdBy",
- "closedAt",
"revisionId",
- "exchangeRateUpdatedAt",
- "purchaseOrderType",
- "supplierInteractionId",
- "supplierReference",
- "id",
- "supplierLocationId",
+ "closedAt",
"internalNotes",
"orderDate",
- "companyId",
- "purchaseOrderId",
- "customFields",
+ "supplierReference",
+ "supplierInteractionId",
+ "supplierLocationId",
+ "id",
"tags",
"supplierContactId",
- "jobReadableId",
+ "jobId",
"supplierId",
- "jobId"
+ "jobReadableId",
+ "companyId",
+ "purchaseOrderId",
+ "customFields"
]
},
{
"name": "purchaseInvoiceLine",
"rows": 0,
"columns": [
- "jobOperationId",
- "ownerId",
- "customFields",
- "accountId",
- "supplierUnitPrice",
- "companyId",
- "taxPercent",
- "createdBy",
- "assetId",
- "purchaseUnitOfMeasureCode",
- "purchaseOrderLineId",
- "tags",
- "modelUploadId",
- "supplierTaxAmount",
- "createdAt",
"costCenterId",
"invoiceLineType",
"quantity",
@@ -6371,35 +6356,50 @@
"exchangeRate",
"sortOrder",
"inventoryUnitOfMeasureCode",
- "itemId",
- "updatedAt",
- "locationId",
- "id",
- "conversionFactor",
+ "tags",
+ "modelUploadId",
+ "createdAt",
+ "supplierTaxAmount",
+ "taxPercent",
+ "createdBy",
+ "assetId",
+ "purchaseUnitOfMeasureCode",
+ "purchaseOrderLineId",
+ "jobOperationId",
+ "ownerId",
+ "customFields",
+ "accountId",
+ "supplierUnitPrice",
+ "companyId",
+ "requiredDate",
+ "invoiceId",
+ "projectId",
+ "description",
"internalNotes",
"serviceId",
"supplierShippingCost",
"storageUnitId",
"updatedBy",
- "requiredDate",
- "invoiceId",
- "projectId",
- "description"
+ "locationId",
+ "id",
+ "conversionFactor",
+ "itemId",
+ "updatedAt"
]
},
{
"name": "purchaseInvoicePriceChange",
"rows": 0,
"columns": [
+ "updatedBy",
+ "invoiceId",
+ "previousQuantity",
"companyId",
"id",
- "previousQuantity",
- "invoiceId",
- "updatedBy",
- "newPrice",
+ "newQuantity",
"invoiceLineId",
"previousPrice",
- "newQuantity"
+ "newPrice"
]
},
{
@@ -6408,186 +6408,186 @@
"columns": [
"invoiceSupplierLocationId",
"invoiceSupplierContactId",
- "tags",
"paymentTermId",
- "companyId",
- "updatedBy",
+ "tags",
"invoiceSupplierId",
- "paymentComplete",
+ "updatedBy",
+ "companyId",
+ "customFields",
"updatedAt",
"id",
- "customFields"
+ "paymentComplete"
]
},
{
"name": "purchaseReturnOrder",
"rows": 0,
"columns": [
- "replacementPurchaseOrderId",
- "locationId",
"orderDate",
"purchaseReturnOrderId",
"externalNotes",
- "supplierContactId",
+ "replacementPurchaseOrderId",
+ "locationId",
"currencyCode",
- "purchaseOrderId",
"id",
- "supplierReference",
- "customFields",
+ "purchaseOrderId",
+ "supplierContactId",
"createdBy",
"companyId",
- "status",
- "expirationDate",
"supplierId",
- "updatedBy",
- "internalNotes",
- "assignee",
+ "expirationDate",
+ "status",
+ "customFields",
+ "supplierReference",
"supplierLocationId",
- "exchangeRate",
"createdAt",
- "updatedAt"
+ "exchangeRate",
+ "updatedAt",
+ "internalNotes",
+ "updatedBy",
+ "assignee"
]
},
{
"name": "memo",
"rows": 0,
"columns": [
- "postedAt",
- "memoId",
- "reference",
- "postingDate",
- "exchangeRate",
- "updatedAt",
- "currencyCode",
- "id",
- "amount",
- "purchaseReturnOrderId",
- "supplierId",
- "customFields",
- "direction",
- "notes",
- "status",
- "voidedAt",
"voidedBy",
- "memoDate",
+ "voidedAt",
+ "status",
+ "notes",
+ "direction",
"updatedBy",
- "createdAt",
- "reasonAccount",
- "companyId",
+ "memoDate",
"customerId",
- "postedBy",
- "salesReturnOrderId",
+ "companyId",
+ "reasonAccount",
+ "createdAt",
"journalId",
- "createdBy"
+ "createdBy",
+ "salesReturnOrderId",
+ "postedBy",
+ "reference",
+ "memoId",
+ "postedAt",
+ "updatedAt",
+ "exchangeRate",
+ "postingDate",
+ "purchaseReturnOrderId",
+ "amount",
+ "id",
+ "currencyCode",
+ "customFields",
+ "supplierId"
]
},
{
"name": "invoiceSettlement",
"rows": 0,
"columns": [
- "targetExchangeRate",
- "id",
- "writeOffAmount",
- "targetMemoId",
+ "discountAmount",
+ "sourceExchangeRate",
+ "createdAt",
"appliedDate",
"paymentId",
- "createdAt",
- "sourceExchangeRate",
- "discountAmount",
- "targetPurchaseInvoiceId",
- "sourceAmount",
- "fxGainLossAmount",
- "createdBy",
- "appliedViaPaymentId",
- "sourcePaymentId",
- "updatedBy",
+ "targetMemoId",
+ "id",
+ "writeOffAmount",
+ "targetExchangeRate",
+ "appliedAmount",
"targetSalesInvoiceId",
- "memoId",
"companyId",
- "appliedAmount"
+ "memoId",
+ "sourcePaymentId",
+ "updatedBy",
+ "createdBy",
+ "appliedViaPaymentId",
+ "targetPurchaseInvoiceId",
+ "sourceAmount",
+ "fxGainLossAmount"
]
},
{
"name": "purchaseReturnOrderLine",
"rows": 0,
"columns": [
+ "returnReasonId",
+ "unitPrice",
+ "purchaseInvoiceLineId",
+ "purchaseReturnOrderId",
+ "createdBy",
+ "quantityShipped",
+ "purchaseOrderLineId",
+ "restockFeePercent",
+ "id",
"unitOfMeasureCode",
"updatedAt",
"updatedBy",
- "lineNumber",
"closedComplete",
+ "lineNumber",
"itemId",
"companyId",
"createdAt",
"quantity",
"receiptLineId",
- "customFields",
- "returnReasonId",
- "unitPrice",
- "purchaseInvoiceLineId",
- "purchaseReturnOrderId",
- "createdBy",
- "quantityShipped",
- "purchaseOrderLineId",
- "restockFeePercent",
- "id"
+ "customFields"
]
},
{
"name": "purchaseReturnOrderCreditLine",
"rows": 0,
"columns": [
- "updatedBy",
- "createdBy",
- "memoId",
+ "unitPrice",
+ "companyId",
+ "purchaseReturnOrderLineId",
+ "quantity",
"restockFee",
"updatedAt",
- "id",
"createdAt",
- "companyId",
- "quantity",
- "purchaseReturnOrderLineId",
- "unitPrice"
+ "id",
+ "updatedBy",
+ "createdBy",
+ "memoId"
]
},
{
"name": "supplierPart",
"rows": 0,
"columns": [
- "active",
- "createdBy",
- "tags",
- "updatedAt",
- "itemId",
- "minimumOrderQuantity",
- "id",
- "companyId",
- "createdAt",
- "conversionFactor",
- "supplierPartId",
"supplierId",
"customFields",
+ "supplierPartId",
+ "conversionFactor",
+ "supplierUnitOfMeasureCode",
+ "updatedBy",
"unitPrice",
"orderMultiple",
- "supplierUnitOfMeasureCode",
- "updatedBy"
+ "tags",
+ "updatedAt",
+ "itemId",
+ "active",
+ "createdBy",
+ "companyId",
+ "id",
+ "createdAt",
+ "minimumOrderQuantity"
]
},
{
"name": "supplierPartPrice",
"rows": 0,
"columns": [
- "quantity",
- "updatedAt",
- "createdAt",
+ "sourceDocumentId",
+ "createdBy",
+ "sourceType",
+ "unitPrice",
+ "companyId",
"leadTime",
- "updatedBy",
"supplierPartId",
- "companyId",
- "unitPrice",
- "sourceType",
- "createdBy",
- "sourceDocumentId"
+ "updatedBy",
+ "updatedAt",
+ "createdAt",
+ "quantity"
]
},
{
@@ -6595,258 +6595,258 @@
"rows": 0,
"columns": [
"paymentTermId",
- "companyId",
"invoiceSupplierContactId",
"invoiceSupplierLocationId",
+ "companyId",
"supplierId",
"updatedBy",
"tags",
+ "invoiceSupplierId",
"updatedAt",
- "customFields",
- "invoiceSupplierId"
+ "customFields"
]
},
{
"name": "supplierProcess",
"rows": 0,
"columns": [
+ "supplierId",
+ "tags",
+ "createdAt",
+ "customFields",
"updatedBy",
"createdBy",
"id",
"leadTime",
- "tags",
- "supplierId",
- "createdAt",
- "customFields",
- "updatedAt",
"processId",
"minimumCost",
- "companyId"
+ "companyId",
+ "updatedAt"
]
},
{
"name": "supplierQuote",
"rows": 0,
"columns": [
- "companyId",
- "externalLinkId",
- "exchangeRate",
- "createdBy",
- "supplierReference",
- "createdAt",
- "expirationDate",
- "updatedAt",
- "internalNotes",
- "updatedBy",
- "customFields",
"tags",
+ "customFields",
+ "quotedDate",
"currencyCode",
"revisionId",
- "quotedDate",
- "supplierQuoteType",
- "status",
- "supplierContactId",
- "supplierId",
- "id",
- "supplierLocationId",
+ "updatedBy",
+ "internalNotes",
+ "expirationDate",
+ "createdAt",
+ "supplierReference",
+ "updatedAt",
+ "createdBy",
+ "exchangeRate",
+ "externalLinkId",
+ "companyId",
+ "assignee",
+ "supplierQuoteId",
+ "exchangeRateUpdatedAt",
"supplierInteractionId",
+ "supplierLocationId",
"externalNotes",
- "supplierQuoteId",
- "assignee",
- "exchangeRateUpdatedAt"
+ "supplierContactId",
+ "id",
+ "supplierId",
+ "supplierQuoteType",
+ "status"
]
},
{
"name": "supplierQuoteFavorite",
"rows": 0,
- "columns": ["supplierQuoteId", "userId"]
+ "columns": ["userId", "supplierQuoteId"]
},
{
"name": "supplierQuoteLine",
"rows": 0,
"columns": [
- "id",
- "supplierPartRevision",
- "ownerId",
"purchaseUnitOfMeasureCode",
+ "ownerId",
+ "supplierPartRevision",
+ "id",
"supplierQuoteLineType",
- "createdBy",
"supplierQuoteId",
- "supplierPartId",
- "accountId",
+ "createdBy",
"inventoryUnitOfMeasureCode",
- "externalNotes",
- "itemId",
- "tags",
+ "accountId",
+ "supplierPartId",
"conversionFactor",
- "companyId",
- "internalNotes",
- "requiredDate",
+ "tags",
+ "itemId",
+ "externalNotes",
"updatedAt",
- "quantity",
- "supplierQuoteRevisionId",
- "customFields",
+ "requiredDate",
+ "internalNotes",
+ "companyId",
"updatedBy",
- "costCenterId",
+ "customFields",
+ "supplierQuoteRevisionId",
+ "quantity",
+ "sortOrder",
"description",
- "sortOrder"
+ "costCenterId"
]
},
{
"name": "supplierQuoteLinePrice",
"rows": 0,
"columns": [
- "updatedAt",
- "quantity",
"leadTime",
- "updatedBy",
- "supplierUnitPrice",
+ "quantity",
+ "updatedAt",
"createdAt",
- "companyId",
- "supplierShippingCost",
- "supplierTaxAmount",
- "createdBy",
+ "supplierUnitPrice",
+ "updatedBy",
"supplierQuoteLineId",
- "exchangeRate",
+ "createdBy",
+ "supplierTaxAmount",
+ "supplierShippingCost",
+ "companyId",
+ "taxPercent",
"supplierQuoteId",
- "taxPercent"
+ "exchangeRate"
]
},
{
"name": "supplierShipping",
"rows": 0,
"columns": [
- "shippingSupplierId",
- "incotermLocation",
- "customFields",
- "updatedAt",
- "tags",
- "updatedBy",
"supplierId",
+ "updatedBy",
+ "tags",
"shippingMethodId",
- "shippingSupplierLocationId",
- "shippingSupplierContactId",
- "companyId",
+ "incotermLocation",
+ "shippingSupplierId",
+ "updatedAt",
+ "customFields",
+ "shippingTermId",
"incoterm",
- "shippingTermId"
+ "shippingSupplierContactId",
+ "shippingSupplierLocationId",
+ "companyId"
]
},
{
"name": "supplierTax",
"rows": 0,
"columns": [
- "taxExempt",
- "taxExemptionCertificateNumber",
- "eori",
- "vatNumber",
"taxExemptionReason",
+ "updatedBy",
"supplierId",
"companyId",
- "updatedBy",
- "taxExemptionCertificatePath",
"updatedAt",
- "taxId"
+ "taxExemptionCertificatePath",
+ "taxId",
+ "taxExempt",
+ "taxExemptionCertificateNumber",
+ "eori",
+ "vatNumber"
]
},
{
"name": "workflow",
"rows": 0,
"columns": [
+ "companyId",
+ "updatedAt",
"nextRunAt",
"createdBy",
- "updatedAt",
- "companyId",
- "id",
"canvasState",
+ "id",
"createdAt",
- "publishedVersionId",
- "description",
"name",
- "ownerId",
- "updatedBy"
+ "description",
+ "publishedVersionId",
+ "updatedBy",
+ "ownerId"
]
},
{
"name": "workflowVersion",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "companyId",
- "nodes",
- "id",
- "createdAt",
- "updatedAt",
+ "formatVersion",
"edges",
- "versionNumber",
"workflowId",
- "formatVersion"
+ "versionNumber",
+ "nodes",
+ "updatedAt",
+ "createdAt",
+ "id",
+ "updatedBy",
+ "createdBy",
+ "companyId"
]
},
{
"name": "workflowRun",
"rows": 0,
"columns": [
- "path",
- "rootRunId",
- "companyId",
- "triggerRecordId",
- "status",
- "ownerId",
- "id",
- "statusReason",
- "sourceEventId",
+ "workflowVersionId",
"workflowId",
"causedByRunId",
- "workflowVersionId",
- "durationMs",
"completedAt",
+ "durationMs",
"triggerTable",
"createdAt",
- "eventId",
- "isTest",
"error",
- "compactedAt",
+ "isTest",
+ "eventId",
+ "startedAt",
"depth",
- "startedAt"
+ "compactedAt",
+ "path",
+ "companyId",
+ "rootRunId",
+ "triggerRecordId",
+ "status",
+ "id",
+ "ownerId",
+ "statusReason",
+ "sourceEventId"
]
},
{
"name": "workflowStepRun",
"rows": 0,
"columns": [
- "output",
- "id",
- "statusReason",
- "nodeType",
- "startedAt",
- "companyId",
- "error",
- "input",
- "status",
- "nodeId",
+ "completedAt",
+ "runId",
+ "sequence",
+ "createdAt",
+ "detail",
+ "itemKey",
"branchTaken",
- "durationMs",
+ "nodeId",
"compactedAt",
- "detail",
- "createdAt",
- "sequence",
- "runId",
- "completedAt",
- "itemKey"
+ "durationMs",
+ "error",
+ "companyId",
+ "startedAt",
+ "status",
+ "input",
+ "statusReason",
+ "id",
+ "output",
+ "nodeType"
]
},
{
"name": "workflowTriggerEvent",
"rows": 0,
"columns": [
- "origin",
"id",
+ "origin",
"companyId",
"eventId",
- "createdAt",
"workflowId",
- "workflowVersionId"
+ "workflowVersionId",
+ "createdAt"
]
}
],
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index cf460b4068..8f3f3c6733 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -1,8 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import {
NODE_ENV,
- SUPABASE_ANON_KEY,
SUPABASE_INTERNAL_URL,
+ SUPABASE_SERVICE_ROLE_KEY,
VERCEL_URL
} from "@carbon/env";
import { storage } from "@carbon/files";
@@ -67,7 +67,7 @@ export const modelThumbnailFunction = inngest.createFunction(
method: "POST",
headers: {
"Content-Type": "application/json",
- Authorization: `Bearer ${SUPABASE_ANON_KEY}`
+ Authorization: `Bearer ${SUPABASE_SERVICE_ROLE_KEY}`
},
body: JSON.stringify({ url })
});