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 the ability to set the deafault method and tracking type for materials in paperless integration

Brad Barbin2d038e0b2521
diff --git a/apps/erp/README.md b/apps/erp/README.md
index a9371de462..00931246be 100644
--- a/apps/erp/README.md
+++ b/apps/erp/README.md
@@ -8,10 +8,6 @@ Application for managing a manufacturing business.
Reusable react components that are specific to this project (and remix). Shared components should live in `packages/react` if they don't rely on some application-specific library. For example, the `Table` relies on some remix internals, so it lives in `app/components`, but the `Date` component is framework agnostic, so it lives in `packages/react`.
-### `app/trigger`
-
-Where background tasks are defined.
-
### `app/modules`
Where services, ui and form validators are defined for each module.
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
index 69538b4ccf..bf94e373ab 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
@@ -1,5 +1,5 @@
import { integrations as availableIntegrations } from "@carbon/ee";
-import { Boolean, Input, Submit, ValidatedForm } from "@carbon/form";
+import { Boolean, Input, Select, Submit, ValidatedForm } from "@carbon/form";
import {
Badge,
Button,
@@ -17,6 +17,7 @@ import {
import { SUPPORT_EMAIL } from "@carbon/utils";
import { useParams } from "@remix-run/react";
import { Processes } from "~/components/Form";
+import { MethodIcon, TrackingTypeIcon } from "~/components/Icons";
import { usePermissions, useUser } from "~/hooks";
import { path } from "~/utils/path";
@@ -127,6 +128,38 @@ export function IntegrationForm({
return (
<Processes name={setting.name} label={setting.label} />
);
+ case "options":
+ return (
+ <Select
+ key={setting.name}
+ name={setting.name}
+ label={setting.label}
+ options={
+ setting.listOptions?.map((option) => {
+ let icon: JSX.Element | null = null;
+ if (setting.name === "methodType") {
+ // @ts-ignore
+ icon = <MethodIcon type={option} />;
+ } else if (setting.name === "trackingType") {
+ // @ts-ignore
+ icon = <TrackingTypeIcon type={option} />;
+ }
+
+ return {
+ label: (
+ <Badge
+ variant="secondary"
+ className="flex items-center gap-2"
+ >
+ {icon ? icon : null} {option}
+ </Badge>
+ ),
+ value: option,
+ };
+ }) ?? []
+ }
+ />
+ );
default:
return null;
}
diff --git a/docs/tech-stack.mdx b/docs/tech-stack.mdx
deleted file mode 100644
index 1ad440f321..0000000000
--- a/docs/tech-stack.mdx
+++ /dev/null
@@ -1,96 +0,0 @@
-# Tech Stack
-
-Our tech stack aims to be as simple as possible, while still being powerful enough to build any web application. We use the following technologies:
-
-- [TypeScript](https://www.typescriptlang.org) is the programming language
-- [React](https://reactjs.org) for the frontend
-- [Chakra UI](https://chakra-ui.com) for the UI components
-- [Remix](https://remix.run) for the routing and compiling
-- [Supabase](https://supabase.io) for the database and authentication
-
-We also use [Redis](https://redis.io) for caching and [Vercel](https://vercel.com) for hosting, though in most cases you probably won't need those.
-
-In this page, we'll give you a basic overview of how the tech stack works together. If you want to learn more about any of the technologies, we recommend checking out their documentation.
-
-## TypeScript
-
-[TypeScript](https://www.typescriptlang.org) is a programming language that builds on top of JavaScript. It adds a bunch of features that make it easier to write code, and it also makes it easier to catch bugs before you ship your code.
-
-We chose TypeScript because it allows us to use a single, strongly-typed language across the entire application. Every time you run `npm run db:build`, we use Supabase to generate TypeScript types for your database schema.
-
-## React
-
-[React](https://reactjs.org) is a JavaScript library for building user interfaces. It's the most popular frontend framework in the world, and it's used by many of the biggest companies in the world, including Facebook, Netflix, and Airbnb.
-
-We have a package called [@carbon/react](https://github.com/crbos/carbon/tree/main/packages/react/src) that has a bunch of React pre-built components that you can use to build your UI. You can also draw from a rich ecosystem of existing React component libraries.
-
-## shadcn/ui
-
-[shadcn/ui](https://ui.shadcn.com) is a collection of reusable components built using Radix UI and Tailwind CSS. It provides accessibility, customization, and simplicity by combining Radix UI's unstyled, accessible components with Tailwind's utility-first CSS framework.
-
-shadcn/ui gives us the best of both worlds: robust accessibility features from Radix UI primitives and complete design control through Tailwind CSS. Components are copy-and-paste friendly, meaning you own the code and can customize it however you need.
-
-Here's an example of a shadcn/ui button:
-
-There are a lot of other component libraries out there, but we chose Chakra UI because it gives us a lot of flexibility while providing great user and developer experience. We're hopeful that Chakra will implement Panda under the hood in v4, which will give us high-level performance. If we had time, we'd probably move everything over to Radix + Tailwind (assuming we could keep things super simple for the developer).
-
-## Remix
-
-[Remix](https://remix.run) is a framework for building full-stack web applications. It's built on top of React, and it allows us to co-locate server-side code and client-side code in the same files. When combined with TypeScript and Supabase, this gives us type-safety from the database to the UI.
-
-Remix makes for a beautiful developer experience. It's use of nested routes, [loaders, actions and components](https://remix.run/blog/remix-data-flow) **minimizes the amount of code that needs written while maximzing performance**. To learn more about Remix, check out their documentation, and take a look at some files from our [routes](https://github.com/barbinbrad/carbon/tree/main/apps/carbon/app/routes) directory.
-
-Here's a slightly-simplified example of how a Remix route works:
-
-```tsx
-// File (route): /products/$productId/edit.tsx
-
-export async function loader({ params }) {
- const product = await getProduct(params.productId);
- return json(product);
-}
-
-export default function Route() {
- const product = useLoaderData();
- return (
- <h2>Edit Product {product.id}</h2>
- <Form method="post">
- <input name="name" defaultValue={product.name} />
- <input name="price" defaultValue={product.price} />
- <button type="submit">Save</button>
- </Form>
- )
-}
-
-export async function action({params, request}) {
- const form = await request.formData();
- const name = form.get("name");
- const price = form.get("price");
- const product = await database.updateProduct({ id: params.productId, name, price });
- return redirect(`/products/${product.id}`);
-}
-```
-
-## Supabase
-
-[Supabase](https://supabase.io) is a database, authentication, and storage service that's built on top of Postgres. It allows us to provide a simple, unified authentication layer across many applications (even those that don't exist yet).
-
-Supabase provides a TypeScript client called [Supabase JS](https://supabase.com/docs/reference/javascript/typescript-support) that makes it incredibly easy to query/modify the database. It also makes it easy to use row-level security to restrict access to certain parts of the database on a per-user basis.
-
-Here's a look at how you can use Supabase JS to query the database from a Remix loader where `client` is the supabase client specific to the user making the request:
-
-```tsx
-export async function loader({request}) {
- const { client } = requirePermissions(request, view: 'purchasing');
- const { data, error } = await client
- .from('purchaseOrder')
- .select(`
- id, name,
- customer(id, name),
- purchaseOrderItems(id, name, quantity, unitPrice, total)
- `)
- .order('createdAt', { ascending: false })
- .limit(10);
-
- if (error) {
-```
diff --git a/packages/ee/src/paperless-parts/config.tsx b/packages/ee/src/paperless-parts/config.tsx
index 5212076046..d5f7eee394 100644
--- a/packages/ee/src/paperless-parts/config.tsx
+++ b/packages/ee/src/paperless-parts/config.tsx
@@ -31,12 +31,30 @@ export const PaperlessParts: IntegrationConfig = {
required: true,
value: "",
},
+ {
+ name: "methodType",
+ label: "Material Method Type",
+ type: "options",
+ listOptions: ["Buy", "Pick"],
+ required: false,
+ value: "Pick",
+ },
+ {
+ name: "trackingType",
+ label: "Material Tracking Type",
+ type: "options",
+ listOptions: ["Inventory", "Non-Inventory", "Batch"],
+ required: false,
+ value: "Inventory",
+ },
],
schema: z.object({
apiKey: z.string().min(1, { message: "API Key is required" }),
secretKey: z
.string()
.min(1, { message: "Webhook Signing Secret is required" }),
+ methodType: z.enum(["Buy", "Pick"]),
+ trackingType: z.enum(["Inventory", "Non-Inventory", "Batch"]),
}),
};
diff --git a/packages/ee/src/paperless-parts/lib/utils.ts b/packages/ee/src/paperless-parts/lib/utils.ts
index 9fbc7d384d..08296aed6f 100644
--- a/packages/ee/src/paperless-parts/lib/utils.ts
+++ b/packages/ee/src/paperless-parts/lib/utils.ts
@@ -528,6 +528,8 @@ export async function getOrCreateMaterial(
input: PaperlessPartsMaterialInput;
createdBy: string;
companyId: string;
+ defaultMethodType: "Buy" | "Pick";
+ defaultTrackingType: "Inventory" | "Non-Inventory" | "Batch";
}
): Promise<{
itemId: string;
@@ -668,8 +670,8 @@ export async function getOrCreateMaterial(
name: description,
type: "Material",
replenishmentSystem: "Buy",
- defaultMethodType: "Buy",
- itemTrackingType: "Inventory",
+ defaultMethodType: args.defaultMethodType,
+ itemTrackingType: args.defaultTrackingType,
unitOfMeasureCode: "EA",
active: true,
companyId: args.companyId,
@@ -1714,9 +1716,17 @@ export async function createPartFromComponent(
number,
z.infer<typeof OrderSchema>["order_items"][number]["components"][number]
>;
+ defaultMethodType: "Buy" | "Pick";
+ defaultTrackingType: "Inventory" | "Non-Inventory" | "Batch";
}
): Promise<{ itemId: string; partId: string }> {
- const { companyId, createdBy, component } = args;
+ const {
+ companyId,
+ createdBy,
+ component,
+ defaultMethodType,
+ defaultTrackingType,
+ } = args;
const operations: Omit<
Database["public"]["Tables"]["methodOperation"]["Insert"],
@@ -1732,6 +1742,8 @@ export async function createPartFromComponent(
companyId,
createdBy,
input: component,
+ defaultMethodType,
+ defaultTrackingType,
});
if (material) {
@@ -1739,7 +1751,7 @@ export async function createPartFromComponent(
itemId: material.itemId,
itemType: "Material",
quantity: material.quantity,
- methodType: "Pick",
+ methodType: defaultMethodType,
companyId,
createdBy,
unitOfMeasureCode: "EA",
@@ -1816,6 +1828,8 @@ export async function createPartFromComponent(
createdBy,
component: childComponent as any,
componentsIndex: index,
+ defaultMethodType,
+ defaultTrackingType,
});
const childIsPurchased =
@@ -2118,9 +2132,11 @@ export async function getOrCreatePart(
number,
z.infer<typeof OrderSchema>["order_items"][number]["components"][number]
>;
+ defaultMethodType: "Buy" | "Pick";
+ defaultTrackingType: "Inventory" | "Non-Inventory" | "Batch";
}
): Promise<{ itemId: string; partId: string }> {
- const { companyId, component } = args;
+ const { companyId, component, defaultMethodType, defaultTrackingType } = args;
if (!component.part_uuid) {
throw new Error("Component part_uuid is required");
@@ -2233,9 +2249,19 @@ export async function insertOrderLines(
companyId: string;
createdBy: string;
orderItems: z.infer<typeof OrderSchema>["order_items"];
+ defaultMethodType: "Buy" | "Pick";
+ defaultTrackingType: "Inventory" | "Non-Inventory" | "Batch";
}
): Promise<void> {
- const { salesOrderId, locationId, companyId, createdBy, orderItems } = args;
+ const {
+ salesOrderId,
+ locationId,
+ companyId,
+ createdBy,
+ orderItems,
+ defaultMethodType,
+ defaultTrackingType,
+ } = args;
if (!orderItems?.length) {
return;
@@ -2295,6 +2321,8 @@ export async function insertOrderLines(
createdBy,
component,
componentsIndex,
+ defaultMethodType,
+ defaultTrackingType,
});
// console.log("component", component);
diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.ts
index 43b85db805..baaea11af5 100644
--- a/packages/ee/src/types.ts
+++ b/packages/ee/src/types.ts
@@ -13,7 +13,8 @@ export type IntegrationConfig = {
settings: {
name: string;
label: string;
- type: "text" | "switch" | "processes";
+ type: "text" | "switch" | "processes" | "options";
+ listOptions?: string[];
required: boolean;
value: unknown;
}[];
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index 90b3748df7..80c809139f 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -103,6 +103,11 @@ const paperlessPartsSchema = z.object({
payload: payloadSchema,
});
+const integrationSchema = z.object({
+ methodType: z.enum(["Buy", "Pick"]).optional(),
+ trackingType: z.enum(["Inventory", "Non-Inventory", "Batch"]).optional(),
+});
+
export const paperlessPartsTask = task({
id: "paperless-parts",
retry: {
@@ -120,16 +125,34 @@ export const paperlessPartsTask = task({
const carbon = getCarbonServiceRole();
const paperless = await getPaperlessParts(payload.apiKey);
- const company = await carbon
- .from("company")
- .select("*")
- .eq("id", payload.companyId)
- .single();
+ const [company, integration] = await Promise.all([
+ carbon.from("company").select("*").eq("id", payload.companyId).single(),
+ carbon
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", payload.companyId)
+ .eq("id", "paperless-parts")
+ .single(),
+ ]);
if (company.error || !company.data) {
throw new Error("Failed to fetch company from Carbon");
}
+ if (integration.error || !integration.data) {
+ throw new Error("Failed to fetch integration from Carbon");
+ }
+
+ const integrationData = integrationSchema.safeParse(
+ integration.data.metadata
+ );
+ let methodType: "Buy" | "Pick" = "Pick";
+ let trackingType: "Inventory" | "Non-Inventory" | "Batch" = "Inventory";
+ if (integrationData.success) {
+ methodType = integrationData.data.methodType;
+ trackingType = integrationData.data.trackingType;
+ }
+
switch (payload.payload.type) {
case "quote.created":
console.info(`📫 Processing quote created event`);
@@ -599,12 +622,14 @@ export const paperlessPartsTask = task({
// Insert order lines after successful sales order creation
try {
await insertOrderLines(carbon, {
- salesOrderId,
+ integration: salesOrderId,
opportunityId: orderOpportunity.data?.id,
locationId: orderLocationId!,
companyId: payload.companyId,
createdBy: orderCreatedBy,
orderItems: orderData.order_items || [],
+ defaultMethodType: methodType,
+ defaultTrackingType: trackingType,
});
console.log("✅ Order lines successfully created");
} catch (error) {
diff --git a/scripts/paperless-test.ts b/scripts/paperless-test.ts
index 9464b55b25..e0aebd70f1 100644
--- a/scripts/paperless-test.ts
+++ b/scripts/paperless-test.ts
@@ -13,9 +13,9 @@ import {
insertOrderLines,
} from "../packages/ee/src/paperless-parts/lib/index";
import { OrderSchema } from "../packages/ee/src/paperless-parts/lib/schemas";
-const orderNumber = 695;
-const apiKey = "**************************";
-const companyId = "XnwmVKtf9NGwjkco3NoSTu";
+const orderNumber = 1387;
+const apiKey = "faaa6a989c4daddf74ec88134400404449a7c105";
+const companyId = "GuPcNVRbkDYKqjFHsV1LNa";
dotenv.config();
@@ -213,6 +213,8 @@ const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY!;
companyId,
createdBy,
orderItems: orderData.order_items || [],
+ defaultMethodType: "Buy",
+ defaultTrackingType: "Batch",
});
console.log("✅ Order and order lines successfully created");
} catch (error) {