Skip to content

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

feat: add versions to bom explorers

Brad Barbin92d29b01b0e7
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 3eb6901b34..31a2eb2901 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1375,7 +1375,11 @@ export async function updateDefaultRevision(
.select("id,readableId, readableIdWithRevision")
.eq("id", data.id)
.single(),
- client.from("makeMethod").select("id").eq("itemId", data.id).maybeSingle(),
+ client
+ .from("activeMakeMethods")
+ .select("id, version")
+ .eq("itemId", data.id)
+ .maybeSingle(),
]);
if (item.error) return item;
const readableId = item.data.readableId;
@@ -2052,9 +2056,8 @@ export async function upsertMethodMaterial(
let materialMakeMethodId: string | null = null;
if (methodMaterial.methodType === "Make") {
const makeMethod = await client
- // TODO: get we need to pass the make method since there can be multiple
- .from("makeMethod")
- .select("id")
+ .from("activeMakeMethods")
+ .select("id, version")
.eq("itemId", methodMaterial.itemId!)
.single();
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index 40fb7e01fa..62c867b660 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -365,6 +365,16 @@ function NodePreview({ node }: { node: FlatTreeItem<Method> }) {
<span>{node.data.itemType}</span>
</HStack>
</VStack>
+ {node.data.methodType === "Make" && node.data.version && (
+ <VStack spacing={1}>
+ <span className="text-xs text-muted-foreground font-medium">
+ Make Method Version
+ </span>
+ <HStack className="w-full">
+ <Badge variant="outline">V{node.data.version}</Badge>
+ </HStack>
+ </VStack>
+ )}
{onShapeState && (
<VStack spacing={1}>
<span className="text-xs text-muted-foreground font-medium">
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
index 01c7af45cc..f0b95f1572 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -202,7 +202,7 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
<div className="flex items-center gap-1">
{node.data.isRoot ? (
<Badge variant="outline" className="text-xs">
- Method
+ V{node.data.version}
</Badge>
) : (
<NodeData node={node} />
@@ -331,6 +331,16 @@ function NodePreview({ node }: { node: FlatTreeItem<JobMethod> }) {
<span>{node.data.itemType}</span>
</HStack>
</VStack>
+ {node.data.methodType === "Make" && (
+ <VStack spacing={1}>
+ <span className="text-xs text-muted-foreground font-medium">
+ Make Method Version
+ </span>
+ <HStack className="w-full">
+ <Badge variant="outline">V{node.data.version}</Badge>
+ </HStack>
+ </VStack>
+ )}
{onShapeState && (
<VStack spacing={1}>
<span className="text-xs text-muted-foreground font-medium">
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index e5a78ddbf7..8a39a718b7 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -210,7 +210,7 @@ const QuoteBoMExplorer = ({
<div className="flex items-center gap-1">
{node.data.isRoot ? (
<Badge variant="outline" className="text-xs">
- Method
+ V{node.data.version}
</Badge>
) : (
<NodeData node={node} />
@@ -339,6 +339,16 @@ function NodePreview({ node }: { node: FlatTreeItem<QuoteMethod> }) {
<span>{node.data.itemType}</span>
</HStack>
</VStack>
+ {node.data.methodType === "Make" && (
+ <VStack spacing={1}>
+ <span className="text-xs text-muted-foreground font-medium">
+ Make Method Version
+ </span>
+ <HStack className="w-full">
+ <Badge variant="outline">V{node.data.version}</Badge>
+ </HStack>
+ </VStack>
+ )}
{onShapeState && (
<VStack spacing={1}>
<span className="text-xs text-muted-foreground font-medium">
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
index 1c7d33d798..5ea6d52a17 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteMakeMethodTools.tsx
@@ -472,21 +472,16 @@ const QuoteMakeMethodTools = () => {
Include Inactive
</label>
</div>
- {hasMethods && (
- <Alert variant="destructive">
- <LuTriangleAlert className="h-4 w-4" />
- <AlertTitle>
- This will overwrite the existing manufacturing method
- </AlertTitle>
- </Alert>
- )}
</VStack>
</ModalBody>
<ModalFooter>
<Button onClick={saveMethodModal.onClose} variant="secondary">
Cancel
</Button>
- <Submit variant={hasMethods ? "destructive" : "primary"}>
+ <Submit
+ isDisabled={!selectedMakeMethod}
+ variant={hasMethods ? "destructive" : "primary"}
+ >
Confirm
</Submit>
</ModalFooter>
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 73ffb4f5d5..b04808a1a5 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -7440,6 +7440,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobMaterialMakeMethodId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.version",
+ },
{
$ref: "#/parameters/select",
},
@@ -8505,6 +8508,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMaterialWithMakeMethodId.quoteMaterialMakeMethodId",
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMaterialWithMakeMethodId.version",
+ },
{
$ref: "#/parameters/select",
},
@@ -14586,6 +14592,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMakeMethod.requiresBatchTracking",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMakeMethod.version",
+ },
{
$ref: "#/parameters/select",
},
@@ -14687,6 +14696,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMakeMethod.requiresBatchTracking",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMakeMethod.version",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -14742,6 +14754,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMakeMethod.requiresBatchTracking",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMakeMethod.version",
+ },
{
$ref: "#/parameters/body.jobMakeMethod",
},
@@ -44529,6 +44544,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMakeMethod.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMakeMethod.version",
+ },
{
$ref: "#/parameters/select",
},
@@ -44627,6 +44645,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMakeMethod.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMakeMethod.version",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -44679,6 +44700,9 @@ export default {
{
$ref: "#/parameters/rowFilter.quoteMakeMethod.tags",
},
+ {
+ $ref: "#/parameters/rowFilter.quoteMakeMethod.version",
+ },
{
$ref: "#/parameters/body.quoteMakeMethod",
},
@@ -58526,6 +58550,10 @@ export default {
format: "text",
type: "string",
},
+ version: {
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -59049,6 +59077,10 @@ export default {
format: "text",
type: "string",
},
+ version: {
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -61976,6 +62008,7 @@ export default {
"createdBy",
"requiresSerialTracking",
"requiresBatchTracking",
+ "version",
],
properties: {
id: {
@@ -62053,6 +62086,11 @@ export default {
format: "boolean",
type: "boolean",
},
+ version: {
+ default: 1,
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -75870,6 +75908,7 @@ export default {
"companyId",
"createdAt",
"createdBy",
+ "version",
],
properties: {
id: {
@@ -75944,6 +75983,11 @@ export default {
},
type: "array",
},
+ version: {
+ default: 1,
+ format: "numeric",
+ type: "number",
+ },
},
type: "object",
},
@@ -82736,6 +82780,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMaterialWithMakeMethodId.version": {
+ name: "version",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.gauges": {
name: "gauges",
description: "gauges",
@@ -83372,6 +83422,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.quoteMaterialWithMakeMethodId.version": {
+ name: "version",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.itemUnitSalePrice": {
name: "itemUnitSalePrice",
description: "itemUnitSalePrice",
@@ -86696,6 +86752,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMakeMethod.version": {
+ name: "version",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.salesRfqLine": {
name: "salesRfqLine",
description: "salesRfqLine",
@@ -102461,6 +102523,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.quoteMakeMethod.version": {
+ name: "version",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.purchaseOrders": {
name: "purchaseOrders",
description: "purchaseOrders",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7b54683d95..47c64ac1de 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8619,7 +8619,6 @@ export type Database = {
itemId: string
jobId: string
locationId: string
- makeMethodId: string | null
modelUploadId: string | null
notes: Json | null
productionQuantity: number | null
@@ -8657,7 +8656,6 @@ export type Database = {
itemId: string
jobId: string
locationId: string
- makeMethodId?: string | null
modelUploadId?: string | null
notes?: Json | null
productionQuantity?: number | null
@@ -8695,7 +8693,6 @@ export type Database = {
itemId?: string
jobId?: string
locationId?: string
- makeMethodId?: string | null
modelUploadId?: string | null
notes?: Json | null
productionQuantity?: number | null
@@ -8878,34 +8875,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "activeMakeMethods"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "makeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "quoteOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
{
foreignKeyName: "job_quoteId_fkey"
columns: ["quoteId"]
@@ -21034,7 +21003,6 @@ export type Database = {
id: string
internalNotes: Json | null
locationId: string | null
- makeMethodId: string | null
opportunityId: string | null
quoteId: string
revisionId: number
@@ -21070,7 +21038,6 @@ export type Database = {
id?: string
internalNotes?: Json | null
locationId?: string | null
- makeMethodId?: string | null
opportunityId?: string | null
quoteId: string
revisionId?: number
@@ -21106,7 +21073,6 @@ export type Database = {
id?: string
internalNotes?: Json | null
locationId?: string | null
- makeMethodId?: string | null
opportunityId?: string | null
quoteId?: string
revisionId?: number
@@ -21306,34 +21272,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "activeMakeMethods"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "makeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "quoteOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
{
foreignKeyName: "quote_opportunityId_fkey"
columns: ["opportunityId"]
@@ -35366,6 +35304,7 @@ export type Database = {
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
+ version: number | null
}
Relationships: [
{
@@ -39102,6 +39041,7 @@ export type Database = {
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
+ version: number | null
}
Relationships: [
{
@@ -40348,14 +40288,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -43500,6 +43440,7 @@ export type Database = {
isRoot: boolean
kit: boolean
revision: string
+ version: number
}[]
}
get_job_methods_by_method_id: {
@@ -43688,6 +43629,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_my_claim: {
@@ -43801,6 +43743,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_quote_methods_by_method_id: {
@@ -43828,6 +43771,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_recent_job_operations_by_employee: {
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index fb81f56a3c..594038f9cb 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -2334,7 +2334,10 @@ serve(async (req: Request) => {
const makeMethodByItemId: Record<string, string> = {};
makeMethods.data?.forEach((m) => {
- makeMethodByItemId[m.itemId ?? ""] = m.id;
+ if (m.itemId) {
+ // @ts-expect-error - itemId is not null
+ makeMethodByItemId[m.itemId!] = m.id;
+ }
});
await db.transaction().execute(async (trx) => {
@@ -2898,7 +2901,10 @@ serve(async (req: Request) => {
const makeMethodByItemId: Record<string, string> = {};
makeMethods.data?.forEach((m) => {
- makeMethodByItemId[m.itemId ?? ""] = m.id;
+ if (m.itemId) {
+ // @ts-expect-error - itemId is not null
+ makeMethodByItemId[m.itemId!] = m.id;
+ }
});
await db.transaction().execute(async (trx) => {
@@ -2990,7 +2996,6 @@ serve(async (req: Request) => {
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
operationType: op.operationType ?? "Inside",
- operationSupplierProcessId: op.operationSupplierProcessId,
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -3072,7 +3077,7 @@ serve(async (req: Request) => {
quoteOperationAttribute.length > 0
) {
await trx
- .insertInto("quoteOperationAttribute")
+ .insertInto("methodOperationAttribute")
.values(
quoteOperationAttribute.map(
({ id: _id, ...attribute }) => ({
@@ -3093,194 +3098,183 @@ serve(async (req: Request) => {
break;
}
- case "quoteLineToJob": {
- const jobId = targetId;
- if (!jobId) {
- throw new Error("Invalid targetId");
- }
-
- const [quoteId, quoteLineId] = (sourceId as string).split(":");
- if (!quoteId || !quoteLineId) {
- throw new Error("Invalid sourceId");
- }
+ case "quoteMakeMethodToItem": {
+ const quoteMakeMethodId = sourceId;
+ const makeMethodId = targetId;
- const [
- jobMakeMethod,
- quoteMakeMethod,
- quoteMaterials,
- quoteOperations,
- ] = await Promise.all([
+ const [makeMethod, quoteMakeMethod] = await Promise.all([
client
- .from("jobMakeMethod")
+ .from("makeMethod")
.select("*")
- .eq("jobId", jobId)
- .is("parentMaterialId", null)
+ .eq("id", makeMethodId)
.eq("companyId", companyId)
.single(),
client
.from("quoteMakeMethod")
.select("*")
- .is("parentMaterialId", null)
- .eq("quoteLineId", quoteLineId)
+ .eq("id", quoteMakeMethodId)
.eq("companyId", companyId)
.single(),
+ ]);
+
+ if (makeMethod.error) {
+ throw new Error("Failed to get make method");
+ }
+
+ if (quoteMakeMethod.error) {
+ throw new Error("Failed to get quote make method");
+ }
+
+ const itemId = makeMethod.data?.itemId;
+
+ const [quoteOperations] = await Promise.all([
client
- .from("quoteMaterial")
- .select("*")
- .eq("quoteLineId", quoteLineId)
- .eq("companyId", companyId),
- client
- .from("quoteOperation")
+ .from("quoteOperationsWithMakeMethods")
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", quoteLineId)
+ .eq("quoteLineId", quoteMakeMethod.data.quoteLineId)
.eq("companyId", companyId),
]);
- if (jobMakeMethod.error || !jobMakeMethod.data) {
- throw new Error("Failed to get job make method");
- }
-
- if (
- quoteMakeMethod.error ||
- quoteMaterials.error ||
- quoteOperations.error
- ) {
- throw new Error("Failed to fetch quote data");
+ if (quoteOperations.error) {
+ throw new Error("Failed to get quote operations");
}
const [quoteMethodTrees] = await Promise.all([
- getQuoteMethodTree(client, quoteMakeMethod.data.id),
+ getQuoteMethodTree(
+ client,
+ quoteMakeMethodId,
+ quoteMakeMethod.data.parentMaterialId
+ ),
]);
if (quoteMethodTrees.error) {
throw new Error("Failed to get method tree");
}
+ if (quoteMethodTrees.error) {
+ throw new Error("Failed to get method tree");
+ }
+
const quoteMethodTree = quoteMethodTrees
.data?.[0] as QuoteMethodTreeItem;
- if (!quoteMethodTree) throw new Error("Method tree not found");
+ if (!quoteMethodTree) throw new Error("Job method tree not found");
- const quoteMaterialIdToJobMaterialId: Record<string, string> = {};
- const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};
+ const madeItemIds: string[] = [];
+
+ traverseQuoteMethod(quoteMethodTree, (node: QuoteMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ madeItemIds.push(node.data.itemId);
+ }
+ });
+
+ const makeMethods = await client
+ .from("activeMakeMethods")
+ .select("*")
+ .in("itemId", madeItemIds)
+ .eq("companyId", companyId);
+ if (makeMethods.error) {
+ throw new Error("Failed to get make methods");
+ }
+
+ const makeMethodByItemId: Record<string, string> = {};
+ makeMethods.data?.forEach((m) => {
+ if (m.itemId) {
+ // @ts-expect-error - itemId is not null
+ makeMethodByItemId[m.itemId!] = m.id;
+ }
+ });
await db.transaction().execute(async (trx) => {
- // Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
- await Promise.all([
- trx
- .deleteFrom("jobMakeMethod")
- .where((eb) =>
- eb.and([
- eb("jobId", "=", jobId),
- eb("parentMaterialId", "is not", null),
- ])
- )
- .execute(),
- trx.deleteFrom("jobMaterial").where("jobId", "=", jobId).execute(),
- trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(),
- ]);
+ let makeMethodsToDelete: string[] = [];
+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
+ [];
+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =
+ [];
await traverseQuoteMethod(
- quoteMethodTree,
- async (node: QuoteMethodTreeItem) => {
- const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
- [];
- const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =
- [];
-
- for await (const child of node.children) {
- const newMaterialId = nanoid();
- quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
+ quoteMethodTree!,
+ (node: QuoteMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]);
+ }
- jobMaterialInserts.push({
- id: newMaterialId,
- jobId,
+ node.children.forEach((child) => {
+ materialInserts.push({
+ makeMethodId: makeMethodByItemId[node.data.itemId],
+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],
itemId: child.data.itemId,
+ kit: child.data.kit,
itemReadableId: child.data.itemReadableId,
itemType: child.data.itemType,
- kit: child.data.kit,
methodType: child.data.methodType,
order: child.data.order,
- description: child.data.description,
- jobMakeMethodId:
- child.data.quoteMakeMethodId === quoteMakeMethod.data.id
- ? jobMakeMethod.data.id
- : quoteMakeMethodIdToJobMakeMethodId[
- child.data.quoteMakeMethodId
- ],
quantity: child.data.quantity,
- requiresBatchTracking:
- child.data.itemTrackingType === "Batch",
- requiresSerialTracking:
- child.data.itemTrackingType === "Serial",
unitOfMeasureCode: child.data.unitOfMeasureCode,
companyId,
createdBy: userId,
customFields: {},
});
-
- if (child.data.quoteMaterialMakeMethodId) {
- const newMakeMethodId = nanoid();
- quoteMakeMethodIdToJobMakeMethodId[
- child.data.quoteMaterialMakeMethodId
- ] = newMakeMethodId;
- jobMakeMethodInserts.push({
- id: newMakeMethodId,
- jobId,
- parentMaterialId: quoteMaterialIdToJobMaterialId[child.id],
- itemId: child.data.itemId,
- quantityPerParent: child.data.quantity,
- companyId,
- createdBy: userId,
- });
- }
- }
-
- if (jobMaterialInserts.length > 0) {
- await trx
- .insertInto("jobMaterial")
- .values(jobMaterialInserts)
- .execute();
- }
-
- if (jobMakeMethodInserts.length > 0) {
- for await (const insert of jobMakeMethodInserts) {
- await trx
- .updateTable("jobMakeMethod")
- .set({
- id: insert.id,
- quantityPerParent: insert.quantityPerParent,
- })
- .where("jobId", "=", jobId)
- .where("parentMaterialId", "=", insert.parentMaterialId)
- .execute();
- }
- }
+ });
}
);
- const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =
- quoteOperations.data.map((op) => ({
- jobId,
- jobMakeMethodId:
- op.quoteMakeMethodId === quoteMakeMethod.data.id
- ? jobMakeMethod.data.id
- : quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],
- processId: op.processId,
+ if (makeMethodsToDelete.length > 0) {
+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>
+ mm === makeMethodByItemId[quoteMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : mm
+ );
+ await Promise.all([
+ trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ trx
+ .deleteFrom("methodOperation")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ ]);
+ }
+
+ if (materialInserts.length > 0) {
+ await trx
+ .insertInto("methodMaterial")
+ .values(
+ materialInserts.map((insert) => ({
+ ...insert,
+ productionQuantity: undefined,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[quoteMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ itemId:
+ insert.itemId === quoteMakeMethod.data.itemId
+ ? itemId
+ : insert.itemId,
+ }))
+ )
+ .execute();
+ }
+
+ quoteOperations.data?.forEach((op) => {
+ operationInserts.push({
+ makeMethodId: op.makeMethodId!,
+ processId: op.processId!,
procedureId: op.procedureId,
workCenterId: op.workCenterId,
- description: op.description,
- setupTime: op.setupTime,
- setupUnit: op.setupUnit,
- laborTime: op.laborTime,
- laborUnit: op.laborUnit,
- machineTime: op.machineTime,
- machineUnit: op.machineUnit,
- order: op.order,
- operationOrder: op.operationOrder,
- operationType: op.operationType,
- operationSupplierProcessId: op.operationSupplierProcessId,
+ description: op.description ?? "",
+ setupTime: op.setupTime ?? 0,
+ setupUnit: op.setupUnit ?? "Total Minutes",
+ laborTime: op.laborTime ?? 0,
+ laborUnit: op.laborUnit ?? "Minutes/Piece",
+ machineTime: op.machineTime ?? 0,
+ machineUnit: op.machineUnit ?? "Minutes/Piece",
+ order: op.order ?? 1,
+ operationOrder: op.operationOrder ?? "After Previous",
+ operationType: op.operationType ?? "Inside",
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -3289,12 +3283,22 @@ serve(async (req: Request) => {
companyId,
createdBy: userId,
customFields: {},
- }));
+ });
+ });
- if (jobOperationInserts.length > 0) {
+ if (operationInserts.length > 0) {
const operationIds = await trx
- .insertInto("jobOperation")
- .values(jobOperationInserts)
+ .insertInto("methodOperation")
+ .values(
+ operationInserts.map((insert) => ({
+ ...insert,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[quoteMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ }))
+ )
.returning(["id"])
.execute();
@@ -3315,7 +3319,7 @@ serve(async (req: Request) => {
quoteOperationTool.length > 0
) {
await trx
- .insertInto("jobOperationTool")
+ .insertInto("methodOperationTool")
.values(
quoteOperationTool.map((tool) => ({
toolId: tool.toolId,
@@ -3328,20 +3332,13 @@ serve(async (req: Request) => {
.execute();
}
- if (procedureId) {
- await insertProcedureDataForJobOperation(trx, client, {
- operationId,
- procedureId,
- companyId,
- userId,
- });
- } else {
+ if (!procedureId) {
if (
Array.isArray(quoteOperationParameter) &&
quoteOperationParameter.length > 0
) {
await trx
- .insertInto("jobOperationParameter")
+ .insertInto("methodOperationParameter")
.values(
quoteOperationParameter.map((param) => ({
operationId,
@@ -3359,7 +3356,7 @@ serve(async (req: Request) => {
quoteOperationAttribute.length > 0
) {
await trx
- .insertInto("quoteOperationAttribute")
+ .insertInto("methodOperationAttribute")
.values(
quoteOperationAttribute.map(
({ id: _id, ...attribute }) => ({
@@ -3380,22 +3377,27 @@ serve(async (req: Request) => {
break;
}
- case "quoteLineToQuoteLine": {
- const [, sourceQuoteLineId] = (sourceId as string).split(":");
- const [targetQuoteId, targetQuoteLineId] = (targetId as string).split(
- ":"
- );
+ case "quoteLineToJob": {
+ const jobId = targetId;
+ if (!jobId) {
+ throw new Error("Invalid targetId");
+ }
+
+ const [quoteId, quoteLineId] = (sourceId as string).split(":");
+ if (!quoteId || !quoteLineId) {
+ throw new Error("Invalid sourceId");
+ }
const [
- targetQuoteMakeMethod,
- sourceQuoteMakeMethod,
- sourceQuoteMaterials,
- sourceQuoteOperations,
+ jobMakeMethod,
+ quoteMakeMethod,
+ quoteMaterials,
+ quoteOperations,
] = await Promise.all([
client
- .from("quoteMakeMethod")
+ .from("jobMakeMethod")
.select("*")
- .eq("quoteLineId", targetQuoteLineId)
+ .eq("jobId", jobId)
.is("parentMaterialId", null)
.eq("companyId", companyId)
.single(),
@@ -3403,38 +3405,37 @@ serve(async (req: Request) => {
.from("quoteMakeMethod")
.select("*")
.is("parentMaterialId", null)
- .eq("quoteLineId", sourceQuoteLineId)
+ .eq("quoteLineId", quoteLineId)
.eq("companyId", companyId)
.single(),
client
.from("quoteMaterial")
.select("*")
- .eq("quoteLineId", sourceQuoteLineId)
+ .eq("quoteLineId", quoteLineId)
.eq("companyId", companyId),
client
.from("quoteOperation")
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", sourceQuoteLineId)
+ .eq("quoteLineId", quoteLineId)
.eq("companyId", companyId),
]);
- if (targetQuoteMakeMethod.error || !targetQuoteMakeMethod.data) {
- console.error(targetQuoteMakeMethod.error);
- throw new Error("Failed to get target quote make method");
+ if (jobMakeMethod.error || !jobMakeMethod.data) {
+ throw new Error("Failed to get job make method");
}
if (
- sourceQuoteMakeMethod.error ||
- sourceQuoteMaterials.error ||
- sourceQuoteOperations.error
+ quoteMakeMethod.error ||
+ quoteMaterials.error ||
+ quoteOperations.error
) {
- throw new Error("Failed to source quote data");
+ throw new Error("Failed to fetch quote data");
}
const [quoteMethodTrees] = await Promise.all([
- getQuoteMethodTree(client, sourceQuoteMakeMethod.data.id),
+ getQuoteMethodTree(client, quoteMakeMethod.data.id),
]);
if (quoteMethodTrees.error) {
@@ -3445,62 +3446,58 @@ serve(async (req: Request) => {
.data?.[0] as QuoteMethodTreeItem;
if (!quoteMethodTree) throw new Error("Method tree not found");
- const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};
- const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> = {};
+ const quoteMaterialIdToJobMaterialId: Record<string, string> = {};
+ const quoteMakeMethodIdToJobMakeMethodId: Record<string, string> = {};
await db.transaction().execute(async (trx) => {
// Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
await Promise.all([
trx
- .deleteFrom("quoteMakeMethod")
+ .deleteFrom("jobMakeMethod")
.where((eb) =>
eb.and([
- eb("quoteLineId", "=", targetQuoteLineId),
+ eb("jobId", "=", jobId),
eb("parentMaterialId", "is not", null),
])
)
.execute(),
- trx
- .deleteFrom("quoteMaterial")
- .where("quoteLineId", "=", targetQuoteLineId)
- .execute(),
- trx
- .deleteFrom("quoteOperation")
- .where("quoteLineId", "=", targetQuoteLineId)
- .execute(),
+ trx.deleteFrom("jobMaterial").where("jobId", "=", jobId).execute(),
+ trx.deleteFrom("jobOperation").where("jobId", "=", jobId).execute(),
]);
await traverseQuoteMethod(
quoteMethodTree,
async (node: QuoteMethodTreeItem) => {
- const quoteMaterialInserts: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =
+ const jobMaterialInserts: Database["public"]["Tables"]["jobMaterial"]["Insert"][] =
[];
- const quoteMakeMethodInserts: Database["public"]["Tables"]["quoteMakeMethod"]["Insert"][] =
+ const jobMakeMethodInserts: Database["public"]["Tables"]["jobMakeMethod"]["Insert"][] =
[];
for await (const child of node.children) {
const newMaterialId = nanoid();
- quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;
+ quoteMaterialIdToJobMaterialId[child.id] = newMaterialId;
- quoteMaterialInserts.push({
+ jobMaterialInserts.push({
id: newMaterialId,
- quoteId: targetQuoteId,
- quoteLineId: targetQuoteLineId,
+ jobId,
itemId: child.data.itemId,
- kit: child.data.kit,
itemReadableId: child.data.itemReadableId,
itemType: child.data.itemType,
+ kit: child.data.kit,
methodType: child.data.methodType,
order: child.data.order,
description: child.data.description,
- quoteMakeMethodId:
- child.data.quoteMakeMethodId ===
- sourceQuoteMakeMethod.data.id
- ? targetQuoteMakeMethod.data.id
- : quoteMakeMethodIdToQuoteMakeMethodId[
+ jobMakeMethodId:
+ child.data.quoteMakeMethodId === quoteMakeMethod.data.id
+ ? jobMakeMethod.data.id
+ : quoteMakeMethodIdToJobMakeMethodId[
child.data.quoteMakeMethodId
],
quantity: child.data.quantity,
+ requiresBatchTracking:
+ child.data.itemTrackingType === "Batch",
+ requiresSerialTracking:
+ child.data.itemTrackingType === "Serial",
unitOfMeasureCode: child.data.unitOfMeasureCode,
companyId,
createdBy: userId,
@@ -3509,15 +3506,13 @@ serve(async (req: Request) => {
if (child.data.quoteMaterialMakeMethodId) {
const newMakeMethodId = nanoid();
- quoteMakeMethodIdToQuoteMakeMethodId[
+ quoteMakeMethodIdToJobMakeMethodId[
child.data.quoteMaterialMakeMethodId
] = newMakeMethodId;
- quoteMakeMethodInserts.push({
+ jobMakeMethodInserts.push({
id: newMakeMethodId,
- quoteId: targetQuoteId,
- quoteLineId: targetQuoteLineId,
- parentMaterialId:
- quoteMaterialIdToQuoteMaterialId[child.id],
+ jobId,
+ parentMaterialId: quoteMaterialIdToJobMaterialId[child.id],
itemId: child.data.itemId,
quantityPerParent: child.data.quantity,
companyId,
@@ -3526,22 +3521,22 @@ serve(async (req: Request) => {
}
}
- if (quoteMaterialInserts.length > 0) {
+ if (jobMaterialInserts.length > 0) {
await trx
- .insertInto("quoteMaterial")
- .values(quoteMaterialInserts)
+ .insertInto("jobMaterial")
+ .values(jobMaterialInserts)
.execute();
}
- if (quoteMakeMethodInserts.length > 0) {
- for await (const insert of quoteMakeMethodInserts) {
+ if (jobMakeMethodInserts.length > 0) {
+ for await (const insert of jobMakeMethodInserts) {
await trx
- .updateTable("quoteMakeMethod")
+ .updateTable("jobMakeMethod")
.set({
id: insert.id,
quantityPerParent: insert.quantityPerParent,
})
- .where("quoteLineId", "=", targetQuoteLineId)
+ .where("jobId", "=", jobId)
.where("parentMaterialId", "=", insert.parentMaterialId)
.execute();
}
@@ -3549,14 +3544,13 @@ serve(async (req: Request) => {
}
);
- const quoteOperationInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
- sourceQuoteOperations.data.map((op) => ({
- quoteId: targetQuoteId,
- quoteLineId: targetQuoteLineId,
- quoteMakeMethodId:
- op.quoteMakeMethodId === sourceQuoteMakeMethod.data.id
- ? targetQuoteMakeMethod.data.id
- : quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],
+ const jobOperationInserts: Database["public"]["Tables"]["jobOperation"]["Insert"][] =
+ quoteOperations.data.map((op) => ({
+ jobId,
+ jobMakeMethodId:
+ op.quoteMakeMethodId === quoteMakeMethod.data.id
+ ? jobMakeMethod.data.id
+ : quoteMakeMethodIdToJobMakeMethodId[op.quoteMakeMethodId!],
processId: op.processId,
procedureId: op.procedureId,
workCenterId: op.workCenterId,
@@ -3581,15 +3575,15 @@ serve(async (req: Request) => {
customFields: {},
}));
- if (quoteOperationInserts.length > 0) {
+ if (jobOperationInserts.length > 0) {
const operationIds = await trx
- .insertInto("quoteOperation")
- .values(quoteOperationInserts)
+ .insertInto("jobOperation")
+ .values(jobOperationInserts)
.returning(["id"])
.execute();
for (const [index, operation] of (
- sourceQuoteOperations.data ?? []
+ quoteOperations.data ?? []
).entries()) {
const operationId = operationIds[index].id;
if (operationId) {
@@ -3597,6 +3591,7 @@ serve(async (req: Request) => {
quoteOperationTool,
quoteOperationParameter,
quoteOperationAttribute,
+ procedureId,
} = operation;
if (
@@ -3604,7 +3599,7 @@ serve(async (req: Request) => {
quoteOperationTool.length > 0
) {
await trx
- .insertInto("quoteOperationTool")
+ .insertInto("jobOperationTool")
.values(
quoteOperationTool.map((tool) => ({
toolId: tool.toolId,
@@ -3617,226 +3612,249 @@ serve(async (req: Request) => {
.execute();
}
- if (
- Array.isArray(quoteOperationParameter) &&
- quoteOperationParameter.length > 0
- ) {
- await trx
- .insertInto("quoteOperationParameter")
- .values(
- quoteOperationParameter.map((param) => ({
- operationId,
- key: param.key,
- value: param.value,
- companyId,
- createdBy: userId,
- }))
- )
- .execute();
- }
-
- if (
- Array.isArray(quoteOperationAttribute) &&
- quoteOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("quoteOperationAttribute")
- .values(
- quoteOperationAttribute.map(
- ({ id: _id, ...attribute }) => ({
- ...attribute,
+ if (procedureId) {
+ await insertProcedureDataForJobOperation(trx, client, {
+ operationId,
+ procedureId,
+ companyId,
+ userId,
+ });
+ } else {
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("jobOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
operationId,
+ key: param.key,
+ value: param.value,
companyId,
createdBy: userId,
- })
+ }))
)
- )
- .execute();
- }
- }
- }
- }
- });
-
- break;
- }
- case "quoteMakeMethodToItem": {
- const quoteMakeMethodId = sourceId;
- const makeMethodId = targetId;
+ .execute();
+ }
- const [makeMethod, quoteMakeMethod] = await Promise.all([
- client
- .from("makeMethod")
- .select("*")
- .eq("id", makeMethodId)
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ quoteOperationAttribute.map(
+ ({ id: _id, ...attribute }) => ({
+ ...attribute,
+ operationId,
+ companyId,
+ createdBy: userId,
+ })
+ )
+ )
+ .execute();
+ }
+ }
+ }
+ }
+ }
+ });
+
+ break;
+ }
+ case "quoteLineToQuoteLine": {
+ const [, sourceQuoteLineId] = (sourceId as string).split(":");
+ const [targetQuoteId, targetQuoteLineId] = (targetId as string).split(
+ ":"
+ );
+
+ const [
+ targetQuoteMakeMethod,
+ sourceQuoteMakeMethod,
+ sourceQuoteMaterials,
+ sourceQuoteOperations,
+ ] = await Promise.all([
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .eq("quoteLineId", targetQuoteLineId)
+ .is("parentMaterialId", null)
.eq("companyId", companyId)
.single(),
client
.from("quoteMakeMethod")
.select("*")
- .eq("id", quoteMakeMethodId)
+ .is("parentMaterialId", null)
+ .eq("quoteLineId", sourceQuoteLineId)
.eq("companyId", companyId)
.single(),
- ]);
-
- if (makeMethod.error) {
- throw new Error("Failed to get make method");
- }
-
- if (quoteMakeMethod.error) {
- throw new Error("Failed to get quote make method");
- }
-
- const itemId = makeMethod.data?.itemId;
-
- const [quoteOperations] = await Promise.all([
client
- .from("quoteOperationsWithMakeMethods")
+ .from("quoteMaterial")
+ .select("*")
+ .eq("quoteLineId", sourceQuoteLineId)
+ .eq("companyId", companyId),
+ client
+ .from("quoteOperation")
.select(
"*, quoteOperationTool(*), quoteOperationParameter(*), quoteOperationAttribute(*)"
)
- .eq("quoteLineId", quoteMakeMethod.data.quoteLineId)
+ .eq("quoteLineId", sourceQuoteLineId)
.eq("companyId", companyId),
]);
- if (quoteOperations.error) {
- throw new Error("Failed to get quote operations");
+ if (targetQuoteMakeMethod.error || !targetQuoteMakeMethod.data) {
+ console.error(targetQuoteMakeMethod.error);
+ throw new Error("Failed to get target quote make method");
+ }
+
+ if (
+ sourceQuoteMakeMethod.error ||
+ sourceQuoteMaterials.error ||
+ sourceQuoteOperations.error
+ ) {
+ throw new Error("Failed to source quote data");
}
const [quoteMethodTrees] = await Promise.all([
- getQuoteMethodTree(
- client,
- quoteMakeMethodId,
- quoteMakeMethod.data.parentMaterialId
- ),
+ getQuoteMethodTree(client, sourceQuoteMakeMethod.data.id),
]);
if (quoteMethodTrees.error) {
throw new Error("Failed to get method tree");
}
- if (quoteMethodTrees.error) {
- throw new Error("Failed to get method tree");
- }
-
const quoteMethodTree = quoteMethodTrees
.data?.[0] as QuoteMethodTreeItem;
- if (!quoteMethodTree) throw new Error("Job method tree not found");
-
- const madeItemIds: string[] = [];
-
- traverseQuoteMethod(quoteMethodTree, (node: QuoteMethodTreeItem) => {
- if (node.data.itemId && node.data.methodType === "Make") {
- madeItemIds.push(node.data.itemId);
- }
- });
-
- const makeMethods = await client
- .from("activeMakeMethods")
- .select("*")
- .in("itemId", madeItemIds)
- .eq("companyId", companyId);
-
- if (makeMethods.error) {
- throw new Error("Failed to get make methods");
- }
+ if (!quoteMethodTree) throw new Error("Method tree not found");
- const makeMethodByItemId: Record<string, string> = {};
- makeMethods.data?.forEach((m) => {
- if (m.itemId) {
- makeMethodByItemId[m.itemId] = m.id;
- }
- });
+ const quoteMaterialIdToQuoteMaterialId: Record<string, string> = {};
+ const quoteMakeMethodIdToQuoteMakeMethodId: Record<string, string> = {};
await db.transaction().execute(async (trx) => {
- let makeMethodsToDelete: string[] = [];
- const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
- [];
- const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =
- [];
+ // Delete existing jobMakeMethods, jobMaterials, and jobOperations for this job
+ await Promise.all([
+ trx
+ .deleteFrom("quoteMakeMethod")
+ .where((eb) =>
+ eb.and([
+ eb("quoteLineId", "=", targetQuoteLineId),
+ eb("parentMaterialId", "is not", null),
+ ])
+ )
+ .execute(),
+ trx
+ .deleteFrom("quoteMaterial")
+ .where("quoteLineId", "=", targetQuoteLineId)
+ .execute(),
+ trx
+ .deleteFrom("quoteOperation")
+ .where("quoteLineId", "=", targetQuoteLineId)
+ .execute(),
+ ]);
await traverseQuoteMethod(
- quoteMethodTree!,
- (node: QuoteMethodTreeItem) => {
- if (node.data.itemId && node.data.methodType === "Make") {
- makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]);
- }
+ quoteMethodTree,
+ async (node: QuoteMethodTreeItem) => {
+ const quoteMaterialInserts: Database["public"]["Tables"]["quoteMaterial"]["Insert"][] =
+ [];
+ const quoteMakeMethodInserts: Database["public"]["Tables"]["quoteMakeMethod"]["Insert"][] =
+ [];
- node.children.forEach((child) => {
- materialInserts.push({
- makeMethodId: makeMethodByItemId[node.data.itemId],
- materialMakeMethodId: makeMethodByItemId[child.data.itemId],
+ for await (const child of node.children) {
+ const newMaterialId = nanoid();
+ quoteMaterialIdToQuoteMaterialId[child.id] = newMaterialId;
+
+ quoteMaterialInserts.push({
+ id: newMaterialId,
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
itemId: child.data.itemId,
kit: child.data.kit,
itemReadableId: child.data.itemReadableId,
itemType: child.data.itemType,
methodType: child.data.methodType,
order: child.data.order,
+ description: child.data.description,
+ quoteMakeMethodId:
+ child.data.quoteMakeMethodId ===
+ sourceQuoteMakeMethod.data.id
+ ? targetQuoteMakeMethod.data.id
+ : quoteMakeMethodIdToQuoteMakeMethodId[
+ child.data.quoteMakeMethodId
+ ],
quantity: child.data.quantity,
unitOfMeasureCode: child.data.unitOfMeasureCode,
companyId,
createdBy: userId,
customFields: {},
});
- });
- }
- );
- if (makeMethodsToDelete.length > 0) {
- makeMethodsToDelete = makeMethodsToDelete.map((mm) =>
- mm === makeMethodByItemId[quoteMakeMethod.data.itemId]
- ? makeMethod.data.id
- : mm
- );
- await Promise.all([
- trx
- .deleteFrom("methodMaterial")
- .where("makeMethodId", "in", makeMethodsToDelete)
- .execute(),
- trx
- .deleteFrom("methodOperation")
- .where("makeMethodId", "in", makeMethodsToDelete)
- .execute(),
- ]);
- }
+ if (child.data.quoteMaterialMakeMethodId) {
+ const newMakeMethodId = nanoid();
+ quoteMakeMethodIdToQuoteMakeMethodId[
+ child.data.quoteMaterialMakeMethodId
+ ] = newMakeMethodId;
+ quoteMakeMethodInserts.push({
+ id: newMakeMethodId,
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
+ parentMaterialId:
+ quoteMaterialIdToQuoteMaterialId[child.id],
+ itemId: child.data.itemId,
+ quantityPerParent: child.data.quantity,
+ companyId,
+ createdBy: userId,
+ });
+ }
+ }
- if (materialInserts.length > 0) {
- await trx
- .insertInto("methodMaterial")
- .values(
- materialInserts.map((insert) => ({
- ...insert,
- productionQuantity: undefined,
- makeMethodId:
- insert.makeMethodId ===
- makeMethodByItemId[quoteMakeMethod.data.itemId]
- ? makeMethod.data.id
- : insert.makeMethodId,
- itemId:
- insert.itemId === quoteMakeMethod.data.itemId
- ? itemId
- : insert.itemId,
- }))
- )
- .execute();
- }
+ if (quoteMaterialInserts.length > 0) {
+ await trx
+ .insertInto("quoteMaterial")
+ .values(quoteMaterialInserts)
+ .execute();
+ }
- quoteOperations.data?.forEach((op) => {
- operationInserts.push({
- makeMethodId: op.makeMethodId!,
- processId: op.processId!,
+ if (quoteMakeMethodInserts.length > 0) {
+ for await (const insert of quoteMakeMethodInserts) {
+ await trx
+ .updateTable("quoteMakeMethod")
+ .set({
+ id: insert.id,
+ quantityPerParent: insert.quantityPerParent,
+ })
+ .where("quoteLineId", "=", targetQuoteLineId)
+ .where("parentMaterialId", "=", insert.parentMaterialId)
+ .execute();
+ }
+ }
+ }
+ );
+
+ const quoteOperationInserts: Database["public"]["Tables"]["quoteOperation"]["Insert"][] =
+ sourceQuoteOperations.data.map((op) => ({
+ quoteId: targetQuoteId,
+ quoteLineId: targetQuoteLineId,
+ quoteMakeMethodId:
+ op.quoteMakeMethodId === sourceQuoteMakeMethod.data.id
+ ? targetQuoteMakeMethod.data.id
+ : quoteMakeMethodIdToQuoteMakeMethodId[op.quoteMakeMethodId!],
+ processId: op.processId,
procedureId: op.procedureId,
workCenterId: op.workCenterId,
- description: op.description ?? "",
- setupTime: op.setupTime ?? 0,
- setupUnit: op.setupUnit ?? "Total Minutes",
- laborTime: op.laborTime ?? 0,
- laborUnit: op.laborUnit ?? "Minutes/Piece",
- machineTime: op.machineTime ?? 0,
- machineUnit: op.machineUnit ?? "Minutes/Piece",
- order: op.order ?? 1,
- operationOrder: op.operationOrder ?? "After Previous",
- operationType: op.operationType ?? "Inside",
+ description: op.description,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ order: op.order,
+ operationOrder: op.operationOrder,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
operationMinimumCost: op.operationMinimumCost ?? 0,
operationLeadTime: op.operationLeadTime ?? 0,
operationUnitCost: op.operationUnitCost ?? 0,
@@ -3845,27 +3863,17 @@ serve(async (req: Request) => {
companyId,
createdBy: userId,
customFields: {},
- });
- });
+ }));
- if (operationInserts.length > 0) {
+ if (quoteOperationInserts.length > 0) {
const operationIds = await trx
- .insertInto("methodOperation")
- .values(
- operationInserts.map((insert) => ({
- ...insert,
- makeMethodId:
- insert.makeMethodId ===
- makeMethodByItemId[quoteMakeMethod.data.itemId]
- ? makeMethod.data.id
- : insert.makeMethodId,
- }))
- )
+ .insertInto("quoteOperation")
+ .values(quoteOperationInserts)
.returning(["id"])
.execute();
for (const [index, operation] of (
- quoteOperations.data ?? []
+ sourceQuoteOperations.data ?? []
).entries()) {
const operationId = operationIds[index].id;
if (operationId) {
@@ -3873,7 +3881,6 @@ serve(async (req: Request) => {
quoteOperationTool,
quoteOperationParameter,
quoteOperationAttribute,
- procedureId,
} = operation;
if (
@@ -3881,7 +3888,7 @@ serve(async (req: Request) => {
quoteOperationTool.length > 0
) {
await trx
- .insertInto("methodOperationTool")
+ .insertInto("quoteOperationTool")
.values(
quoteOperationTool.map((tool) => ({
toolId: tool.toolId,
@@ -3894,43 +3901,41 @@ serve(async (req: Request) => {
.execute();
}
- if (!procedureId) {
- if (
- Array.isArray(quoteOperationParameter) &&
- quoteOperationParameter.length > 0
- ) {
- await trx
- .insertInto("methodOperationParameter")
- .values(
- quoteOperationParameter.map((param) => ({
+ if (
+ Array.isArray(quoteOperationParameter) &&
+ quoteOperationParameter.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationParameter")
+ .values(
+ quoteOperationParameter.map((param) => ({
+ operationId,
+ key: param.key,
+ value: param.value,
+ companyId,
+ createdBy: userId,
+ }))
+ )
+ .execute();
+ }
+
+ if (
+ Array.isArray(quoteOperationAttribute) &&
+ quoteOperationAttribute.length > 0
+ ) {
+ await trx
+ .insertInto("quoteOperationAttribute")
+ .values(
+ quoteOperationAttribute.map(
+ ({ id: _id, ...attribute }) => ({
+ ...attribute,
operationId,
- key: param.key,
- value: param.value,
companyId,
createdBy: userId,
- }))
- )
- .execute();
- }
-
- if (
- Array.isArray(quoteOperationAttribute) &&
- quoteOperationAttribute.length > 0
- ) {
- await trx
- .insertInto("methodOperationAttribute")
- .values(
- quoteOperationAttribute.map(
- ({ id: _id, ...attribute }) => ({
- ...attribute,
- operationId,
- companyId,
- createdBy: userId,
- })
- )
+ })
)
- .execute();
- }
+ )
+ .execute();
}
}
}
@@ -3939,6 +3944,7 @@ serve(async (req: Request) => {
break;
}
+
case "quoteToQuote": {
const sourceQuoteId = sourceId;
const asRevision = !!targetId;
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 7b54683d95..47c64ac1de 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -8619,7 +8619,6 @@ export type Database = {
itemId: string
jobId: string
locationId: string
- makeMethodId: string | null
modelUploadId: string | null
notes: Json | null
productionQuantity: number | null
@@ -8657,7 +8656,6 @@ export type Database = {
itemId: string
jobId: string
locationId: string
- makeMethodId?: string | null
modelUploadId?: string | null
notes?: Json | null
productionQuantity?: number | null
@@ -8695,7 +8693,6 @@ export type Database = {
itemId?: string
jobId?: string
locationId?: string
- makeMethodId?: string | null
modelUploadId?: string | null
notes?: Json | null
productionQuantity?: number | null
@@ -8878,34 +8875,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "activeMakeMethods"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "makeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "job_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "quoteOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
{
foreignKeyName: "job_quoteId_fkey"
columns: ["quoteId"]
@@ -21034,7 +21003,6 @@ export type Database = {
id: string
internalNotes: Json | null
locationId: string | null
- makeMethodId: string | null
opportunityId: string | null
quoteId: string
revisionId: number
@@ -21070,7 +21038,6 @@ export type Database = {
id?: string
internalNotes?: Json | null
locationId?: string | null
- makeMethodId?: string | null
opportunityId?: string | null
quoteId: string
revisionId?: number
@@ -21106,7 +21073,6 @@ export type Database = {
id?: string
internalNotes?: Json | null
locationId?: string | null
- makeMethodId?: string | null
opportunityId?: string | null
quoteId?: string
revisionId?: number
@@ -21306,34 +21272,6 @@ export type Database = {
referencedRelation: "location"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "activeMakeMethods"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "jobOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "makeMethod"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quote_makeMethodId_fkey"
- columns: ["makeMethodId"]
- isOneToOne: false
- referencedRelation: "quoteOperationsWithMakeMethods"
- referencedColumns: ["makeMethodId"]
- },
{
foreignKeyName: "quote_opportunityId_fkey"
columns: ["opportunityId"]
@@ -35366,6 +35304,7 @@ export type Database = {
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
+ version: number | null
}
Relationships: [
{
@@ -39102,6 +39041,7 @@ export type Database = {
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
+ version: number | null
}
Relationships: [
{
@@ -40348,14 +40288,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -43500,6 +43440,7 @@ export type Database = {
isRoot: boolean
kit: boolean
revision: string
+ version: number
}[]
}
get_job_methods_by_method_id: {
@@ -43688,6 +43629,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_my_claim: {
@@ -43801,6 +43743,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_quote_methods_by_method_id: {
@@ -43828,6 +43771,7 @@ export type Database = {
kit: boolean
revision: string
externalId: Json
+ version: number
}[]
}
get_recent_job_operations_by_employee: {
diff --git a/packages/database/supabase/migrations/20250603011801_make-method-version.sql b/packages/database/supabase/migrations/20250603011801_make-method-version.sql
index 8bc8d260f8..3397e9dfec 100644
--- a/packages/database/supabase/migrations/20250603011801_make-method-version.sql
+++ b/packages/database/supabase/migrations/20250603011801_make-method-version.sql
@@ -150,19 +150,22 @@ END;
$$ LANGUAGE plpgsql;
-
+DROP VIEW IF EXISTS "quoteMaterialWithMakeMethodId";
CREATE OR REPLACE VIEW "quoteMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
SELECT
qm.*,
- qmm."id" AS "quoteMaterialMakeMethodId"
+ qmm."id" AS "quoteMaterialMakeMethodId",
+ qmm.version AS "version"
FROM "quoteMaterial" qm
LEFT JOIN "quoteMakeMethod" qmm
ON qmm."parentMaterialId" = qm."id";
+DROP VIEW IF EXISTS "jobMaterialWithMakeMethodId";
CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
SELECT
jm.*,
- jmm."id" AS "jobMaterialMakeMethodId"
+ jmm."id" AS "jobMaterialMakeMethodId",
+ jmm.version AS "version"
FROM "jobMaterial" jm
LEFT JOIN "jobMakeMethod" jmm
ON jmm."parentMaterialId" = jm."id";
@@ -178,6 +181,7 @@ CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true
ON jmm."itemId" = mm."itemId" AND jmm."version" = mm."version";
+
DROP VIEW IF EXISTS "quoteOperationsWithMakeMethods";
COMMIT;
CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
@@ -190,7 +194,25 @@ CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=tr
LEFT JOIN "makeMethod" mm
ON qmm."itemId" = mm."itemId" AND qmm."version" = mm."version";
+DROP VIEW IF EXISTS "quoteMaterialWithMakeMethodId";
+CREATE OR REPLACE VIEW "quoteMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ qm.*,
+ qmm."id" AS "quoteMaterialMakeMethodId",
+ qmm.version AS "version"
+ FROM "quoteMaterial" qm
+ LEFT JOIN "quoteMakeMethod" qmm
+ ON qmm."parentMaterialId" = qm."id";
+DROP VIEW IF EXISTS "jobMaterialWithMakeMethodId";
+CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jm.*,
+ jmm."id" AS "jobMaterialMakeMethodId",
+ jmm.version AS "version"
+ FROM "jobMaterial" jm
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."parentMaterialId" = jm."id";
CREATE OR REPLACE FUNCTION insert_quote_line_make_method()
RETURNS TRIGGER AS $$
@@ -274,4 +296,400 @@ BEGIN
END IF;
RETURN NEW;
END;
-$$ LANGUAGE plpgsql;
\ No newline at end of file
+$$ LANGUAGE plpgsql;
+
+
+DROP FUNCTION IF EXISTS get_quote_methods_by_method_id;
+CREATE OR REPLACE FUNCTION get_quote_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "itemTrackingType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2)
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "version",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "id" = mid
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."version",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ item."itemTrackingType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ item."externalId",
+ material."version"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+DROP FUNCTION get_method_tree;
+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)
+RETURNS TABLE (
+ "methodMaterialId" TEXT,
+ "makeMethodId" TEXT,
+ "materialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemType" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "unitCost" NUMERIC,
+ "quantity" NUMERIC,
+ "methodType" "methodType",
+ "itemTrackingType" TEXT,
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "operationId" TEXT,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2)
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "id",
+ "makeMethodId",
+ "methodType",
+ "materialMakeMethodId",
+ "itemId",
+ "itemType",
+ "quantity",
+ "makeMethodId" AS "parentMaterialId",
+ NULL AS "operationId",
+ COALESCE("order", 1) AS "order",
+ "kit"
+ FROM
+ "methodMaterial"
+ WHERE
+ "makeMethodId" = uid
+ UNION
+ SELECT
+ child."id",
+ child."makeMethodId",
+ child."methodType",
+ child."materialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ parent."id" AS "parentMaterialId",
+ child."methodOperationId" AS "operationId",
+ child."order",
+ child."kit"
+ FROM
+ "methodMaterial" child
+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"
+)
+SELECT
+ material.id as "methodMaterialId",
+ material."makeMethodId",
+ material."materialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ material."itemType",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ material."quantity",
+ material."methodType",
+ item."itemTrackingType",
+ material."parentMaterialId",
+ material."order",
+ material."operationId",
+ false AS "isRoot",
+ material."kit",
+ item."revision",
+ item."externalId",
+ mm2."version"
+FROM material
+INNER JOIN item
+ ON material."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+INNER JOIN "makeMethod" mm
+ ON material."makeMethodId" = mm.id
+LEFT JOIN "makeMethod" mm2
+ ON material."materialMakeMethodId" = mm2.id
+UNION
+SELECT
+ mm."id" AS "methodMaterialId",
+ NULL AS "makeMethodId",
+ mm.id AS "materialMakeMethodId",
+ mm."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."type"::text,
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ 1 AS "quantity",
+ 'Make' AS "methodType",
+ item."itemTrackingType",
+ NULL AS "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ NULL AS "operationId",
+ true AS "isRoot",
+ false AS "kit",
+ item."revision",
+ item."externalId",
+ mm."version"
+FROM "makeMethod" mm
+INNER JOIN item
+ ON mm."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+WHERE mm.id = uid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+DROP FUNCTION IF EXISTS get_quote_methods;
+CREATE OR REPLACE FUNCTION get_quote_methods(qid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2)
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "quoteId" = qid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ item."externalId",
+ material."version"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+DROP FUNCTION IF EXISTS get_job_method;
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "version" NUMERIC(10,2)
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ material."version"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
\ No newline at end of file