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: edge function for customer and supplier bulk imports
Brad Barbin60fb5b2d1155
diff --git a/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx b/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsxindex 52055ef0ec..f2919631b0 100644--- a/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx+++ b/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx@@ -111,7 +111,7 @@ function FieldRow({name={name}onChange={(value) => setValue(value?.value)}isLoading={isLoading}- value={value}+ value={value ?? undefined}options={[// Filter out empty columns...(fileColumns?.filter((column) => column !== "") || []),diff --git a/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsxindex a21845bb69..11ee52e629 100644--- a/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx+++ b/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx@@ -6,6 +6,7 @@ import {ModalDescription,ModalHeader,ModalTitle,+ toast,} from "@carbon/react";import { useFetcher } from "@remix-run/react";import { useEffect, useState } from "react";@@ -15,6 +16,8 @@ import {importSchemas,type fieldMappings,} from "~/modules/shared/imports.models";+import type { action } from "~/routes/x+/shared+/import.$tableId";+import { path } from "~/utils/path";import { AnimatedSizeContainer } from "../AnimatedSizeContainer";import { FieldMapping } from "./FieldMappings";import { UploadCSV } from "./UploadCSV";@@ -33,18 +36,28 @@ type ImportCSVModalProps = {};export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {- const fetcher = useFetcher<{}>();+ const fetcher = useFetcher<typeof action>();const [page, setPage] = useState<(typeof pages)[number]>(ImportCSVPage.UploadCSV);const [file, setFile] = useState<File | null>(null);- const [path, setPath] = useState<string | null>(null);+ const [filePath, setFilePath] = useState<string | null>(null);const [fileColumns, setFileColumns] = useState<string[] | null>(null);const [firstRows, setFirstRows] = useState<Record<string, string>[] | null>(null);+ useEffect(() => {+ if (fetcher.data?.success === true) {+ toast.success("Import successful.");+ onClose();+ } else if (fetcher.data?.success === false) {+ toast.error(fetcher.data.message);+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [fetcher.data?.success]);+// if the file upload is successful, set the page to field-mappinguseEffect(() => {if (file && fileColumns && page === ImportCSVPage.UploadCSV) {@@ -85,29 +98,36 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {file,fileColumns,firstRows,- path,+ filePath,setFile,setFileColumns,setFirstRows,- setPath,+ setFilePath,}}><div><ValidatedFormclassName="flex flex-col gap-y-4"fetcher={fetcher}+ method="post"+ action={path.to.import(table)}validator={importSchemas[table].extend({- path: z.string().min(1, { message: "Path is required" }),+ filePath: z+ .string()+ .min(1, { message: "Path is required" }),})}+ onSubmit={() => {+ toast.info("Importing...");+ }}>- <Hidden name="path" value={path ?? ""} />+ <Hidden name="filePath" value={filePath ?? ""} />{page === ImportCSVPage.UploadCSV && <UploadCSV />}{page === ImportCSVPage.FieldMappings && (<><FieldMapping table={table} /><Submit- isDisabled={!path || fetcher.state !== "idle"}+ isDisabled={!filePath || fetcher.state !== "idle"}className="mt-4"type="submit">diff --git a/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx b/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsxindex a5ddcca3f4..fe18364a2f 100644--- a/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx+++ b/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx@@ -11,7 +11,8 @@ import { useCsvContext } from "./useCsvContext";export const UploadCSV = () => {const { carbon } = useCarbon();const { company } = useUser();- const { setFile, setFileColumns, setFirstRows, setPath } = useCsvContext();+ const { setFile, setFileColumns, setFirstRows, setFilePath } =+ useCsvContext();const [uploading, setUploading] = useState(false);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);@@ -85,7 +86,7 @@ export const UploadCSV = () => {return;}- setPath(data.path);+ setFilePath(data.path);};const onDrop = async (acceptedFiles: File[]) => {diff --git a/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx b/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsxindex 17a3481777..de83dd9bf9 100644--- a/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx+++ b/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx@@ -1,14 +1,14 @@import { createContext, useContext } from "react";export const ImportCsvContext = createContext<{- path: string | null;+ filePath: string | null;file: File | null;fileColumns: string[] | null;firstRows: Record<string, string>[] | null;setFile: (file: File | null) => void;setFileColumns: (columns: string[] | null) => void;setFirstRows: (rows: Record<string, string>[] | null) => void;- setPath: (path: string | null) => void;+ setFilePath: (filePath: string | null) => void;} | null>(null);export function useCsvContext() {diff --git a/apps/carbon/app/components/New.tsx b/apps/carbon/app/components/New.tsxindex 8e1bfcfdd8..6af4a1d730 100644--- a/apps/carbon/app/components/New.tsx+++ b/apps/carbon/app/components/New.tsx@@ -30,7 +30,7 @@ const New = ({ label, to }: NewProps) => {<TooltipTrigger><Button asChild leftIcon={<LuPlus />} ref={buttonRef}><Link to={to} prefetch="intent">- New {label}+ New</Link></Button></TooltipTrigger>diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsxindex 39aeb243ef..6c9b2e2d58 100644--- a/apps/carbon/app/components/Table/Table.tsx+++ b/apps/carbon/app/components/Table/Table.tsx@@ -90,6 +90,7 @@ const Table = <T extends object>({defaultColumnPinning,defaultColumnVisibility,editableComponents,+ importCSV,primaryAction,withInlineEditing = false,withPagination = true,@@ -556,6 +557,7 @@ const Table = <T extends object>({columns={table.getAllLeafColumns()}editMode={editMode}filters={filters}+ importCSV={importCSV}primaryAction={primaryAction}selectedRows={selectedRows}setColumnOrder={setColumnOrder}diff --git a/apps/carbon/app/components/Table/components/TableHeader.tsx b/apps/carbon/app/components/Table/components/TableHeader.tsxindex 4e936f39a2..8918e547c1 100644--- a/apps/carbon/app/components/Table/components/TableHeader.tsx+++ b/apps/carbon/app/components/Table/components/TableHeader.tsx@@ -1,9 +1,23 @@-import { Button, HStack } from "@carbon/react";+import {+ Button,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuIcon,+ DropdownMenuItem,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ HStack,+ IconButton,+} from "@carbon/react";import type { Column, ColumnOrderState } from "@tanstack/react-table";-import { type ReactNode } from "react";-import { LuFileEdit, LuLock } from "react-icons/lu";+import { useState, type ReactNode } from "react";+import { BsThreeDotsVertical } from "react-icons/bs";+import { LuFileEdit, LuImport, LuLock } from "react-icons/lu";import { SearchFilter } from "~/components";+import { ImportCSVModal } from "~/components/ImportCSVModal";import { useUrlParams } from "~/hooks";+import type { fieldMappings } from "~/modules/shared/imports.models";import type { TableAction } from "../types";import Actions from "./Actions";import Columns from "./Columns";@@ -20,6 +34,10 @@ type HeaderProps<T> = {columns: Column<T, unknown>[];editMode: boolean;filters: ColumnFilter[];+ importCSV?: {+ table: keyof typeof fieldMappings;+ label: string;+ }[];primaryAction?: ReactNode;pagination: PaginationProps;selectedRows: T[];@@ -38,6 +56,7 @@ const TableHeader = <T extends object>({columns,editMode,filters,+ importCSV,primaryAction,pagination,selectedRows,@@ -50,6 +69,9 @@ const TableHeader = <T extends object>({}: HeaderProps<T>) => {const [params] = useUrlParams();const currentFilters = params.getAll("filter");+ const [importCSVTable, setImportCSVTable] = useState<+ keyof typeof fieldMappings | null+ >(null);return (<>@@ -97,6 +119,32 @@ const TableHeader = <T extends object>({</Button>))}<>{primaryAction}</>+ {importCSV && (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="Additional actions"+ variant="secondary"+ icon={<BsThreeDotsVertical />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ <DropdownMenuLabel>Bulk Import</DropdownMenuLabel>+ <DropdownMenuSeparator />+ {importCSV.map(({ table, label }) => (+ <DropdownMenuItem+ key={table}+ onClick={() => {+ setImportCSVTable(table);+ }}+ >+ <DropdownMenuIcon icon={<LuImport />} />+ Import {label} CSV+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>+ )}</HStack></HStack>{currentFilters.length > 0 && (@@ -106,6 +154,12 @@ const TableHeader = <T extends object>({</HStack></HStack>)}+ {importCSVTable && (+ <ImportCSVModal+ table={importCSVTable}+ onClose={() => setImportCSVTable(null)}+ />+ )}</>);};diff --git a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsxindex ddb04cbbaf..528aed112a 100644--- a/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx+++ b/apps/carbon/app/modules/purchasing/ui/Suppliers/SuppliersTable.tsx@@ -210,6 +210,12 @@ const SuppliersTable = memo(updatedBy: false,updatedAt: false,}}+ importCSV={[+ {+ table: "supplier",+ label: "Suppliers",+ },+ ]}primaryAction={permissions.can("create", "purchasing") && (<New label="Supplier" to={path.to.newSupplier} />diff --git a/apps/carbon/app/modules/shared/imports.models.ts b/apps/carbon/app/modules/shared/imports.models.tsindex 5ca1aa035d..20ad385698 100644--- a/apps/carbon/app/modules/shared/imports.models.ts+++ b/apps/carbon/app/modules/shared/imports.models.ts@@ -3,7 +3,7 @@ import { z } from "zod";export const fieldMappings = {customer: {id: {- label: "ID",+ label: "External ID",required: true,type: "string",},@@ -17,8 +17,8 @@ export const fieldMappings = {required: false,type: "string",},- email: {- label: "Email",+ fax: {+ label: "Fax",required: false,type: "string",},@@ -27,6 +27,48 @@ export const fieldMappings = {required: false,type: "string",},+ currencyCode: {+ label: "Currency Code",+ required: false,+ type: "string",+ },+ website: {+ label: "Website",+ required: false,+ type: "string",+ },+ },+ supplier: {+ id: {+ label: "External ID",+ required: true,+ type: "string",+ },+ name: {+ label: "Name",+ required: true,+ type: "string",+ },+ phone: {+ label: "Phone",+ required: false,+ type: "string",+ },+ fax: {+ label: "Fax",+ required: false,+ type: "string",+ },+ taxId: {+ label: "Tax ID",+ required: false,+ type: "string",+ },+ currencyCode: {+ label: "Currency Code",+ required: false,+ type: "string",+ },website: {label: "Website",required: false,@@ -35,6 +77,11 @@ export const fieldMappings = {},} as const;+export const importPermissions: Record<keyof typeof fieldMappings, string> = {+ customer: "sales",+ supplier: "purchasing",+};+export const importSchemas: Record<keyof typeof fieldMappings,z.ZodObject<any>@@ -53,13 +100,47 @@ export const importSchemas: Record<"The name of the customer. Sometimes contains Inc or LLC. Usually a proper noun."),phone: z.string().optional().describe("The phone number of the customer"),- email: z.string().optional().describe("The email address of the customer"),+ fax: z.string().optional().describe("The fax number of the customer"),taxId: z.string().optional().describe("The tax identification number of the customer. Usually numeric."),+ currencyCode: z+ .string()+ .optional()+ .describe("The currency code of the customer. Usually a 3-letter code."),+ website: z+ .string()+ .optional()+ .describe("The website url. Usually begins with http:// or https://"),+ }),+ supplier: z.object({+ id: z+ .string()+ .min(1, { message: "ID is required" })+ .describe(+ "The id of the supplier, usually a number or set of alphanumeric characters."+ ),+ name: z+ .string()+ .min(1, { message: "Name is required" })+ .describe(+ "The name of the supplier. Sometimes contains Inc or LLC. Usually a proper noun."+ ),+ phone: z.string().optional().describe("The phone number of the supplier"),+ fax: z.string().optional().describe("The fax number of the supplier"),+ taxId: z+ .string()+ .optional()+ .describe(+ "The tax identification number of the supplier. Usually numeric."+ ),+ currencyCode: z+ .string()+ .optional()+ .describe("The currency code of the supplier. Usually a 3-letter code."),website: z.string().optional()diff --git a/apps/carbon/app/modules/shared/shared.service.ts b/apps/carbon/app/modules/shared/shared.service.tsindex eed6fbf0a5..662417e85c 100644--- a/apps/carbon/app/modules/shared/shared.service.ts+++ b/apps/carbon/app/modules/shared/shared.service.ts@@ -43,6 +43,21 @@ export async function getNotes(.order("createdAt");}+export async function importCsv(+ client: SupabaseClient<Database>,+ args: {+ table: string;+ filePath: string;+ mappings: Record<string, string>;+ companyId: string;+ userId: string;+ }+) {+ return client.functions.invoke("import-csv", {+ body: args,+ });+}+export async function insertNote(client: SupabaseClient<Database>,note: {diff --git a/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsxindex b6bebea302..900d206d04 100644--- a/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx+++ b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx@@ -10,7 +10,7 @@ import { importSchemas } from "~/modules/shared";const inputSchema = z.object({fileColumns: z.array(z.string()),- firstRows: z.array(z.record(z.string())),+ // firstRows: z.array(z.record(z.string())),});export async function action({ request, params }: ActionFunctionArgs) {@@ -28,7 +28,7 @@ export async function action({ request, params }: ActionFunctionArgs) {throw notFound("Table not found in the list of supported tables");}- const { fileColumns, firstRows } = result.data;+ const { fileColumns } = result.data;const schema = importSchemas[table as keyof typeof importSchemas];@@ -44,12 +44,11 @@ export async function action({ request, params }: ActionFunctionArgs) {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.++ If you are not sure or there is no matching column, omit the value.+Columns:${fileColumns.join(",")}- First few rows of data:- ${firstRows.map((row) => JSON.stringify(row)).join("\n")}`,temperature: 0.2,});diff --git a/apps/carbon/app/routes/onboarding+/_index.tsx b/apps/carbon/app/routes/onboarding+/_index.tsxindex 6cc2a0a40e..3c1735ad1d 100644--- a/apps/carbon/app/routes/onboarding+/_index.tsx+++ b/apps/carbon/app/routes/onboarding+/_index.tsx@@ -34,7 +34,7 @@ export default function GetStarted() {<Heading{...fade}transition={{ duration: 1.2, ease: "easeInOut", delay: 1.5 }}- size="display"+ size="h1"className="m-0">Welcome to CarbonOSdiff --git a/apps/carbon/app/routes/onboarding+/company.tsx b/apps/carbon/app/routes/onboarding+/company.tsxindex 3f3eefc4b0..6ebd230c94 100644--- a/apps/carbon/app/routes/onboarding+/company.tsx+++ b/apps/carbon/app/routes/onboarding+/company.tsx@@ -167,7 +167,8 @@ export default function OnboardingCompany() {city: company?.city ?? "",stateProvince: company?.stateProvince ?? "",postalCode: company?.postalCode ?? "",- countryCode: company?.countryCode ?? "",+ countryCode: company?.countryCode ?? "US",+ baseCurrencyCode: company?.baseCurrencyCode ?? "USD",};return (diff --git a/apps/carbon/app/routes/x+/shared+/import.$tableId.tsx b/apps/carbon/app/routes/x+/shared+/import.$tableId.tsxnew file mode 100644index 0000000000..229718efe7--- /dev/null+++ b/apps/carbon/app/routes/x+/shared+/import.$tableId.tsx@@ -0,0 +1,58 @@+import { getCarbonServiceRole, notFound } from "@carbon/auth";+import { requirePermissions } from "@carbon/auth/auth.server";+import { validator } from "@carbon/form";+import { json, type ActionFunctionArgs } from "@vercel/remix";+import { z } from "zod";+import { importCsv, importPermissions, importSchemas } from "~/modules/shared";++export async function action({ request, params }: ActionFunctionArgs) {+ const { tableId } = params;+ if (!tableId) {+ throw notFound("No table ID provided");+ }+ const table = tableId as keyof typeof importPermissions;++ if (!(table in importPermissions)) {+ throw notFound("Table not found in the list of supported tables");+ }++ const { companyId, userId } = await requirePermissions(request, {+ update: importPermissions[table],+ });++ const schema = importSchemas[table].extend({+ filePath: z.string().min(1, { message: "Path is required" }),+ });++ const validation = await validator(schema).validate(await request.formData());++ if (validation.error) {+ return json({+ success: false,+ message: "Validation failed",+ });+ }++ const { filePath, ...mappings } = validation.data;++ const serviceRole = getCarbonServiceRole();+ const importResult = await importCsv(serviceRole, {+ table,+ filePath: filePath as string,+ mappings,+ companyId,+ userId,+ });++ if (importResult.error) {+ return json({+ success: false,+ message: importResult.error.message,+ });+ }++ return json({+ success: true,+ message: "Import successful",+ });+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex d728c54d42..232af6d601 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -356,6 +356,7 @@ export const path = {groups: `${x}/users/groups`,holiday: (id: string) => generatePath(`${x}/people/holidays/${id}`),holidays: `${x}/people/holidays`,+ import: (tableId: string) => generatePath(`${x}/shared/import/${tableId}`),integration: (id: string) =>generatePath(`${x}/settings/integrations/${id}`),integrationDeactivate: (id: string) =>diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.tsindex 627e7d8657..844ceac58a 100644--- a/packages/database/src/swagger-docs-schema.ts+++ b/packages/database/src/swagger-docs-schema.ts@@ -3,7 +3,7 @@ export default {info: {description: "",title: "standard public schema",- version: "12.0.1 (cd38da5)",+ version: "12.0.2 (a4e00ff)",},host: "0.0.0.0:3000",basePath: "/",@@ -13353,6 +13353,9 @@ export default {{$ref: "#/parameters/rowFilter.customer.website",},+ {+ $ref: "#/parameters/rowFilter.customer.externalId",+ },{$ref: "#/parameters/select",},@@ -13466,6 +13469,9 @@ export default {{$ref: "#/parameters/rowFilter.customer.website",},+ {+ $ref: "#/parameters/rowFilter.customer.externalId",+ },{$ref: "#/parameters/preferReturn",},@@ -13533,6 +13539,9 @@ export default {{$ref: "#/parameters/rowFilter.customer.website",},+ {+ $ref: "#/parameters/rowFilter.customer.externalId",+ },{$ref: "#/parameters/body.customer",},@@ -14889,6 +14898,9 @@ export default {{$ref: "#/parameters/rowFilter.supplier.website",},+ {+ $ref: "#/parameters/rowFilter.supplier.externalId",+ },{$ref: "#/parameters/select",},@@ -15002,6 +15014,9 @@ export default {{$ref: "#/parameters/rowFilter.supplier.website",},+ {+ $ref: "#/parameters/rowFilter.supplier.externalId",+ },{$ref: "#/parameters/preferReturn",},@@ -15069,6 +15084,9 @@ export default {{$ref: "#/parameters/rowFilter.supplier.website",},+ {+ $ref: "#/parameters/rowFilter.supplier.externalId",+ },{$ref: "#/parameters/body.supplier",},@@ -42394,6 +42412,9 @@ export default {format: "text",type: "string",},+ externalId: {+ format: "jsonb",+ },},type: "object",},@@ -43071,6 +43092,9 @@ export default {format: "text",type: "string",},+ externalId: {+ format: "jsonb",+ },},type: "object",},@@ -47122,7 +47146,7 @@ export default {properties: {id: {description:- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string",},@@ -47171,7 +47195,7 @@ export default {},supplierLocationId: {description:- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",format: "text",type: "string",},@@ -59927,6 +59951,13 @@ export default {in: "query",type: "string",},+ "rowFilter.customer.externalId": {+ name: "externalId",+ required: false,+ format: "jsonb",+ in: "query",+ type: "string",+ },"body.note": {name: "note",description: "note",@@ -60839,6 +60870,13 @@ export default {in: "query",type: "string",},+ "rowFilter.supplier.externalId": {+ name: "externalId",+ required: false,+ format: "jsonb",+ in: "query",+ type: "string",+ },"body.customFieldTable": {name: "customFieldTable",description: "customFieldTable",diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 9df854173d..3119ed8ebf 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -2801,6 +2801,7 @@ export type Database = {customerStatusId: string | nullcustomerTypeId: string | nullcustomFields: Json | null+ externalId: Json | nullfax: string | nullid: stringlogo: string | null@@ -2821,6 +2822,7 @@ export type Database = {customerStatusId?: string | nullcustomerTypeId?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -2841,6 +2843,7 @@ export type Database = {customerStatusId?: string | nullcustomerTypeId?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -18964,6 +18967,7 @@ export type Database = {createdBy: string | nullcurrencyCode: string | nullcustomFields: Json | null+ externalId: Json | nullfax: string | nullid: stringlogo: string | null@@ -18984,6 +18988,7 @@ export type Database = {createdBy?: string | nullcurrencyCode?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -19004,6 +19009,7 @@ export type Database = {createdBy?: string | nullcurrencyCode?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | nulldiff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.tsnew file mode 100644index 0000000000..b97cb22154--- /dev/null+++ b/packages/database/supabase/functions/import-csv/index.ts@@ -0,0 +1,250 @@+import { parse } from "https://deno.land/[email protected]/encoding/csv.ts";+import { serve } from "https://deno.land/[email protected]/http/server.ts";+import z from "https://deno.land/x/[email protected]/index.ts";+import { DB, getConnectionPool, getDatabaseClient } from "../lib/database.ts";+import { corsHeaders } from "../lib/headers.ts";+import { getSupabaseServiceRole } from "../lib/supabase.ts";+import { Database } from "../lib/types.ts";++const pool = getConnectionPool(1);+const db = getDatabaseClient<DB>(pool);++const importCsvValidator = z.object({+ table: z.enum(["customer", "supplier"]),+ filePath: z.string(),+ mappings: z.record(z.string()),+ companyId: z.string(),+ userId: z.string(),+});++const EXTERNAL_ID_KEY = "csv";++serve(async (req: Request) => {+ if (req.method === "OPTIONS") {+ return new Response("ok", { headers: corsHeaders });+ }+ const payload = await req.json();++ try {+ const { table, filePath, mappings, companyId, userId } =+ importCsvValidator.parse(payload);++ console.log({+ function: "import-csv",+ table,+ filePath,+ mappings,+ companyId,+ userId,+ });++ const client = getSupabaseServiceRole(req.headers.get("Authorization"));+ const csvFile = await client.storage.from("private").download(filePath);+ if (!csvFile.data) {+ throw new Error("Failed to download file");+ }+ const csvText = new TextDecoder().decode(+ new Uint8Array(await csvFile.data.arrayBuffer())+ );+ const parsedCsv = parse(csvText, { skipFirstRow: true }) as Record<+ string,+ string+ >[];++ const mappedRecords = parsedCsv.map((row) => {+ const record: Record<string, string> = {};+ for (const [key, value] of Object.entries(mappings)) {+ if (row[value]) {+ record[key] = row[value];+ }+ }+ return record;+ });++ switch (table) {+ case "customer": {+ const currentCustomers = await db+ .selectFrom(table)+ .where("companyId", "=", companyId)+ .select(["id", "externalId"])+ .execute();++ const externalIdMap = new Map(+ currentCustomers.reduce((acc, customer) => {+ if (+ customer.externalId &&+ typeof customer.externalId === "object" &&+ EXTERNAL_ID_KEY in customer.externalId+ ) {+ acc.set(customer.externalId[EXTERNAL_ID_KEY] as string, {+ id: customer.id!,+ externalId: customer.externalId as Record<string, string>,+ });+ }+ return acc;+ }, new Map<string, { id: string; externalId: Record<string, string> }>())+ );++ await db.transaction().execute(async (trx) => {+ const customerInserts: Database["public"]["Tables"]["customer"]["Insert"][] =+ [];+ const customerUpdates: {+ id: string;+ data: Database["public"]["Tables"]["customer"]["Update"];+ }[] = [];++ const isCustomerValid = (+ record: Record<string, string>+ ): record is { name: string } => {+ return typeof record.name === "string" && record.name.trim() !== "";+ };++ for (const record of mappedRecords) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id)) {+ const existingCustomer = externalIdMap.get(id)!;+ if (isCustomerValid(rest)) {+ customerUpdates.push({+ id: existingCustomer.id,+ data: {+ ...rest,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ externalId: {+ ...existingCustomer.externalId,+ },+ },+ });+ }+ } else if (isCustomerValid(rest)) {+ customerInserts.push({+ ...rest,+ companyId,+ createdAt: new Date().toISOString(),+ createdBy: userId,+ externalId: {+ [EXTERNAL_ID_KEY]: id,+ },+ });+ }+ }++ if (customerInserts.length > 0) {+ await trx.insertInto(table).values(customerInserts).execute();+ }+ if (customerUpdates.length > 0) {+ for (const update of customerUpdates) {+ await trx+ .updateTable(table)+ .set(update.data)+ .where("id", "=", update.id)+ .execute();+ }+ }+ });+ break;+ }+ case "supplier": {+ const currentSuppliers = await db+ .selectFrom(table)+ .where("companyId", "=", companyId)+ .select(["id", "externalId"])+ .execute();++ const externalIdMap = new Map(+ currentSuppliers.reduce((acc, supplier) => {+ if (+ supplier.externalId &&+ typeof supplier.externalId === "object" &&+ EXTERNAL_ID_KEY in supplier.externalId+ ) {+ acc.set(supplier.externalId[EXTERNAL_ID_KEY] as string, {+ id: supplier.id!,+ externalId: supplier.externalId as Record<string, string>,+ });+ }+ return acc;+ }, new Map<string, { id: string; externalId: Record<string, string> }>())+ );++ await db.transaction().execute(async (trx) => {+ const supplierInserts: Database["public"]["Tables"]["supplier"]["Insert"][] =+ [];+ const supplierUpdates: {+ id: string;+ data: Database["public"]["Tables"]["supplier"]["Update"];+ }[] = [];++ const isSupplierValid = (+ record: Record<string, string>+ ): record is { name: string } => {+ return typeof record.name === "string" && record.name.trim() !== "";+ };++ for (const record of mappedRecords) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id)) {+ const existingSupplier = externalIdMap.get(id)!;+ if (isSupplierValid(rest)) {+ supplierUpdates.push({+ id: existingSupplier.id,+ data: {+ ...rest,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ externalId: {+ ...existingSupplier.externalId,+ },+ },+ });+ }+ } else if (isSupplierValid(rest)) {+ supplierInserts.push({+ ...rest,+ companyId,+ createdAt: new Date().toISOString(),+ createdBy: userId,+ externalId: {+ [EXTERNAL_ID_KEY]: id,+ },+ });+ }+ }++ if (supplierInserts.length > 0) {+ await trx.insertInto(table).values(supplierInserts).execute();+ }+ if (supplierUpdates.length > 0) {+ for (const update of supplierUpdates) {+ await trx+ .updateTable(table)+ .set(update.data)+ .where("id", "=", update.id)+ .execute();+ }+ }+ });+ break;+ }+ default: {+ throw new Error("Invalid type");+ }+ }++ return new Response(+ JSON.stringify({+ success: true,+ }),+ {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 200,+ }+ );+ } catch (err) {+ console.error(err);+ return new Response(JSON.stringify(err), {+ headers: { ...corsHeaders, "Content-Type": "application/json" },+ status: 500,+ });+ }+});diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 9df854173d..3119ed8ebf 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -2801,6 +2801,7 @@ export type Database = {customerStatusId: string | nullcustomerTypeId: string | nullcustomFields: Json | null+ externalId: Json | nullfax: string | nullid: stringlogo: string | null@@ -2821,6 +2822,7 @@ export type Database = {customerStatusId?: string | nullcustomerTypeId?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -2841,6 +2843,7 @@ export type Database = {customerStatusId?: string | nullcustomerTypeId?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -18964,6 +18967,7 @@ export type Database = {createdBy: string | nullcurrencyCode: string | nullcustomFields: Json | null+ externalId: Json | nullfax: string | nullid: stringlogo: string | null@@ -18984,6 +18988,7 @@ export type Database = {createdBy?: string | nullcurrencyCode?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | null@@ -19004,6 +19009,7 @@ export type Database = {createdBy?: string | nullcurrencyCode?: string | nullcustomFields?: Json | null+ externalId?: Json | nullfax?: string | nullid?: stringlogo?: string | nulldiff --git a/packages/database/supabase/migrations/20241010023911_customer-import.sql b/packages/database/supabase/migrations/20241010023911_customer-import.sqlnew file mode 100644index 0000000000..1caf2c2aac--- /dev/null+++ b/packages/database/supabase/migrations/20241010023911_customer-import.sql@@ -0,0 +1,11 @@+-- Add external_id column to customer table+ALTER TABLE customer ADD COLUMN "externalId" JSONB;++-- Create GIN index on external_id column+CREATE INDEX idx_customer_external_id ON customer USING GIN ("externalId");++-- Add external_id column to supplier table+ALTER TABLE supplier ADD COLUMN "externalId" JSONB;++-- Create GIN index on external_id column+CREATE INDEX idx_supplier_external_id ON supplier USING GIN ("externalId");diff --git a/packages/react/src/Dropdown.tsx b/packages/react/src/Dropdown.tsxindex 04442fd8ac..7df09d3c0b 100644--- a/packages/react/src/Dropdown.tsx+++ b/packages/react/src/Dropdown.tsx@@ -167,7 +167,7 @@ const DropdownMenuLabel = forwardRef<<DropdownMenuPrimitive.Labelref={ref}className={cn(- "px-2 py-1.5 text-sm font-semibold",+ "px-2 py-1.5 text-xs text-muted-foreground",inset && "pl-8",className)}