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: ui for bulk importer

Brad Barbine56a030a5675
diff --git a/apps/carbon/app/components/AnimatedSizeContainer.tsx b/apps/carbon/app/components/AnimatedSizeContainer.tsx
new file mode 100644
index 0000000000..8e5ecb423d
--- /dev/null
+++ b/apps/carbon/app/components/AnimatedSizeContainer.tsx
@@ -0,0 +1,60 @@
+import { cn } from "@carbon/react";
+import { motion } from "framer-motion";
+import {
+ type ComponentPropsWithoutRef,
+ type PropsWithChildren,
+ forwardRef,
+} from "react";
+import useMeasure from "react-use-measure";
+
+type AnimatedSizeContainerProps = PropsWithChildren<{
+ width?: boolean;
+ height?: boolean;
+}> &
+ Omit<ComponentPropsWithoutRef<typeof motion.div>, "animate" | "children">;
+
+/**
+ * A container with animated width and height (each optional) based on children dimensions
+ */
+const AnimatedSizeContainer = forwardRef<
+ HTMLDivElement,
+ AnimatedSizeContainerProps
+>(
+ (
+ {
+ width = false,
+ height = false,
+ className,
+ transition,
+ children,
+ ...rest
+ }: AnimatedSizeContainerProps,
+ forwardedRef
+ ) => {
+ const [containerRef, bounds] = useMeasure();
+
+ return (
+ <motion.div
+ ref={forwardedRef}
+ className={cn("overflow-hidden p-1", className)}
+ animate={{
+ width: width ? bounds?.width ?? "auto" : "auto",
+ height: height ? bounds?.height ?? "auto" : "auto",
+ }}
+ transition={transition ?? { type: "spring", duration: 0.3 }}
+ {...rest}
+ >
+ <div
+ ref={containerRef}
+ className={cn(height && "h-max", width && "w-max")}
+ >
+ {children}
+ </div>
+ </motion.div>
+ );
+ }
+);
+
+AnimatedSizeContainer.displayName = "AnimatedSizeContainer";
+
+export { AnimatedSizeContainer };
diff --git a/apps/carbon/app/components/DirectionAwareTabs.tsx b/apps/carbon/app/components/DirectionAwareTabs.tsx
index 09f79f1c2f..941ba41b5a 100644
--- a/apps/carbon/app/components/DirectionAwareTabs.tsx
+++ b/apps/carbon/app/components/DirectionAwareTabs.tsx
@@ -64,7 +64,18 @@ function DirectionAwareTabs({
};
return (
- <div className=" flex flex-col items-center w-full">
+ <motion.div
+ initial={{
+ opacity: 0,
+ filter: "blur(4px)",
+ }}
+ animate={{
+ opacity: 1,
+ filter: "blur(0px)",
+ }}
+ transition={{ duration: 0.2, delay: 0.3 }}
+ className=" flex flex-col items-center w-full"
+ >
<div
className={cn(
"flex space-x-1 rounded-lg cursor-pointer bg-muted px-[3px] py-[3.2px] shadow-inner-shadow",
@@ -126,7 +137,7 @@ function DirectionAwareTabs({
</div>
</motion.div>
</MotionConfig>
- </div>
+ </motion.div>
);
}
export { DirectionAwareTabs };
diff --git a/apps/carbon/app/components/Documents.tsx b/apps/carbon/app/components/Documents.tsx
index 327b0ba85f..6016def9b1 100644
--- a/apps/carbon/app/components/Documents.tsx
+++ b/apps/carbon/app/components/Documents.tsx
@@ -31,6 +31,7 @@ import { usePermissions, useUser } from "~/hooks";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ModelUpload, StorageItem } from "~/types";
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
type DocumentsProps = {
files: StorageItem[];
@@ -72,7 +73,9 @@ const Documents = ({
const getWritePath = useCallback(
(file: { name: string }) => {
const id = sourceDocumentLineId || sourceDocumentId;
- return `${company.id}/${writeBucket}/${id}/${file.name}`;
+ return `${company.id}/${writeBucket}/${id}/${stripSpecialCharacters(
+ file.name
+ )}`;
},
[company.id, sourceDocumentId, sourceDocumentLineId, writeBucket]
);
diff --git a/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx b/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx
new file mode 100644
index 0000000000..afb5bc6eca
--- /dev/null
+++ b/apps/carbon/app/components/ImportCSVModal/FieldMappings.tsx
@@ -0,0 +1,150 @@
+"use client";
+
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipProvider,
+ TooltipTrigger,
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { LuInfo, LuMoveRight } from "react-icons/lu";
+import { SelectControlled } from "~/components/Form";
+import { useCurrencyFormatter } from "~/hooks";
+import type { importSchemas } from "~/modules/shared";
+import { fieldMappings } from "~/modules/shared";
+import type { action } from "~/routes/api+/ai+/csv+/$table.columns";
+import { path } from "~/utils/path";
+import { useCsvContext } from "./useCsvContext";
+
+export function FieldMapping({ table }: { table: keyof typeof importSchemas }) {
+ const { fileColumns, firstRows } = useCsvContext();
+ const fetcher = useFetcher<typeof action>();
+ const mappableFields = fieldMappings[table];
+
+ useEffect(() => {
+ if (!fileColumns || !firstRows) return;
+
+ fetcher.submit(
+ {
+ fileColumns,
+ firstRows,
+ },
+ {
+ method: "POST",
+ action: path.to.api.generateCsvColumns(table),
+ encType: "application/json",
+ }
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fileColumns, firstRows]);
+
+ return (
+ <div className="mt-6">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-2">
+ <div className="text-sm">CSV Data column</div>
+ <div className="text-sm">Carbon data column</div>
+ {Object.entries(mappableFields).map(
+ ([name, { label, required, type }]) => (
+ <FieldRow
+ key={name}
+ label={label}
+ type={type}
+ required={required}
+ name={name}
+ mappedColumn={fetcher.data?.[name]}
+ isLoading={fetcher.state !== "idle"}
+ />
+ )
+ )}
+ </div>
+ </div>
+ );
+}
+
+function FieldRow({
+ name,
+ label,
+ type,
+ required,
+ mappedColumn,
+ isLoading,
+}: {
+ name: string;
+ label: string;
+ type: "string" | "number" | "date" | "boolean" | "currency";
+ required: boolean;
+ mappedColumn: string | undefined;
+ isLoading: boolean;
+}) {
+ const formatter = useCurrencyFormatter();
+ const { fileColumns, firstRows } = useCsvContext();
+ const [value, setValue] = useState<string | undefined>(mappedColumn);
+
+ useEffect(() => {
+ setValue(mappedColumn);
+ }, [mappedColumn]);
+
+ const firstRow = firstRows?.at(0);
+ const description = firstRow?.[value as keyof typeof firstRow];
+
+ const formatDescription = (description?: string) => {
+ if (!description) return;
+
+ if (type === "date") {
+ return formatDate(description);
+ }
+
+ if (type === "currency") {
+ return formatter.format(parseFloat(description));
+ }
+
+ if (type === "boolean") {
+ return description.toLowerCase() === "true" ? "Yes" : "No";
+ }
+
+ return description;
+ };
+
+ return (
+ <>
+ <div className="relative flex min-w-0 items-center gap-2">
+ <SelectControlled
+ name={name}
+ onChange={(value) => setValue(value?.value)}
+ isLoading={isLoading}
+ value={value}
+ options={[
+ // Filter out empty columns
+ ...(fileColumns?.filter((column) => column !== "") || []),
+ ...(value && !required ? ["None"] : []),
+ ]?.map((column) => ({ value: column, label: column }))}
+ />
+
+ <div className="flex items-center justify-end">
+ <LuMoveRight className="text-muted-foreground" />
+ </div>
+ </div>
+
+ <span className="flex h-10 w-full items-center justify-between whitespace-nowrap border border-border bg-transparent px-3 py-2 rounded-md text-base space-x-3">
+ <div className="grow whitespace-nowrap font-normal text-muted-foreground justify-between flex">
+ <span>{label}</span>
+
+ {description && (
+ <TooltipProvider delayDuration={50}>
+ <Tooltip>
+ <TooltipTrigger>
+ <LuInfo />
+ </TooltipTrigger>
+ <TooltipContent className="p-2 text-sm">
+ {formatDescription(description)}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ )}
+ </div>
+ </span>
+ </>
+ );
+}
diff --git a/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx
new file mode 100644
index 0000000000..a21845bb69
--- /dev/null
+++ b/apps/carbon/app/components/ImportCSVModal/ImportCSVModal.tsx
@@ -0,0 +1,142 @@
+import { Hidden, Submit, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Modal,
+ ModalContent,
+ ModalDescription,
+ ModalHeader,
+ ModalTitle,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import { flushSync } from "react-dom";
+import { z } from "zod";
+import {
+ importSchemas,
+ type fieldMappings,
+} from "~/modules/shared/imports.models";
+import { AnimatedSizeContainer } from "../AnimatedSizeContainer";
+import { FieldMapping } from "./FieldMappings";
+import { UploadCSV } from "./UploadCSV";
+import { ImportCsvContext } from "./useCsvContext";
+
+enum ImportCSVPage {
+ UploadCSV = "upload-csv",
+ FieldMappings = "field-mapping",
+}
+
+const pages = [ImportCSVPage.UploadCSV, ImportCSVPage.FieldMappings] as const;
+
+type ImportCSVModalProps = {
+ table: keyof typeof fieldMappings;
+ onClose: () => void;
+};
+
+export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
+ const fetcher = useFetcher<{}>();
+
+ const [page, setPage] = useState<(typeof pages)[number]>(
+ ImportCSVPage.UploadCSV
+ );
+ const [file, setFile] = useState<File | null>(null);
+ const [path, setPath] = useState<string | null>(null);
+ const [fileColumns, setFileColumns] = useState<string[] | null>(null);
+ const [firstRows, setFirstRows] = useState<Record<string, string>[] | null>(
+ null
+ );
+
+ // if the file upload is successful, set the page to field-mapping
+ useEffect(() => {
+ if (file && fileColumns && page === ImportCSVPage.UploadCSV) {
+ setPage(ImportCSVPage.FieldMappings);
+ }
+ }, [file, fileColumns, page]);
+
+ return (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <div className="p-4">
+ <ModalHeader>
+ <div className="flex space-x-4 items-center mb-4">
+ <ModalTitle className="m-0 p-0">
+ {page === ImportCSVPage.UploadCSV && "Upload CSV"}
+ {page === ImportCSVPage.FieldMappings && "Field mapping"}
+ </ModalTitle>
+ </div>
+ <ModalDescription>
+ {page === ImportCSVPage.UploadCSV &&
+ `Please upload a CSV file of your ${table} data`}
+ {page === ImportCSVPage.FieldMappings &&
+ "We've mapped each column to what we believe is correct, but please review the data below to confirm it's accurate."}
+ </ModalDescription>
+ </ModalHeader>
+
+ <div className="relative">
+ <AnimatedSizeContainer height>
+ <ImportCsvContext.Provider
+ value={{
+ file,
+ fileColumns,
+ firstRows,
+ path,
+ setFile,
+ setFileColumns,
+ setFirstRows,
+ setPath,
+ }}
+ >
+ <div>
+ <ValidatedForm
+ className="flex flex-col gap-y-4"
+ fetcher={fetcher}
+ validator={importSchemas[table].extend({
+ path: z.string().min(1, { message: "Path is required" }),
+ })}
+ >
+ <Hidden name="path" value={path ?? ""} />
+ {page === ImportCSVPage.UploadCSV && <UploadCSV />}
+ {page === ImportCSVPage.FieldMappings && (
+ <>
+ <FieldMapping table={table} />
+
+ <Submit
+ isDisabled={!path || fetcher.state !== "idle"}
+ className="mt-4"
+ type="submit"
+ >
+ Confirm Import
+ </Submit>
+
+ <Button
+ variant="link"
+ type="button"
+ onClick={() => {
+ flushSync(() => {
+ setFile(null);
+ setFileColumns(null);
+ setFirstRows(null);
+ });
+ setPage(ImportCSVPage.UploadCSV);
+ }}
+ >
+ Choose another file
+ </Button>
+ </>
+ )}
+ </ValidatedForm>
+ </div>
+ </ImportCsvContext.Provider>
+ </AnimatedSizeContainer>
+ </div>
+ </div>
+ </ModalContent>
+ </Modal>
+ );
+};
diff --git a/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx b/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx
new file mode 100644
index 0000000000..a5ddcca3f4
--- /dev/null
+++ b/apps/carbon/app/components/ImportCSVModal/UploadCSV.tsx
@@ -0,0 +1,175 @@
+import { useCarbon } from "@carbon/auth";
+import { Spinner, cn, toast } from "@carbon/react";
+import { nanoid } from "nanoid";
+import Papa from "papaparse";
+import { useState } from "react";
+import { flushSync } from "react-dom";
+import { useDropzone } from "react-dropzone";
+import { useUser } from "~/hooks/useUser";
+import { useCsvContext } from "./useCsvContext";
+
+export const UploadCSV = () => {
+ const { carbon } = useCarbon();
+ const { company } = useUser();
+ const { setFile, setFileColumns, setFirstRows, setPath } = useCsvContext();
+ const [uploading, setUploading] = useState(false);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const processFile = async (file: File) => {
+ if (!file) {
+ setFileColumns(null);
+ return;
+ }
+
+ flushSync(() => {
+ setLoading(true);
+ });
+
+ readLines(file, 4)
+ .then((lines) => {
+ const { data, meta } = Papa.parse(lines, {
+ worker: false,
+ skipEmptyLines: true,
+ header: true,
+ });
+
+ if (!data || data.length < 2) {
+ setError("CSV file must have at least 2 rows.");
+ setFileColumns(null);
+ setFirstRows(null);
+ setLoading(false);
+ return;
+ }
+
+ if (!meta || !meta.fields || meta.fields.length <= 1) {
+ setError("Failed to retrieve CSV column data.");
+ setFileColumns(null);
+ setFirstRows(null);
+ setLoading(false);
+ return;
+ }
+
+ setFileColumns(meta.fields);
+ setFirstRows(data as Record<string, string>[]);
+ setLoading(false);
+ })
+ .catch(() => {
+ setError("Failed to read CSV file.");
+ setFileColumns(null);
+ setFirstRows(null);
+ setLoading(false);
+ });
+ };
+
+ const uploadFile = async (file: File) => {
+ const fileName = `${company.id}/imports/${nanoid()}.csv`;
+
+ if (!carbon) {
+ setError("Carbon client not available");
+ setFileColumns(null);
+ setFirstRows(null);
+ setLoading(false);
+ return;
+ }
+
+ const { data, error } = await carbon.storage
+ .from("private")
+ .upload(fileName, file);
+
+ if (error) {
+ setError("Failed to upload CSV file.");
+ setFileColumns(null);
+ setFirstRows(null);
+ setLoading(false);
+ return;
+ }
+
+ setPath(data.path);
+ };
+
+ const onDrop = async (acceptedFiles: File[]) => {
+ if (!carbon) {
+ toast.error("Carbon client not available");
+ return;
+ }
+
+ if (acceptedFiles.length > 0) {
+ flushSync(() => {
+ setUploading(true);
+ });
+
+ if (acceptedFiles[0]) {
+ setFile(acceptedFiles[0]);
+ await Promise.all([
+ processFile(acceptedFiles[0]),
+ uploadFile(acceptedFiles[0]),
+ ]);
+ }
+
+ setUploading(false);
+ }
+ };
+
+ const { getRootProps, getInputProps, isDragActive, isDragReject } =
+ useDropzone({
+ onDrop,
+ accept: { "text/csv": [".csv"] },
+ maxFiles: 1,
+ maxSize: 5 * 1024 * 1024, // 5MB
+ disabled: uploading,
+ });
+
+ return (
+ <div
+ {...getRootProps()}
+ className={cn(
+ "w-full border-2 border-dashed h-[200px] rounded-md mt-8 mb-8 flex items-center justify-center text-muted-foreground hover:border-primary hover:text-foreground cursor-pointer focus-visible:border-primary focus-visible:text-foreground hover:bg-primary/5 focus-visible:outline-none",
+ isDragActive
+ ? "border-primary text-foreground bg-primary/5"
+ : "border-muted",
+ isDragReject && "border-destructive"
+ )}
+ >
+ <div className="text-center flex items-center justify-center flex-col text-xs">
+ <input {...getInputProps()} />
+
+ {loading ? (
+ <div className="flex space-x-1 items-center">
+ <Spinner />
+ <span>Loading...</span>
+ </div>
+ ) : (
+ <div>
+ <p>Drop your file here, or click to browse.</p>
+ <span>5MB file limit</span>
+ </div>
+ )}
+
+ {error && (
+ <p className="text-center text-sm text-red-600 mt-4">{error}</p>
+ )}
+ </div>
+ </div>
+ );
+};
+
+async function readLines(file: File, count = 4): Promise<string> {
+ const reader = file.stream().getReader();
+ const decoder = new TextDecoder("utf-8");
+ let { value: chunk, done: readerDone } = await reader.read();
+ let content = "";
+ const result: string[] = [];
+
+ while (!readerDone) {
+ content += decoder.decode(chunk, { stream: true });
+ const lines = content.split("\n");
+ if (lines.length >= count) {
+ reader.cancel();
+ return lines.slice(0, count).join("\n");
+ }
+ ({ value: chunk, done: readerDone } = await reader.read());
+ }
+
+ return result.join("\n");
+}
diff --git a/apps/carbon/app/components/ImportCSVModal/index.ts b/apps/carbon/app/components/ImportCSVModal/index.ts
new file mode 100644
index 0000000000..7dae66b7ce
--- /dev/null
+++ b/apps/carbon/app/components/ImportCSVModal/index.ts
@@ -0,0 +1,3 @@
+import { ImportCSVModal } from "./ImportCSVModal";
+
+export { ImportCSVModal };
diff --git a/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx b/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx
new file mode 100644
index 0000000000..17a3481777
--- /dev/null
+++ b/apps/carbon/app/components/ImportCSVModal/useCsvContext.tsx
@@ -0,0 +1,23 @@
+import { createContext, useContext } from "react";
+
+export const ImportCsvContext = createContext<{
+ path: 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;
+} | null>(null);
+
+export function useCsvContext() {
+ const context = useContext(ImportCsvContext);
+
+ if (!context)
+ throw new Error(
+ "useCsvContext must be used within an ImportCsvContext.Provider"
+ );
+
+ return context;
+}
diff --git a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
index a039db7d72..fc50ab9856 100644
--- a/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
+++ b/apps/carbon/app/components/Layout/Navigation/GroupedContentSidebar.tsx
@@ -25,7 +25,7 @@ const GroupedContentSidebar = ({
className="border-b border-border p-2"
spacing={1}
>
- <h4 className="text-xs text-muted-foreground font-mono pl-4 py-1 uppercase">
+ <h4 className="text-xs text-muted-foreground font-bold pl-4 py-1 uppercase">
{group.name}
</h4>
{group.routes.map((route) => {
@@ -39,7 +39,7 @@ const GroupedContentSidebar = ({
leftIcon={route.icon}
variant={isActive ? "active" : "ghost"}
className={cn(
- "w-full justify-start",
+ "w-full justify-start truncate",
!isActive &&
"hover:bg-active hover:text-active-foreground"
)}
diff --git a/apps/carbon/app/components/Select.tsx b/apps/carbon/app/components/Select.tsx
index 2f790ad962..3fde856917 100644
--- a/apps/carbon/app/components/Select.tsx
+++ b/apps/carbon/app/components/Select.tsx
@@ -9,7 +9,7 @@ import {
} from "@carbon/react";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef } from "react";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
export type SelectProps = Omit<
ComponentPropsWithoutRef<"button">,
@@ -69,7 +69,7 @@ const Select = forwardRef<HTMLButtonElement, SelectProps>(
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => onChange("")}
size={size === "sm" ? "md" : size}
/>
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 8632e2c49f..39aeb243ef 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -44,6 +44,7 @@ import type {
EditableTableCellComponent,
Position,
} from "~/components/Editable";
+import type { fieldMappings } from "~/modules/shared";
import {
IndeterminateCheckbox,
Pagination,
@@ -66,6 +67,10 @@ interface TableProps<T extends object> {
defaultColumnPinning?: ColumnPinningState;
defaultColumnVisibility?: Record<string, boolean>;
editableComponents?: Record<string, EditableTableCellComponent<T>>;
+ importCSV?: {
+ table: keyof typeof fieldMappings;
+ label: string;
+ }[];
primaryAction?: ReactNode;
withInlineEditing?: boolean;
withPagination?: boolean;
diff --git a/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx b/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx
index 438f6ddc23..dd2f9e0e02 100644
--- a/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx
+++ b/apps/carbon/app/components/Table/components/Filter/ActiveFilters.tsx
@@ -16,7 +16,7 @@ import {
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { useEffect, useState } from "react";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
import Filter from "./Filter";
import type { ColumnFilter } from "./types";
import { useFilters } from "./useFilters";
@@ -190,7 +190,7 @@ const ActiveFilter = ({ filter, operator, value }: ActiveFilterProps) => {
removeKey(filter.accessorKey);
}}
>
- <MdClose />
+ <LuX />
</Button>
</HStack>
);
diff --git a/apps/carbon/app/components/Table/components/Filter/Filter.tsx b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
index 25404f0b2f..c9b9d5d152 100644
--- a/apps/carbon/app/components/Table/components/Filter/Filter.tsx
+++ b/apps/carbon/app/components/Table/components/Filter/Filter.tsx
@@ -17,8 +17,7 @@ import type { PostgrestResponse } from "@supabase/supabase-js";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useCallback, useEffect, useMemo, useState } from "react";
import { IoMdAdd } from "react-icons/io";
-import { LuListFilter } from "react-icons/lu";
-import { MdClose } from "react-icons/md";
+import { LuListFilter, LuX } from "react-icons/lu";
import type { ColumnFilter, Option } from "./types";
import { useFilters } from "./useFilters";
@@ -103,7 +102,7 @@ const Filter = forwardRef<HTMLButtonElement, FilterProps>(
return hasFilters && !open && trigger !== "icon" ? (
<HStack>
<Button
- rightIcon={<MdClose />}
+ rightIcon={<LuX />}
ref={ref}
variant="secondary"
onClick={clearFilters}
diff --git a/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx b/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
index 42464db105..3906effc69 100644
--- a/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
+++ b/apps/carbon/app/modules/accounting/ui/ChartOfAccounts/ChartOfAccountsTableFilters.tsx
@@ -8,7 +8,8 @@ import {
PopoverTrigger,
} from "@carbon/react";
import { parseDate } from "@internationalized/date";
-import { MdCalendarMonth, MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
+import { MdCalendarMonth } from "react-icons/md";
import { New, Select } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import { incomeBalanceTypes } from "~/modules/accounting";
@@ -67,7 +68,7 @@ const ChartOfAccountsTableFilters = () => {
{[...params.entries()].length > 0 && (
<Button
variant="solid"
- rightIcon={<MdClose />}
+ rightIcon={<LuX />}
onClick={() =>
setParams({
incomeBalance: undefined,
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 277b14b740..a963270cca 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -320,16 +320,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
label: "Work Instructions",
content: (
<div className="flex flex-col">
- <motion.div
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- bounce: 0.2,
- duration: 0.75,
- delay: 0.15,
- }}
- >
+ <div>
{permissions.can("update", "parts") ? (
<Editor
initialValue={
@@ -348,7 +339,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
}}
/>
)}
- </motion.div>
+ </div>
</div>
),
},
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
index 53d52b537b..588687ccd3 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -35,6 +35,7 @@ import { useCallback } from "react";
import { usePermissions, useUser } from "~/hooks";
import type { ModelUpload } from "~/types";
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
type ItemDocumentsProps = {
files: ItemFile[];
@@ -260,7 +261,9 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
const canDelete = permissions.can("delete", "parts");
const getPath = useCallback(
(file: { name: string }) => {
- return `${company.id}/parts/${itemId}/${file.name}`;
+ return `${company.id}/parts/${itemId}/${stripSpecialCharacters(
+ file.name
+ )}`;
},
[company.id, itemId]
);
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 0d57318827..562fee6b7d 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -427,16 +427,7 @@ const JobBillOfProcess = ({
label: "Work Instructions",
content: (
<div className="flex flex-col">
- <motion.div
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- bounce: 0.2,
- duration: 0.75,
- delay: 0.15,
- }}
- >
+ <div>
{permissions.can("update", "parts") ? (
<Editor
initialValue={
@@ -455,7 +446,7 @@ const JobBillOfProcess = ({
}}
/>
)}
- </motion.div>
+ </div>
</div>
),
},
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
index a0602b456d..d6f38422ca 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
@@ -5,6 +5,7 @@ import type { ChangeEvent } from "react";
import { LuUpload } from "react-icons/lu";
import { useUser } from "~/hooks";
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
type PurchaseOrderDocumentFormProps = {
orderId: string;
@@ -24,7 +25,7 @@ const PurchaseOrderDocumentForm = ({
const file = e.target.files[0];
const fileName = `${company.id}/purchasing/${
isExternal ? "external" : "internal"
- }/${orderId}/${file.name}`;
+ }/${orderId}/${stripSpecialCharacters(file.name)}`;
const fileUpload = await carbon.storage
.from("private")
diff --git a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
index feb3d91c0e..0ea74a8df0 100644
--- a/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customers/CustomersTable.tsx
@@ -1,14 +1,20 @@
-import { Button, MenuIcon, MenuItem } from "@carbon/react";
+import { MenuIcon, MenuItem } from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { useFetcher, useNavigate } from "@remix-run/react";
+import { 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, Table } from "~/components";
+import {
+ CustomerAvatar,
+ EmployeeAvatar,
+ Hyperlink,
+ New,
+ 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";
@@ -21,55 +27,8 @@ 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>[]>(() => {
@@ -203,17 +162,16 @@ const CustomersTable = memo(
updatedBy: false,
updatedAt: false,
}}
+ importCSV={[
+ {
+ table: "customer",
+ label: "Customers",
+ },
+ ]}
primaryAction={
- // permissions.can("create", "sales") && (
- // <New label="Customer" to={path.to.newCustomer} />
- // )
- <Button
- onClick={letsGo}
- isLoading={fetcher.state !== "idle"}
- isDisabled={fetcher.state !== "idle"}
- >
- Import
- </Button>
+ permissions.can("create", "sales") && (
+ <New label="Customer" to={path.to.newCustomer} />
+ )
}
renderContextMenu={renderContextMenu}
/>
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
index dd42304fcc..ca57415948 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
@@ -38,6 +38,7 @@ import { DocumentPreview, FileDropzone } from "~/components";
import { usePermissions, useUser } from "~/hooks";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
import type { Opportunity } from "../../types";
import { useOptimisticDocumentDrag } from "../SalesRFQ/useOptimiticDocumentDrag";
@@ -227,7 +228,11 @@ export const useOpportunityDocuments = ({
const getPath = useCallback(
(attachment: { name: string }) => {
- return `${company.id}/opportunity/${opportunityId}/${attachment.name}`;
+ return `${
+ company.id
+ }/opportunity/${opportunityId}/${stripSpecialCharacters(
+ attachment.name
+ )}`;
},
[company.id, opportunityId]
);
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
index 0334e8f84c..a77d48eb6e 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
@@ -35,6 +35,7 @@ import { path } from "~/utils/path";
import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
import type { ModelUpload } from "~/types";
+import { stripSpecialCharacters } from "~/utils/string";
const useOpportunityLineDocuments = ({
id,
@@ -57,7 +58,9 @@ const useOpportunityLineDocuments = ({
const getPath = useCallback(
(file: { name: string }) => {
- return `${company.id}/opportunity-line/${lineId}/${file.name}`;
+ return `${company.id}/opportunity-line/${lineId}/${stripSpecialCharacters(
+ file.name
+ )}`;
},
[company.id, lineId]
);
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index fa9b040955..37e9798351 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -329,16 +329,7 @@ const QuoteBillOfProcess = ({
label: "Work Instructions",
content: (
<div className="flex flex-col">
- <motion.div
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- bounce: 0.2,
- duration: 0.75,
- delay: 0.15,
- }}
- >
+ <div>
{permissions.can("update", "parts") ? (
<Editor
initialValue={
@@ -357,7 +348,7 @@ const QuoteBillOfProcess = ({
}}
/>
)}
- </motion.div>
+ </div>
</div>
),
},
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
index 2f1994a85d..f10c2c8d62 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLinePricing.tsx
@@ -71,6 +71,7 @@ const QuoteLinePricing = ({
if (!lineId) throw new Error("Could not find lineId");
const [prices, setPrices] =
useState<Record<number, QuotationPrice>>(pricesByQuantity);
+
useEffect(() => {
setPrices(pricesByQuantity);
}, [pricesByQuantity]);
diff --git a/apps/carbon/app/modules/shared/imports.models.ts b/apps/carbon/app/modules/shared/imports.models.ts
new file mode 100644
index 0000000000..5ca1aa035d
--- /dev/null
+++ b/apps/carbon/app/modules/shared/imports.models.ts
@@ -0,0 +1,68 @@
+import { z } from "zod";
+
+export const fieldMappings = {
+ customer: {
+ id: {
+ label: "ID",
+ required: true,
+ type: "string",
+ },
+ name: {
+ label: "Name",
+ required: true,
+ type: "string",
+ },
+ phone: {
+ label: "Phone",
+ required: false,
+ type: "string",
+ },
+ email: {
+ label: "Email",
+ required: false,
+ type: "string",
+ },
+ taxId: {
+ label: "Tax ID",
+ required: false,
+ type: "string",
+ },
+ website: {
+ label: "Website",
+ required: false,
+ type: "string",
+ },
+ },
+} as const;
+
+export const importSchemas: Record<
+ keyof typeof fieldMappings,
+ z.ZodObject<any>
+> = {
+ customer: z.object({
+ id: z
+ .string()
+ .min(1, { message: "ID is required" })
+ .describe(
+ "The id of the customer, usually a number or set of alphanumeric characters."
+ ),
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe(
+ "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"),
+ taxId: z
+ .string()
+ .optional()
+ .describe(
+ "The tax identification number of the customer. Usually numeric."
+ ),
+ website: z
+ .string()
+ .optional()
+ .describe("The website url. Usually begins with http:// or https://"),
+ }),
+} as const;
diff --git a/apps/carbon/app/modules/shared/index.ts b/apps/carbon/app/modules/shared/index.ts
index ed2f95099d..1bbd970225 100644
--- a/apps/carbon/app/modules/shared/index.ts
+++ b/apps/carbon/app/modules/shared/index.ts
@@ -1,3 +1,4 @@
+export * from "./imports.models";
export * from "./shared.models";
export * from "./shared.service";
export * from "./types";
diff --git a/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx
index 90b93746c7..b6bebea302 100644
--- a/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx
+++ b/apps/carbon/app/routes/api+/ai+/csv+/$table.columns.tsx
@@ -6,31 +6,13 @@ import { json } from "@vercel/remix";
import { generateObject } from "ai";
import type { ZodSchema } from "zod";
import { z } from "zod";
+import { importSchemas } from "~/modules/shared";
const inputSchema = z.object({
- fieldColumns: z.array(z.string()),
+ fileColumns: 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",
@@ -38,26 +20,20 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { table } = params;
if (!table) {
- return notFound("No table parameter provided");
+ throw 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 }
- );
+ throw notFound("Table not found in the list of supported tables");
}
- const { fieldColumns, firstRows } = result.data;
+ const { fileColumns, firstRows } = result.data;
- const schema = importSchemas[table];
+ const schema = importSchemas[table as keyof typeof importSchemas];
if (!schema) {
- return json(
- { error: "Table not found in the list of supported tables" },
- { status: 404 }
- );
+ throw notFound("Table not found in the list of supported tables");
}
const { object } = await generateObject<Record<string, string>>({
@@ -71,7 +47,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
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(",")}
+ ${fileColumns.join(",")}
First few rows of data:
${firstRows.map((row) => JSON.stringify(row)).join("\n")}
`,
diff --git a/apps/carbon/app/routes/x+/api+/$lang.intro.tsx b/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
index 8d8c65d525..5bf6bec885 100644
--- a/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
+++ b/apps/carbon/app/routes/x+/api+/$lang.intro.tsx
@@ -42,7 +42,7 @@ export default function Route() {
<code>PUBLIC_KEY</code> (shown below) in addition to your{" "}
<code>carbon-key</code> API Key.
</p>
- <Alert variant="destructive">
+ <Alert variant="success">
<LuAlertTriangle className="h-4 w-4 my-1" />
<AlertTitle className="!my-0 font-bold text-base">
You should never expose the <code>carbon-key</code> in the
diff --git a/apps/carbon/app/routes/x+/api+/_layout.tsx b/apps/carbon/app/routes/x+/api+/_layout.tsx
index 401f4598a1..12dc7b9627 100644
--- a/apps/carbon/app/routes/x+/api+/_layout.tsx
+++ b/apps/carbon/app/routes/x+/api+/_layout.tsx
@@ -118,7 +118,11 @@ function useApiDocsMenu(): RouteGroup[] {
.map((table) => ({
name: table,
to: path.to.apiTable(selectedLang, table),
- icon: isTable(table) ? <LuTable2 /> : <LuEye />,
+ icon: isTable(table) ? (
+ <LuTable2 className="flex-shrink-0" />
+ ) : (
+ <LuEye className="flex-shrink-0" />
+ ),
})),
});
diff --git a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
index 23981f75af..3209857deb 100644
--- a/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
+++ b/apps/carbon/app/routes/x+/purchase-order+/$orderId.release.tsx
@@ -20,6 +20,7 @@ import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/purchase-order+/$orderId[.]pdf";
import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have a sendEmail task defined
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
// export const config = { runtime: "nodejs" };
@@ -66,9 +67,11 @@ export async function action(args: ActionFunctionArgs) {
throw new Error("Failed to generate PDF");
file = await pdf.arrayBuffer();
- fileName = `${purchaseOrder.data.purchaseOrderId} - ${new Date()
- .toISOString()
- .slice(0, -5)}.pdf`;
+ fileName = stripSpecialCharacters(
+ `${purchaseOrder.data.purchaseOrderId} - ${new Date()
+ .toISOString()
+ .slice(0, -5)}.pdf`
+ );
const documentFilePath = `${companyId}/purchasing/external/${orderId}/${fileName}`;
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
index 7e4a1d9707..4752c2ca76 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -20,6 +20,7 @@ import { getUser } from "~/modules/users/users.server";
import { loader as pdfLoader } from "~/routes/file+/quote+/$id[.]pdf";
import type { sendEmailResendTask } from "~/trigger/send-email-resend"; // Assuming you have this task defined
import { path } from "~/utils/path";
+import { stripSpecialCharacters } from "~/utils/string";
// export const config = { runtime: "nodejs" };
@@ -64,9 +65,9 @@ export async function action(args: ActionFunctionArgs) {
throw new Error("Failed to generate PDF");
file = await pdf.arrayBuffer();
- fileName = `${quote.data.quoteId} - ${new Date()
- .toISOString()
- .slice(0, -5)}.pdf`;
+ fileName = stripSpecialCharacters(
+ `${quote.data.quoteId} - ${new Date().toISOString().slice(0, -5)}.pdf`
+ );
const documentFilePath = `${companyId}/opportunity/${opportunity.data.id}/${fileName}`;
diff --git a/apps/carbon/app/routes/x+/sales+/customers.tsx b/apps/carbon/app/routes/x+/sales+/customers.tsx
index 140d53aae4..bd7e5ad8ca 100644
--- a/apps/carbon/app/routes/x+/sales+/customers.tsx
+++ b/apps/carbon/app/routes/x+/sales+/customers.tsx
@@ -66,6 +66,7 @@ export default function SalesCustomersRoute() {
count={count}
customerStatuses={customerStatuses}
/>
+
<Outlet />
</VStack>
);
diff --git a/apps/carbon/app/utils/string.ts b/apps/carbon/app/utils/string.ts
index 16a83c9819..df66c2db56 100644
--- a/apps/carbon/app/utils/string.ts
+++ b/apps/carbon/app/utils/string.ts
@@ -3,6 +3,11 @@ export const capitalize = (words: string) => {
return [first.toLocaleUpperCase(), ...otherLetters].join("");
};
+export function stripSpecialCharacters(inputString: string) {
+ // Use a regular expression to replace all non-alphanumeric characters except hyphen, space, dot,and parentheses with an empty string
+ return inputString?.replace(/[^a-zA-Z0-9\s.()-]/g, "");
+}
+
export const snakeToCamel = (str: string) =>
str.replace(/([-_][a-z])/g, (group: string) =>
group.toUpperCase().replace("-", "").replace("_", "")
diff --git a/apps/carbon/package.json b/apps/carbon/package.json
index 7661d2b784..c1c4ae11c8 100644
--- a/apps/carbon/package.json
+++ b/apps/carbon/package.json
@@ -83,6 +83,7 @@
"@carbon/tsconfig": "*",
"@trigger.dev/build": "3.0.6",
"@types/nprogress": "^0.2.0",
+ "@types/papaparse": "^5.3.14",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.24",
"autoprefixer": "10.4.14",
diff --git a/package-lock.json b/package-lock.json
index df52b181bc..a0e843167f 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -114,6 +114,7 @@
"@carbon/tsconfig": "*",
"@trigger.dev/build": "3.0.6",
"@types/nprogress": "^0.2.0",
+ "@types/papaparse": "^5.3.14",
"@types/react": "^18.2.74",
"@types/react-dom": "^18.2.24",
"autoprefixer": "10.4.14",
@@ -10709,6 +10710,15 @@
"integrity": "sha512-k7kRA033QNtC+gLc4VPlfnue58CM1iQLgn1IMAU8VPHGOj7oIHPp9UlhedEnD/Gl8evoCjwkZjlBORtZ3JByUA==",
"dev": true
},
+ "node_modules/@types/papaparse": {
+ "version": "5.3.14",
+ "resolved": "https://registry.npmjs.org/@types/papaparse/-/papaparse-5.3.14.tgz",
+ "integrity": "sha512-LxJ4iEFcpqc6METwp9f6BV6VVc43m6MfH0VqFosHvrUgfXiFe6ww7R3itkOQ+TCK6Y+Iv/+RnnvtRZnkc5Kc9g==",
+ "dev": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
"node_modules/@types/phoenix": {
"version": "1.6.5",
"resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.5.tgz",
diff --git a/packages/database/supabase/migrations/20241009032956_imports.sql b/packages/database/supabase/migrations/20241009032956_imports.sql
new file mode 100644
index 0000000000..a3909488d2
--- /dev/null
+++ b/packages/database/supabase/migrations/20241009032956_imports.sql
@@ -0,0 +1,6 @@
+CREATE POLICY "Employees can upload imports" ON storage.objects
+FOR INSERT WITH CHECK (
+ bucket_id = 'private'
+ AND has_role('employee', (storage.foldername(name))[1])
+ AND (storage.foldername(name))[2] = 'imports'
+);
\ No newline at end of file
diff --git a/packages/form/src/components/Select.tsx b/packages/form/src/components/Select.tsx
index d97697928b..836f5f2c85 100644
--- a/packages/form/src/components/Select.tsx
+++ b/packages/form/src/components/Select.tsx
@@ -10,11 +10,12 @@ import {
SelectItem,
SelectTrigger,
SelectValue,
+ Spinner,
} from "@carbon/react";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef } from "react";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
import { useControlField, useField } from "../hooks";
export type SelectProps = Omit<SelectBaseProps, "onChange"> & {
@@ -30,6 +31,7 @@ const Select = ({
label,
helperText,
isOptional = false,
+ isLoading,
...props
}: SelectProps) => {
const { getInputProps, error } = useField(name);
@@ -67,6 +69,7 @@ const Select = ({
onChange(newValue ?? "");
}}
isClearable={isOptional && !props.isReadOnly}
+ isLoading={isLoading}
className="w-full"
/>
@@ -94,6 +97,7 @@ export type SelectBaseProps = Omit<
value: string;
}[];
isClearable?: boolean;
+ isLoading?: boolean;
isReadOnly?: boolean;
placeholder?: string;
onChange: (selected: string) => void;
@@ -106,6 +110,7 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
value,
options,
isClearable,
+ isLoading,
isReadOnly,
placeholder,
onChange,
@@ -125,9 +130,15 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
size={size}
// isReadOnly={isReadOnly}
{...props}
- className="min-w-[160px]"
+ className="min-w-[160px] relative"
+ hideIcon={isLoading}
>
<SelectValue placeholder={placeholder} />
+ {isLoading && (
+ <div className="absolute top-2 right-2">
+ <Spinner />
+ </div>
+ )}
</SelectTrigger>
<SelectContent>
{options.map((option) => (
@@ -141,7 +152,7 @@ export const SelectBase = forwardRef<HTMLButtonElement, SelectBaseProps>(
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => onChange("")}
size={size === "sm" ? "md" : size}
/>
diff --git a/packages/form/src/components/SelectControlled.tsx b/packages/form/src/components/SelectControlled.tsx
index 3eff591739..2433b56326 100644
--- a/packages/form/src/components/SelectControlled.tsx
+++ b/packages/form/src/components/SelectControlled.tsx
@@ -14,6 +14,7 @@ export type SelectProps = Omit<SelectBaseProps, "onChange"> & {
name: string;
label?: string;
helperText?: string;
+ isOptional?: boolean;
options: { value: string | number; label: string }[];
onChange?: (newValue: { value: string; label: string } | null) => void;
};
@@ -23,6 +24,7 @@ const SelectControlled = ({
label,
helperText,
options,
+ isOptional,
...props
}: SelectProps) => {
const { getInputProps, error } = useField(name);
@@ -44,7 +46,11 @@ const SelectControlled = ({
return (
<FormControl isInvalid={!!error}>
- {label && <FormLabel htmlFor={name}>{label}</FormLabel>}
+ {label && (
+ <FormLabel htmlFor={name} isOptional={isOptional}>
+ {label}
+ </FormLabel>
+ )}
<input
{...getInputProps({
id: name,
diff --git a/packages/form/src/components/Timezone.tsx b/packages/form/src/components/Timezone.tsx
index 39bd466976..f00de83631 100644
--- a/packages/form/src/components/Timezone.tsx
+++ b/packages/form/src/components/Timezone.tsx
@@ -14,7 +14,7 @@ import {
SelectValue,
} from "@carbon/react";
import { timezones } from "@carbon/utils";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
import { useControlField, useField } from "../hooks";
import type { SelectProps } from "./Select";
@@ -73,7 +73,7 @@ const Timezone = ({
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => setValue("")}
size={size === "sm" ? "md" : size}
/>
diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsx
index 6e5080259d..9b772b15cf 100644
--- a/packages/react/src/Badge.tsx
+++ b/packages/react/src/Badge.tsx
@@ -5,8 +5,8 @@ import type {
HTMLAttributes,
} from "react";
import { forwardRef } from "react";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
import { cn } from "./utils/cn";
const badgeVariants = cva(
@@ -59,7 +59,7 @@ const BadgeCloseButton = forwardRef<
)}
{...props}
>
- <MdClose className="h-3 w-3 " />
+ <LuX className="h-3 w-3 " />
</button>
));
BadgeCloseButton.displayName = "BadgeCloseButton";
diff --git a/packages/react/src/Card.tsx b/packages/react/src/Card.tsx
index 9b4a3e5815..fcdfaf5773 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 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",
+ "relative flex flex-col rounded-lg border border-border 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 p-4 w-full",
className
)}
{...props}
@@ -40,7 +40,7 @@ const Card = forwardRef<HTMLDivElement, CardProps>(
<button
type="button"
onClick={toggle}
- className="absolute right-3 top-4 p-2 text-muted-foreground hover:text-foreground"
+ className="absolute right-4 top-4 p-4 text-muted-foreground hover:text-foreground"
>
{isCollapsed ? (
<LuChevronDown className="w-6 h-6" />
diff --git a/packages/react/src/Combobox.tsx b/packages/react/src/Combobox.tsx
index b71204f157..29c0cf9d06 100644
--- a/packages/react/src/Combobox.tsx
+++ b/packages/react/src/Combobox.tsx
@@ -1,8 +1,7 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useMemo, useRef, useState } from "react";
-import { LuCheck } from "react-icons/lu";
-import { MdClose } from "react-icons/md";
+import { LuCheck, LuX } from "react-icons/lu";
import {
Command,
CommandGroup,
@@ -88,7 +87,7 @@ const Combobox = forwardRef<HTMLButtonElement, ComboboxProps>(
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => onChange?.("")}
size={size === "sm" ? "md" : size}
/>
diff --git a/packages/react/src/CreateableCombobox.tsx b/packages/react/src/CreateableCombobox.tsx
index 60d6b8518e..719423e4ba 100644
--- a/packages/react/src/CreateableCombobox.tsx
+++ b/packages/react/src/CreateableCombobox.tsx
@@ -1,8 +1,7 @@
import { useVirtualizer } from "@tanstack/react-virtual";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useMemo, useRef, useState } from "react";
-import { LuCheck } from "react-icons/lu";
-import { MdClose } from "react-icons/md";
+import { LuCheck, LuX } from "react-icons/lu";
import {
Command,
CommandGroup,
@@ -100,7 +99,7 @@ const CreatableCombobox = forwardRef<HTMLButtonElement, CreatableComboboxProps>(
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => onChange?.("")}
size={size === "sm" ? "md" : size}
/>
diff --git a/packages/react/src/CreateableMultiSelect.tsx b/packages/react/src/CreateableMultiSelect.tsx
index b490cd00bc..f1c0fe87af 100644
--- a/packages/react/src/CreateableMultiSelect.tsx
+++ b/packages/react/src/CreateableMultiSelect.tsx
@@ -3,8 +3,7 @@ import { CommandEmpty } from "cmdk";
import type { ComponentPropsWithoutRef } from "react";
import { forwardRef, useId, useMemo, useRef, useState } from "react";
import { FaRegSquare, FaSquareCheck } from "react-icons/fa6";
-import { LuPlus } from "react-icons/lu";
-import { MdClose } from "react-icons/md";
+import { LuPlus, LuX } from "react-icons/lu";
import { RxMagnifyingGlass } from "react-icons/rx";
import { Badge, BadgeCloseButton } from "./Badge";
import { Button } from "./Button";
@@ -143,7 +142,7 @@ const CreatableMultiSelect = forwardRef<
<IconButton
variant="ghost"
aria-label="Clear"
- icon={<MdClose />}
+ icon={<LuX />}
onClick={() => onChange?.([])}
size={size === "sm" ? "md" : size}
/>
diff --git a/packages/react/src/Drawer.tsx b/packages/react/src/Drawer.tsx
index d2d09ae857..a497679d89 100644
--- a/packages/react/src/Drawer.tsx
+++ b/packages/react/src/Drawer.tsx
@@ -9,8 +9,7 @@ import type {
} from "react";
import { forwardRef } from "react";
-import { MdClose } from "react-icons/md";
-
+import { LuX } from "react-icons/lu";
import { ClientOnly } from "./ClientOnly";
import { cn } from "./utils/cn";
@@ -194,7 +193,7 @@ const DrawerContent = forwardRef<
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-full opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
- <MdClose className="h-6 w-6" />
+ <LuX className="h-6 w-6" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
diff --git a/packages/react/src/Form/FormControl.tsx b/packages/react/src/Form/FormControl.tsx
index c47ed683d5..1f708f512c 100644
--- a/packages/react/src/Form/FormControl.tsx
+++ b/packages/react/src/Form/FormControl.tsx
@@ -233,7 +233,7 @@ export const FormControl = forwardRef<HTMLDivElement, FormControlProps>(
<FormControlContext.Provider value={context}>
<div
{...getRootProps({}, ref)}
- className={cn("flex flex-col w-full space-y-2", props.className)}
+ className={cn("flex flex-col w-full gap-y-2", props.className)}
/>
</FormControlContext.Provider>
);
diff --git a/packages/react/src/Modal.tsx b/packages/react/src/Modal.tsx
index 2befca87bb..7c27c88cc6 100644
--- a/packages/react/src/Modal.tsx
+++ b/packages/react/src/Modal.tsx
@@ -9,8 +9,8 @@ import type {
HTMLAttributes,
} from "react";
import { forwardRef } from "react";
-import { MdClose } from "react-icons/md";
+import { LuX } from "react-icons/lu";
import { ClientOnly } from "./ClientOnly";
import { cn } from "./utils/cn";
@@ -42,7 +42,7 @@ ModalOverlay.displayName = DialogPrimitive.Overlay.displayName;
const ModalContentVariants = cva(
cn(
- "p-6",
+ "p-10",
"relative z-50 grid w-full gap-4 border shadow-md dark:shadow-sm duration-200",
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95",
@@ -84,8 +84,8 @@ const ModalContent = forwardRef<
{...props}
>
{children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-foreground-muted">
- <MdClose className="h-4 w-4" />
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-full opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-foreground-muted p-2 hover:bg-accent/80">
+ <LuX className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
@@ -102,7 +102,7 @@ const ModalHeader = ({
}: HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
- "flex flex-col space-y-1.5 text-center sm:text-left p-1 mb-2",
+ "flex flex-col space-y-1.5 text-center sm:text-left p-1 pt-0 mb-4",
className
)}
{...props}
diff --git a/packages/react/src/Select.tsx b/packages/react/src/Select.tsx
index 0e11fc34fd..6e6eeb6cb3 100644
--- a/packages/react/src/Select.tsx
+++ b/packages/react/src/Select.tsx
@@ -38,12 +38,14 @@ const selectTriggerVariants = cva(
interface SelectTriggerProps
extends ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>,
- VariantProps<typeof selectTriggerVariants> {}
+ VariantProps<typeof selectTriggerVariants> {
+ hideIcon?: boolean;
+}
const SelectTrigger = forwardRef<
ElementRef<typeof SelectPrimitive.Trigger>,
SelectTriggerProps
->(({ size, className, children, ...props }, ref) => (
+>(({ size, className, children, hideIcon, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
@@ -55,9 +57,11 @@ const SelectTrigger = forwardRef<
{...props}
>
{children}
- <SelectPrimitive.Icon asChild>
- <LuChevronsUpDown className="h-4 w-4 opacity-50" />
- </SelectPrimitive.Icon>
+ {!hideIcon && (
+ <SelectPrimitive.Icon asChild>
+ <LuChevronsUpDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ )}
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
diff --git a/packages/utils/src/themes.ts b/packages/utils/src/themes.ts
index 3f58e40eb3..b98d7d0e0a 100644
--- a/packages/utils/src/themes.ts
+++ b/packages/utils/src/themes.ts
@@ -277,7 +277,7 @@ export const themes = [
"destructive-foreground": "61 9.1% 97.8%",
border: "12 6.5% 15.1%",
input: "12 6.5% 15.1%",
- ring: "35.5 91.7% 32.9%",
+ ring: "61 91.7% 32.9%",
},
},
},