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.

fix: onshape sync overwriting make method versions that are active

Brad Barbin7c05522b4150
diff --git a/onshape-sync-overview.md b/onshape-sync-overview.md
new file mode 100644
index 0000000000..db63a3e886
--- /dev/null
+++ b/onshape-sync-overview.md
@@ -0,0 +1,110 @@
+# Onshape Part Sync Overview
+
+The sync process happens in two main phases: **fetching BOM data** and **syncing to the database**.
+
+## Phase 1: Fetching BOM Data (BOM Route)
+
+**File:** `apps/erp/app/routes/api+/integrations.onshape.d.$did.v.$vid.e.$eid.bom.ts`
+
+1. Calls the Onshape API to get the Bill of Materials for a document/version/element
+2. Transforms raw BOM rows into structured objects with headers as keys
+3. **Looks up existing items** by building unique part numbers using `readableIdWithRevision` (part number + revision, e.g., "WIDGET-001-A")
+4. Queries the `item` table to find matches:
+ ```typescript
+ client.from("item")
+ .select("id, readableId, readableIdWithRevision, defaultMethodType, replenishmentSystem")
+ .in("readableIdWithRevision", Array.from(uniquePartNumbers))
+ ```
+5. For each row, attaches:
+ - `id`: The existing Carbon item ID if found, otherwise `undefined`
+ - Preserves existing `replenishmentSystem` and `defaultMethodType` if the item exists
+ - Falls back to Onshape's "Purchasing Level" field for new items ("Purchased" → Buy/Pick, otherwise → Make)
+
+## Phase 2: Syncing to Database (Edge Function)
+
+**File:** `packages/database/supabase/functions/sync/index.ts`
+
+The sync function processes BOM data in a **transaction** and handles existing vs new parts differently:
+
+### When an Existing Part is Synced (has `id`)
+
+```typescript
+if (itemId) {
+ // Update existing item with Onshape data
+ await trx
+ .updateTable("item")
+ .set({
+ externalId: { onshapeData: data.data },
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ })
+ .where("id", "=", itemId)
+ .execute();
+}
+```
+
+**What happens:**
+- The item record is **updated** (not replaced) with the Onshape metadata stored in `externalId.onshapeData`
+- The `updatedBy` and `updatedAt` fields are updated
+- **No other fields are changed** — the item's name, readableId, revision, replenishment system, etc. are preserved
+
+### When a New Part is Synced (no `id`)
+
+```typescript
+// Create new item and part
+const item = await trx.insertInto("item").values({
+ readableId: partId,
+ revision: revision ?? "0",
+ name,
+ type: "Part",
+ unitOfMeasureCode: "EA",
+ itemTrackingType: "Inventory",
+ replenishmentSystem,
+ defaultMethodType,
+ companyId,
+ externalId: { onshapeData: data.data },
+ createdBy: userId,
+});
+
+// Create or update the part record
+await trx.insertInto("part").values({ id: partId, companyId, createdBy: userId })
+ .onConflict((oc) => oc.columns(["id", "companyId"]).doUpdateSet({
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ }));
+```
+
+**What happens:**
+- A new `item` record is created
+- A new `part` record is created (or updated if the part ID already exists)
+- The item is tracked in a `newlyCreatedItemsByPartId` map to prevent duplicates within the same sync
+
+## Additional Processing (Both Cases)
+
+For all items (new or existing):
+
+1. **Method Materials are deleted and recreated**: The function first deletes all existing `methodMaterial` entries for the parent make method, then recreates them with the synced data:
+ ```typescript
+ await trx.deleteFrom("methodMaterial").where("makeMethodId", "=", makeMethodId).execute();
+ ```
+
+2. **Make Methods are created if needed**: If an item has children (sub-assemblies) or `defaultMethodType === "Make"`, a `makeMethod` is created (or looked up if it exists)
+
+3. **Tree traversal**: The BOM is processed as a tree using dotted index notation (e.g., "1", "1.1", "1.1.1"), ensuring parents are processed before children
+
+## After Sync Completes
+
+The API route (`integrations.onshape.sync.ts:76-92`) updates the parent item's `externalId` with sync metadata:
+
+```typescript
+currentExternalId["onshape"] = {
+ documentId,
+ versionId,
+ elementId,
+ lastSyncedAt: new Date().toISOString()
+};
+```
+
+## Key Takeaway
+
+**Existing parts preserve their core data** (readableId, revision, name, replenishmentSystem, defaultMethodType) — only the `externalId.onshapeData` metadata is updated. The method materials (BOM relationships) are fully recreated to match the current Onshape structure.
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
index 4de2918863..9bd4f14d0f 100644
--- a/packages/database/supabase/functions/sync/index.ts
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -1,4 +1,5 @@
import { serve } from "https://deno.land/[email protected]/http/server.ts";
+import { Transaction } from "npm:kysely";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
import z from "npm:zod@^3.24.1";
@@ -31,6 +32,138 @@ const payloadValidator = z.discriminatedUnion("type", [
}),
]);
+interface MakeMethodInfo {
+ id: string;
+ itemId: string;
+ version: number;
+ status: "Draft" | "Active" | "Archived";
+}
+
+async function copyMakeMethodOperations(
+ trx: Transaction<DB>,
+ sourceMakeMethodId: string,
+ targetMakeMethodId: string,
+ companyId: string,
+ userId: string
+) {
+ // Fetch source operations
+ const sourceOperations = await trx
+ .selectFrom("methodOperation")
+ .selectAll()
+ .where("makeMethodId", "=", sourceMakeMethodId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ if (sourceOperations.length === 0) return;
+
+ // Insert operations and copy related records
+ for (const operation of sourceOperations) {
+ const {
+ id: oldOpId,
+ createdAt: _createdAt,
+ updatedAt: _updatedAt,
+ updatedBy: _updatedBy,
+ ...opData
+ } = operation;
+
+ const newOperation = await trx
+ .insertInto("methodOperation")
+ .values({
+ ...opData,
+ makeMethodId: targetMakeMethodId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (!newOperation) continue;
+
+ // Copy tools
+ const tools = await trx
+ .selectFrom("methodOperationTool")
+ .selectAll()
+ .where("operationId", "=", oldOpId)
+ .execute();
+
+ if (tools.length > 0) {
+ await trx
+ .insertInto("methodOperationTool")
+ .values(
+ tools.map(
+ ({
+ id: _id,
+ createdAt: _createdAt,
+ updatedAt: _updatedAt,
+ updatedBy: _updatedBy,
+ ...tool
+ }) => ({
+ ...tool,
+ operationId: newOperation.id,
+ createdBy: userId,
+ })
+ )
+ )
+ .execute();
+ }
+
+ // Copy parameters
+ const parameters = await trx
+ .selectFrom("methodOperationParameter")
+ .selectAll()
+ .where("operationId", "=", oldOpId)
+ .execute();
+
+ if (parameters.length > 0) {
+ await trx
+ .insertInto("methodOperationParameter")
+ .values(
+ parameters.map(
+ ({
+ id: _id,
+ createdAt: _createdAt,
+ updatedAt: _updatedAt,
+ updatedBy: _updatedBy,
+ ...param
+ }) => ({
+ ...param,
+ operationId: newOperation.id,
+ createdBy: userId,
+ })
+ )
+ )
+ .execute();
+ }
+
+ // Copy steps
+ const steps = await trx
+ .selectFrom("methodOperationStep")
+ .selectAll()
+ .where("operationId", "=", oldOpId)
+ .execute();
+
+ if (steps.length > 0) {
+ await trx
+ .insertInto("methodOperationStep")
+ .values(
+ steps.map(
+ ({
+ id: _id,
+ createdAt: _createdAt,
+ updatedAt: _updatedAt,
+ updatedBy: _updatedBy,
+ ...step
+ }) => ({
+ ...step,
+ operationId: newOperation.id,
+ createdBy: userId,
+ })
+ )
+ )
+ .execute();
+ }
+ }
+}
+
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
@@ -57,14 +190,80 @@ serve(async (req: Request) => {
req.headers.get("carbon-key") ?? ""
);
+ // Check if top-level make method is Active and find or create a Draft
+ const topLevelMakeMethod = await client
+ .from("makeMethod")
+ .select("id, itemId, version, status")
+ .eq("id", makeMethodId)
+ .single();
+
+ let activeMakeMethodId = makeMethodId;
+ let topLevelSourceMakeMethodId: string | null = null;
+
+ if (topLevelMakeMethod.data?.status === "Active") {
+ // Check if there's already a Draft version we can use
+ const existingDraft = await client
+ .from("makeMethod")
+ .select("id, version")
+ .eq("itemId", topLevelMakeMethod.data.itemId)
+ .eq("status", "Draft")
+ .eq("companyId", companyId)
+ .order("version", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ if (existingDraft.data) {
+ // Use the existing Draft
+ activeMakeMethodId = existingDraft.data.id;
+ } else {
+ // Get max version across ALL make methods for this item
+ const allVersions = await client
+ .from("makeMethod")
+ .select("version")
+ .eq("itemId", topLevelMakeMethod.data.itemId)
+ .eq("companyId", companyId)
+ .order("version", { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ const maxVersion = Number(allVersions.data?.version ?? 0);
+ const newVersion = maxVersion + 1;
+
+ console.log({
+ function: "sync",
+ action: "creating_top_level_draft",
+ itemId: topLevelMakeMethod.data.itemId,
+ maxVersion,
+ newVersion,
+ });
+
+ const newTopLevelMakeMethod = await client
+ .from("makeMethod")
+ .insert({
+ itemId: topLevelMakeMethod.data.itemId,
+ version: newVersion,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ })
+ .select("id")
+ .single();
+
+ if (newTopLevelMakeMethod.data) {
+ activeMakeMethodId = newTopLevelMakeMethod.data.id;
+ topLevelSourceMakeMethodId = makeMethodId;
+ }
+ }
+ }
+
const existingItemIds = new Set(
data.map((item: { id?: string }) => item.id).filter(Boolean)
);
const [existingMakeMethods, existingItems] = await Promise.all([
client
- .from("makeMethod")
- .select("id, itemId")
+ .from("activeMakeMethods")
+ .select("id, itemId, version, status")
.eq("companyId", companyId)
.in("itemId", Array.from(existingItemIds)),
client
@@ -76,10 +275,22 @@ serve(async (req: Request) => {
.in("id", Array.from(existingItemIds)),
]);
- const existingMakeMethodIdsByItemId = new Map(
+ console.log({
+ function: "sync",
+ action: "fetched_active_make_methods",
+ count: existingMakeMethods.data?.length ?? 0,
+ data: existingMakeMethods.data,
+ });
+
+ const existingMakeMethodsByItemId = new Map<string, MakeMethodInfo>(
existingMakeMethods.data?.map((makeMethod) => [
- makeMethod.itemId,
- makeMethod.id,
+ makeMethod.itemId!,
+ {
+ id: makeMethod.id!,
+ itemId: makeMethod.itemId!,
+ version: Number(makeMethod.version),
+ status: makeMethod.status as "Draft" | "Active" | "Archived",
+ },
]) ?? []
);
@@ -149,15 +360,26 @@ serve(async (req: Request) => {
const tree = buildTree(sortedData);
- await db.transaction().execute(async (trx) => {
+ await db.transaction().execute(async (trx: Transaction<DB>) => {
+ // If we created a new draft for the top-level, copy operations from the active version
+ if (topLevelSourceMakeMethodId) {
+ await copyMakeMethodOperations(
+ trx,
+ topLevelSourceMakeMethodId,
+ activeMakeMethodId,
+ companyId,
+ userId
+ );
+ }
+
await trx
.deleteFrom("methodMaterial")
- .where("makeMethodId", "=", makeMethodId)
+ .where("makeMethodId", "=", activeMakeMethodId)
.execute();
// Track newly created items and make methods to avoid duplicate inserts
const newlyCreatedItemsByPartId = new Map<string, string>();
- const newlyCreatedMakeMethodsByItemId = new Map<string, string>();
+ const newlyCreatedMakeMethodsByItemId = new Map<string, MakeMethodInfo>();
async function traverseTree(
node: TreeNode,
@@ -258,48 +480,160 @@ serve(async (req: Request) => {
if (!itemId) throw new Error("Failed to create item");
- let materialMakeMethodId =
- existingMakeMethodIdsByItemId.get(itemId) ||
+ let materialMakeMethodId: string | undefined;
+ const existingMakeMethod =
+ existingMakeMethodsByItemId.get(itemId) ||
newlyCreatedMakeMethodsByItemId.get(itemId);
- if (
- (defaultMethodType === "Make" || isMade) &&
- !materialMakeMethodId
- ) {
- const makeMethod = await trx
- .selectFrom("makeMethod")
- .select(["id"])
- .where("itemId", "=", itemId)
- .executeTakeFirst();
-
- materialMakeMethodId = makeMethod?.id;
-
- if (
- !materialMakeMethodId &&
- (defaultMethodType === "Make" || isMade)
- ) {
- // Create a new make method if needed
- const newMakeMethod = await trx
- .insertInto("makeMethod")
- .values({
+ console.log({
+ function: "sync",
+ action: "processing_item",
+ itemId,
+ partId,
+ isMade,
+ defaultMethodType,
+ existingMakeMethod: existingMakeMethod ?? null,
+ });
+
+ if (defaultMethodType === "Make" || isMade) {
+ if (existingMakeMethod) {
+ if (existingMakeMethod.status === "Draft") {
+ // Draft - use existing make method directly
+ materialMakeMethodId = existingMakeMethod.id;
+ } else {
+ // Active - check if there's already a Draft we can use
+ const existingDraft = await trx
+ .selectFrom("makeMethod")
+ .select(["id", "version"])
+ .where("itemId", "=", itemId)
+ .where("status", "=", "Draft")
+ .where("companyId", "=", companyId)
+ .orderBy("version", "desc")
+ .executeTakeFirst();
+
+ console.log({
+ function: "sync",
+ action: "check_existing_draft",
itemId,
companyId,
- createdBy: userId,
- })
- .returning(["id"])
- .executeTakeFirst();
+ existingDraft: existingDraft ?? null,
+ });
- materialMakeMethodId = newMakeMethod?.id;
+ if (existingDraft) {
+ // Use the existing Draft
+ materialMakeMethodId = existingDraft.id;
+ const makeMethodInfo: MakeMethodInfo = {
+ id: existingDraft.id,
+ itemId,
+ version: Number(existingDraft.version),
+ status: "Draft",
+ };
+ newlyCreatedMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ } else {
+ // Get max version across ALL make methods for this item
+ const maxVersionRow = await trx
+ .selectFrom("makeMethod")
+ .select(["version"])
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .orderBy("version", "desc")
+ .executeTakeFirst();
+
+ const maxVersion = Number(maxVersionRow?.version ?? 0);
+ const newVersion = maxVersion + 1;
+
+ console.log({
+ function: "sync",
+ action: "creating_child_draft",
+ itemId,
+ companyId,
+ maxVersionRow: maxVersionRow ?? null,
+ maxVersion,
+ newVersion,
+ });
+
+ const newMakeMethod = await trx
+ .insertInto("makeMethod")
+ .values({
+ itemId,
+ version: newVersion,
+ status: "Draft",
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (newMakeMethod) {
+ materialMakeMethodId = newMakeMethod.id;
+
+ // Copy operations from active version to new draft
+ await copyMakeMethodOperations(
+ trx,
+ existingMakeMethod.id,
+ newMakeMethod.id,
+ companyId,
+ userId
+ );
+
+ // Update tracking maps
+ const newMakeMethodInfo: MakeMethodInfo = {
+ id: newMakeMethod.id,
+ itemId,
+ version: newVersion,
+ status: "Draft",
+ };
+ newlyCreatedMakeMethodsByItemId.set(itemId, newMakeMethodInfo);
+ existingMakeMethodsByItemId.set(itemId, newMakeMethodInfo);
+ }
+ }
+ }
+ } else {
+ // No existing make method - check if trigger created one, or create new
+ const triggerCreatedMakeMethod = await trx
+ .selectFrom("makeMethod")
+ .select(["id", "version", "status"])
+ .where("itemId", "=", itemId)
+ .executeTakeFirst();
- if (materialMakeMethodId) {
- newlyCreatedMakeMethodsByItemId.set(
+ if (triggerCreatedMakeMethod) {
+ materialMakeMethodId = triggerCreatedMakeMethod.id;
+ const makeMethodInfo: MakeMethodInfo = {
+ id: triggerCreatedMakeMethod.id,
itemId,
- materialMakeMethodId
- );
- existingMakeMethodIdsByItemId.set(
- itemId,
- materialMakeMethodId
- );
+ version: Number(triggerCreatedMakeMethod.version),
+ status: triggerCreatedMakeMethod.status as
+ | "Draft"
+ | "Active"
+ | "Archived",
+ };
+ newlyCreatedMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ } else {
+ // Create a new make method if needed
+ const newMakeMethod = await trx
+ .insertInto("makeMethod")
+ .values({
+ itemId,
+ companyId,
+ createdBy: userId,
+ })
+ .returning(["id"])
+ .executeTakeFirst();
+
+ materialMakeMethodId = newMakeMethod?.id;
+
+ if (materialMakeMethodId) {
+ const makeMethodInfo: MakeMethodInfo = {
+ id: materialMakeMethodId,
+ itemId,
+ version: 1,
+ status: "Draft",
+ };
+ newlyCreatedMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ existingMakeMethodsByItemId.set(itemId, makeMethodInfo);
+ }
}
}
}
@@ -336,7 +670,7 @@ serve(async (req: Request) => {
let index = 0;
for await (const node of tree) {
- await traverseTree(node, makeMethodId, index);
+ await traverseTree(node, activeMakeMethodId, index);
index++;
}
});
@@ -351,6 +685,7 @@ serve(async (req: Request) => {
return new Response(
JSON.stringify({
success: true,
+ makeMethodId: activeMakeMethodId,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },