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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: api endpoint for column mapping with open ai
Brad Barbin6c1b47364018
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsxindex 175f24fba6..feb3d91c0e 100644--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx@@ -1,20 +1,14 @@-import { MenuIcon, MenuItem } from "@carbon/react";+import { Button, MenuIcon, MenuItem } from "@carbon/react";import { formatDate } from "@carbon/utils";-import { useNavigate } from "@remix-run/react";+import { useFetcher, useNavigate } from "@remix-run/react";import type { ColumnDef } from "@tanstack/react-table";import { memo, useMemo } from "react";import { LuPencil } from "react-icons/lu";-import {- CustomerAvatar,- EmployeeAvatar,- Hyperlink,- New,- Table,-} from "~/components";+import { CustomerAvatar, EmployeeAvatar, Hyperlink, Table } from "~/components";import { Enumerable } from "~/components/Enumerable";-import { usePermissions } from "~/hooks";import { useCustomColumns } from "~/hooks/useCustomColumns";import type { Customer, CustomerStatus } from "~/modules/sales";+import type { action } from "~/routes/api+/ai+/csv+/$table.columns";import { usePeople } from "~/stores";import { path } from "~/utils/path";@@ -27,8 +21,55 @@ type CustomersTableProps = {const CustomersTable = memo(({ data, count, customerStatuses }: CustomersTableProps) => {const navigate = useNavigate();- const permissions = usePermissions();+ // const permissions = usePermissions();const [people] = usePeople();+ const fetcher = useFetcher<typeof action>();++ const letsGo = () => {+ fetcher.submit(+ {+ fieldColumns: [+ "ID",+ "Customer Name",+ "EIN",+ "Website",+ "Address",+ "City",+ "State",+ "Zip",+ ],+ firstRows: [+ {+ ID: "31294323",+ "Customer Name": "Acme Corp",+ EIN: "12-3456789",+ Website: "https://www.acmecorp.com",+ Address: "123 Main St",+ City: "Anytown",+ State: "CA",+ Zip: "12345",+ },+ {+ ID: "2324393",+ "Customer Name": "XYZ Industries",+ EIN: "98-7654321",+ Website: "https://www.xyzindustries.com",+ Address: "456 Oak Ave",+ City: "Somewhere",+ State: "NY",+ Zip: "67890",+ },+ ],+ },+ {+ method: "POST",+ action: path.to.api.generateCsvColumns("customer"),+ encType: "application/json",+ }+ );+ };++ console.log(fetcher);const customColumns = useCustomColumns<Customer>("customer");const columns = useMemo<ColumnDef<Customer>[]>(() => {@@ -163,9 +204,16 @@ const CustomersTable = memo(updatedAt: false,}}primaryAction={- permissions.can("create", "sales") && (- <New label="Customer" to={path.to.newCustomer} />- )+ // permissions.can("create", "sales") && (+ // <New label="Customer" to={path.to.newCustomer} />+ // )+ <Button+ onClick={letsGo}+ isLoading={fetcher.state !== "idle"}+ isDisabled={fetcher.state !== "idle"}+ >+ Import+ </Button>}renderContextMenu={renderContextMenu}/>diff --git a/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsxnew file mode 100644index 0000000000..90b93746c7--- /dev/null+++ b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx@@ -0,0 +1,96 @@+import { openai } from "@ai-sdk/openai";+import { notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import type { ActionFunctionArgs } from "@vercel/remix";+import { json } from "@vercel/remix";+import { generateObject } from "ai";+import type { ZodSchema } from "zod";+import { z } from "zod";++const inputSchema = z.object({+ fieldColumns: z.array(z.string()),+ firstRows: z.array(z.record(z.string())),+});++const importSchemas: Record<string, z.ZodType> = {+ customer: z.object({+ id: z+ .string()+ .describe(+ "The id of the customer, usually a number or set of alphanumeric characters."+ ),+ name: z.string().describe("The name of the customer"),+ taxId: z+ .string()+ .optional()+ .describe("The tax identification number of the customer"),+ website: z+ .string()+ .optional()+ .describe("The website url. Usually begins with http:// or https://"),+ }),+};++export async function action({ request, params }: ActionFunctionArgs) {+ await requirePermissions(request, {+ update: "settings",+ });++ const { table } = params;+ if (!table) {+ return notFound("No table parameter provided");+ }++ const result = inputSchema.safeParse(await request.json());+ if (!result.success) {+ return json(+ { error: "Invalid input data", details: result.error.format() },+ { status: 400 }+ );+ }++ const { fieldColumns, firstRows } = result.data;++ const schema = importSchemas[table];++ if (!schema) {+ return json(+ { error: "Table not found in the list of supported tables" },+ { status: 404 }+ );+ }++ const { object } = await generateObject<Record<string, string>>({+ model: openai("gpt-4o-mini"),+ schema,+ prompt: `+ The following columns are the headings from a CSV import file for importing a ${table}.+ Map these column names to the correct fields in our database (${[+ ...Object.keys(getZodSchemaFieldsShallow(schema)),+ ].join(", ")}) by providing the matching column name for each field.+ You may also consult the first few rows of data to help you make the mapping, but you are mapping the columns, not the values.+ If you are not sure or there is no matching column, omit the value. Only include the columns as possible values. Don't include data from the first few rows.+ Columns:+ ${fieldColumns.join(",")}+ First few rows of data:+ ${firstRows.map((row) => JSON.stringify(row)).join("\n")}+ `,+ temperature: 0.2,+ });++ return json(object);+}++export function getZodSchemaFieldsShallow(schema: ZodSchema) {+ const fields: Record<string, true> = {};+ const proxy = new Proxy(fields, {+ get(_, key) {+ if (key === "then" || typeof key !== "string") {+ return;+ }+ fields[key] = true;+ },+ });+ schema.safeParse(proxy);+ return fields;+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex a48d99c1ae..d728c54d42 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -28,6 +28,8 @@ export const path = {departments: `${api}/people/departments`,employeeTypes: `${api}/users/employee-types`,emptyPermissions: `${api}/users/empty-permissions`,+ generateCsvColumns: (table: string) =>+ generatePath(`${api}/ai/csv/${table}/columns`),groupsByType: (type?: string) =>generatePath(`${api}/users/groups?type=${type}`),item: (type: string) => generatePath(`${api}/item/${type}`),