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 costing component

Brad Barbina65b398ad61b
diff --git a/apps/carbon/app/components/TreeView/index.ts b/apps/carbon/app/components/TreeView/index.ts
index b7766fcf41..9215489cf1 100644
--- a/apps/carbon/app/components/TreeView/index.ts
+++ b/apps/carbon/app/components/TreeView/index.ts
@@ -1,5 +1,10 @@
import type { NodesState, NodeState } from "./reducer";
-import type { FlatTree, FlatTreeItem, UseTreeStateOutput } from "./TreeView";
+import type {
+ FlatTree,
+ FlatTreeItem,
+ Tree,
+ UseTreeStateOutput,
+} from "./TreeView";
import { flattenTree, LevelLine, TreeView, useTree } from "./TreeView";
export { flattenTree, LevelLine, TreeView, useTree };
@@ -8,5 +13,6 @@ export type {
FlatTreeItem,
NodesState,
NodeState,
+ Tree,
UseTreeStateOutput,
};
diff --git a/apps/carbon/app/entry.server.tsx b/apps/carbon/app/entry.server.tsx
index 6bc243546a..368b255099 100644
--- a/apps/carbon/app/entry.server.tsx
+++ b/apps/carbon/app/entry.server.tsx
@@ -14,7 +14,7 @@ const ABORT_DELAY = 30000;
// This code has the effect of registering jobs with trigger.dev
// in a way that doesn't interfere with the vite compiler.
-export * from "~/jobs.server";
+export * from "~/jobs";
// Workaround for vite single fetch mode
installAndLockGlobals();
diff --git a/apps/carbon/app/jobs/autodesk-poll.server.ts b/apps/carbon/app/jobs/autodesk-poll.server.ts
new file mode 100644
index 0000000000..60e9c72c3c
--- /dev/null
+++ b/apps/carbon/app/jobs/autodesk-poll.server.ts
@@ -0,0 +1,72 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+import { getAutodeskToken, getManifest } from "~/lib/autodesk/autodesk.server";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import { upsertModelUpload } from "~/modules/shared";
+
+const supabaseClient = getSupabaseServiceRole();
+
+const job = triggerClient.defineJob({
+ id: "autodesk-poll",
+ name: "Poll Autodesk for Translation Progress",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "autodesk.poll",
+ schema: z.object({
+ id: z.string(),
+ name: z.string(),
+ size: z.number(),
+ autodeskUrn: z.string(),
+ companyId: z.string(),
+ }),
+ }),
+ run: async (payload, io, ctx) => {
+ const { companyId, id, name, size, autodeskUrn } = payload;
+
+ await io.runTask(
+ "autodesk-manifest-poll",
+ async () => {
+ const token = await getAutodeskToken();
+ if (token.error) {
+ throw new Error(
+ "Failed to get Autodesk token: " + token.error.message
+ );
+ }
+
+ const manifest = await getManifest(
+ autodeskUrn,
+ token.data.token,
+ companyId
+ );
+ if (manifest.error) {
+ throw new Error("Failed to get manifest: " + manifest.error.message);
+ }
+
+ const modelRecord = await upsertModelUpload(supabaseClient, {
+ id,
+ name,
+ size,
+ thumbnailPath: manifest.data.thumbnailPath,
+ autodeskUrn,
+ });
+
+ if (modelRecord.error) {
+ throw new Error(
+ "Failed to record upload: " + modelRecord.error.message
+ );
+ }
+ },
+ {
+ name: "Autodesk Manifest Poll",
+ retry: {
+ limit: 5,
+ maxTimeoutInMs: 1000 * 15,
+ },
+ }
+ );
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/autodesk-upload.server.ts b/apps/carbon/app/jobs/autodesk-upload.server.ts
new file mode 100644
index 0000000000..b8fef39f9e
--- /dev/null
+++ b/apps/carbon/app/jobs/autodesk-upload.server.ts
@@ -0,0 +1,130 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+import {
+ finalizeAutodeskUpload,
+ getAutodeskSignedUrl,
+ getAutodeskToken,
+ translateFile,
+ uploadToAutodesk,
+} from "~/lib/autodesk/autodesk.server";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+
+const supabaseClient = getSupabaseServiceRole();
+
+const job = triggerClient.defineJob({
+ id: "autodesk-upload",
+ name: "Upload CAD Model to Autodesk",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "autodesk.upload",
+ schema: z.object({
+ name: z.string(),
+ modelPath: z.string(),
+ fileId: z.string(),
+ companyId: z.string(),
+ itemId: z.union([z.string(), z.null()]),
+ salesRfqLineId: z.union([z.string(), z.null()]),
+ quoteLineId: z.union([z.string(), z.null()]),
+ }),
+ }),
+ run: async (payload, io, ctx) => {
+ const {
+ companyId,
+ modelPath,
+ fileId,
+ name,
+ itemId,
+ salesRfqLineId,
+ quoteLineId,
+ } = payload;
+
+ try {
+ const autodeskToken = await getAutodeskToken();
+ if (autodeskToken.error) {
+ throw new Error(
+ "Failed to get Autodesk token: " + autodeskToken.error.message
+ );
+ }
+ const token = autodeskToken.data?.token;
+ const encodedFilename = modelPath.split("/").pop() as string;
+
+ const [signedUrl, blob] = await Promise.all([
+ getAutodeskSignedUrl(encodedFilename, token),
+ supabaseClient.storage.from("private").download(modelPath),
+ ]);
+ if (signedUrl.error) {
+ throw new Error("Failed to get signed URL: " + signedUrl.error.message);
+ }
+ if (blob.error) {
+ throw new Error("Failed to download blob: " + blob.error.message);
+ }
+
+ const file = new File([blob.data], encodedFilename);
+ const { uploadKey, url } = signedUrl.data;
+
+ const initialUpload = await uploadToAutodesk(url, file, uploadKey);
+ if (initialUpload.error) {
+ throw new Error(
+ "Failed to upload file: " + initialUpload.error.message
+ );
+ }
+
+ const upload = await finalizeAutodeskUpload(
+ encodedFilename,
+ token,
+ uploadKey
+ );
+ if (upload.error) {
+ throw new Error("Failed to finalize upload: " + upload.error.message);
+ }
+
+ const { urn } = upload.data;
+ const autodeskUrn = Buffer.from(urn).toString("base64");
+
+ const translation = await translateFile(autodeskUrn, token);
+ if (translation.error) {
+ throw new Error(
+ "Failed to translate file: " + translation.error.message
+ );
+ }
+
+ const event = await triggerClient.sendEvent({
+ name: "autodesk.poll",
+ payload: {
+ id: fileId,
+ size: file.size,
+ name,
+ autodeskUrn,
+ companyId,
+ },
+ });
+
+ io.logger.info("Event sent", event);
+ } catch (err) {
+ const client = getSupabaseServiceRole();
+ if (itemId) {
+ await client
+ .from("item")
+ .update({ modelUploadId: null })
+ .eq("id", itemId);
+ }
+ if (salesRfqLineId) {
+ await client
+ .from("salesRfqLine")
+ .update({ modelUploadId: null })
+ .eq("id", salesRfqLineId);
+ }
+ if (quoteLineId) {
+ await client
+ .from("quoteLine")
+ .update({ modelUploadId: null })
+ .eq("id", quoteLineId);
+ }
+ io.logger.error("Error uploading to Autodesk");
+ }
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/index.ts b/apps/carbon/app/jobs/index.ts
new file mode 100644
index 0000000000..a6ccfbf58a
--- /dev/null
+++ b/apps/carbon/app/jobs/index.ts
@@ -0,0 +1,17 @@
+import autodeskPoll from "./autodesk-poll.server";
+import autodeskUpload from "./autodesk-upload.server";
+import postTransaction from "./post-transaction.server";
+import sendEmailResend from "./send-email-resend.server";
+import updateExchangeRates from "./update-exchange-rates.server";
+import updatePermissions from "./update-permissions.server";
+import userAdminServer from "./user-admin.server";
+
+export {
+ autodeskPoll,
+ autodeskUpload,
+ postTransaction,
+ sendEmailResend,
+ updateExchangeRates,
+ updatePermissions,
+ userAdminServer,
+};
diff --git a/apps/carbon/app/jobs/post-transaction.server.ts b/apps/carbon/app/jobs/post-transaction.server.ts
new file mode 100644
index 0000000000..8aecf77b7a
--- /dev/null
+++ b/apps/carbon/app/jobs/post-transaction.server.ts
@@ -0,0 +1,103 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import type { Result } from "~/types";
+
+const supabaseClient = getSupabaseServiceRole();
+export const postTransactionSchema = z.object({
+ documentId: z.string(),
+ type: z.enum(["receipt", "purchase-invoice"]),
+});
+
+const job = triggerClient.defineJob({
+ id: "post-transactions",
+ name: "Post Transactions",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "post.transactions",
+ schema: postTransactionSchema,
+ }),
+ run: async (payload, io, ctx) => {
+ await io.logger.info(
+ `🔰 User admin update ${payload.type} for ${payload.documentId}`
+ );
+
+ let result: Result;
+
+ switch (payload.type) {
+ case "receipt":
+ await io.logger.info(`📫 Posting receipt ${payload.documentId}`);
+ const postReceipt = await supabaseClient.functions.invoke(
+ "post-receipt",
+ {
+ body: {
+ receiptId: payload.documentId,
+ },
+ }
+ );
+
+ result = {
+ success: postReceipt.error === null ? true : false,
+ message: postReceipt.error?.message,
+ };
+
+ break;
+ case "purchase-invoice":
+ await io.logger.info(
+ `📫 Posting purchase invoice ${payload.documentId}`
+ );
+ const postPurchaseInvoice = await supabaseClient.functions.invoke(
+ "post-purchase-invoice",
+ {
+ body: {
+ invoiceId: payload.documentId,
+ },
+ }
+ );
+
+ result = {
+ success: postPurchaseInvoice.error === null ? true : false,
+ message: postPurchaseInvoice.error?.message,
+ };
+
+ if (result.success) {
+ await io.logger.info(
+ `💵 Updating pricing from invoice ${payload.documentId}`
+ );
+ const priceUpdate = await supabaseClient.functions.invoke(
+ "update-purchased-prices",
+ {
+ body: {
+ invoiceId: payload.documentId,
+ },
+ }
+ );
+
+ result = {
+ success: priceUpdate.error === null ? true : false,
+ message: priceUpdate.error?.message,
+ };
+ }
+
+ break;
+ default:
+ result = {
+ success: false,
+ message: `Invalid posting type: ${payload.type}`,
+ };
+ break;
+ }
+
+ if (result.success) {
+ await io.logger.info(`✅ Success ${payload.documentId}`);
+ } else {
+ await io.logger.error(
+ `❌ Admin action ${payload.type} failed for ${payload.documentId}: ${result.message}`
+ );
+ }
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/send-email-resend.server.ts b/apps/carbon/app/jobs/send-email-resend.server.ts
new file mode 100644
index 0000000000..4b7e3e61b7
--- /dev/null
+++ b/apps/carbon/app/jobs/send-email-resend.server.ts
@@ -0,0 +1,71 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { nanoid } from "nanoid";
+import { Resend } from "resend";
+import { z } from "zod";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import { resendFormValidator } from "~/modules/settings";
+
+const supabaseClient = getSupabaseServiceRole();
+
+const job = triggerClient.defineJob({
+ id: "send-email-resend",
+ name: "Send Email with Resend",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "resend.email",
+ schema: z.object({
+ to: z.union([z.string(), z.array(z.string())]),
+ cc: z.union([z.string(), z.array(z.string())]).optional(),
+ from: z.string().optional(),
+ subject: z.string(),
+ text: z.string(),
+ html: z.string(),
+ attachments: z
+ .object({
+ filename: z.string(),
+ content: z.any(),
+ })
+ .array()
+ .optional(),
+ companyId: z.string(),
+ }),
+ }),
+ run: async (payload, io, ctx) => {
+ const integration = await supabaseClient
+ .from("companyIntegration")
+ .select("active, metadata")
+ .eq("companyId", payload.companyId)
+ .eq("id", "resend")
+ .maybeSingle();
+
+ // TODO: integration should include from email
+ const integrationMetadata = resendFormValidator.safeParse(
+ integration?.data?.metadata
+ );
+
+ if (!integrationMetadata.success || integration?.data?.active !== true)
+ return;
+
+ const resend = new Resend(integrationMetadata.data.apiKey);
+
+ const email = {
+ to: payload.to,
+ reply_to: payload.from,
+ subject: payload.subject,
+ html: payload.html,
+ text: payload.text,
+ attachments: payload.attachments,
+ headers: {
+ "X-Entity-Ref-ID": nanoid(7),
+ },
+ };
+
+ await io.logger.info(`📬 Resend Email Job`);
+ await resend.emails.send(email);
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/update-exchange-rates.server.ts b/apps/carbon/app/jobs/update-exchange-rates.server.ts
new file mode 100644
index 0000000000..fce5e7d10d
--- /dev/null
+++ b/apps/carbon/app/jobs/update-exchange-rates.server.ts
@@ -0,0 +1,95 @@
+import { intervalTrigger } from "@trigger.dev/sdk";
+import type { ExchangeRatesClient, Rates } from "~/lib/exchange-rates.server";
+import { getExchangeRatesClient } from "~/lib/exchange-rates.server";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import type { CurrencyCode } from "~/modules/accounting";
+import { exchangeRatesFormValidator } from "~/modules/settings";
+
+const supabaseClient = getSupabaseServiceRole();
+
+const job = triggerClient.defineJob({
+ id: "update-exchange-rates",
+ name: "Update Currency Exchange Rates",
+ version: "0.0.1",
+ trigger: intervalTrigger({
+ seconds: 60 * 60 * 8, // thrice a day
+ }),
+ run: async (payload, io, ctx) => {
+ let rates: Rates;
+ let hasRates = false;
+ let exchangeRatesClient: ExchangeRatesClient | undefined;
+
+ const integrations = await supabaseClient
+ .from("companyIntegration")
+ .select("active, metadata, companyId")
+ .eq("id", "exchange-rates-v1");
+
+ if (integrations.error) {
+ io.logger.error(JSON.stringify(integrations.error));
+ return;
+ }
+
+ await io.logger.info(`💵 Exchange Rates Job: ${payload.lastTimestamp}`);
+ for await (const integration of integrations.data) {
+ const integrationMetadata = exchangeRatesFormValidator.safeParse(
+ integration?.metadata
+ );
+
+ if (!integrationMetadata.success || integration?.active !== true) return;
+
+ try {
+ if (!hasRates) {
+ exchangeRatesClient = getExchangeRatesClient(
+ integrationMetadata.data.apiKey
+ );
+
+ if (!exchangeRatesClient) return;
+ await io.logger.info(
+ JSON.stringify(exchangeRatesClient.getMetaData())
+ );
+ rates = await exchangeRatesClient.getExchangeRates();
+ await io.logger.info(JSON.stringify(rates));
+ hasRates = true;
+ }
+ // @ts-expect-error
+ if (!rates) throw new Error("No rates found");
+
+ const updatedAt = new Date().toISOString();
+
+ const { data } = await supabaseClient
+ .from("currency")
+ .select("*")
+ .eq("companyId", integration.companyId);
+ if (!data) return;
+
+ const updates = data
+ // eslint-disable-next-line no-loop-func
+ .map((currency) => ({
+ ...currency,
+ exchangeRate: Number(
+ rates[currency.code as CurrencyCode]?.toFixed(
+ currency.decimalPlaces
+ )
+ ),
+ updatedAt,
+ }))
+ .filter((currency) => currency.exchangeRate);
+
+ if (updates?.length === 0) return;
+
+ const { error } = await supabaseClient.from("currency").upsert(updates);
+ if (error) {
+ await io.logger.error(JSON.stringify(error));
+ return;
+ }
+ } catch (err) {
+ // TODO: notify someone
+ await io.logger.error(JSON.stringify(err));
+ }
+ }
+ io.logger.log("Success");
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/update-permissions.server.ts b/apps/carbon/app/jobs/update-permissions.server.ts
new file mode 100644
index 0000000000..c76bd1c288
--- /dev/null
+++ b/apps/carbon/app/jobs/update-permissions.server.ts
@@ -0,0 +1,48 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import { updatePermissions } from "~/modules/users/users.server";
+
+const supabaseClient = getSupabaseServiceRole();
+export const permissionsUpdateSchema = z.object({
+ id: z.string(),
+ addOnly: z.boolean(),
+ permissions: z.record(
+ z.string(),
+ z.object({
+ view: z.boolean(),
+ create: z.boolean(),
+ update: z.boolean(),
+ delete: z.boolean(),
+ })
+ ),
+ companyId: z.string(),
+});
+
+const job = triggerClient.defineJob({
+ id: "update-permissions",
+ name: "Update Permissions",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "update.permissions",
+ schema: permissionsUpdateSchema,
+ }),
+ run: async (payload, io, ctx) => {
+ await io.logger.info(`🔰 Permission Update for ${payload.id}`);
+ const { success, message } = await updatePermissions(
+ supabaseClient,
+ payload
+ );
+ if (success) {
+ await io.logger.info(`✅ Permission Update for ${payload.id}`);
+ } else {
+ await io.logger.error(
+ `❌ Permission Update for ${payload.id}: ${message}`
+ );
+ }
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/jobs/user-admin.server.ts b/apps/carbon/app/jobs/user-admin.server.ts
new file mode 100644
index 0000000000..19c30e23da
--- /dev/null
+++ b/apps/carbon/app/jobs/user-admin.server.ts
@@ -0,0 +1,58 @@
+import { eventTrigger } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { triggerClient } from "~/lib/trigger.server";
+import { deactivateUser, resendInvite } from "~/modules/users/users.server";
+import type { Result } from "~/types";
+
+const supabaseClient = getSupabaseServiceRole();
+export const userAdminSchema = z.object({
+ id: z.string(),
+ type: z.enum(["resend", "deactivate"]),
+});
+
+const job = triggerClient.defineJob({
+ id: "user-admin",
+ name: "User Admin",
+ version: "0.0.1",
+ trigger: eventTrigger({
+ name: "user.admin",
+ schema: userAdminSchema,
+ }),
+ run: async (payload, io, ctx) => {
+ await io.logger.info(
+ `🔰 User admin update ${payload.type} for ${payload.id}`
+ );
+
+ let result: Result;
+
+ switch (payload.type) {
+ case "resend":
+ await io.logger.info(`📫 Resending invite for ${payload.id}`);
+ result = await resendInvite(supabaseClient, payload.id);
+
+ break;
+ case "deactivate":
+ await io.logger.info(`🚭 Deactivating ${payload.id}`);
+ result = await deactivateUser(supabaseClient, payload.id);
+ break;
+ default:
+ result = {
+ success: false,
+ message: `Invalid user admin type: ${payload.type}`,
+ };
+ break;
+ }
+
+ if (result.success) {
+ await io.logger.info(`✅ Success ${payload.id}`);
+ } else {
+ await io.logger.error(
+ `❌ Admin action ${payload.type} failed for ${payload.id}: ${result.message}`
+ );
+ }
+ },
+});
+
+export default job;
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index df5d80b3c4..6a90e0c3e4 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -19,11 +19,6 @@ import type {
getSalesRFQs,
} from "./sales.service";
-// TODO: we should just use the FileObject type from supabase
-export type SalesOrderAttachment = NonNullable<
- Awaited<ReturnType<typeof getSalesOrderExternalDocuments>>["data"]
->[number];
-
export type Customer = NonNullable<
Awaited<ReturnType<typeof getCustomers>>["data"]
>[number];
@@ -82,6 +77,11 @@ export type SalesOrder = NonNullable<
Awaited<ReturnType<typeof getSalesOrders>>["data"]
>[number];
+// TODO: we should just use the FileObject type from supabase
+export type SalesOrderAttachment = NonNullable<
+ Awaited<ReturnType<typeof getSalesOrderExternalDocuments>>["data"]
+>[number];
+
export type SalesOrderLine = NonNullable<
Awaited<ReturnType<typeof getSalesOrderLines>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index d78016f20b..b4ab96e934 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -58,7 +58,8 @@ const QuoteBoMExplorer = ({ methods }: QuoteBoMExplorerProps) => {
? "bg-muted hover:bg-muted/90"
: "bg-transparent hover:bg-muted/90"
)}
- onClick={() => {
+ onClick={(e) => {
+ e.stopPropagation();
navigate(getNodePath(node));
}}
>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index e38b8813ad..255dd1dbf2 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -122,10 +122,11 @@ const QuoteMaterialForm = ({
initialValues.methodType.toLowerCase(),
initialValues.id!
);
- if (location.pathname !== newPath) {
+ if (fetcher.data && location.pathname !== newPath) {
navigate(newPath);
}
}, [
+ fetcher.data,
initialValues.id,
initialValues.methodType,
initialValues.quoteMaterialMakeMethodId,
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
index dc1fcdc407..a3dda2d8b2 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -13,13 +13,19 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData, useParams } from "@remix-run/react";
-import { usePermissions, useUser } from "~/hooks";
+import type { Tree } from "~/components/TreeView";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { CadModel } from "~/modules/items";
-import type { QuotationLine } from "~/modules/sales";
+import type {
+ QuotationLine,
+ QuotationOperation,
+ QuoteMethod,
+} from "~/modules/sales";
import {
getFilesByQuoteLineId,
getQuoteLine,
+ getQuoteOperationsByLine,
quotationPricingValidator,
QuoteLineDocuments,
QuoteLineForm,
@@ -43,8 +49,9 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
- const [line, files] = await Promise.all([
+ const [line, operations, files] = await Promise.all([
getQuoteLine(client, lineId),
+ getQuoteOperationsByLine(client, lineId),
getFilesByQuoteLineId(client, companyId, lineId),
]);
@@ -57,6 +64,7 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
return json({
line: line.data,
+ operations: operations?.data ?? [],
files: files?.data ?? [],
});
};
@@ -130,12 +138,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function QuoteLine() {
- const { line, files } = useLoaderData<typeof loader>();
+ const { line, operations, files } = useLoaderData<typeof loader>();
const permissions = usePermissions();
const { quoteId, lineId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
if (!lineId) throw new Error("Could not find lineId");
+ const quoteData = useRouteData<{ methods: Tree<QuoteMethod>[] }>(
+ path.to.quote(quoteId)
+ );
+
+ const methodTree = quoteData?.methods?.find(
+ (m) => m.data.quoteLineId === line.id
+ );
+
const initialValues = {
...line,
id: line.id ?? undefined,
@@ -173,6 +189,7 @@ export default function QuoteLine() {
modelUpload={line ?? undefined}
/>
</div>
+ <QuoteLineCosting methodTree={methodTree} operations={operations} />
<QuoteLineNotes line={line} />
<Outlet />
</>
@@ -181,6 +198,27 @@ export default function QuoteLine() {
);
}
+const QuoteLineCosting = ({
+ methodTree,
+ operations,
+}: {
+ methodTree?: Tree<QuoteMethod>;
+ operations: QuotationOperation[];
+}) => {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Costing</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="grid grid-cols-1 gap-2">
+ <pre>{JSON.stringify({ methodTree, operations }, null, 2)}</pre>
+ </div>
+ </CardContent>
+ </Card>
+ );
+};
+
const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
const {
id: userId,
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
index b3f8b8567e..d1e11945b6 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
@@ -22,8 +22,8 @@ import { Outlet, useNavigate, useParams } from "@remix-run/react";
import { useState } from "react";
import { LuChevronsUpDown, LuGhost, LuImage, LuPlus } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
+import type { Tree } from "~/components/TreeView";
import { flattenTree } from "~/components/TreeView";
-import type { Tree } from "~/components/TreeView/TreeView";
import { useOptimisticLocation, useRouteData, useUser } from "~/hooks";
import type { QuotationLine, QuoteMethod } from "~/modules/sales";
import {