Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: add ui for webhooks crud

Brad Barbine95df6917719
diff --git a/apps/erp/app/components/Hyperlink.tsx b/apps/erp/app/components/Hyperlink.tsx
index f0873024f8..19f1d126ee 100644
--- a/apps/erp/app/components/Hyperlink.tsx
+++ b/apps/erp/app/components/Hyperlink.tsx
@@ -20,7 +20,7 @@ const Hyperlink = ({
)}
{...props}
>
- <span>{children}</span>
+ <span className="flex flex-row items-center gap-1">{children}</span>
<Button
leftIcon={<LuSquareArrowOutUpRight />}
variant="secondary"
diff --git a/apps/erp/app/modules/settings/settings.models.ts b/apps/erp/app/modules/settings/settings.models.ts
index c496fc9b37..4b5826adb2 100644
--- a/apps/erp/app/modules/settings/settings.models.ts
+++ b/apps/erp/app/modules/settings/settings.models.ts
@@ -109,3 +109,14 @@ export const themeValidator = z.object({
errorMap: (issue, ctx) => ({ message: "Theme is required" }),
}),
});
+
+export const webhookValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Name is required" }),
+ table: z.string().min(1, { message: "Table is required" }),
+ url: z.string().url({ message: "Must be a valid URL" }),
+ onInsert: zfd.checkbox(),
+ onUpdate: zfd.checkbox(),
+ onDelete: zfd.checkbox(),
+ active: zfd.checkbox(),
+});
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index f875ba3a6e..d99bea4d6f 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -11,6 +11,7 @@ import type {
apiKeyValidator,
companyValidator,
sequenceValidator,
+ webhookValidator,
} from "./settings.models";
export async function deactivateIntegration(
@@ -41,6 +42,23 @@ export async function deleteApiKey(
return client.from("apiKey").delete().eq("id", id);
}
+export async function deleteWebhook(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("webhook").delete().eq("id", id);
+}
+
+export async function deactivateWebhooks(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client
+ .from("webhook")
+ .update({ active: false })
+ .eq("companyId", companyId);
+}
+
export async function getApiKeys(
client: SupabaseClient<Database>,
companyId: string,
@@ -66,6 +84,46 @@ export async function getApiKeys(
return query;
}
+export async function getTerms(
+ client: SupabaseClient<Database>,
+ companyId: string
+) {
+ return client.from("terms").select("*").eq("id", companyId).single();
+}
+
+export async function getWebhook(client: SupabaseClient<Database>, id: string) {
+ return client.from("webhook").select("*").eq("id", id).single();
+}
+
+export async function getWebhookTables(client: SupabaseClient<Database>) {
+ return client.from("webhookTable").select("*");
+}
+
+export async function getWebhooks(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ args?: GenericQueryFilters & { search: string | null }
+) {
+ let query = client
+ .from("webhook")
+ .select("*", {
+ count: "exact",
+ })
+ .eq("companyId", companyId);
+
+ if (args?.search) {
+ query = query.ilike("name", `%${args.search}%`);
+ }
+
+ if (args) {
+ query = setGenericQueryFilters(query, args, [
+ { column: "createdAt", ascending: true },
+ ]);
+ }
+
+ return query;
+}
+
export async function getCompanies(
client: SupabaseClient<Database>,
userId: string
@@ -459,10 +517,19 @@ export async function updateSequence(
.eq("table", table);
}
-// Add this function to the file
-export async function getTerms(
+export async function upsertWebhook(
client: SupabaseClient<Database>,
- companyId: string
+ webhook:
+ | (Omit<z.infer<typeof webhookValidator>, "id"> & {
+ createdBy: string;
+ companyId: string;
+ })
+ | (Omit<z.infer<typeof apiKeyValidator>, "id"> & {
+ id: string;
+ })
) {
- return client.from("terms").select("*").eq("id", companyId).single();
+ if ("createdBy" in webhook) {
+ return client.from("webhook").insert(webhook).select("id").single();
+ }
+ return client.from("webhook").update(sanitize(webhook)).eq("id", webhook.id);
}
diff --git a/apps/erp/app/modules/settings/types.ts b/apps/erp/app/modules/settings/types.ts
index b5b7aecbef..3b2fcf07ea 100644
--- a/apps/erp/app/modules/settings/types.ts
+++ b/apps/erp/app/modules/settings/types.ts
@@ -5,6 +5,7 @@ import type {
getCustomFieldsTables,
getIntegrations,
getSequences,
+ getWebhooks,
} from "./settings.service";
export type ApiKey = NonNullable<
@@ -30,3 +31,7 @@ export type Integration = NonNullable<
export type Sequence = NonNullable<
Awaited<ReturnType<typeof getSequences>>["data"]
>[number];
+
+export type Webhook = NonNullable<
+ Awaited<ReturnType<typeof getWebhooks>>["data"]
+>[number];
diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
index a6ecab865f..76d469e7c4 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
@@ -1,10 +1,11 @@
-import { Badge, MenuIcon, MenuItem } from "@carbon/react";
+import { Badge, Button, HStack, MenuIcon, MenuItem } from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { Outlet, useNavigate } from "@remix-run/react";
+import { Link, Outlet, useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
import {
LuCalendar,
+ LuCode,
LuKey,
LuPencil,
LuTag,
@@ -115,12 +116,17 @@ const ApiKeysTable = memo(({ data, count }: ApiKeysTableProps) => {
columns={columns}
count={count ?? 0}
primaryAction={
- permissions.can("update", "users") && (
- <New
- label="API Key"
- to={`${path.to.newApiKey}?${params.toString()}`}
- />
- )
+ <HStack>
+ {permissions.can("update", "users") && (
+ <New
+ label="API Key"
+ to={`${path.to.newApiKey}?${params.toString()}`}
+ />
+ )}
+ <Button leftIcon={<LuCode />} variant="secondary" asChild>
+ <Link to={path.to.apiIntroduction}>API Docs</Link>
+ </Button>
+ </HStack>
}
renderContextMenu={renderContextMenu}
title="API Keys"
diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx
new file mode 100644
index 0000000000..981125fe45
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhookForm.tsx
@@ -0,0 +1,143 @@
+import { Boolean, Combobox, Input, ValidatedForm } from "@carbon/form";
+import {
+ Button,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerFooter,
+ DrawerHeader,
+ DrawerTitle,
+ FormControl,
+ FormLabel,
+ HStack,
+ Separator,
+ VStack,
+ toast,
+ useMount,
+} from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect } from "react";
+import type { z } from "zod";
+import { Hidden, Submit } from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { path } from "~/utils/path";
+import { webhookValidator } from "../../settings.models";
+import type { getWebhookTables } from "../../settings.service";
+
+type WebhookFormProps = {
+ initialValues: z.infer<typeof webhookValidator>;
+ type?: "modal" | "drawer";
+ open?: boolean;
+ onClose: (data?: { id: string; name: string }) => void;
+};
+
+const WebhookForm = ({
+ initialValues,
+ open = true,
+ onClose,
+}: WebhookFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<{ id: string }>>();
+
+ const tables = useWebhookTables();
+
+ useEffect(() => {
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ toast.success(`Created unit of measure`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(
+ `Failed to create unit of measure: ${fetcher.data.error.message}`
+ );
+ }
+ }, [fetcher.data, fetcher.state, onClose]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "parts")
+ : !permissions.can("create", "parts");
+
+ return (
+ <Drawer
+ open={open}
+ onOpenChange={(open) => {
+ if (!open) onClose?.();
+ }}
+ >
+ <DrawerContent size="sm">
+ <ValidatedForm
+ validator={webhookValidator}
+ method="post"
+ action={
+ isEditing ? path.to.webhook(initialValues.id!) : path.to.newWebhook
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <DrawerHeader>
+ <DrawerTitle>{isEditing ? "Edit" : "New"} Webhook</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ <Hidden name="id" />
+
+ <VStack spacing={4}>
+ <Input
+ name="name"
+ label="Name"
+ helperText="This is a unique identifier for the webhook"
+ />
+ <Input
+ name="url"
+ label="Webhook URL"
+ helperText="The URL of the webhook"
+ />
+ <Combobox name="table" label="Table" options={tables} />
+ <FormControl>
+ <FormLabel>Notifications</FormLabel>
+ <VStack>
+ <Boolean name="onInsert" description="Insert" />
+ <Boolean name="onUpdate" description="Update" />
+ <Boolean name="onDelete" description="Delete" />
+ </VStack>
+ </FormControl>
+
+ <Separator />
+
+ <Boolean name="active" label="Active" />
+ </VStack>
+ </DrawerBody>
+ <DrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose()}>
+ Cancel
+ </Button>
+ </HStack>
+ </DrawerFooter>
+ </ValidatedForm>
+ </DrawerContent>
+ </Drawer>
+ );
+};
+
+export default WebhookForm;
+
+export const useWebhookTables = () => {
+ const tablesFetcher =
+ useFetcher<Awaited<ReturnType<typeof getWebhookTables>>>();
+
+ useMount(() => {
+ tablesFetcher.load(path.to.api.webhookTables);
+ });
+
+ const tables = tablesFetcher.data?.data ?? [];
+
+ const options = tables.map((t) => ({
+ value: t.table,
+ label: t.name,
+ }));
+
+ return options;
+};
diff --git a/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx
new file mode 100644
index 0000000000..c087988e8d
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Webhooks/WebhooksTable.tsx
@@ -0,0 +1,168 @@
+import { Badge, HStack, MenuIcon, MenuItem } from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { Outlet, useNavigate } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import {
+ LuCalendar,
+ LuDatabase,
+ LuPencil,
+ LuTable2,
+ LuTag,
+ LuTrash,
+ LuUser,
+} from "react-icons/lu";
+import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
+import { usePermissions, useUrlParams } from "~/hooks";
+import type { Webhook } from "~/modules/settings";
+import { usePeople } from "~/stores";
+import { path } from "~/utils/path";
+import { useWebhookTables } from "./WebhookForm";
+
+type WebhooksTableProps = {
+ data: Webhook[];
+ count: number;
+};
+
+const WebhooksTable = memo(({ data, count }: WebhooksTableProps) => {
+ const navigate = useNavigate();
+ const [params] = useUrlParams();
+ const permissions = usePermissions();
+ const [people] = usePeople();
+ const webhookTables = useWebhookTables();
+
+ const columns = useMemo<ColumnDef<Webhook>[]>(() => {
+ return [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => (
+ <div className="flex flex-col gap-1 justify-start items-start pb-1">
+ <Hyperlink to={row.original.id!}>{row.original.name}</Hyperlink>
+ <HStack>
+ {row.original.active ? (
+ <Badge variant="green">Active</Badge>
+ ) : (
+ <Badge variant="red">Inactive</Badge>
+ )}
+ <span className="text-xs text-muted-foreground font-mono">
+ {row.original.url}
+ </span>
+ </HStack>
+ </div>
+ ),
+ meta: {
+ icon: <LuTag />,
+ },
+ },
+ {
+ accessorKey: "table",
+ header: "Table",
+ cell: ({ row }) => (
+ <div className="flex flex-col gap-1 justify-start items-start pb-1">
+ <Hyperlink
+ className="flex flex-row gap-1 items-center"
+ to={path.to.apiTable("js", row.original.table)}
+ >
+ <LuTable2 className="size-4" />
+ <span className="text-sm font-medium">
+ {`public.${row.original.table}`}
+ </span>
+ </Hyperlink>
+ <HStack>
+ {row.original.onInsert && <Badge variant="green">Insert</Badge>}
+ {row.original.onUpdate && <Badge variant="blue">Update</Badge>}
+ {row.original.onDelete && <Badge variant="red">Delete</Badge>}
+ </HStack>
+ </div>
+ ),
+ meta: {
+ icon: <LuDatabase />,
+ filter: {
+ type: "static",
+ options: webhookTables,
+ },
+ },
+ },
+ {
+ id: "createdBy",
+ header: "Created By",
+ cell: ({ row }) => (
+ <EmployeeAvatar employeeId={row.original.createdBy} />
+ ),
+ meta: {
+ icon: <LuUser />,
+ filter: {
+ type: "static",
+ options: people.map((employee) => ({
+ value: employee.id,
+ label: employee.name,
+ })),
+ },
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created At",
+ cell: (item) => formatDate(item.getValue<string>()),
+ meta: {
+ icon: <LuCalendar />,
+ },
+ },
+ ];
+ }, [people, webhookTables]);
+
+ const renderContextMenu = useCallback(
+ (row: (typeof data)[number]) => {
+ return (
+ <>
+ <MenuItem
+ onClick={() => {
+ navigate(`${path.to.webhook(row.id!)}?${params?.toString()}`);
+ }}
+ >
+ <MenuIcon icon={<LuPencil />} />
+ Edit Webhook
+ </MenuItem>
+ <MenuItem
+ destructive
+ onClick={() => {
+ navigate(
+ `${path.to.deleteWebhook(row.id!)}?${params?.toString()}`
+ );
+ }}
+ >
+ <MenuIcon icon={<LuTrash />} />
+ Delete Webhook
+ </MenuItem>
+ </>
+ );
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [navigate, params, permissions]
+ );
+
+ return (
+ <>
+ <Table<Webhook>
+ data={data}
+ columns={columns}
+ count={count ?? 0}
+ primaryAction={
+ permissions.can("update", "users") && (
+ <New
+ label="Webhook"
+ to={`${path.to.newWebhook}?${params.toString()}`}
+ />
+ )
+ }
+ renderContextMenu={renderContextMenu}
+ title="Webhooks"
+ />
+ <Outlet />
+ </>
+ );
+});
+
+WebhooksTable.displayName = "WebhooksTable";
+export default WebhooksTable;
diff --git a/apps/erp/app/modules/settings/ui/Webhooks/index.ts b/apps/erp/app/modules/settings/ui/Webhooks/index.ts
new file mode 100644
index 0000000000..f2da691d56
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/Webhooks/index.ts
@@ -0,0 +1,4 @@
+import WebhookForm from "./WebhookForm";
+import WebhooksTable from "./WebhooksTable";
+
+export { WebhookForm, WebhooksTable };
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 8357f9529d..f2d8eaee51 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -5,6 +5,7 @@ import {
LuLayoutDashboard,
LuSheet,
LuShoppingCart,
+ LuWebhook,
LuWorkflow,
} from "react-icons/lu";
import { usePermissions } from "~/hooks";
@@ -67,6 +68,12 @@ const settingsRoutes: AuthenticatedRouteGroup[] = [
role: "employee",
icon: <LuSheet />,
},
+ {
+ name: "Webhooks",
+ to: path.to.webhooks,
+ role: "employee",
+ icon: <LuWebhook />,
+ },
],
},
];
diff --git a/apps/erp/app/routes/api+/webhook.tables.ts b/apps/erp/app/routes/api+/webhook.tables.ts
new file mode 100644
index 0000000000..ad377f5a89
--- /dev/null
+++ b/apps/erp/app/routes/api+/webhook.tables.ts
@@ -0,0 +1,33 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ClientLoaderFunctionArgs } from "@remix-run/react";
+import type { LoaderFunctionArgs, SerializeFrom } from "@vercel/remix";
+import { json } from "@vercel/remix";
+import { getWebhookTables } from "~/modules/settings/settings.service";
+import { getCompanyId, webhookTablesQuery } from "~/utils/react-query";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {});
+
+ return json(await getWebhookTables(client));
+}
+
+export async function clientLoader({ serverLoader }: ClientLoaderFunctionArgs) {
+ const companyId = getCompanyId();
+
+ if (!companyId) {
+ return await serverLoader<typeof loader>();
+ }
+
+ const queryKey = webhookTablesQuery().queryKey;
+ const data =
+ window?.clientCache?.getQueryData<SerializeFrom<typeof loader>>(queryKey);
+
+ if (!data) {
+ const serverData = await serverLoader<typeof loader>();
+ window?.clientCache?.setQueryData(queryKey, serverData);
+ return serverData;
+ }
+
+ return data;
+}
+clientLoader.hydrate = true;
diff --git a/apps/erp/app/routes/x+/batch+/$batchId.tsx b/apps/erp/app/routes/x+/batch+/$batchId.tsx
index 4decaba65d..1f0d2d992c 100644
--- a/apps/erp/app/routes/x+/batch+/$batchId.tsx
+++ b/apps/erp/app/routes/x+/batch+/$batchId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole, useCarbon } from "@carbon/auth";
+import { error, useCarbon } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { JSONContent } from "@carbon/react";
@@ -67,16 +67,15 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "inventory",
+ bypassRls: true,
});
- const serviceRole = await getCarbonServiceRole();
-
const { batchId } = params;
if (!batchId) throw new Error("Batch ID is required");
- const batch = await getBatch(serviceRole, batchId, companyId);
+ const batch = await getBatch(client, batchId, companyId);
if (batch.error) {
throw redirect(
path.to.batches,
@@ -85,7 +84,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
const batchProperties = await getBatchProperties(
- serviceRole,
+ client,
[batch.data.itemId],
companyId
);
@@ -97,7 +96,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
batch: batch.data,
batchProperties: batchProperties?.data ?? [],
- receiptFiles: getBatchFiles(serviceRole, companyId, {
+ receiptFiles: getBatchFiles(client, companyId, {
receiptLineIds,
batchId,
}) ?? { data: [], error: null },
diff --git a/apps/erp/app/routes/x+/job+/$jobId.tsx b/apps/erp/app/routes/x+/job+/$jobId.tsx
index d99310c2cd..34105c3c00 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { ClientOnly } from "@carbon/react";
@@ -40,6 +40,7 @@ export const handle: Handle = {
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "production",
+ bypassRls: true,
});
const { jobId } = params;
@@ -53,7 +54,6 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
if (companyId !== job.data?.companyId) {
throw redirect(path.to.jobs);
}
- const serviceRole = await getCarbonServiceRole();
if (job.error) {
throw redirect(
@@ -65,10 +65,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
job: job.data,
tags: tags.data ?? [],
- files: getJobDocuments(serviceRole, companyId, job.data),
- method: getJobMethodTree(serviceRole, jobId), // returns a promise
+ files: getJobDocuments(client, companyId, job.data),
+ method: getJobMethodTree(client, jobId), // returns a promise
configurationParameters: getConfigurationParameters(
- serviceRole,
+ client,
job.data.itemId!,
companyId
),
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 81fce63df7..1ef29715b2 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -1,4 +1,4 @@
-import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
+import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
@@ -12,8 +12,9 @@ import { setCustomFields } from "~/utils/form";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
- const { companyId, userId } = await requirePermissions(request, {
+ const { client, companyId, userId } = await requirePermissions(request, {
create: "production",
+ bypassRls: true,
});
const { jobId, id } = params;
@@ -32,8 +33,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
- const serviceRole = getCarbonServiceRole();
- const updateJobMaterial = await upsertJobMaterial(serviceRole, {
+ const updateJobMaterial = await upsertJobMaterial(client, {
jobId,
...validation.data,
id: id,
@@ -66,14 +66,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- const recalculateResult = await recalculateJobMakeMethodRequirements(
- serviceRole,
- {
- id: validation.data.jobMakeMethodId,
- companyId,
- userId,
- }
- );
+ const recalculateResult = await recalculateJobMakeMethodRequirements(client, {
+ id: validation.data.jobMakeMethodId,
+ companyId,
+ userId,
+ });
if (recalculateResult.error) {
return json(
diff --git a/apps/erp/app/routes/x+/material+/$itemId.tsx b/apps/erp/app/routes/x+/material+/$itemId.tsx
index 71e8057e05..8a2812ecc4 100644
--- a/apps/erp/app/routes/x+/material+/$itemId.tsx
+++ b/apps/erp/app/routes/x+/material+/$itemId.tsx
@@ -1,4 +1,4 @@
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { Outlet } from "@remix-run/react";
@@ -26,21 +26,20 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { companyId } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "parts",
+ bypassRls: true,
});
- const serviceRole = await getCarbonServiceRole();
-
const { itemId } = params;
if (!itemId) throw new Error("Could not find itemId");
const [materialSummary, supplierParts, pickMethods, tags] = await Promise.all(
[
- getMaterial(serviceRole, itemId, companyId),
- getSupplierParts(serviceRole, itemId, companyId),
- getPickMethods(serviceRole, itemId, companyId),
- getTagsList(serviceRole, companyId, "material"),
+ getMaterial(client, itemId, companyId),
+ getSupplierParts(client, itemId, companyId),
+ getPickMethods(client, itemId, companyId),
+ getTagsList(client, companyId, "material"),
]
);
@@ -56,7 +55,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return defer({
materialSummary: materialSummary.data,
- files: getItemFiles(serviceRole, itemId, companyId),
+ files: getItemFiles(client, itemId, companyId),
supplierParts: supplierParts.data ?? [],
pickMethods: pickMethods.data ?? [],
tags: tags.data ?? [],
diff --git a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
index a9e576ca41..b9a89a8916 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.manufacturing.tsx
@@ -16,7 +16,7 @@ import {
} from "@remix-run/react";
import type { LoaderFunctionArgs } from "@vercel/remix";
-import { error, getCarbonServiceRole } from "@carbon/auth";
+import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { FlatTreeItem } from "~/components/TreeView";
@@ -49,6 +49,7 @@ export const shouldRevalidate = ({
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
view: "parts",
+ bypassRls: true,
});
const { itemId } = params;
@@ -72,14 +73,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
await flash(request, error("Access denied"))
);
}
- const serviceRole = await getCarbonServiceRole();
const [methodTree, methodMaterials, methodOperations, partManufacturing] =
await Promise.all([
- getMethodTree(serviceRole, makeMethod.data.id),
- getMethodMaterialsByMakeMethod(serviceRole, makeMethod.data.id),
- getMethodOperationsByMakeMethodId(serviceRole, makeMethod.data.id),
- getItemManufacturing(serviceRole, itemId, companyId),
+ getMethodTree(client, makeMethod.data.id),
+ getMethodMaterialsByMakeMethod(client, makeMethod.data.id),
+ getMethodOperationsByMakeMethodId(client, makeMethod.data.id),
+ getItemManufacturing(client, itemId, companyId),
]);
if (methodTree?.error) {
throw redirect(
@@ -133,10 +133,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
partManufacturing: partManufacturing.data,
configurationParametersAndGroups: partManufacturing.data
?.requiresConfiguration
- ? await getConfigurationParameters(serviceRole, itemId, companyId)
+ ? await getConfigurationParameters(client, itemId, companyId)
: { groups: [], parameters: [] },
configurationRules: partManufacturing.data?.requiresConfiguration
- ? await getConfigurationRules(serviceRole, itemId, companyId)
+ ? await getConfigurationRules(client, itemId, companyId)
: [],
});
}
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx b/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx
new file mode 100644
index 0000000000..d5cf559b7b
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/webhooks.$id.tsx
@@ -0,0 +1,96 @@
+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 { useLoaderData, useNavigate } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import {
+ getWebhook,
+ upsertWebhook,
+ webhookValidator,
+} from "~/modules/settings";
+import { WebhookForm } from "~/modules/settings/ui/Webhooks";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const webhook = await getWebhook(client, id);
+ if (webhook.error) {
+ throw redirect(
+ path.to.webhooks,
+ await flash(request, error(webhook.error, "Failed to load webhook"))
+ );
+ }
+
+ return json({
+ webhook: webhook.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const validation = await validator(webhookValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateWebhook = await upsertWebhook(client, {
+ id,
+ ...validation.data,
+ });
+
+ if (updateWebhook.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateWebhook.error, "Failed to update webhook")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.webhooks}?${getParams(request)}`,
+ await flash(request, success("Updated webhook"))
+ );
+}
+
+export default function EditWebhookRoute() {
+ const navigate = useNavigate();
+ const { webhook } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: webhook?.id ?? undefined,
+ name: webhook?.name ?? "",
+ url: webhook?.url ?? "",
+ table: webhook?.table ?? "",
+ onInsert: webhook?.onInsert ?? false,
+ onUpdate: webhook?.onUpdate ?? false,
+ onDelete: webhook?.onDelete ?? false,
+ active: webhook?.active ?? false,
+ };
+
+ return (
+ <WebhookForm
+ key={initialValues.id}
+ initialValues={initialValues}
+ onClose={() => navigate(-1)}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx b/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx
new file mode 100644
index 0000000000..197eaec93f
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/webhooks.delete.$id.tsx
@@ -0,0 +1,79 @@
+import { error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { ConfirmDelete } from "~/components/Modals";
+import { deleteWebhook, getWebhook } from "~/modules/settings";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const { id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const webhook = await getWebhook(client, id);
+ if (webhook.error) {
+ throw redirect(
+ path.to.webhooks,
+ await flash(request, error(webhook.error, "Failed to load webhook"))
+ );
+ }
+
+ return json({
+ webhook: webhook.data,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ update: "users",
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw redirect(
+ path.to.itemPostingGroups,
+ await flash(request, error(params, "Failed to get an id"))
+ );
+ }
+
+ const { error: deleteWebhookError } = await deleteWebhook(client, id);
+ if (deleteWebhookError) {
+ throw redirect(
+ `${path.to.webhooks}?${getParams(request)}`,
+ await flash(
+ request,
+ error(deleteWebhookError, "Failed to delete webhook")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.webhooks}?${getParams(request)}`,
+ await flash(request, success("Successfully deleted webhook"))
+ );
+}
+
+export default function DeleteWebhookRoute() {
+ const { webhook } = useLoaderData<typeof loader>();
+
+ const { id } = useParams();
+ if (!id) throw new Error("Could not find id");
+
+ const navigate = useNavigate();
+ const onCancel = () => navigate(-1);
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteWebhook(id)}
+ name={webhook.name}
+ text={`Are you sure you want to delete the webhook: ${webhook.name}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.new.tsx b/apps/erp/app/routes/x+/settings+/webhooks.new.tsx
new file mode 100644
index 0000000000..7647981be8
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/webhooks.new.tsx
@@ -0,0 +1,69 @@
+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 { useNavigate } from "@remix-run/react";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
+import { upsertWebhook, webhookValidator } from "~/modules/settings";
+import { WebhookForm } from "~/modules/settings/ui/Webhooks";
+import { getParams, path } from "~/utils/path";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ view: "settings",
+ });
+
+ return null;
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(webhookValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const createWebhook = await upsertWebhook(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+ if (createWebhook.error) {
+ return json(
+ {},
+ await flash(
+ request,
+ error(createWebhook.error, "Failed to create webhook")
+ )
+ );
+ }
+
+ throw redirect(
+ `${path.to.webhooks}?${getParams(request)}`,
+ await flash(request, success("Created webhook"))
+ );
+}
+
+export default function NewWebhookRoute() {
+ const navigate = useNavigate();
+ const initialValues = {
+ name: "",
+ url: "",
+ table: "",
+ onInsert: false,
+ onUpdate: false,
+ onDelete: false,
+ active: false,
+ };
+
+ return (
+ <WebhookForm initialValues={initialValues} onClose={() => navigate(-1)} />
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.tsx b/apps/erp/app/routes/x+/settings+/webhooks.tsx
new file mode 100644
index 0000000000..8dbcc841eb
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/webhooks.tsx
@@ -0,0 +1,56 @@
+import { error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import { json, redirect, type LoaderFunctionArgs } from "@vercel/remix";
+import { getWebhooks } from "~/modules/settings";
+import { WebhooksTable } from "~/modules/settings/ui/Webhooks";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+export const handle: Handle = {
+ breadcrumb: "Webhooks",
+ to: path.to.webhooks,
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const search = searchParams.get("search");
+ const { limit, offset, sorts, filters } =
+ getGenericQueryFilters(searchParams);
+
+ const webhooks = await getWebhooks(client, companyId, {
+ limit,
+ offset,
+ sorts,
+ search,
+ filters,
+ });
+ if (webhooks.error) {
+ throw redirect(
+ path.to.settings,
+ await flash(request, error(webhooks.error, "Failed to load webhooks"))
+ );
+ }
+
+ return json({
+ webhooks: webhooks.data ?? [],
+ count: webhooks.count ?? 0,
+ });
+}
+
+export default function WebhooksRoute() {
+ const { webhooks, count } = useLoaderData<typeof loader>();
+ return (
+ <>
+ <WebhooksTable count={count} data={webhooks} />
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 403a8b18b7..fe580c6b1a 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -75,6 +75,7 @@ export const path = {
tags: (table?: string) =>
generatePath(`${api}/shared/tags?table=${table}`),
unitOfMeasures: `${api}/items/uoms`,
+ webhookTables: `${api}/webhook/tables`,
workCentersByLocation: (id: string) =>
generatePath(`${api}/resources/work-centers?location=${id}`),
workCenters: `${api}/resources/work-centers`,
@@ -377,6 +378,8 @@ export const path = {
deleteUom: (id: string) => generatePath(`${x}/items/uom/delete/${id}`),
deleteUserAttribute: (id: string) =>
generatePath(`${x}/account/${id}/delete/attribute`),
+ deleteWebhook: (id: string) =>
+ generatePath(`${x}/settings/webhooks/delete/${id}`),
deleteWorkCenter: (id: string) =>
generatePath(`${x}/resources/work-centers/delete/${id}`),
department: (id: string) => generatePath(`${x}/people/departments/${id}`),
@@ -618,6 +621,7 @@ export const path = {
generatePath(`${x}/tool/${id}/purchasing/new`),
newUom: `${x}/items/uom/new`,
newWorkCenter: `${x}/resources/work-centers/new`,
+ newWebhook: `${x}/settings/webhooks/new`,
noQuoteReasons: `${x}/sales/no-quote-reasons`,
noQuoteReason: (id: string) =>
generatePath(`${x}/sales/no-quote-reasons/${id}`),
@@ -926,6 +930,8 @@ export const path = {
uoms: `${x}/items/uom`,
userAttribute: (id: string) => generatePath(`${x}/account/${id}/attribute`),
users: `${x}/users`,
+ webhook: (id: string) => generatePath(`${x}/settings/webhooks/${id}`),
+ webhooks: `${x}/settings/webhooks`,
workCenters: `${x}/resources/work-centers`,
workCenter: (id: string) =>
generatePath(`${x}/resources/work-centers/${id}`),
diff --git a/apps/erp/app/utils/react-query.ts b/apps/erp/app/utils/react-query.ts
index 253fd95205..a96e9aad98 100644
--- a/apps/erp/app/utils/react-query.ts
+++ b/apps/erp/app/utils/react-query.ts
@@ -86,6 +86,11 @@ export const uomsQuery = (companyId: string | null) => ({
staleTime: RefreshRate.Medium,
});
+export const webhookTablesQuery = () => ({
+ queryKey: ["webhookTables"],
+ staleTime: RefreshRate.Never,
+});
+
export const workCentersQuery = (companyId: string | null) => ({
queryKey: ["workCenters", companyId ?? "null"],
staleTime: RefreshRate.Low,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2c9bd3c146..36da23634d 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -25411,6 +25411,108 @@ export type Database = {
},
]
}
+ webhook: {
+ Row: {
+ active: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ onDelete: boolean
+ onInsert: boolean
+ onUpdate: boolean
+ table: string
+ updatedAt: string | null
+ updatedBy: string | null
+ url: string
+ }
+ Insert: {
+ active?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ onDelete?: boolean
+ onInsert?: boolean
+ onUpdate?: boolean
+ table: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ url: string
+ }
+ Update: {
+ active?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ onDelete?: boolean
+ onInsert?: boolean
+ onUpdate?: boolean
+ table?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ url?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "webhook_table_fkey"
+ columns: ["table"]
+ isOneToOne: false
+ referencedRelation: "webhookTable"
+ referencedColumns: ["table"]
+ },
+ ]
+ }
+ webhookTable: {
+ Row: {
+ module: Database["public"]["Enums"]["module"]
+ name: string
+ table: string
+ }
+ Insert: {
+ module: Database["public"]["Enums"]["module"]
+ name: string
+ table: string
+ }
+ Update: {
+ module?: Database["public"]["Enums"]["module"]
+ name?: string
+ table?: string
+ }
+ Relationships: []
+ }
workCenter: {
Row: {
active: boolean
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2c9bd3c146..36da23634d 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -25411,6 +25411,108 @@ export type Database = {
},
]
}
+ webhook: {
+ Row: {
+ active: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string
+ id: string
+ name: string
+ onDelete: boolean
+ onInsert: boolean
+ onUpdate: boolean
+ table: string
+ updatedAt: string | null
+ updatedBy: string | null
+ url: string
+ }
+ Insert: {
+ active?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ id?: string
+ name: string
+ onDelete?: boolean
+ onInsert?: boolean
+ onUpdate?: boolean
+ table: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ url: string
+ }
+ Update: {
+ active?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ id?: string
+ name?: string
+ onDelete?: boolean
+ onInsert?: boolean
+ onUpdate?: boolean
+ table?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ url?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "webhook_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "webhook_table_fkey"
+ columns: ["table"]
+ isOneToOne: false
+ referencedRelation: "webhookTable"
+ referencedColumns: ["table"]
+ },
+ ]
+ }
+ webhookTable: {
+ Row: {
+ module: Database["public"]["Enums"]["module"]
+ name: string
+ table: string
+ }
+ Insert: {
+ module: Database["public"]["Enums"]["module"]
+ name: string
+ table: string
+ }
+ Update: {
+ module?: Database["public"]["Enums"]["module"]
+ name?: string
+ table?: string
+ }
+ Relationships: []
+ }
workCenter: {
Row: {
active: boolean
diff --git a/packages/database/supabase/migrations/20250203121216_webhooks.sql b/packages/database/supabase/migrations/20250203121216_webhooks.sql
new file mode 100644
index 0000000000..0e6878cfc5
--- /dev/null
+++ b/packages/database/supabase/migrations/20250203121216_webhooks.sql
@@ -0,0 +1,89 @@
+CREATE TABLE "webhookTable" (
+ "table" TEXT NOT NULL,
+ "module" module NOT NULL,
+ "name" TEXT NOT NULL,
+
+ CONSTRAINT "webhookTable_pkey" PRIMARY KEY ("table"),
+ CONSTRAINT "webhookTable_name_key" UNIQUE ("name")
+);
+
+ALTER TABLE "webhookTable" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "SELECT" ON "webhookTable"
+FOR SELECT
+USING (
+ auth.role() = 'authenticated'
+);
+
+INSERT INTO "webhookTable" ("table", "module", "name") VALUES
+('quote', 'Sales', 'Quote'),
+('salesOrder', 'Sales', 'Sales Order'),
+('salesRfq', 'Sales', 'Sales RFQ');
+
+
+CREATE TABLE "webhook" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "name" TEXT NOT NULL,
+ "table" TEXT NOT NULL,
+ "url" TEXT NOT NULL,
+ "active" BOOLEAN NOT NULL DEFAULT TRUE,
+ "onInsert" BOOLEAN NOT NULL DEFAULT FALSE,
+ "onUpdate" BOOLEAN NOT NULL DEFAULT FALSE,
+ "onDelete" BOOLEAN NOT NULL DEFAULT FALSE,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "webhook_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "webhook_table_fkey" FOREIGN KEY ("table") REFERENCES "webhookTable"("table") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "webhook_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+ALTER TABLE "webhook" ENABLE ROW LEVEL SECURITY;
+
+
+CREATE POLICY "SELECT" ON "public"."webhook"
+FOR SELECT
+USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('settings_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."webhook"
+FOR INSERT
+WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('settings_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."webhook"
+FOR UPDATE
+USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('settings_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."webhook"
+FOR DELETE
+USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('settings_delete')
+ )::text[]
+ )
+);
\ No newline at end of file