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: supplier status as enum

Brad Barbinfd6a63170f9d
diff --git a/apps/erp/app/components/Form/CustomerContact.tsx b/apps/erp/app/components/Form/CustomerContact.tsx
index cd2804fce0..ede6a766f6 100644
--- a/apps/erp/app/components/Form/CustomerContact.tsx
+++ b/apps/erp/app/components/Form/CustomerContact.tsx
@@ -57,6 +57,7 @@ const CustomerContact = (props: CustomerContactSelectProps) => {
ref={triggerRef}
options={options}
{...props}
+ placeholder="Select Contact"
inline={props.inline ? CustomerContactPreview : undefined}
label={props?.label ?? "Customer Contact"}
onChange={onChange}
diff --git a/apps/erp/app/components/Form/SupplierContact.tsx b/apps/erp/app/components/Form/SupplierContact.tsx
index 620ffcd93a..2f8d3b761e 100644
--- a/apps/erp/app/components/Form/SupplierContact.tsx
+++ b/apps/erp/app/components/Form/SupplierContact.tsx
@@ -79,6 +79,7 @@ const SupplierContact = (props: SupplierContactSelectProps) => {
ref={triggerRef}
options={options}
{...props}
+ placeholder="Select Contact"
inline={props.inline ? SupplierContactPreview : undefined}
label={props?.label ?? "Supplier Contact"}
onChange={onChange}
diff --git a/apps/erp/app/components/Form/SupplierStatus.tsx b/apps/erp/app/components/Form/SupplierStatus.tsx
index b2ee10dc04..97cb420cab 100644
--- a/apps/erp/app/components/Form/SupplierStatus.tsx
+++ b/apps/erp/app/components/Form/SupplierStatus.tsx
@@ -1,95 +1,25 @@
import type { ComboboxProps } from "@carbon/form";
-import { CreatableCombobox } from "@carbon/form";
-import { useDisclosure, useMount } from "@carbon/react";
-import { useMemo, useRef, useState } from "react";
-import { useFetcher } from "react-router";
-import { Enumerable } from "~/components/Enumerable";
-import { useRouteData } from "~/hooks";
-import type {
- getSupplierStatusesList,
- SupplierStatus as SupplierStatusStatus
-} from "~/modules/purchasing";
-import { SupplierStatusForm } from "~/modules/purchasing/ui/SupplierStatuses";
-
-import { path } from "~/utils/path";
+import { Combobox } from "@carbon/form";
+import { supplierStatusType } from "~/modules/purchasing";
+import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
type SupplierStatusSelectProps = Omit<ComboboxProps, "options">;
const SupplierStatus = (props: SupplierStatusSelectProps) => {
- const newSupplierStatusModal = useDisclosure();
- const [created, setCreated] = useState<string>("");
- const triggerRef = useRef<HTMLButtonElement>(null);
-
- const options = useSupplierStatuses();
+ const options = supplierStatusType.map((status) => ({
+ value: status,
+ label: <SupplierStatusIndicator status={status} />
+ }));
return (
- <>
- <CreatableCombobox
- ref={triggerRef}
- options={
- options.map((o) => ({
- value: o.value,
- label: <Enumerable value={o.label} />
- })) ?? []
- }
- {...props}
- label={props?.label ?? "SupplierStatus"}
- onCreateOption={(option) => {
- newSupplierStatusModal.onOpen();
- setCreated(option);
- }}
- />
- {newSupplierStatusModal.isOpen && (
- <SupplierStatusForm
- type="modal"
- onClose={() => {
- setCreated("");
- newSupplierStatusModal.onClose();
- triggerRef.current?.click();
- }}
- initialValues={{
- name: created
- }}
- />
- )}
- </>
+ <Combobox
+ options={options}
+ {...props}
+ label={props?.label ?? "Supplier Status"}
+ />
);
};
SupplierStatus.displayName = "SupplierStatus";
export default SupplierStatus;
-
-export const useSupplierStatuses = () => {
- const supplierStatusFetcher =
- useFetcher<Awaited<ReturnType<typeof getSupplierStatusesList>>>();
-
- const sharedSupplierData = useRouteData<{
- supplierStatuses: SupplierStatusStatus[];
- }>(path.to.supplierRoot);
-
- const hasSupplierData = sharedSupplierData?.supplierStatuses;
-
- useMount(() => {
- if (!hasSupplierData)
- supplierStatusFetcher.load(path.to.api.supplierStatuses);
- });
-
- const options = useMemo(() => {
- const dataSource =
- (hasSupplierData
- ? sharedSupplierData.supplierStatuses
- : supplierStatusFetcher.data?.data) ?? [];
-
- return dataSource.map((c) => ({
- value: c.id,
- label: c.name
- }));
- }, [
- supplierStatusFetcher.data?.data,
- hasSupplierData,
- sharedSupplierData?.supplierStatuses
- ]);
-
- return options;
-};
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.ts
index ae2efd8ef2..db1ba2ef94 100644
--- a/apps/erp/app/modules/purchasing/purchasing.models.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts
@@ -60,6 +60,21 @@ export const purchaseOrderStatusType = [
"Closed"
] as const;
+export const supplierStatusType = [
+ "Active",
+ "Inactive",
+ "Pending",
+ "Rejected"
+] as const;
+
+export const supplierQuoteStatusType = [
+ "Draft",
+ "Active",
+ "Expired",
+ "Declined",
+ "Cancelled"
+] as const;
+
export const externalSupplierQuoteValidator = z.object({
digitalSupplierQuoteSubmittedBy: zfd.text(
z.string().min(1, { message: "Name is required" })
@@ -284,7 +299,7 @@ export const selectedLinesValidator = z.record(z.string(), selectedLineSchema);
export const supplierValidator = z.object({
id: zfd.text(z.string().optional()),
name: z.string().min(1, { message: "Name is required" }),
- supplierStatusId: zfd.text(z.string().optional()),
+ supplierStatus: z.enum(supplierStatusType).optional().nullable(),
supplierTypeId: zfd.text(z.string().optional()),
accountManagerId: zfd.text(z.string().optional()),
currencyCode: zfd.text(z.string().optional()),
@@ -344,19 +359,6 @@ export const supplierTypeValidator = z.object({
name: z.string().min(1, { message: "Name is required" })
});
-export const supplierStatusValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Name is required" })
-});
-
-export const supplierQuoteStatusType = [
- "Draft",
- "Active",
- "Expired",
- "Declined",
- "Cancelled"
-] as const;
-
export const supplierQuoteValidator = z
.object({
id: zfd.text(z.string().optional()),
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index fe9dc313d0..a27dfed8b9 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -31,7 +31,6 @@ import type {
supplierQuoteStatusType,
supplierQuoteValidator,
supplierShippingValidator,
- supplierStatusValidator,
supplierTypeValidator,
supplierValidator
} from "./purchasing.models";
@@ -169,13 +168,6 @@ export async function deleteSupplierQuoteLine(
return client.from("supplierQuoteLine").delete().eq("id", id);
}
-export async function deleteSupplierStatus(
- client: SupabaseClient<Database>,
- supplierStatusId: string
-) {
- return client.from("supplierStatus").delete().eq("id", supplierStatusId);
-}
-
export async function deleteSupplierType(
client: SupabaseClient<Database>,
supplierTypeId: string
@@ -714,7 +706,7 @@ export async function getSuppliers(
}
if (args.status) {
- query = query.eq("supplierStatusId", args.status);
+ query = query.eq("status", args.status);
}
query = setGenericQueryFilters(query, args, [
@@ -735,51 +727,6 @@ export async function getSuppliersList(
);
}
-export async function getSupplierStatus(
- client: SupabaseClient<Database>,
- supplierStatusId: string
-) {
- return client
- .from("supplierStatus")
- .select("*")
- .eq("id", supplierStatusId)
- .single();
-}
-
-export async function getSupplierStatuses(
- client: SupabaseClient<Database>,
- companyId: string,
- args?: GenericQueryFilters & { search: string | null }
-) {
- let query = client
- .from("supplierStatus")
- .select("*", { count: "exact" })
- .eq("companyId", companyId);
-
- if (args?.search) {
- query = query.ilike("name", `%${args.search}%`);
- }
-
- if (args) {
- query = setGenericQueryFilters(query, args, [
- { column: "name", ascending: true }
- ]);
- }
-
- return query;
-}
-
-export async function getSupplierStatusesList(
- client: SupabaseClient<Database>,
- companyId: string
-) {
- return client
- .from("supplierStatus")
- .select("id, name")
- .eq("companyId", companyId)
- .order("name");
-}
-
export async function getSupplierType(
client: SupabaseClient<Database>,
supplierTypeId: string
@@ -1645,34 +1592,6 @@ export async function upsertSupplierQuoteLine(
.single();
}
-export async function upsertSupplierStatus(
- client: SupabaseClient<Database>,
- supplierStatus:
- | (Omit<z.infer<typeof supplierStatusValidator>, "id"> & {
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })
- | (Omit<z.infer<typeof supplierStatusValidator>, "id"> & {
- id: string;
- updatedBy: string;
- customFields?: Json;
- })
-) {
- if ("createdBy" in supplierStatus) {
- return client
- .from("supplierStatus")
- .insert([supplierStatus])
- .select("id")
- .single();
- } else {
- return client
- .from("supplierStatus")
- .update(sanitize(supplierStatus))
- .eq("id", supplierStatus.id);
- }
-}
-
export async function upsertSupplierType(
client: SupabaseClient<Database>,
supplierType:
diff --git a/apps/erp/app/modules/purchasing/types.ts b/apps/erp/app/modules/purchasing/types.ts
index a5c3443ca0..8f007eebc6 100644
--- a/apps/erp/app/modules/purchasing/types.ts
+++ b/apps/erp/app/modules/purchasing/types.ts
@@ -16,7 +16,6 @@ import type {
getSupplierQuoteLinePricesByQuoteId,
getSupplierQuoteLines,
getSupplierQuotes,
- getSupplierStatuses,
getSuppliers,
getSupplierTypes
} from "./purchasing.service";
@@ -102,10 +101,6 @@ export type SupplierQuoteLinePrice = NonNullable<
Awaited<ReturnType<typeof getSupplierQuoteLinePricesByQuoteId>>["data"]
>[number];
-export type SupplierStatus = NonNullable<
- Awaited<ReturnType<typeof getSupplierStatuses>>["data"]
->[number];
-
export type SupplierType = NonNullable<
Awaited<ReturnType<typeof getSupplierTypes>>["data"]
>[number];
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
index 28e76084d7..a6a2be6f19 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
@@ -101,7 +101,7 @@ const SupplierForm = ({
>
<Input autoFocus={!isEditing} name="name" label="Name" />
<SupplierStatus
- name="supplierStatusId"
+ name="supplierStatus"
label="Supplier Status"
placeholder="Select Supplier Status"
/>
@@ -111,10 +111,6 @@ const SupplierForm = ({
placeholder="Select Supplier Type"
/>
<Employee name="accountManagerId" label="Account Manager" />
- <Currency name="currencyCode" label="Currency" />
- <Input name="taxId" label="Tax ID" />
- <Input name="vatNumber" label="VAT Number" />
- <Input name="website" label="Website" />
{isEditing && (
<>
<SupplierContact
@@ -124,6 +120,11 @@ const SupplierForm = ({
/>
</>
)}
+ <Currency name="currencyCode" label="Currency" />
+ <Input name="taxId" label="Tax ID" />
+ <Input name="vatNumber" label="VAT Number" />
+ <Input name="website" label="Website" />
+
{/* <EmailRecipients name="defaultCc" label="Default CC" /> */}
<CustomFormFields table="supplier" />
</div>
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
index c41d5ed32d..15c9e454cf 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
@@ -30,7 +30,8 @@ import { Tags } from "~/components/Form";
import { useSupplierTypes } from "~/components/Form/SupplierType";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import type { SupplierDetail, SupplierStatus } from "~/modules/purchasing";
+import type { SupplierDetail } from "~/modules/purchasing";
+import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
import type { action } from "~/routes/x+/settings+/tags";
import { path } from "~/utils/path";
@@ -59,14 +60,6 @@ const SupplierHeader = () => {
(type) => type.value === routeData?.supplier?.supplierTypeId
)?.label;
- const sharedSupplierData = useRouteData<{
- supplierStatuses: SupplierStatus[];
- }>(path.to.supplierRoot);
-
- const supplierStatus = sharedSupplierData?.supplierStatuses?.find(
- (status) => status.id === routeData?.supplier?.supplierStatusId
- )?.name;
-
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
const onUpdateTags = useCallback(
(value: string[]) => {
@@ -126,8 +119,10 @@ const SupplierHeader = () => {
<CardAttribute>
<CardAttributeLabel>Status</CardAttributeLabel>
<CardAttributeValue>
- {supplierStatus ? (
- <Enumerable value={supplierStatus!} />
+ {routeData?.supplier?.status ? (
+ <SupplierStatusIndicator
+ status={routeData.supplier.status as "Active"}
+ />
) : (
"-"
)}
@@ -173,20 +168,6 @@ const SupplierHeader = () => {
</ValidatedForm>
</CardAttributeValue>
</CardAttribute>
-
- {/* {permissions.is("employee") && (
- <CardAttribute>
- <CardAttributeLabel>Assignee</CardAttributeLabel>
- <CardAttributeValue>
- <Assignee
- id={supplierId}
- table="supplier"
- value={assignee ?? ""}
- isReadOnly={!permissions.can("update", "purchasing")}
- />
- </CardAttributeValue>
- </CardAttribute>
- )} */}
</CardAttributes>
</CardContent>
</Card>
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierStatusIndicator.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierStatusIndicator.tsx
new file mode 100644
index 0000000000..402e1c38cb
--- /dev/null
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierStatusIndicator.tsx
@@ -0,0 +1,23 @@
+import { Status } from "@carbon/react";
+import type { supplierStatusType } from "~/modules/purchasing";
+
+type SupplierStatusIndicatorProps = {
+ status?: (typeof supplierStatusType)[number] | null;
+};
+
+const colorMap: Record<
+ (typeof supplierStatusType)[number],
+ "green" | "gray" | "orange" | "red"
+> = {
+ Active: "green",
+ Inactive: "gray",
+ Pending: "orange",
+ Rejected: "red"
+};
+
+const SupplierStatusIndicator = ({ status }: SupplierStatusIndicatorProps) => {
+ if (!status) return null;
+ return <Status color={colorMap[status]}>{status}</Status>;
+};
+
+export { SupplierStatusIndicator };
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
index 42cee06490..7172451614 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SuppliersTable.tsx
@@ -36,7 +36,9 @@ import { useSupplierTypes } from "~/components/Form/SupplierType";
import { ConfirmDelete } from "~/components/Modals";
import { usePermissions } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import type { Supplier, SupplierStatus } from "~/modules/purchasing";
+import type { Supplier } from "~/modules/purchasing";
+import { supplierStatusType } from "~/modules/purchasing";
+import { SupplierStatusIndicator } from "~/modules/purchasing/ui/Supplier/SupplierStatusIndicator";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
@@ -44,318 +46,287 @@ type SuppliersTableProps = {
data: Supplier[];
count: number;
tags: { name: string }[];
- supplierStatuses: SupplierStatus[];
};
-const SuppliersTable = memo(
- ({ data, count, tags, supplierStatuses }: SuppliersTableProps) => {
- const navigate = useNavigate();
- const permissions = usePermissions();
- const [people] = usePeople();
- const deleteModal = useDisclosure();
- const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(
- null
- );
- const supplierTypes = useSupplierTypes();
+const SuppliersTable = memo(({ data, count, tags }: SuppliersTableProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const [people] = usePeople();
+ const deleteModal = useDisclosure();
+ const [selectedSupplier, setSelectedSupplier] = useState<Supplier | null>(
+ null
+ );
+ const supplierTypes = useSupplierTypes();
- const customColumns = useCustomColumns<Supplier>("supplier");
- const columns = useMemo<ColumnDef<Supplier>[]>(() => {
- const defaultColumns: ColumnDef<Supplier>[] = [
- {
- accessorKey: "name",
- header: "Name",
- cell: ({ row }) => (
- <div className="max-w-[320px] truncate">
- <Hyperlink to={path.to.supplierDetails(row.original.id!)}>
- <SupplierAvatar supplierId={row.original.id!} />
- </Hyperlink>
- </div>
- ),
- meta: {
- icon: <LuBookMarked />
- }
- },
- {
- accessorKey: "status",
- header: "Supplier Status",
- cell: (item) => <Enumerable value={item.getValue<string>()} />,
- meta: {
- filter: {
- type: "static",
- options: supplierStatuses?.map((status) => ({
- value: status.name,
- label: <Enumerable value={status.name ?? ""} />
- }))
- },
- icon: <LuStar />
- }
- },
- {
- accessorKey: "supplierTypeId",
- header: "Type",
- cell: (item) => {
- if (!item.getValue<string>()) return null;
- const supplierType = supplierTypes?.find(
- (type) => type.value === item.getValue<string>()
- )?.label;
- return <Enumerable value={supplierType ?? ""} />;
+ const customColumns = useCustomColumns<Supplier>("supplier");
+ const columns = useMemo<ColumnDef<Supplier>[]>(() => {
+ const defaultColumns: ColumnDef<Supplier>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <div className="max-w-[320px] truncate">
+ <Hyperlink to={path.to.supplierDetails(row.original.id!)}>
+ <SupplierAvatar supplierId={row.original.id!} />
+ </Hyperlink>
+ </div>
+ ),
+ meta: {
+ icon: <LuBookMarked />
+ }
+ },
+ {
+ accessorKey: "status",
+ header: "Supplier Status",
+ cell: (item) => (
+ <SupplierStatusIndicator status={item.getValue<string>()} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: supplierStatusType.map((status) => ({
+ value: status,
+ label: <SupplierStatusIndicator status={status} />
+ }))
},
- meta: {
- icon: <LuShapes />,
- filter: {
- type: "static",
- options: supplierTypes?.map((type) => ({
- value: type.value,
- label: <Enumerable value={type.label} />
- }))
- }
- }
- },
- {
- id: "accountManagerId",
- header: "Account Manager",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.accountManagerId} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name
- }))
- },
- icon: <LuUser />
- }
- },
- {
- accessorKey: "tags",
- header: "Tags",
- cell: ({ row }) => (
- <HStack spacing={0} className="gap-1">
- {row.original.tags?.map((tag) => (
- <Badge key={tag} variant="secondary">
- {tag}
- </Badge>
- ))}
- </HStack>
- ),
- meta: {
- filter: {
- type: "static",
- options: tags?.map((tag) => ({
- value: tag.name,
- label: <Badge variant="secondary">{tag.name}</Badge>
- })),
- isArray: true
- },
- icon: <LuTag />
- }
- },
- // {
- // id: "assignee",
- // header: "Assignee",
- // cell: ({ row }) => (
- // <EmployeeAvatar employeeId={row.original.assignee} />
- // ),
- // meta: {
- // filter: {
- // type: "static",
- // options: people.map((employee) => ({
- // value: employee.id,
- // label: employee.name,
- // })),
- // },
- // },
- // },
- // {
- // id: "orders",
- // header: "Orders",
- // cell: ({ row }) => (
- // <Button variant="secondary" asChild>
- // <Link
- // to={`${path.to.purchaseOrders}?filter=supplierId:eq:${row.original.id}`}
- // >
- // {row.original.orderCount ?? 0} Orders
- // </Link>
- // </Button>
- // ),
- // },
-
- {
- accessorKey: "currencyCode",
- header: "Currency",
- cell: (item) => item.getValue(),
- meta: {
- icon: <LuEuro />
- }
- },
- {
- accessorKey: "phone",
- header: "Phone",
- cell: (item) => item.getValue(),
- meta: {
- icon: <LuPhone />
- }
- },
- {
- accessorKey: "fax",
- header: "Fax",
- cell: (item) => item.getValue(),
- meta: {
- icon: <LuPrinter />
- }
- },
- {
- accessorKey: "website",
- header: "Website",
- cell: (item) => item.getValue(),
- meta: {
- icon: <LuGlobe />
- }
- },
- {
- id: "createdBy",
- header: "Created By",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.createdBy} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name
- }))
- },
- icon: <LuUser />
- }
- },
- {
- accessorKey: "createdAt",
- header: "Created At",
- cell: (item) => formatDate(item.getValue<string>()),
- meta: {
- icon: <LuCalendar />
- }
- },
- {
- id: "updatedBy",
- header: "Updated By",
- cell: ({ row }) => (
- <EmployeeAvatar employeeId={row.original.updatedBy} />
- ),
- meta: {
- filter: {
- type: "static",
- options: people.map((employee) => ({
- value: employee.id,
- label: employee.name
- }))
- },
- icon: <LuUser />
- }
+ icon: <LuStar />
+ }
+ },
+ {
+ accessorKey: "supplierTypeId",
+ header: "Type",
+ cell: (item) => {
+ if (!item.getValue<string>()) return null;
+ const supplierType = supplierTypes?.find(
+ (type) => type.value === item.getValue<string>()
+ )?.label;
+ return <Enumerable value={supplierType ?? ""} />;
},
- {
- accessorKey: "updatedAt",
- header: "Updated At",
- cell: (item) => formatDate(item.getValue<string>()),
- meta: {
- icon: <LuCalendar />
+ meta: {
+ icon: <LuShapes />,
+ filter: {
+ type: "static",
+ options: supplierTypes?.map((type) => ({
+ value: type.value,
+ label: <Enumerable value={type.label} />
+ }))
}
}
- ];
-
- return [...defaultColumns, ...customColumns];
- }, [supplierStatuses, supplierTypes, people, tags, customColumns]);
+ },
+ {
+ id: "accountManagerId",
+ header: "Account Manager",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.accountManagerId} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ },
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "tags",
+ header: "Tags",
+ cell: ({ row }) => (
+ <HStack spacing={0} className="gap-1">
+ {row.original.tags?.map((tag) => (
+ <Badge key={tag} variant="secondary">
+ {tag}
+ </Badge>
+ ))}
+ </HStack>
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: tags?.map((tag) => ({
+ value: tag.name,
+ label: <Badge variant="secondary">{tag.name}</Badge>
+ })),
+ isArray: true
+ },
+ icon: <LuTag />
+ }
+ },
+ {
+ accessorKey: "currencyCode",
+ header: "Currency",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuEuro />
+ }
+ },
+ {
+ accessorKey: "phone",
+ header: "Phone",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuPhone />
+ }
+ },
+ {
+ accessorKey: "fax",
+ header: "Fax",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuPrinter />
+ }
+ },
+ {
+ accessorKey: "website",
+ header: "Website",
+ cell: (item) => item.getValue(),
+ meta: {
+ icon: <LuGlobe />
+ }
+ },
+ {
+ id: "createdBy",
+ header: "Created By",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ },
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />
+ }
+ },
+ {
+ id: "updatedBy",
+ header: "Updated By",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.updatedBy} />
+ ),
+ meta: {
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name
+ }))
+ },
+ icon: <LuUser />
+ }
+ },
+ {
+ accessorKey: "updatedAt",
+ header: "Updated At",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />
+ }
+ }
+ ];
- const renderContextMenu = useMemo(
- () => (row: Supplier) => (
- <>
- <MenuItem onClick={() => navigate(path.to.supplier(row.id!))}>
- <MenuIcon icon={<LuPencil />} />
- Edit Supplier
- </MenuItem>
- <MenuItem
- destructive
- disabled={!permissions.can("delete", "purchasing")}
- onClick={() => {
- setSelectedSupplier(row);
- deleteModal.onOpen();
- }}
- >
- <MenuIcon icon={<LuTrash />} />
- Delete Supplier
- </MenuItem>
- </>
- ),
- [navigate, deleteModal, permissions]
- );
+ return [...defaultColumns, ...customColumns];
+ }, [supplierTypes, people, tags, customColumns]);
- return (
+ const renderContextMenu = useMemo(
+ () => (row: Supplier) => (
<>
- <Table<Supplier>
- count={count}
- columns={columns}
- data={data}
- defaultColumnPinning={{
- left: ["name"]
+ <MenuItem onClick={() => navigate(path.to.supplier(row.id!))}>
+ <MenuIcon icon={<LuPencil />} />
+ Edit Supplier
+ </MenuItem>
+ <MenuItem
+ destructive
+ disabled={!permissions.can("delete", "purchasing")}
+ onClick={() => {
+ setSelectedSupplier(row);
+ deleteModal.onOpen();
}}
- defaultColumnVisibility={{
- currencyCode: false,
- phone: false,
- fax: false,
- website: false,
- createdBy: false,
- createdAt: false,
- updatedBy: false,
- updatedAt: false
- }}
- importCSV={[
- {
- table: "supplier",
- label: "Suppliers"
- },
- {
- table: "supplierContact",
- label: "Contacts"
- }
- ]}
- primaryAction={
- permissions.can("create", "purchasing") && (
- <div className="flex items-center gap-2">
- <Button variant="secondary" leftIcon={<LuShapes />} asChild>
- <Link to={path.to.supplierTypes}>Supplier Types</Link>
- </Button>
- <New label="Supplier" to={path.to.newSupplier} />
- </div>
- )
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Supplier
+ </MenuItem>
+ </>
+ ),
+ [navigate, deleteModal, permissions]
+ );
+
+ return (
+ <>
+ <Table<Supplier>
+ count={count}
+ columns={columns}
+ data={data}
+ defaultColumnPinning={{
+ left: ["name"]
+ }}
+ defaultColumnVisibility={{
+ currencyCode: false,
+ phone: false,
+ fax: false,
+ website: false,
+ createdBy: false,
+ createdAt: false,
+ updatedBy: false,
+ updatedAt: false
+ }}
+ importCSV={[
+ {
+ table: "supplier",
+ label: "Suppliers"
+ },
+ {
+ table: "supplierContact",
+ label: "Contacts"
}
- renderContextMenu={renderContextMenu}
- title="Suppliers"
- table="supplier"
- withSavedView
+ ]}
+ primaryAction={
+ permissions.can("create", "purchasing") && (
+ <div className="flex items-center gap-2">
+ <Button variant="secondary" leftIcon={<LuShapes />} asChild>
+ <Link to={path.to.supplierTypes}>Supplier Types</Link>
+ </Button>
+ <New label="Supplier" to={path.to.newSupplier} />
+ </div>
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Suppliers"
+ table="supplier"
+ withSavedView
+ />
+ {selectedSupplier && selectedSupplier.id && (
+ <ConfirmDelete
+ action={path.to.deleteSupplier(selectedSupplier.id)}
+ isOpen={deleteModal.isOpen}
+ name={selectedSupplier.name!}
+ text={`Are you sure you want to delete ${selectedSupplier.name!}? This cannot be undone.`}
+ onCancel={() => {
+ deleteModal.onClose();
+ setSelectedSupplier(null);
+ }}
+ onSubmit={() => {
+ deleteModal.onClose();
+ setSelectedSupplier(null);
+ }}
/>
- {selectedSupplier && selectedSupplier.id && (
- <ConfirmDelete
- action={path.to.deleteSupplier(selectedSupplier.id)}
- isOpen={deleteModal.isOpen}
- name={selectedSupplier.name!}
- text={`Are you sure you want to delete ${selectedSupplier.name!}? This cannot be undone.`}
- onCancel={() => {
- deleteModal.onClose();
- setSelectedSupplier(null);
- }}
- onSubmit={() => {
- deleteModal.onClose();
- setSelectedSupplier(null);
- }}
- />
- )}
- </>
- );
- }
-);
+ )}
+ </>
+ );
+});
SuppliersTable.displayName = "SupplierTable";
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusForm.tsx b/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusForm.tsx
deleted file mode 100644
index 6d375bc61c..0000000000
--- a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusForm.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-import { ValidatedForm } from "@carbon/form";
-import {
- Button,
- HStack,
- ModalDrawer,
- ModalDrawerBody,
- ModalDrawerContent,
- ModalDrawerFooter,
- ModalDrawerHeader,
- ModalDrawerProvider,
- ModalDrawerTitle,
- toast,
- VStack
-} from "@carbon/react";
-import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
-import { useFetcher } from "react-router";
-import type { z } from "zod";
-import { CustomFormFields, Hidden, Input, Submit } from "~/components/Form";
-import { usePermissions } from "~/hooks";
-import { supplierStatusValidator } from "~/modules/purchasing";
-import { path } from "~/utils/path";
-
-type SupplierStatusFormProps = {
- initialValues: z.infer<typeof supplierStatusValidator>;
- type?: "modal" | "drawer";
- open?: boolean;
- onClose: () => void;
-};
-
-const SupplierStatusForm = ({
- initialValues,
- open = true,
- type = "drawer",
- onClose
-}: SupplierStatusFormProps) => {
- const permissions = usePermissions();
- const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
-
- useEffect(() => {
- if (type !== "modal") return;
-
- if (fetcher.state === "loading" && fetcher.data?.data) {
- onClose?.();
- toast.success(`Created supplier status`);
- } else if (fetcher.state === "idle" && fetcher.data?.error) {
- toast.error(
- `Failed to create supplier status: ${fetcher.data.error.message}`
- );
- }
- }, [fetcher.data, fetcher.state, onClose, type]);
-
- const isEditing = initialValues.id !== undefined;
- const isDisabled = isEditing
- ? !permissions.can("update", "purchasing")
- : !permissions.can("create", "purchasing");
-
- return (
- <ModalDrawerProvider type={type}>
- <ModalDrawer
- open={open}
- onOpenChange={(open) => {
- if (!open) onClose?.();
- }}
- >
- <ModalDrawerContent>
- <ValidatedForm
- validator={supplierStatusValidator}
- method="post"
- action={
- isEditing
- ? path.to.supplierStatus(initialValues.id!)
- : path.to.newSupplierStatus
- }
- defaultValues={initialValues}
- fetcher={fetcher}
- className="flex flex-col h-full"
- >
- <ModalDrawerHeader>
- <ModalDrawerTitle>
- {isEditing ? "Edit" : "New"} Supplier Status
- </ModalDrawerTitle>
- </ModalDrawerHeader>
- <ModalDrawerBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <VStack spacing={4}>
- <Input name="name" label="Supplier Status" />
- <CustomFormFields table="supplierStatus" />
- </VStack>
- </ModalDrawerBody>
- <ModalDrawerFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- <Button size="md" variant="solid" onClick={() => onClose()}>
- Cancel
- </Button>
- </HStack>
- </ModalDrawerFooter>
- </ValidatedForm>
- </ModalDrawerContent>
- </ModalDrawer>
- </ModalDrawerProvider>
- );
-};
-
-export default SupplierStatusForm;
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx b/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx
deleted file mode 100644
index 81636ccd58..0000000000
--- a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/SupplierStatusesTable.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { MenuIcon, MenuItem } from "@carbon/react";
-import type { ColumnDef } from "@tanstack/react-table";
-import { memo, useCallback, useMemo } from "react";
-import { BsPeopleFill } from "react-icons/bs";
-import { LuPencil, LuStar, LuTrash } from "react-icons/lu";
-import { useNavigate } from "react-router";
-import { Hyperlink, New, Table } from "~/components";
-import { Enumerable } from "~/components/Enumerable";
-import { usePermissions, useUrlParams } from "~/hooks";
-import { useCustomColumns } from "~/hooks/useCustomColumns";
-import type { SupplierStatus } from "~/modules/purchasing";
-import { path } from "~/utils/path";
-
-type SupplierStatusesTableProps = {
- data: SupplierStatus[];
- count: number;
-};
-
-const SupplierStatusesTable = memo(
- ({ data, count }: SupplierStatusesTableProps) => {
- const [params] = useUrlParams();
- const navigate = useNavigate();
- const permissions = usePermissions();
-
- const customColumns = useCustomColumns<SupplierStatus>("supplierStatus");
- const columns = useMemo<ColumnDef<SupplierStatus>[]>(() => {
- const defaultColumns: ColumnDef<SupplierStatus>[] = [
- {
- accessorKey: "name",
- header: "Supplier Status",
- cell: ({ row }) => (
- <Hyperlink to={`${row.original.id}?${params.toString()}`}>
- <Enumerable value={row.original.name} />
- </Hyperlink>
- ),
- meta: {
- icon: <LuStar />
- }
- }
- ];
- return [...defaultColumns, ...customColumns];
- }, [params, customColumns]);
-
- const renderContextMenu = useCallback(
- (row: SupplierStatus) => {
- return (
- <>
- <MenuItem
- onClick={() => {
- navigate(`${path.to.suppliers}?filter=status:eq:${row.name}`);
- }}
- >
- <MenuIcon icon={<BsPeopleFill />} />
- View Suppliers
- </MenuItem>
- <MenuItem
- onClick={() => {
- navigate(
- `${path.to.supplierStatus(row.id)}?${params.toString()}`
- );
- }}
- >
- <MenuIcon icon={<LuPencil />} />
- Edit Supplier Status
- </MenuItem>
- <MenuItem
- destructive
- disabled={!permissions.can("delete", "purchasing")}
- onClick={() => {
- navigate(
- `${path.to.deleteSupplierStatus(row.id)}?${params.toString()}`
- );
- }}
- >
- <MenuIcon icon={<LuTrash />} />
- Delete Supplier Status
- </MenuItem>
- </>
- );
- },
- [navigate, params, permissions]
- );
-
- return (
- <Table<SupplierStatus>
- data={data}
- columns={columns}
- count={count}
- primaryAction={
- permissions.can("create", "purchasing") && (
- <New
- label="Supplier Status"
- to={`${path.to.newSupplierStatus}?${params.toString()}`}
- />
- )
- }
- renderContextMenu={renderContextMenu}
- title="Supplier Statuses"
- />
- );
- }
-);
-
-SupplierStatusesTable.displayName = "SupplierStatusesTable";
-export default SupplierStatusesTable;
diff --git a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/index.ts b/apps/erp/app/modules/purchasing/ui/SupplierStatuses/index.ts
deleted file mode 100644
index 568766c31f..0000000000
--- a/apps/erp/app/modules/purchasing/ui/SupplierStatuses/index.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-import SupplierStatusesTable from "./SupplierStatusesTable";
-import SupplierStatusForm from "./SupplierStatusForm";
-
-export { SupplierStatusForm, SupplierStatusesTable };
diff --git a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
index 3429d12345..0f64328a09 100644
--- a/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
+++ b/apps/erp/app/modules/purchasing/ui/usePurchasingSubmodules.tsx
@@ -4,7 +4,6 @@ import {
LuFileText,
LuLayoutList,
LuPackageSearch,
- LuShapes,
LuSquareChartGantt,
LuStar
} from "react-icons/lu";
@@ -64,12 +63,6 @@ const purchasingRoutes: AuthenticatedRouteGroup[] = [
{
name: "Configure",
routes: [
- {
- name: "Statuses",
- to: path.to.supplierStatuses,
- role: "employee",
- icon: <LuShapes />
- },
{
name: "Types",
to: path.to.supplierTypes,
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
index 8d3cf4eccf..dfc8d2af94 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerForm.tsx
@@ -114,7 +114,15 @@ const CustomerForm = ({
placeholder="Select Customer Type"
/>
<Employee name="accountManagerId" label="Account Manager" />
-
+ {isEditing && (
+ <>
+ <CustomerContact
+ customer={initialValues.id}
+ name="salesContactId"
+ label="Sales Contact"
+ />
+ </>
+ )}
<Currency name="currencyCode" label="Currency" />
<Number
@@ -134,15 +142,6 @@ const CustomerForm = ({
<Input name="vatNumber" label="VAT Number" />
<Input name="website" label="Website" />
- {isEditing && (
- <>
- <CustomerContact
- customer={initialValues.id}
- name="salesContactId"
- label="Sales Contact"
- />
- </>
- )}
{/* <EmailRecipients name="defaultCc" label="Default CC" /> */}
<CustomFormFields table="customer" />
</div>
diff --git a/apps/erp/app/routes/api+/purchasing.supplier-statuses.ts b/apps/erp/app/routes/api+/purchasing.supplier-statuses.ts
deleted file mode 100644
index 6036a0e993..0000000000
--- a/apps/erp/app/routes/api+/purchasing.supplier-statuses.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { requirePermissions } from "@carbon/auth/auth.server";
-import type { LoaderFunctionArgs } from "react-router";
-import { getSupplierStatusesList } from "~/modules/purchasing";
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "purchasing"
- });
-
- return await getSupplierStatusesList(client, companyId);
-}
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.$supplierStatusId.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-statuses.$supplierStatusId.tsx
deleted file mode 100644
index 886b5168d8..0000000000
--- a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.$supplierStatusId.tsx
+++ /dev/null
@@ -1,100 +0,0 @@
-import { assertIsPost, error, notFound, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, redirect, useLoaderData, useNavigate } from "react-router";
-import {
- getSupplierStatus,
- supplierStatusValidator,
- upsertSupplierStatus
-} from "~/modules/purchasing";
-import { SupplierStatusForm } from "~/modules/purchasing/ui/SupplierStatuses";
-import { getCustomFields, setCustomFields } from "~/utils/form";
-import { getParams, path } from "~/utils/path";
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "purchasing",
- role: "employee"
- });
-
- const { supplierStatusId } = params;
- if (!supplierStatusId) throw notFound("supplierStatusId not found");
-
- const supplierStatus = await getSupplierStatus(client, supplierStatusId);
-
- if (supplierStatus.error) {
- throw redirect(
- path.to.supplierStatuses,
- await flash(
- request,
- error(supplierStatus.error, "Failed to get supplier status")
- )
- );
- }
-
- return {
- supplierStatus: supplierStatus.data
- };
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- update: "purchasing"
- });
-
- const formData = await request.formData();
- const validation = await validator(supplierStatusValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const { id, ...d } = validation.data;
- if (!id) throw new Error("id not found");
-
- const updateSupplierStatus = await upsertSupplierStatus(client, {
- id,
- ...d,
- updatedBy: userId,
- customFields: setCustomFields(formData)
- });
-
- if (updateSupplierStatus.error) {
- return data(
- {},
- await flash(
- request,
- error(updateSupplierStatus.error, "Failed to update supplier status")
- )
- );
- }
-
- throw redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(request, success("Updated supplier status"))
- );
-}
-
-export default function EditSupplierStatusesRoute() {
- const { supplierStatus } = useLoaderData<typeof loader>();
- const navigate = useNavigate();
-
- const initialValues = {
- id: supplierStatus.id ?? undefined,
- name: supplierStatus.name ?? "",
- ...getCustomFields(supplierStatus.customFields)
- };
-
- return (
- <SupplierStatusForm
- key={initialValues.id}
- initialValues={initialValues}
- onClose={() => navigate(-1)}
- />
- );
-}
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.delete.$supplierStatusId.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-statuses.delete.$supplierStatusId.tsx
deleted file mode 100644
index b0652d6016..0000000000
--- a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.delete.$supplierStatusId.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { error, notFound, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { redirect, useLoaderData, useNavigate, useParams } from "react-router";
-import { ConfirmDelete } from "~/components/Modals";
-import { deleteSupplierStatus, getSupplierStatus } from "~/modules/purchasing";
-import { getParams, path } from "~/utils/path";
-
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "purchasing",
- role: "employee"
- });
- const { supplierStatusId } = params;
- if (!supplierStatusId) throw notFound("supplierStatusId not found");
-
- const supplierStatus = await getSupplierStatus(client, supplierStatusId);
- if (supplierStatus.error) {
- throw redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(
- request,
- error(supplierStatus.error, "Failed to get supplier status")
- )
- );
- }
-
- return { supplierStatus: supplierStatus.data };
-}
-
-export async function action({ request, params }: ActionFunctionArgs) {
- const { client } = await requirePermissions(request, {
- delete: "purchasing"
- });
-
- const { supplierStatusId } = params;
- if (!supplierStatusId) {
- throw redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(request, error(params, "Failed to get an supplier status id"))
- );
- }
-
- const { error: deleteStatusError } = await deleteSupplierStatus(
- client,
- supplierStatusId
- );
- if (deleteStatusError) {
- throw redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(
- request,
- error(deleteStatusError, "Failed to delete supplier status")
- )
- );
- }
-
- throw redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(request, success("Successfully deleted supplier status"))
- );
-}
-
-export default function DeleteSupplierStatusRoute() {
- const { supplierStatusId } = useParams();
- const { supplierStatus } = useLoaderData<typeof loader>();
- const navigate = useNavigate();
-
- if (!supplierStatus) return null;
- if (!supplierStatusId) throw notFound("supplierStatusId not found");
-
- const onCancel = () => navigate(path.to.supplierStatuses);
- return (
- <ConfirmDelete
- action={path.to.deleteSupplierStatus(supplierStatusId)}
- name={supplierStatus.name}
- text={`Are you sure you want to delete the supplier status: ${supplierStatus.name}? This cannot be undone.`}
- onCancel={onCancel}
- />
- );
-}
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.new.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-statuses.new.tsx
deleted file mode 100644
index 0e99adb7c9..0000000000
--- a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.new.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-import { assertIsPost, error, success } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import { validationError, validator } from "@carbon/form";
-import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, redirect, useNavigate } from "react-router";
-import {
- supplierStatusValidator,
- upsertSupplierStatus
-} from "~/modules/purchasing";
-import { SupplierStatusForm } from "~/modules/purchasing/ui/SupplierStatuses";
-import { setCustomFields } from "~/utils/form";
-import { getParams, path } from "~/utils/path";
-
-export async function loader({ request }: LoaderFunctionArgs) {
- await requirePermissions(request, {
- create: "purchasing"
- });
-
- return null;
-}
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "purchasing"
- });
-
- const formData = await request.formData();
- const modal = formData.get("type") === "modal";
-
- const validation = await validator(supplierStatusValidator).validate(
- formData
- );
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
- const { id, ...d } = validation.data;
-
- const insertSupplierStatus = await upsertSupplierStatus(client, {
- ...d,
- companyId,
- createdBy: userId,
- customFields: setCustomFields(formData)
- });
- if (insertSupplierStatus.error) {
- return modal
- ? insertSupplierStatus
- : redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(
- request,
- error(
- insertSupplierStatus.error,
- "Failed to insert supplier status"
- )
- )
- );
- }
-
- return modal
- ? data(insertSupplierStatus, { status: 201 })
- : redirect(
- `${path.to.supplierStatuses}?${getParams(request)}`,
- await flash(request, success("Supplier status created"))
- );
-}
-
-export default function NewSupplierStatusesRoute() {
- const navigate = useNavigate();
- const initialValues = {
- name: ""
- };
-
- return (
- <SupplierStatusForm
- initialValues={initialValues}
- onClose={() => navigate(-1)}
- />
- );
-}
diff --git a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.tsx b/apps/erp/app/routes/x+/purchasing+/supplier-statuses.tsx
deleted file mode 100644
index f682947c0b..0000000000
--- a/apps/erp/app/routes/x+/purchasing+/supplier-statuses.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { VStack } from "@carbon/react";
-import type { LoaderFunctionArgs } from "react-router";
-import { Outlet, useLoaderData } from "react-router";
-import { getSupplierStatuses } from "~/modules/purchasing";
-import { SupplierStatusesTable } from "~/modules/purchasing/ui/SupplierStatuses";
-import type { Handle } from "~/utils/handle";
-import { path } from "~/utils/path";
-import { getGenericQueryFilters } from "~/utils/query";
-
-export const handle: Handle = {
- breadcrumb: "Supplier Statuses",
- to: path.to.supplierStatuses
-};
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "purchasing",
- role: "employee"
- });
-
- const url = new URL(request.url);
- const searchParams = new URLSearchParams(url.search);
- const search = searchParams.get("search");
- const { limit, offset, sorts, filters } =
- getGenericQueryFilters(searchParams);
-
- return await getSupplierStatuses(client, companyId, {
- search,
- limit,
- offset,
- sorts,
- filters
- });
-}
-
-export default function SupplierStatusesRoute() {
- const { data, count } = useLoaderData<typeof loader>();
-
- return (
- <VStack spacing={0} className="h-full">
- <SupplierStatusesTable data={data ?? []} count={count ?? 0} />
- <Outlet />
- </VStack>
- );
-}
diff --git a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
index 85ae7fc446..73aac14ccb 100644
--- a/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/suppliers.tsx
@@ -4,7 +4,7 @@ import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData } from "react-router";
-import { getSupplierStatuses, getSuppliers } from "~/modules/purchasing";
+import { getSuppliers } from "~/modules/purchasing";
import { SuppliersTable } from "~/modules/purchasing/ui/Supplier";
import { getTagsList } from "~/modules/shared";
import type { Handle } from "~/utils/handle";
@@ -31,7 +31,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { limit, offset, sorts, filters } =
getGenericQueryFilters(searchParams);
- const [suppliers, supplierStatuses, tags] = await Promise.all([
+ const [suppliers, tags] = await Promise.all([
getSuppliers(client, companyId, {
search,
type,
@@ -41,7 +41,6 @@ export async function loader({ request }: LoaderFunctionArgs) {
sorts,
filters
}),
- getSupplierStatuses(client, companyId),
getTagsList(client, companyId, "supplier")
]);
@@ -55,23 +54,16 @@ export async function loader({ request }: LoaderFunctionArgs) {
return {
count: suppliers.count ?? 0,
suppliers: suppliers.data ?? [],
- supplierStatuses: supplierStatuses.data ?? [],
tags: tags.data ?? []
};
}
export default function PurchasingSuppliersRoute() {
- const { count, suppliers, supplierStatuses, tags } =
- useLoaderData<typeof loader>();
+ const { count, suppliers, tags } = useLoaderData<typeof loader>();
return (
<VStack spacing={0} className="h-full">
- <SuppliersTable
- data={suppliers}
- count={count}
- supplierStatuses={supplierStatuses}
- tags={tags}
- />
+ <SuppliersTable data={suppliers} count={count} tags={tags} />
<Outlet />
</VStack>
);
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
index 2b13c7bd15..84400eeb24 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.details.tsx
@@ -62,7 +62,7 @@ export default function SupplierEditRoute() {
id: routeData?.supplier?.id ?? undefined,
name: routeData?.supplier?.name ?? "",
supplierTypeId: routeData?.supplier?.supplierTypeId ?? undefined,
- supplierStatusId: routeData?.supplier?.supplierStatusId ?? undefined,
+ supplierStatus: routeData?.supplier?.status as "Active",
accountManagerId: routeData?.supplier?.accountManagerId ?? undefined,
taxId: routeData?.supplier?.taxId ?? "",
vatNumber: routeData?.supplier?.vatNumber ?? "",
diff --git a/apps/erp/app/routes/x+/supplier+/_layout.tsx b/apps/erp/app/routes/x+/supplier+/_layout.tsx
index c91411cda9..8c91c7e2c7 100644
--- a/apps/erp/app/routes/x+/supplier+/_layout.tsx
+++ b/apps/erp/app/routes/x+/supplier+/_layout.tsx
@@ -3,7 +3,7 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs, MetaFunction } from "react-router";
import { Outlet } from "react-router";
import { getShippingTermsList } from "~/modules/inventory";
-import { getSupplierStatuses, getSupplierTypes } from "~/modules/purchasing";
+import { getSupplierTypes } from "~/modules/purchasing";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -23,17 +23,14 @@ export async function loader({ request }: LoaderFunctionArgs) {
});
const [
- supplierTypes,
- supplierStatuses
+ supplierTypes
// shippingTerms,
] = await Promise.all([
getSupplierTypes(client, companyId),
- getSupplierStatuses(client, companyId),
getShippingTermsList(client, companyId)
]);
return {
- supplierStatuses: supplierStatuses.data ?? [],
supplierTypes: supplierTypes.data ?? []
// shippingTerms: shippingTerms.data ?? [],
};
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 392a35827f..4a593efdf4 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -177,7 +177,6 @@ export const path = {
generatePath(`${api}/purchasing/supplier-locations/${id}`),
supplierProcesses: (id?: string) =>
generatePath(`${api}/purchasing/supplier-processes/${id}`),
- supplierStatuses: `${api}/purchasing/supplier-statuses`,
supplierTypes: `${api}/purchasing/supplier-types`,
tags: (table?: string) =>
generatePath(`${api}/shared/tags?table=${table}`),
@@ -744,8 +743,6 @@ export const path = {
generatePath(`${x}/supplier-quote/${id}/delete`),
deleteSupplierQuoteLine: (id: string, lineId: string) =>
generatePath(`${x}/supplier-quote/${id}/${lineId}/delete`),
- deleteSupplierStatus: (id: string) =>
- generatePath(`${x}/purchasing/supplier-statuses/delete/${id}`),
deleteSupplierType: (id: string) =>
generatePath(`${x}/purchasing/supplier-types/delete/${id}`),
deleteSuggestion: (id: string) =>
@@ -1149,7 +1146,6 @@ export const path = {
newSupplierQuote: `${x}/supplier-quote/new`,
newSupplierQuoteLine: (id: string) =>
generatePath(`${x}/supplier-quote/${id}/new`),
- newSupplierStatus: `${x}/purchasing/supplier-statuses/new`,
newSupplierType: `${x}/purchasing/supplier-types/new`,
newTag: `${x}/settings/tags/new`,
newTool: `${x}/tool/new`,
@@ -1550,9 +1546,6 @@ export const path = {
supplierQuoteStatus: (id: string) =>
generatePath(`${x}/supplier-quote/${id}/status`),
supplierRoot: `${x}/supplier`,
- supplierStatus: (id: string) =>
- generatePath(`${x}/purchasing/supplier-statuses/${id}`),
- supplierStatuses: `${x}/purchasing/supplier-statuses`,
supplierType: (id: string) =>
generatePath(`${x}/purchasing/supplier-types/${id}`),
supplierTypes: `${x}/purchasing/supplier-types`,
diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.ts
index a4f9c09e77..e87308913b 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -31,7 +31,6 @@ import {
postingGroupSales,
scrapReasons,
sequences,
- supplierStatuses,
unitOfMeasures
} from "../supabase/functions/lib/seed.data.ts";
import { getPostgresConnectionPool } from "./client.ts";
@@ -257,14 +256,6 @@ async function seedDev() {
[userId, employeeTypeId, companyId]
);
- // Seed supplier statuses
- for (const name of supplierStatuses) {
- await client.query(
- `INSERT INTO "supplierStatus" (name, "companyId", "createdBy") VALUES ($1, $2, 'system')`,
- [name, companyId]
- );
- }
-
// Seed customer statuses
for (const name of customerStatuses) {
await client.query(
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 7cdf93cec8..1c8747d4cf 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -33308,6 +33308,48 @@ export type Database = {
},
]
}
+ searchIndex_WzwEWaV48VbxPNogD92qWD: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -35594,7 +35636,9 @@ export type Database = {
name: string
phone: string | null
purchasingContactId: string | null
- supplierStatusId: string | null
+ supplierStatus:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId: string | null
tags: string[] | null
taxId: string | null
@@ -35620,7 +35664,9 @@ export type Database = {
name: string
phone?: string | null
purchasingContactId?: string | null
- supplierStatusId?: string | null
+ supplierStatus?:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId?: string | null
tags?: string[] | null
taxId?: string | null
@@ -35646,7 +35692,9 @@ export type Database = {
name?: string
phone?: string | null
purchasingContactId?: string | null
- supplierStatusId?: string | null
+ supplierStatus?:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId?: string | null
tags?: string[] | null
taxId?: string | null
@@ -35804,13 +35852,6 @@ export type Database = {
referencedRelation: "supplierContact"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "supplier_supplierStatusId_fkey"
- columns: ["supplierStatusId"]
- isOneToOne: false
- referencedRelation: "supplierStatus"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "supplier_supplierTypeId_fkey"
columns: ["supplierTypeId"]
@@ -38076,141 +38117,6 @@ export type Database = {
},
]
}
- supplierStatus: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- customFields: Json | null
- id: string
- name: string
- tags: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- customFields?: Json | null
- id?: string
- name: string
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- customFields?: Json | null
- id?: string
- name?: string
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
supplierType: {
Row: {
companyId: string
@@ -49235,14 +49141,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55146,7 +55052,6 @@ export type Database = {
phone: string | null
purchasingContactId: string | null
status: string | null
- supplierStatusId: string | null
supplierTypeId: string | null
tags: string[] | null
taxId: string | null
@@ -55305,13 +55210,6 @@ export type Database = {
referencedRelation: "supplierContact"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "supplier_supplierStatusId_fkey"
- columns: ["supplierStatusId"]
- isOneToOne: false
- referencedRelation: "supplierStatus"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "supplier_supplierTypeId_fkey"
columns: ["supplierTypeId"]
@@ -58110,6 +58008,7 @@ export type Database = {
| "Draft"
| "Declined"
| "Cancelled"
+ supplierStatusType: "Active" | "Inactive" | "Pending" | "Rejected"
supplySourceType: "Purchase Order" | "Production Order"
tableViewType: "Public" | "Private"
trackedEntityStatus: "Available" | "Reserved" | "On Hold" | "Consumed"
@@ -59267,6 +59166,7 @@ export const Constants = {
"Declined",
"Cancelled",
],
+ supplierStatusType: ["Active", "Inactive", "Pending", "Rejected"],
supplySourceType: ["Purchase Order", "Production Order"],
tableViewType: ["Public", "Private"],
trackedEntityStatus: ["Available", "Reserved", "On Hold", "Consumed"],
diff --git a/packages/database/supabase/functions/lib/seed.ts b/packages/database/supabase/functions/lib/seed.ts
index 2fc2b1a4fb..fd271ccc56 100644
--- a/packages/database/supabase/functions/lib/seed.ts
+++ b/packages/database/supabase/functions/lib/seed.ts
@@ -21,7 +21,6 @@ export {
scrapReasons,
sequences,
unitOfMeasures,
- supplierStatuses as supplierStauses,
} from "./seed.data.ts";
import { groups as _groups } from "./seed.data.ts";
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 7cdf93cec8..1c8747d4cf 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -33308,6 +33308,48 @@ export type Database = {
},
]
}
+ searchIndex_WzwEWaV48VbxPNogD92qWD: {
+ Row: {
+ createdAt: string
+ description: string | null
+ entityId: string
+ entityType: string
+ id: number
+ link: string
+ metadata: Json | null
+ searchVector: unknown
+ tags: string[] | null
+ title: string
+ updatedAt: string | null
+ }
+ Insert: {
+ createdAt?: string
+ description?: string | null
+ entityId: string
+ entityType: string
+ id?: number
+ link: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title: string
+ updatedAt?: string | null
+ }
+ Update: {
+ createdAt?: string
+ description?: string | null
+ entityId?: string
+ entityType?: string
+ id?: number
+ link?: string
+ metadata?: Json | null
+ searchVector?: unknown
+ tags?: string[] | null
+ title?: string
+ updatedAt?: string | null
+ }
+ Relationships: []
+ }
searchIndexRegistry: {
Row: {
companyId: string
@@ -35594,7 +35636,9 @@ export type Database = {
name: string
phone: string | null
purchasingContactId: string | null
- supplierStatusId: string | null
+ supplierStatus:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId: string | null
tags: string[] | null
taxId: string | null
@@ -35620,7 +35664,9 @@ export type Database = {
name: string
phone?: string | null
purchasingContactId?: string | null
- supplierStatusId?: string | null
+ supplierStatus?:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId?: string | null
tags?: string[] | null
taxId?: string | null
@@ -35646,7 +35692,9 @@ export type Database = {
name?: string
phone?: string | null
purchasingContactId?: string | null
- supplierStatusId?: string | null
+ supplierStatus?:
+ | Database["public"]["Enums"]["supplierStatusType"]
+ | null
supplierTypeId?: string | null
tags?: string[] | null
taxId?: string | null
@@ -35804,13 +35852,6 @@ export type Database = {
referencedRelation: "supplierContact"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "supplier_supplierStatusId_fkey"
- columns: ["supplierStatusId"]
- isOneToOne: false
- referencedRelation: "supplierStatus"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "supplier_supplierTypeId_fkey"
columns: ["supplierTypeId"]
@@ -38076,141 +38117,6 @@ export type Database = {
},
]
}
- supplierStatus: {
- Row: {
- companyId: string
- createdAt: string
- createdBy: string
- customFields: Json | null
- id: string
- name: string
- tags: string[] | null
- updatedAt: string | null
- updatedBy: string | null
- }
- Insert: {
- companyId: string
- createdAt?: string
- createdBy: string
- customFields?: Json | null
- id?: string
- name: string
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Update: {
- companyId?: string
- createdAt?: string
- createdBy?: string
- customFields?: Json | null
- id?: string
- name?: string
- tags?: string[] | null
- updatedAt?: string | null
- updatedBy?: string | null
- }
- Relationships: [
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "companies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "company"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "customFieldTables"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "supplierStatus_companyId_fkey"
- columns: ["companyId"]
- isOneToOne: false
- referencedRelation: "integrations"
- referencedColumns: ["companyId"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_createdBy_fkey"
- columns: ["createdBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employees"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeesAcrossCompanies"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "employeeSummary"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "user"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "supplierStatus_updatedBy_fkey"
- columns: ["updatedBy"]
- isOneToOne: false
- referencedRelation: "userDefaults"
- referencedColumns: ["userId"]
- },
- ]
- }
supplierType: {
Row: {
companyId: string
@@ -49235,14 +49141,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55146,7 +55052,6 @@ export type Database = {
phone: string | null
purchasingContactId: string | null
status: string | null
- supplierStatusId: string | null
supplierTypeId: string | null
tags: string[] | null
taxId: string | null
@@ -55305,13 +55210,6 @@ export type Database = {
referencedRelation: "supplierContact"
referencedColumns: ["id"]
},
- {
- foreignKeyName: "supplier_supplierStatusId_fkey"
- columns: ["supplierStatusId"]
- isOneToOne: false
- referencedRelation: "supplierStatus"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "supplier_supplierTypeId_fkey"
columns: ["supplierTypeId"]
@@ -58110,6 +58008,7 @@ export type Database = {
| "Draft"
| "Declined"
| "Cancelled"
+ supplierStatusType: "Active" | "Inactive" | "Pending" | "Rejected"
supplySourceType: "Purchase Order" | "Production Order"
tableViewType: "Public" | "Private"
trackedEntityStatus: "Available" | "Reserved" | "On Hold" | "Consumed"
@@ -59267,6 +59166,7 @@ export const Constants = {
"Declined",
"Cancelled",
],
+ supplierStatusType: ["Active", "Inactive", "Pending", "Rejected"],
supplySourceType: ["Purchase Order", "Production Order"],
tableViewType: ["Public", "Private"],
trackedEntityStatus: ["Available", "Reserved", "On Hold", "Consumed"],
diff --git a/packages/database/supabase/functions/seed-company/index.ts b/packages/database/supabase/functions/seed-company/index.ts
index ed145340c8..62795c498c 100644
--- a/packages/database/supabase/functions/seed-company/index.ts
+++ b/packages/database/supabase/functions/seed-company/index.ts
@@ -21,7 +21,6 @@ import {
postingGroupSales,
scrapReasons,
sequences,
- supplierStauses,
unitOfMeasures,
} from "../lib/seed.ts";
import { getSupabaseServiceRole } from "../lib/supabase.ts";
@@ -151,18 +150,6 @@ serve(async (req: Request) => {
])
.execute();
- // supplier status
- await trx
- .insertInto("supplierStatus")
- .values(
- supplierStauses.map((name) => ({
- name,
- companyId,
- createdBy: "system",
- }))
- )
- .execute();
-
// customer status
await trx
.insertInto("customerStatus")
diff --git a/packages/database/supabase/migrations/20260309211117_supplier-status-enums.sql b/packages/database/supabase/migrations/20260309211117_supplier-status-enums.sql
new file mode 100644
index 0000000000..1b36d17ed7
--- /dev/null
+++ b/packages/database/supabase/migrations/20260309211117_supplier-status-enums.sql
@@ -0,0 +1,407 @@
+-- Migration: Convert supplier status from FK table to enum
+
+-- Step 1: Create the enum type
+CREATE TYPE "supplierStatusType" AS ENUM ('Active', 'Inactive', 'Pending', 'Rejected');
+
+-- Step 2: Add new enum column (nullable)
+ALTER TABLE "supplier" ADD COLUMN "supplierStatus" "supplierStatusType";
+
+-- Step 3: Backfill from existing supplierStatus table (exact match only, otherwise null)
+UPDATE "supplier" s
+SET "supplierStatus" = ss.name::"supplierStatusType"
+FROM "supplierStatus" ss
+WHERE ss.id = s."supplierStatusId"
+ AND ss.name IN ('Active', 'Inactive', 'Pending', 'Rejected');
+
+-- Step 4: Drop the suppliers view (depends on supplierStatusId column)
+DROP VIEW IF EXISTS "suppliers";
+
+-- Step 5: Drop FK constraint and column
+ALTER TABLE "supplier" DROP CONSTRAINT "supplier_supplierStatusId_fkey";
+ALTER TABLE "supplier" DROP COLUMN "supplierStatusId";
+
+-- Step 6: Drop RLS policies on supplierStatus table
+DROP POLICY IF EXISTS "SELECT" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "INSERT" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "UPDATE" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "DELETE" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_view can view supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_create can create supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_update can update supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Employees with purchasing_delete can delete supplier statuses" ON "public"."supplierStatus";
+DROP POLICY IF EXISTS "Requests with an API key can access supplier statuses" ON "public"."supplierStatus";
+
+-- Step 6: Drop supplierStatus table
+DROP TABLE IF EXISTS "supplierStatus";
+
+-- Step 7: Recreate the suppliers view with enum column instead of FK join
+DROP VIEW IF EXISTS "suppliers";
+CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.id,
+ s.name,
+ s."supplierTypeId",
+ s."supplierStatus" as "status",
+ s."taxId",
+ s."accountManagerId",
+ s.logo,
+ s.assignee,
+ s."companyId",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."customFields",
+ s."currencyCode",
+ s."vatNumber",
+ s.website,
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL OR eim."metadata" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'supplier' AND eim."entityId" = s.id
+ ) AS "externalId",
+ s.tags,
+ s."taxPercent",
+ s."purchasingContactId",
+ s.embedding,
+ s."defaultCc",
+ st.name AS "type",
+ po.count AS "orderCount",
+ p.count AS "partCount",
+ pc."workPhone" AS "phone",
+ pc.fax AS "fax"
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "purchaseOrder"
+ GROUP BY "supplierId"
+ ) po ON po."supplierId" = s.id
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "supplierPart"
+ GROUP BY "supplierId"
+ ) p ON p."supplierId" = s.id
+ LEFT JOIN (
+ SELECT DISTINCT ON (sc."supplierId")
+ sc."supplierId" AS id,
+ co."workPhone",
+ co."fax"
+ FROM "supplierContact" sc
+ JOIN "contact" co
+ ON co.id = sc."contactId"
+ ORDER BY sc."supplierId", sc.id
+ ) pc
+ ON pc.id = s.id;
+
+-- Step 8: Update search trigger function for supplier
+CREATE OR REPLACE FUNCTION sync_supplier_to_search_index()
+RETURNS TRIGGER AS $$
+DECLARE
+ v_table_name TEXT;
+ v_supp_type TEXT;
+ v_supp_status TEXT;
+BEGIN
+ IF TG_OP = 'DELETE' THEN
+ v_table_name := 'searchIndex_' || OLD."companyId";
+ EXECUTE format('DELETE FROM %I WHERE "entityType" = $1 AND "entityId" = $2', v_table_name)
+ USING 'supplier', OLD.id;
+ RETURN OLD;
+ END IF;
+
+ v_table_name := 'searchIndex_' || NEW."companyId";
+
+ SELECT name INTO v_supp_type FROM "supplierType" WHERE id = NEW."supplierTypeId";
+ v_supp_status := NEW."supplierStatus"::TEXT;
+
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ VALUES ($1, $2, $3, $4, $5, $6, to_tsvector(''english'', $3 || '' '' || COALESCE(array_to_string($5, '' ''), '''')))
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = to_tsvector(''english'', EXCLUDED."title" || '' '' || COALESCE(array_to_string(EXCLUDED."tags", '' ''), '''')),
+ "updatedAt" = NOW()
+ ', v_table_name) USING
+ 'supplier',
+ NEW.id,
+ NEW.name,
+ '/x/supplier/' || NEW.id,
+ ARRAY_REMOVE(ARRAY[v_supp_type, v_supp_status], NULL),
+ jsonb_build_object('taxId', NEW."taxId");
+
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Step 9: Update the populate_company_search_index function (supplier section)
+CREATE OR REPLACE FUNCTION populate_company_search_index(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ v_table_name TEXT := 'searchIndex_' || p_company_id;
+BEGIN
+ -- Populate employees
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''employee'',
+ e.id,
+ COALESCE(u."fullName", ''''),
+ ''/x/person/'' || e.id,
+ ARRAY_REMOVE(ARRAY[et.name], NULL),
+ jsonb_build_object(''active'', e.active),
+ to_tsvector(''english'', COALESCE(u."fullName", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[et.name], NULL), '' ''), ''''))
+ FROM "employee" e
+ INNER JOIN "user" u ON u.id = e.id
+ LEFT JOIN "employeeType" et ON et.id = e."employeeTypeId"
+ WHERE e."companyId" = $1 AND e.active = true
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate customers
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''customer'',
+ c.id,
+ c.name,
+ ''/x/customer/'' || c.id,
+ ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL),
+ jsonb_build_object(''taxId'', c."taxId"),
+ to_tsvector(''english'', c.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[ct.name, cs.name], NULL), '' ''), ''''))
+ FROM "customer" c
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
+ WHERE c."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate suppliers (uses enum column instead of FK join)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''supplier'',
+ s.id,
+ s.name,
+ ''/x/supplier/'' || s.id,
+ ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL),
+ jsonb_build_object(''taxId'', s."taxId"),
+ to_tsvector(''english'', s.name || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[st.name, s."supplierStatus"::TEXT], NULL), '' ''), ''''))
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ WHERE s."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate items
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''item'',
+ i.id,
+ i."readableId",
+ i.name || '' '' || COALESCE(i.description, ''''),
+ CASE i.type
+ WHEN ''Part'' THEN ''/x/part/'' || i.id
+ WHEN ''Service'' THEN ''/x/service/'' || i.id
+ WHEN ''Tool'' THEN ''/x/tool/'' || i.id
+ WHEN ''Consumable'' THEN ''/x/consumable/'' || i.id
+ WHEN ''Material'' THEN ''/x/material/'' || i.id
+ WHEN ''Fixture'' THEN ''/x/fixture/'' || i.id
+ ELSE ''/x/part/'' || i.id
+ END,
+ ARRAY_REMOVE(ARRAY[i.type::TEXT, i."replenishmentSystem"::TEXT], NULL),
+ jsonb_build_object(''active'', i.active),
+ to_tsvector(''english'', i."readableId" || '' '' || i.name || '' '' || COALESCE(i.description, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[i.type::TEXT, i."replenishmentSystem"::TEXT], NULL), '' ''), ''''))
+ FROM "item" i
+ WHERE i."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "link" = EXCLUDED."link",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate jobs
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''job'',
+ j.id,
+ j."jobId",
+ COALESCE(i.name, '''') || '' '' || COALESCE(c.name, ''''),
+ ''/x/job/'' || j.id,
+ ARRAY_REMOVE(ARRAY[j.status::TEXT, j."deadlineType"::TEXT], NULL),
+ jsonb_build_object(''quantity'', j.quantity, ''dueDate'', j."dueDate"),
+ to_tsvector(''english'', j."jobId" || '' '' || COALESCE(i.name, '''') || '' '' || COALESCE(c.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[j.status::TEXT, j."deadlineType"::TEXT], NULL), '' ''), ''''))
+ FROM "job" j
+ LEFT JOIN "item" i ON i.id = j."itemId"
+ LEFT JOIN "customer" c ON c.id = j."customerId"
+ WHERE j."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate purchase orders
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''purchaseOrder'',
+ po.id,
+ po."purchaseOrderId",
+ COALESCE(s.name, ''''),
+ ''/x/purchase-order/'' || po.id,
+ ARRAY_REMOVE(ARRAY[po.status::TEXT], NULL),
+ jsonb_build_object(''orderDate'', po."orderDate", ''supplierReference'', po."supplierReference"),
+ to_tsvector(''english'', po."purchaseOrderId" || '' '' || COALESCE(s.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[po.status::TEXT], NULL), '' ''), ''''))
+ FROM "purchaseOrder" po
+ LEFT JOIN "supplier" s ON s.id = po."supplierId"
+ WHERE po."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate sales invoices
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''salesInvoice'',
+ si.id,
+ si."invoiceId",
+ COALESCE(c.name, ''''),
+ ''/x/invoicing/sales/'' || si.id,
+ ARRAY_REMOVE(ARRAY[si.status::TEXT], NULL),
+ jsonb_build_object(''totalAmount'', si."totalAmount", ''dateDue'', si."dateDue"),
+ to_tsvector(''english'', si."invoiceId" || '' '' || COALESCE(c.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[si.status::TEXT], NULL), '' ''), ''''))
+ FROM "salesInvoice" si
+ LEFT JOIN "customer" c ON c.id = si."customerId"
+ WHERE si."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate purchase invoices
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''purchaseInvoice'',
+ pi.id,
+ pi."invoiceId",
+ COALESCE(s.name, ''''),
+ ''/x/invoicing/purchasing/'' || pi.id,
+ ARRAY_REMOVE(ARRAY[pi.status::TEXT], NULL),
+ jsonb_build_object(''totalAmount'', pi."totalAmount", ''dateDue'', pi."dateDue"),
+ to_tsvector(''english'', pi."invoiceId" || '' '' || COALESCE(s.name, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[pi.status::TEXT], NULL), '' ''), ''''))
+ FROM "purchaseInvoice" pi
+ LEFT JOIN "supplier" s ON s.id = pi."supplierId"
+ WHERE pi."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate non-conformances (issues)
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''issue'',
+ nc.id,
+ nc."nonConformanceId",
+ nc.name || '' '' || COALESCE(nc.description, ''''),
+ ''/x/issue/'' || nc.id,
+ ARRAY_REMOVE(ARRAY[nc.status::TEXT, nc.priority::TEXT, nct.name], NULL),
+ jsonb_build_object(''source'', nc.source, ''dueDate'', nc."dueDate"),
+ to_tsvector(''english'', nc."nonConformanceId" || '' '' || nc.name || '' '' || COALESCE(nc.description, '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[nc.status::TEXT, nc.priority::TEXT, nct.name], NULL), '' ''), ''''))
+ FROM "nonConformance" nc
+ LEFT JOIN "nonConformanceType" nct ON nct.id = nc."nonConformanceTypeId"
+ WHERE nc."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Populate gauges
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "title", "description", "link", "tags", "metadata", "searchVector")
+ SELECT
+ ''gauge'',
+ g.id,
+ g."gaugeId",
+ COALESCE(g.description, '''') || '' '' || COALESCE(g."serialNumber", ''''),
+ ''/x/quality/gauges/'' || g.id,
+ ARRAY_REMOVE(ARRAY[g."gaugeStatus"::TEXT, g."gaugeCalibrationStatus"::TEXT, gt.name], NULL),
+ jsonb_build_object(''nextCalibrationDate'', g."nextCalibrationDate", ''serialNumber'', g."serialNumber"),
+ to_tsvector(''english'', g."gaugeId" || '' '' || COALESCE(g.description, '''') || '' '' || COALESCE(g."serialNumber", '''') || '' '' || COALESCE(array_to_string(ARRAY_REMOVE(ARRAY[g."gaugeStatus"::TEXT, g."gaugeCalibrationStatus"::TEXT, gt.name], NULL), '' ''), ''''))
+ FROM "gauge" g
+ LEFT JOIN "gaugeType" gt ON gt.id = g."gaugeTypeId"
+ WHERE g."companyId" = $1
+ ON CONFLICT ("entityType", "entityId") DO UPDATE SET
+ "title" = EXCLUDED."title",
+ "description" = EXCLUDED."description",
+ "tags" = EXCLUDED."tags",
+ "metadata" = EXCLUDED."metadata",
+ "searchVector" = EXCLUDED."searchVector",
+ "updatedAt" = NOW()
+ ', v_table_name) USING p_company_id;
+
+ -- Update registry
+ UPDATE "searchIndexRegistry"
+ SET "lastRebuiltAt" = NOW()
+ WHERE "companyId" = p_company_id;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/jobs/trigger/event/search.ts b/packages/jobs/trigger/event/search.ts
index 9474c8664e..5e002470c8 100644
--- a/packages/jobs/trigger/event/search.ts
+++ b/packages/jobs/trigger/event/search.ts
@@ -94,7 +94,7 @@ const SEARCH_ENTITY_CONFIGS: Record<string, SearchEntityConfig> = {
entityType: "supplier",
getTitle: (r) => r.name,
getLink: (r) => `/x/supplier/${r.id}`,
- getTags: (r) => [r.supplierTypeName, r.supplierStatusName].filter(Boolean),
+ getTags: (r) => [r.supplierTypeName, r.supplierStatus].filter(Boolean),
getMetadata: (r) => ({ taxId: r.taxId }),
enrichRecord: async (record, client) => {
const { data: suppType } = await client
@@ -102,15 +102,9 @@ const SEARCH_ENTITY_CONFIGS: Record<string, SearchEntityConfig> = {
.select("name")
.eq("id", record.supplierTypeId)
.single();
- const { data: suppStatus } = await client
- .from("supplierStatus")
- .select("name")
- .eq("id", record.supplierStatusId)
- .single();
return {
...record,
supplierTypeName: suppType?.name,
- supplierStatusName: suppStatus?.name,
};
},
},
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index e6ec86b1ed..a1be118903 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -24,7 +24,7 @@ export const buttonVariants = cva(
primary:
"bg-gradient-to-br from-primary/90 to-primary text-primary-foreground hover:bg-primary/90 saturate-[105%] shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)] before:pointer-events-none before:bg-gradient-to-b before:transition-opacity before:duration-100 before:ease before:from-white/[0.12] before:absolute before:inset-0 before:z-[1] before:rounded before:opacity-0 hover:before:opacity-100 active:before:opacity-0",
active:
- "bg-active text-active-foreground hover:bg-active/90 hover:text-active-foreground shadow-button-base before:hidden",
+ "bg-active text-active-foreground hover:bg-active/90 hover:text-active-foreground dark:shadow-button-base before:hidden",
secondary:
"bg-background hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50 shadow-button-base",
solid: