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: recalculate requirements when methods change

Brad Barbind640bdc1f865
diff --git a/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
index 989816425b..6a116c4b50 100644
--- a/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/CollapsibleSidebar.tsx
@@ -7,7 +7,7 @@ import {
} from "@carbon/react";
import { motion } from "framer-motion";
import { useMemo, type PropsWithChildren } from "react";
-import { TbArrowBarLeft, TbArrowBarRight } from "react-icons/tb";
+import { LuArrowLeftFromLine, LuArrowRightFromLine } from "react-icons/lu";
export const CollapsibleSidebar = ({
children,
@@ -41,7 +41,13 @@ export const CollapsibleSidebar = ({
<TooltipTrigger asChild>
<IconButton
onClick={sidebar.onToggle}
- icon={sidebar.isOpen ? <TbArrowBarLeft /> : <TbArrowBarRight />}
+ icon={
+ sidebar.isOpen ? (
+ <LuArrowLeftFromLine />
+ ) : (
+ <LuArrowRightFromLine />
+ )
+ }
aria-label="Toggle sidebar"
className="bg-popover inline-block border border-border border-l-0 absolute pl-2 top-[calc(100vh-135px)] text-muted-foreground right-[-31px] left-auto rounded-l-none z-[3] hover:bg-popover p-0 shadow-none"
/>
diff --git a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
index da04b92252..1dbd9c3d48 100644
--- a/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/ContentSidebar.tsx
@@ -23,6 +23,7 @@ const ContentSidebar = ({ links }: { links: Route[] }) => {
asChild
leftIcon={route.icon}
variant={isActive ? "active" : "ghost"}
+ size="sm"
className="w-full justify-start"
>
<Link
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index 328223c05d..d61008eecf 100644
--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -34,6 +34,7 @@ const GroupedContentSidebar = ({
asChild
leftIcon={route.icon}
variant={isActive ? "active" : "ghost"}
+ size="sm"
className="w-full justify-start"
>
<Link
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index a2e78d6267..344c019b19 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -223,7 +223,7 @@ export async function getJobOperationsByMethodId(
export async function recalculateJobRequirements(
client: SupabaseClient<Database>,
params: {
- id: string;
+ id: string; // job id
companyId: string;
userId: string;
}
@@ -236,6 +236,22 @@ export async function recalculateJobRequirements(
});
}
+export async function recalculateJobMakeMethodRequirements(
+ client: SupabaseClient<Database>,
+ params: {
+ id: string; // job make method id
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("recalculate", {
+ body: {
+ type: "jobMakeMethodRequirements",
+ ...params,
+ },
+ });
+}
+
export async function updateJobMaterialOrder(
client: SupabaseClient<Database>,
updates: {
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
index e83850d844..2b4e18be93 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
@@ -28,10 +28,12 @@ import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useMemo, useState } from "react";
import {
LuAlertTriangle,
+ LuComponent,
LuDownload,
LuHardHat,
LuUpload,
} from "react-icons/lu";
+import { RiProgress4Line } from "react-icons/ri";
import { BreadcrumbItem, Breadcrumbs } from "~/components";
import {
Hidden,
@@ -151,8 +153,13 @@ const JobBreadcrumbs = () => {
<Tabs defaultValue="item" className="w-full">
{isJobMethod && (
<TabsList className="grid w-full grid-cols-2 my-4">
- <TabsTrigger value="item">Item</TabsTrigger>
- <TabsTrigger value="quote">Quote</TabsTrigger>
+ <TabsTrigger value="item">
+ <LuComponent className="mr-2" /> Item
+ </TabsTrigger>
+ <TabsTrigger value="quote">
+ <RiProgress4Line className="mr-2" />
+ Quote
+ </TabsTrigger>
</TabsList>
)}
<TabsContent value="item">
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index b6b3dddbc7..2f69c8e046 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -227,6 +227,7 @@ function QuoteLineItem({
<IconButton
aria-label={disclosure.isOpen ? "Hide" : "Show"}
icon={<LuChevronsUpDown />}
+ size="sm"
variant="ghost"
onClick={(e) => {
e.stopPropagation();
@@ -239,6 +240,7 @@ function QuoteLineItem({
<IconButton
aria-label="More"
icon={<MdMoreVert />}
+ size="sm"
variant="ghost"
onClick={(e) => e.stopPropagation()}
/>
diff --git a/apps/carbon/app/routes/x+/_index.tsx b/apps/carbon/app/routes/x+/_index.tsx
index 2e1080a815..fed557c51c 100644
--- a/apps/carbon/app/routes/x+/_index.tsx
+++ b/apps/carbon/app/routes/x+/_index.tsx
@@ -51,7 +51,7 @@ const ModuleCard = ({ module }: { module: Authenticated<NavItem> }) => (
<Link
to={module.to}
prefetch="intent"
- className="flex flex-col gap-6 items-center justify-center py-8 bg-gradient-to-bl from-card to-background rounded-lg shadow text-center group ring-2 ring-transparent hover:ring-white/10 cursor-pointer"
+ className="flex flex-col gap-6 items-center justify-center py-8 border border-border shadow-md dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card to-background rounded-lg text-center group ring-2 ring-transparent hover:ring-white/10 cursor-pointer"
>
<module.icon className="text-3xl" />
<span className="text-sm py-1 px-4 border border-border rounded-full group-hover:bg-accent">
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
index 260453fc6d..26248bf570 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.details.tsx
@@ -1,6 +1,7 @@
import { validationError, validator } from "@carbon/form";
import { VStack } from "@carbon/react";
import { useParams } from "@remix-run/react";
+import { tasks } from "@trigger.dev/sdk/v3";
import type { ActionFunctionArgs } from "@vercel/remix";
import { redirect } from "@vercel/remix";
import { CadModel, Documents } from "~/components";
@@ -9,6 +10,7 @@ import type { Job } from "~/modules/production";
import { JobForm, jobValidator, upsertJob } from "~/modules/production";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
+import type { recalculateTask } from "~/trigger/recalculate";
import type { StorageItem } from "~/types";
import { getCustomFields, setCustomFields } from "~/utils/form";
import { assertIsPost } from "~/utils/http";
@@ -17,7 +19,7 @@ import { error, success } from "~/utils/result";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
update: "production",
});
@@ -48,6 +50,14 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // TODO: we really only want to do this if the quantity has changed
+ await tasks.trigger<typeof recalculateTask>("recalculate", {
+ type: "jobRequirements",
+ id,
+ companyId,
+ userId,
+ });
+
throw redirect(path.to.job(id), await flash(request, success("Updated job")));
}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 3adf54b4a9..2f589083b9 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -1,7 +1,11 @@
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
import { getSupabaseServiceRole } from "~/lib/supabase";
-import { jobMaterialValidator, upsertJobMaterial } from "~/modules/production";
+import {
+ jobMaterialValidator,
+ recalculateJobMakeMethodRequirements,
+ upsertJobMaterial,
+} from "~/modules/production";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import { setCustomFields } from "~/utils/form";
@@ -64,6 +68,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ const recalculateResult = await recalculateJobMakeMethodRequirements(
+ serviceRole,
+ {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ }
+ );
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
+
return json({
id: jobMaterialId,
methodType: updateJobMaterial.data.methodType,
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
index 60cf997bd2..280cd8dd81 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
@@ -29,5 +29,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // TODO: if it is a make method -- we should get the tree from the jobMakeMethod with parentMaterialId = id, and delete everything that comes back
+
return json({});
}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index bc6feaf436..93fc8525e7 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -3,6 +3,7 @@ import { json, type ActionFunctionArgs } from "@vercel/remix";
import { getSupabaseServiceRole } from "~/lib/supabase";
import {
jobMaterialValidator,
+ recalculateJobMakeMethodRequirements,
upsertJobMaterial,
upsertJobMaterialMakeMethod,
} from "~/modules/production";
@@ -86,5 +87,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
+ const recalculateResult = await recalculateJobMakeMethodRequirements(
+ serviceRole,
+ {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ }
+ );
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobMaterialId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
+
return json({ id: jobMaterialId });
}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
index 243c24ec45..9ffcb85aa8 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -1,7 +1,9 @@
import { validationError, validator } from "@carbon/form";
import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { getSupabaseServiceRole } from "~/lib/supabase";
import {
jobOperationValidator,
+ recalculateJobMakeMethodRequirements,
upsertJobOperation,
} from "~/modules/production";
import { requirePermissions } from "~/services/auth/auth.server";
@@ -12,10 +14,11 @@ import { error } from "~/utils/result";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
+ const { companyId, userId } = await requirePermissions(request, {
create: "production",
});
+ const serviceRole = getSupabaseServiceRole();
const { jobId } = params;
if (!jobId) {
throw new Error("jobId not found");
@@ -30,7 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const insertJobOperation = await upsertJobOperation(client, {
+ const insertJobOperation = await upsertJobOperation(serviceRole, {
...data,
jobId,
companyId,
@@ -62,5 +65,27 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ const recalculateResult = await recalculateJobMakeMethodRequirements(
+ serviceRole,
+ {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ }
+ );
+
+ if (recalculateResult.error) {
+ return json(
+ { id: jobOperationId },
+ await flash(
+ request,
+ error(
+ recalculateResult.error,
+ "Failed to recalculate job make method requirements"
+ )
+ )
+ );
+ }
+
return json({ id: jobOperationId });
}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/get.tsx b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
index ffe6ef74ad..f4420739b5 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
@@ -3,6 +3,7 @@ import { json, redirect, type ActionFunctionArgs } from "@vercel/remix";
import { getSupabaseServiceRole } from "~/lib/supabase";
import {
getJobMethodValidator,
+ recalculateJobRequirements,
upsertJobMaterialMakeMethod,
upsertJobMethod,
} from "~/modules/production";
@@ -35,6 +36,18 @@ export async function action({ request }: ActionFunctionArgs) {
}
);
+ const calculateQuantities = await recalculateJobRequirements(serviceRole, {
+ id: validation.data.targetId,
+ companyId: companyId,
+ userId: userId,
+ });
+
+ if (calculateQuantities.error) {
+ return json({
+ error: "Failed to calculate job quantities",
+ });
+ }
+
return json({
error: jobMethod.error ? "Failed to get job method" : null,
});
diff --git a/apps/carbon/app/trigger/recalculate.ts b/apps/carbon/app/trigger/recalculate.ts
index 580396f8e6..26ec11f6b8 100644
--- a/apps/carbon/app/trigger/recalculate.ts
+++ b/apps/carbon/app/trigger/recalculate.ts
@@ -1,11 +1,15 @@
+import type { FunctionsResponse } from "@supabase/functions-js";
import { task } from "@trigger.dev/sdk/v3";
import { z } from "zod";
import { getSupabaseServiceRole } from "~/lib/supabase";
import type { Result } from "~/types";
-import { recalculateJobRequirements } from "../modules/production/production.service";
+import {
+ recalculateJobMakeMethodRequirements,
+ recalculateJobRequirements,
+} from "../modules/production/production.service";
const recalculateSchema = z.object({
- type: z.enum(["jobRequirements"]),
+ type: z.enum(["jobRequirements", "jobMakeMethodRequirements"]),
id: z.string(),
companyId: z.string(),
userId: z.string(),
@@ -18,11 +22,27 @@ export const recalculateTask = task({
const serviceRole = getSupabaseServiceRole();
let result: Result;
+ let calculateQuantities: FunctionsResponse<{ success: boolean }>;
switch (payload.type) {
case "jobRequirements":
console.info(`📊 Recalculating job requirements for ${payload.id}`);
- const calculateQuantities = await recalculateJobRequirements(
+ calculateQuantities = await recalculateJobRequirements(serviceRole, {
+ id: payload.id,
+ companyId: payload.companyId,
+ userId: payload.userId,
+ });
+
+ result = {
+ success: !calculateQuantities.error,
+ message: calculateQuantities.error?.message,
+ };
+ break;
+ case "jobMakeMethodRequirements":
+ console.info(
+ `📊 Recalculating job make method requirements for ${payload.id}`
+ );
+ calculateQuantities = await recalculateJobMakeMethodRequirements(
serviceRole,
{
id: payload.id,
diff --git a/packages/database/supabase/functions/lib/methods.ts b/packages/database/supabase/functions/lib/methods.ts
index ca42c12828..38a1f87ccc 100644
--- a/packages/database/supabase/functions/lib/methods.ts
+++ b/packages/database/supabase/functions/lib/methods.ts
@@ -13,12 +13,13 @@ export type JobMethodTreeItem = {
export async function getJobMethodTree(
client: SupabaseClient<Database>,
- methodId: string
+ methodId: string,
+ parentMaterialId: string | null = null
) {
const items = await getJobMethodTreeArray(client, methodId);
if (items.error) return items;
- const tree = getJobMethodTreeArrayToTree(items.data);
+ const tree = getJobMethodTreeArrayToTree(items.data, parentMaterialId);
return {
data: tree,
@@ -35,7 +36,10 @@ export function getJobMethodTreeArray(
});
}
-function getJobMethodTreeArrayToTree(items: JobMethod[]): JobMethodTreeItem[] {
+function getJobMethodTreeArrayToTree(
+ items: JobMethod[],
+ parentMaterialId: string | null = null
+): JobMethodTreeItem[] {
// function traverseAndRenameIds(node: JobMethodTreeItem) {
// const clone = structuredClone(node);
// clone.id = `node-${Math.random().toString(16).slice(2)}`;
@@ -59,7 +63,7 @@ function getJobMethodTreeArrayToTree(items: JobMethod[]): JobMethodTreeItem[] {
const treeItem = lookup[itemId];
- if (parentId === null || parentId === undefined) {
+ if (parentId === parentMaterialId || parentId === undefined) {
rootItems.push(treeItem);
} else {
if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {
diff --git a/packages/database/supabase/functions/recalculate/index.ts b/packages/database/supabase/functions/recalculate/index.ts
index f2dfcdc3c2..7aa5eaf22e 100644
--- a/packages/database/supabase/functions/recalculate/index.ts
+++ b/packages/database/supabase/functions/recalculate/index.ts
@@ -3,6 +3,7 @@ import { z } from "https://deno.land/x/[email protected]/mod.ts";
import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";
+import { Transaction } from "https://esm.sh/v135/[email protected]/dist/cjs/kysely.d.ts";
import { corsHeaders } from "../lib/headers.ts";
import { getJobMethodTree, JobMethodTreeItem } from "../lib/methods.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
@@ -11,7 +12,7 @@ const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
const payloadValidator = z.object({
- type: z.enum(["jobRequirements"]),
+ type: z.enum(["jobMakeMethodRequirements", "jobRequirements"]),
id: z.string(),
companyId: z.string(),
userId: z.string(),
@@ -37,6 +38,96 @@ serve(async (req: Request) => {
const client = getSupabaseServiceRole(req.headers.get("Authorization"));
switch (type) {
+ case "jobMakeMethodRequirements": {
+ const jobMakeMethodId = id;
+
+ const [jobMakeMethod] = await Promise.all([
+ client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("id", jobMakeMethodId)
+ .single(),
+ ]);
+
+ if (jobMakeMethod.error) {
+ throw new Error(
+ `Failed to get job makeMethod: ${jobMakeMethod.error.message}`
+ );
+ }
+
+ let parentQuantity = 1;
+ if (jobMakeMethod.data.parentMaterialId) {
+ const jobMaterial = await client
+ .from("jobMaterial")
+ .select("*")
+ .eq("id", jobMakeMethod.data.parentMaterialId)
+ .single();
+ if (jobMaterial.data?.methodType !== "Make") {
+ return new Response(JSON.stringify({ success: true }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ });
+ }
+
+ if (jobMaterial.error) {
+ throw new Error(
+ `Failed to get job material: ${jobMaterial.error.message}`
+ );
+ }
+
+ if (!jobMaterial.data) {
+ throw new Error(
+ `Job material not found for id: ${jobMakeMethod.data.parentMaterialId}`
+ );
+ }
+
+ if (jobMaterial.data.methodType !== "Make") {
+ console.log(
+ `Job material ${jobMakeMethod.data.parentMaterialId} is not a 'Make' type. Skipping recalculation.`
+ );
+ return new Response(JSON.stringify({ success: true }), {
+ headers: { ...corsHeaders, "Content-Type": "application/json" },
+ status: 200,
+ });
+ }
+
+ parentQuantity =
+ jobMaterial.data.estimatedQuantity ?? jobMaterial.data.quantity;
+ } else {
+ const job = await client
+ .from("job")
+ .select("*")
+ .eq("id", jobMakeMethod.data.jobId)
+ .single();
+ if (job.error) {
+ throw new Error(`Failed to get job: ${job.error.message}`);
+ }
+ parentQuantity = job.data.productionQuantity ?? 1;
+ }
+
+ const jobMethodTrees = await getJobMethodTree(
+ client,
+ jobMakeMethod.data.id,
+ jobMakeMethod.data.parentMaterialId
+ );
+
+ if (jobMethodTrees.error) {
+ throw new Error(
+ `Failed to get method tree: ${jobMethodTrees.error.message}`
+ );
+ }
+
+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;
+ if (!jobMethodTree) {
+ throw new Error("Method tree not found");
+ }
+
+ await db.transaction().execute(async (trx) => {
+ await updateQuantities(trx, jobMethodTree, parentQuantity);
+ });
+
+ break;
+ }
case "jobRequirements": {
const jobId = id;
const [job, jobMakeMethod] = await Promise.all([
@@ -71,35 +162,7 @@ serve(async (req: Request) => {
}
await db.transaction().execute(async (trx) => {
- const updateQuantities = async (
- tree: JobMethodTreeItem,
- parentQuantity: number = 1
- ) => {
- const currentQuantity = tree.data.quantity * parentQuantity;
-
- // Update jobMaterial
- await trx
- .updateTable("jobMaterial")
- .set({ estimatedQuantity: currentQuantity })
- .where("id", "=", tree.id)
- .execute();
-
- // Update jobOperation
- await trx
- .updateTable("jobOperation")
- .set({ operationQuantity: currentQuantity })
- .where("jobMakeMethodId", "=", tree.data.jobMakeMethodId)
- .execute();
-
- // Recursively update children
- if (tree.children) {
- for (const child of tree.children) {
- await updateQuantities(child, currentQuantity);
- }
- }
- };
-
- await updateQuantities(jobMethodTree, job.data?.quantity);
+ await updateQuantities(trx, jobMethodTree, job.data?.quantity);
});
break;
@@ -126,3 +189,32 @@ serve(async (req: Request) => {
});
}
});
+
+const updateQuantities = async (
+ trx: Transaction<DB>,
+ tree: JobMethodTreeItem,
+ parentQuantity: number = 1
+) => {
+ const currentQuantity = tree.data.quantity * parentQuantity;
+
+ // Update jobMaterial
+ await trx
+ .updateTable("jobMaterial")
+ .set({ estimatedQuantity: currentQuantity })
+ .where("id", "=", tree.id)
+ .execute();
+
+ // Update jobOperation
+ await trx
+ .updateTable("jobOperation")
+ .set({ operationQuantity: parentQuantity })
+ .where("jobMakeMethodId", "=", tree.data.jobMakeMethodId)
+ .execute();
+
+ // Recursively update children
+ if (tree.children) {
+ for (const child of tree.children) {
+ await updateQuantities(trx, child, currentQuantity);
+ }
+ }
+};
diff --git a/packages/database/supabase/migrations/20240920171731_job-requirements.sql b/packages/database/supabase/migrations/20240920171731_job-requirements.sql
index 1de6567615..47253b0683 100644
--- a/packages/database/supabase/migrations/20240920171731_job-requirements.sql
+++ b/packages/database/supabase/migrations/20240920171731_job-requirements.sql
@@ -14,4 +14,6 @@ CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true)
ALTER TABLE "jobOperation"
ADD COLUMN "operationQuantity" NUMERIC(10,4) DEFAULT 0,
ADD COLUMN "quantityComplete" NUMERIC(10,4) DEFAULT 0,
- ADD COLUMN "quantityScrapped" NUMERIC(10,4) DEFAULT 0;
\ No newline at end of file
+ ADD COLUMN "quantityScrapped" NUMERIC(10,4) DEFAULT 0;
+
+
diff --git a/packages/database/supabase/migrations/20240921113841_method-tree-short-circuit.sql b/packages/database/supabase/migrations/20240921113841_method-tree-short-circuit.sql
new file mode 100644
index 0000000000..f1c3c64152
--- /dev/null
+++ b/packages/database/supabase/migrations/20240921113841_method-tree-short-circuit.sql
@@ -0,0 +1,307 @@
+-- short circuit tree if it's not a make method:
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC(10,4) AS "quantity",
+ 0::NUMERIC(10,4) AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot"
+ 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"
+ 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."readableId" AS "itemReadableId",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+CREATE OR REPLACE FUNCTION get_job_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC(10,4) AS "quantity",
+ 0::NUMERIC(10,4) AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "id" = mid
+ 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"
+ 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."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+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,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN
+) 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(10,4) AS "quantity",
+ 0::NUMERIC(10,4) AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot"
+ 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"
+ 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."readableId" AS "itemReadableId",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+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,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN
+) 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(10,4) AS "quantity",
+ 0::NUMERIC(10,4) AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "id" = mid
+ 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"
+ 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."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
\ No newline at end of file
diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsx
index a517d71806..63d17c63b6 100644
--- a/packages/react/src/Card.tsx
+++ b/packages/react/src/Card.tsx
@@ -31,7 +31,7 @@ const Card = forwardRef<HTMLDivElement, CardProps>(
<div
ref={ref}
className={cn(
- "relative flex flex-col rounded-lg border border-border bg-gradient-to-bl from-card to-background text-card-foreground shadow-sm w-full",
+ "relative flex flex-col rounded-lg border border-border shadow-md dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] bg-gradient-to-bl from-card via-card to-background text-card-foreground w-full",
className
)}
{...props}
diff --git a/packages/react/src/Menubar.tsx b/packages/react/src/Menubar.tsx
index 7866643136..aa94ac1aaa 100644
--- a/packages/react/src/Menubar.tsx
+++ b/packages/react/src/Menubar.tsx
@@ -10,7 +10,7 @@ const Menubar = forwardRef<HTMLDivElement, ComponentProps<"div">>(
<div
{...props}
className={cn(
- "min-h-[2.5rem] flex items-center bg-card border border-border rounded-lg shadow-sm justify-start p-1 w-full space-x-1 overflow-x-scroll scrollbar-hide",
+ "min-h-[2.5rem] flex items-center bg-card border border-border shadow-sm dark:border-0 dark:shadow-[0px_1px_0px_0px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_hsla(0,0%,100%,.03)_inset,0px_0px_0px_1px_rgba(0,0,0,.1),0px_2px_2px_0px_rgba(0,0,0,.1),0px_4px_4px_0px_rgba(0,0,0,.1),0px_8px_8px_0px_rgba(0,0,0,.1)] rounded-lg justify-start p-1 w-full space-x-1 overflow-x-scroll scrollbar-hide",
className
)}
>