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: Audit logs (#500)

Sid71a2ce6d5c16
diff --git a/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx
new file mode 100644
index 0000000000..92562831fb
--- /dev/null
+++ b/apps/erp/app/components/AuditLog/AuditLogDrawer.tsx
@@ -0,0 +1,232 @@
+import { getTableLabel } from "@carbon/database/audit.config";
+import type { AuditLogEntry } from "@carbon/database/audit.types";
+import {
+ Badge,
+ cn,
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle,
+ HStack,
+ Skeleton,
+ VStack
+} from "@carbon/react";
+import { formatDateTime } from "@carbon/utils";
+import { memo, useEffect, useRef } from "react";
+import { LuFilePen, LuFilePlus, LuFileX, LuHistory } from "react-icons/lu";
+import { useFetcher } from "react-router";
+import { EmployeeAvatar, Empty } from "~/components";
+
+type AuditLogDrawerProps = {
+ isOpen: boolean;
+ onClose: () => void;
+ entityType: string;
+ entityId: string;
+ companyId: string;
+};
+
+type AuditLogFetcherData = {
+ entries: AuditLogEntry[];
+};
+
+const operationLabels: Record<
+ string,
+ { label: string; variant: "green" | "blue" | "red"; icon: React.ReactNode }
+> = {
+ INSERT: {
+ label: "Created",
+ variant: "green",
+ icon: <LuFilePlus className="size-3" />
+ },
+ UPDATE: {
+ label: "Updated",
+ variant: "blue",
+ icon: <LuFilePen className="size-3" />
+ },
+ DELETE: {
+ label: "Deleted",
+ variant: "red",
+ icon: <LuFileX className="size-3" />
+ }
+};
+
+const AuditLogDrawer = memo(
+ ({
+ isOpen,
+ onClose,
+ entityType,
+ entityId,
+ companyId
+ }: AuditLogDrawerProps) => {
+ const fetcher = useFetcher<AuditLogFetcherData>();
+ const lastLoadedRef = useRef<string | null>(null);
+ const loadKey = `${entityType}:${entityId}:${companyId}`;
+
+ // Load audit log data when drawer opens or entity changes
+ useEffect(() => {
+ if (
+ isOpen &&
+ entityType &&
+ entityId &&
+ fetcher.state === "idle" &&
+ lastLoadedRef.current !== loadKey
+ ) {
+ lastLoadedRef.current = loadKey;
+ const params = new URLSearchParams({
+ entityType,
+ entityId,
+ companyId
+ });
+ fetcher.load(`/api/audit-log?${params.toString()}`);
+ }
+ }, [isOpen, entityType, entityId, companyId, loadKey, fetcher]);
+
+ // Reset tracking when drawer closes so it re-fetches on next open
+ useEffect(() => {
+ if (!isOpen) {
+ lastLoadedRef.current = null;
+ }
+ }, [isOpen]);
+
+ const entries = fetcher.data?.entries ?? [];
+ const isLoading = fetcher.state === "loading";
+
+ return (
+ <Drawer
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DrawerContent size="lg" position="left">
+ <DrawerHeader>
+ <DrawerTitle className="flex items-center gap-2">
+ <LuHistory className="size-5" />
+ History
+ </DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody>
+ {isLoading ? (
+ <VStack spacing={3}>
+ <Skeleton className="w-full h-[151px]" />
+ <Skeleton className="w-full h-[151px]" />
+ </VStack>
+ ) : entries.length === 0 ? (
+ <Empty />
+ ) : (
+ <VStack spacing={3}>
+ {entries.map((entry) => (
+ <AuditLogEntryCard key={entry.id} entry={entry} />
+ ))}
+ </VStack>
+ )}
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+ }
+);
+
+AuditLogDrawer.displayName = "AuditLogDrawer";
+export default AuditLogDrawer;
+
+type AuditLogEntryCardProps = {
+ entry: AuditLogEntry;
+};
+
+const AuditLogEntryCard = memo(({ entry }: AuditLogEntryCardProps) => {
+ const opInfo = operationLabels[entry.operation] ?? {
+ label: entry.operation,
+ variant: "secondary" as const,
+ icon: null
+ };
+
+ const diffKeys = entry.diff ? Object.keys(entry.diff) : [];
+
+ return (
+ <div className="border bg-muted/40 rounded-lg p-4 w-full">
+ <HStack className="justify-between items-start mb-3">
+ <VStack spacing={1}>
+ {entry.actorId ? (
+ <EmployeeAvatar employeeId={entry.actorId} />
+ ) : (
+ <span className="font-medium">System</span>
+ )}
+ <span
+ className={cn(
+ "text-xs text-muted-foreground",
+ entry.actorId && "pl-8"
+ )}
+ >
+ {formatDateTime(entry.createdAt)}
+ </span>
+ </VStack>
+ <VStack spacing={1} className="items-end">
+ <Badge variant={opInfo.variant} className="flex-shrink-0">
+ <HStack className="gap-1">
+ {opInfo.icon}
+ <span>{opInfo.label}</span>
+ </HStack>
+ </Badge>
+ <span className="text-xs text-muted-foreground">
+ {getTableLabel(entry.tableName)}
+ </span>
+ </VStack>
+ </HStack>
+
+ <div className="mt-3 pt-3 border-t">
+ <p className="text-sm font-medium mb-2">Changes</p>
+ {diffKeys.length > 0 ? (
+ <div className="space-y-1">
+ {diffKeys.map((key) => {
+ const change = entry.diff![key];
+ return (
+ <div
+ key={key}
+ className="flex items-center gap-2 font-mono text-sm py-1"
+ >
+ <span className="text-muted-foreground font-medium min-w-[120px]">
+ {key}:
+ </span>
+ {change.old !== undefined && (
+ <span className="px-2 py-0.5 rounded bg-red-500/10 text-red-500">
+ {formatValue(change.old)}
+ </span>
+ )}
+ {change.old !== undefined && change.new !== undefined && (
+ <span className="text-muted-foreground">→</span>
+ )}
+ {change.new !== undefined && (
+ <span className="px-2 py-0.5 rounded bg-green-500/10 text-green-500">
+ {formatValue(change.new)}
+ </span>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground italic">
+ {entry.operation === "INSERT"
+ ? "New record created"
+ : entry.operation === "DELETE"
+ ? "Record deleted"
+ : "No changes recorded"}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+});
+
+AuditLogEntryCard.displayName = "AuditLogEntryCard";
+
+function formatValue(value: unknown): string {
+ if (value === null) return "null";
+ if (value === undefined) return "undefined";
+ if (typeof value === "string") return value;
+ if (typeof value === "number" || typeof value === "boolean")
+ return String(value);
+ return JSON.stringify(value);
+}
diff --git a/apps/erp/app/components/AuditLog/index.ts b/apps/erp/app/components/AuditLog/index.ts
new file mode 100644
index 0000000000..612c657863
--- /dev/null
+++ b/apps/erp/app/components/AuditLog/index.ts
@@ -0,0 +1 @@
+export { default as AuditLogDrawer } from "./AuditLogDrawer";
diff --git a/apps/erp/app/components/Chat/PromptInput.tsx b/apps/erp/app/components/Chat/PromptInput.tsx
index 94354b638c..64e1d4bd7a 100644
--- a/apps/erp/app/components/Chat/PromptInput.tsx
+++ b/apps/erp/app/components/Chat/PromptInput.tsx
@@ -37,7 +37,7 @@ import {
useRef,
useState
} from "react";
-import { LuPaperclip, LuPlus, LuSend, LuSquare, LuX } from "react-icons/lu";
+import { LuArrowUp, LuPaperclip, LuPlus, LuSquare, LuX } from "react-icons/lu";
type AttachmentsContextType = {
files: (FileUIPart & { id: string })[];
@@ -606,7 +606,7 @@ export const PromptInputSubmit = ({
children,
...props
}: PromptInputSubmitProps) => {
- let Icon = <LuSend />;
+ let Icon = <LuArrowUp />;
if (status === "streaming") {
Icon = <LuSquare />;
diff --git a/apps/erp/app/components/Form/AddressAutocomplete.tsx b/apps/erp/app/components/Form/AddressAutocomplete.tsx
index d5e85936e0..36944e7997 100644
--- a/apps/erp/app/components/Form/AddressAutocomplete.tsx
+++ b/apps/erp/app/components/Form/AddressAutocomplete.tsx
@@ -157,6 +157,7 @@ const AddressAutocomplete = ({
onFocus={handleInputFocus}
onKeyDown={handleKeyDown}
autoComplete="off"
+ className="bg-transparent"
/>
{open && suggestions.length > 0 && (
<CommandList className="absolute w-full top-10 z-[9999] rounded-md border bg-popover text-popover-foreground shadow-md p-0">
diff --git a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
index 390ac03abb..5059fa47f8 100644
--- a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
+++ b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
@@ -39,6 +39,8 @@ export function CollapsibleSidebarProvider({ children }: PropsWithChildren) {
useEffect(() => {
if (isMobile) {
setSidebarOpen(false);
+ } else {
+ setSidebarOpen(true);
}
}, [isMobile, setSidebarOpen]);
diff --git a/apps/erp/app/components/Table/Table.tsx b/apps/erp/app/components/Table/Table.tsx
index f33493bcad..2a58dfb428 100644
--- a/apps/erp/app/components/Table/Table.tsx
+++ b/apps/erp/app/components/Table/Table.tsx
@@ -39,11 +39,20 @@ import {
useReactTable
} from "@tanstack/react-table";
import type { CSSProperties, ReactElement, ReactNode } from "react";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ Fragment,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
import {
LuArrowDown,
LuArrowUp,
LuArrowUpDown,
+ LuChevronDown,
+ LuChevronRight,
LuHash,
LuSigma,
LuTrendingUpDown,
@@ -95,6 +104,7 @@ interface TableProps<T extends object> {
onSelectedRowsChange?: (selectedRows: T[]) => void;
renderActions?: (selectedRows: T[]) => ReactNode;
renderContextMenu?: (row: T) => JSX.Element | null;
+ renderExpandedRow?: (row: T) => ReactNode;
}
type AggregateFunction = "sum" | "average" | "min" | "max" | "median" | "count";
@@ -228,12 +238,23 @@ const Table = <T extends object>({
withSimpleSorting = true,
onSelectedRowsChange,
renderActions,
- renderContextMenu
+ renderContextMenu,
+ renderExpandedRow
}: TableProps<T>) => {
const tableContainerRef = useRef<HTMLDivElement>(null);
const { currentView, view } = useSavedViews();
+ /* Expandable Rows */
+ const [expandedRows, setExpandedRows] = useState<Record<number, boolean>>({});
+
+ const toggleRowExpanded = useCallback((rowIndex: number) => {
+ setExpandedRows((prev) => ({
+ ...prev,
+ [rowIndex]: !prev[rowIndex]
+ }));
+ }, []);
+
/* Data for Optimistic Updates */
const [internalData, setInternalData] = useState<T[]>(data);
useEffect(() => {
@@ -267,6 +288,9 @@ const Table = <T extends object>({
const [columnPinning, setColumnPinning] = useState<ColumnPinningState>(() => {
const left: string[] = [];
const right: string[] = [];
+ if (renderExpandedRow) {
+ left.push("Expand");
+ }
if (withSelectableRows) {
left.push("Select");
}
@@ -311,6 +335,9 @@ const Table = <T extends object>({
setColumnPinning(() => {
const left: string[] = [];
const right: string[] = [];
+ if (renderExpandedRow) {
+ left.push("Expand");
+ }
if (withSelectableRows) {
left.push("Select");
}
@@ -366,6 +393,9 @@ const Table = <T extends object>({
const internalColumns = useMemo(() => {
let result: ColumnDef<T>[] = [];
+ if (renderExpandedRow) {
+ result.push(...getExpandColumn<T>(expandedRows, toggleRowExpanded));
+ }
if (withSelectableRows) {
result.push(...getRowSelectionColumn<T>());
}
@@ -374,7 +404,14 @@ const Table = <T extends object>({
result.push(...getActionColumn<T>(renderContextMenu));
}
return result;
- }, [columns, renderContextMenu, withSelectableRows]);
+ }, [
+ columns,
+ renderContextMenu,
+ withSelectableRows,
+ renderExpandedRow,
+ expandedRows,
+ toggleRowExpanded
+ ]);
const table = useReactTable({
data: internalData,
@@ -1002,7 +1039,12 @@ const Table = <T extends object>({
</Thead>
<Tbody>
{rows.map((row) => {
- return renderContextMenu ? (
+ const isRowExpanded =
+ renderExpandedRow && expandedRows[row.index];
+ const handleRowClick = renderExpandedRow
+ ? () => toggleRowExpanded(row.index)
+ : undefined;
+ const rowContent = renderContextMenu ? (
<Menu type="context" key={row.index}>
<ContextMenu>
<ContextMenuTrigger asChild>
@@ -1021,6 +1063,10 @@ const Table = <T extends object>({
getPinnedStyles={getPinnedStyles}
onCellClick={onCellClick}
onCellUpdate={onCellUpdate}
+ onClick={handleRowClick}
+ className={
+ renderExpandedRow ? "cursor-pointer" : undefined
+ }
/>
</ContextMenuTrigger>
<ContextMenuContent className="w-128">
@@ -1044,8 +1090,28 @@ const Table = <T extends object>({
getPinnedStyles={getPinnedStyles}
onCellClick={onCellClick}
onCellUpdate={onCellUpdate}
+ onClick={handleRowClick}
+ className={
+ renderExpandedRow ? "cursor-pointer" : undefined
+ }
/>
);
+
+ return (
+ <Fragment key={row.id}>
+ {rowContent}
+ {isRowExpanded && (
+ <Tr>
+ <Td
+ colSpan={visibleColumns.length}
+ className="p-0 bg-muted/20 border-b border-border"
+ >
+ {renderExpandedRow(row.original)}
+ </Td>
+ </Tr>
+ )}
+ </Fragment>
+ );
})}
{table.getFooterGroups().map((footerGroup) => (
<Tr key={footerGroup.id} className="h-10">
@@ -1147,4 +1213,38 @@ function getActionColumn<T>(
];
}
+function getExpandColumn<T>(
+ expandedRows: Record<number, boolean>,
+ toggleRowExpanded: (rowIndex: number) => void
+): ColumnDef<T>[] {
+ return [
+ {
+ id: "Expand",
+ size: 40,
+ enablePinning: true,
+ header: () => <span className="sr-only">Expand</span>,
+ cell: ({ row }) => {
+ const isExpanded = expandedRows[row.index] ?? false;
+ return (
+ <button
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ toggleRowExpanded(row.index);
+ }}
+ className="p-1 hover:bg-muted rounded transition-colors text-muted-foreground hover:text-foreground"
+ aria-label={isExpanded ? "Collapse row" : "Expand row"}
+ >
+ {isExpanded ? (
+ <LuChevronDown className="size-4" />
+ ) : (
+ <LuChevronRight className="size-4" />
+ )}
+ </button>
+ );
+ }
+ }
+ ];
+}
+
export default Table;
diff --git a/apps/erp/app/components/Table/components/Row.tsx b/apps/erp/app/components/Table/components/Row.tsx
index 7d0a3672c8..b684e2f02c 100644
--- a/apps/erp/app/components/Table/components/Row.tsx
+++ b/apps/erp/app/components/Table/components/Row.tsx
@@ -38,6 +38,7 @@ const Row = <T extends object>({
getPinnedStyles,
onCellClick,
onCellUpdate,
+ className,
...props
}: RowProps<T>) => {
const onUpdate = isEditMode ? onCellUpdate(row.index) : undefined;
@@ -47,7 +48,8 @@ const Row = <T extends object>({
key={row.id}
className={cn(
"border-b border-border transition-colors",
- isFrozenColumn && "bg-card"
+ isFrozenColumn && "bg-card",
+ className
)}
{...props}
>
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
index 444440f351..0c6addaa70 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoiceHeader.tsx
@@ -8,6 +8,7 @@ import {
DropdownMenuItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -15,22 +16,24 @@ import {
useDisclosure
} from "@carbon/react";
import { getItemReadableId } from "@carbon/utils";
-import { useEffect, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import { flushSync } from "react-dom";
import {
LuCheckCheck,
LuChevronDown,
LuEllipsisVertical,
LuHandCoins,
+ LuHistory,
LuPanelLeft,
LuPanelRight,
LuShoppingCart,
LuTrash
} from "react-icons/lu";
-import { Link, useFetcher, useParams } from "react-router";
+import { Await, Link, useFetcher, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { usePanels } from "~/components/Layout/Panels";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import type { PurchaseInvoice, PurchaseInvoiceLine } from "~/modules/invoicing";
import { PurchaseInvoicingStatus } from "~/modules/invoicing";
import type { action as statusAction } from "~/routes/x+/purchase-invoice+/$invoiceId.status";
@@ -41,8 +44,10 @@ import PurchaseInvoicePostModal from "./PurchaseInvoicePostModal";
const PurchaseInvoiceHeader = () => {
const permissions = usePermissions();
const { invoiceId } = useParams();
+ const { company } = useUser();
const postingModal = useDisclosure();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const statusFetcher = useFetcher<typeof statusAction>();
const { carbon } = useCarbon();
@@ -68,6 +73,10 @@ const PurchaseInvoiceHeader = () => {
const { toggleExplorer, toggleProperties } = usePanels();
const isPosted = purchaseInvoice.postingDate !== null;
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const [relatedDocs, setRelatedDocs] = useState<{
purchaseOrders: { id: string; readableId: string }[];
receipts: { id: string; readableId: string }[];
@@ -171,6 +180,23 @@ const PurchaseInvoiceHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "invoicing") ||
@@ -338,6 +364,13 @@ const PurchaseInvoiceHeader = () => {
}}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="purchaseInvoice"
+ entityId={invoiceId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
index 6f6d692166..4211daed89 100644
--- a/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
+++ b/apps/erp/app/modules/invoicing/ui/SalesInvoice/SalesInvoiceHeader.tsx
@@ -15,23 +15,26 @@ import {
useDisclosure
} from "@carbon/react";
import { getItemReadableId } from "@carbon/utils";
-import { useEffect, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import { flushSync } from "react-dom";
import {
LuCheckCheck,
LuChevronDown,
LuDollarSign,
+ LuEllipsisVertical,
LuEye,
LuFile,
+ LuHistory,
LuPanelLeft,
LuPanelRight,
LuTicketX,
LuTruck
} from "react-icons/lu";
import { RiProgress8Line } from "react-icons/ri";
-import { Link, useFetcher, useParams } from "react-router";
+import { Await, Link, useFetcher, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { usePanels } from "~/components/Layout/Panels";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import type { SalesInvoice, SalesInvoiceLine } from "~/modules/invoicing";
import { salesInvoiceStatusType } from "~/modules/invoicing";
@@ -46,8 +49,10 @@ import SalesInvoiceVoidModal from "./SalesInvoiceVoidModal";
const SalesInvoiceHeader = () => {
const permissions = usePermissions();
const { invoiceId } = useParams();
+ const { company } = useUser();
const postingModal = useDisclosure();
const voidModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const postFetcher = useFetcher<typeof action>();
const statusFetcher = useFetcher<typeof statusAction>();
@@ -76,6 +81,10 @@ const SalesInvoiceHeader = () => {
const isPosted = salesInvoice.postingDate !== null;
const isVoided = salesInvoice.status === "Voided";
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const [relatedDocs, setRelatedDocs] = useState<{
salesOrders: { id: string; readableId: string }[];
shipments: { id: string; readableId: string; status: string }[];
@@ -171,6 +180,34 @@ const SalesInvoiceHeader = () => {
</Heading>
</Link>
<Copy text={routeData?.salesInvoice?.invoiceId ?? ""} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More options"
+ icon={<LuEllipsisVertical />}
+ variant="secondary"
+ size="sm"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ </DropdownMenuContent>
+ </DropdownMenu>
<SalesInvoiceStatus status={salesInvoice.status} />
</HStack>
<HStack>
@@ -350,6 +387,13 @@ const SalesInvoiceHeader = () => {
{voidModal.isOpen && (
<SalesInvoiceVoidModal onClose={voidModal.onClose} />
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="salesInvoice"
+ entityId={invoiceId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
index 77596a32dd..5d2d59c588 100644
--- a/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Consumables/ConsumableHeader.tsx
@@ -4,6 +4,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -11,11 +12,13 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";
-import { Link, useParams } from "react-router";
+import { Suspense } from "react";
+import { LuEllipsisVertical, LuHistory, LuTrash } from "react-icons/lu";
+import { Await, Link, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { DetailsTopbar } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { Consumable } from "../../types";
import { useConsumableNavigation } from "./useConsumableNavigation";
@@ -25,13 +28,19 @@ const ConsumableHeader = () => {
const { itemId } = useParams();
if (!itemId) throw new Error("itemId not found");
+ const { company } = useUser();
const permissions = usePermissions();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ consumableSummary: Consumable }>(
path.to.consumable(itemId)
);
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
<VStack spacing={0} className="flex-grow">
@@ -54,6 +63,23 @@ const ConsumableHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "parts") ||
@@ -88,6 +114,15 @@ const ConsumableHeader = () => {
}}
/>
)}
+ {auditDrawer.isOpen && company?.id && (
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="item"
+ entityId={itemId}
+ companyId={company.id}
+ />
+ )}
</div>
);
};
diff --git a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
index c033d7818a..8f5ca9d208 100644
--- a/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Materials/MaterialHeader.tsx
@@ -4,6 +4,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -11,11 +12,13 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";
-import { Link, useParams } from "react-router";
+import { Suspense } from "react";
+import { LuEllipsisVertical, LuHistory, LuTrash } from "react-icons/lu";
+import { Await, Link, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { DetailsTopbar } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { Material } from "../../types";
import { useMaterialNavigation } from "./useMaterialNavigation";
@@ -25,13 +28,19 @@ const MaterialHeader = () => {
const { itemId } = useParams();
if (!itemId) throw new Error("itemId not found");
+ const { company } = useUser();
const permissions = usePermissions();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ materialSummary: Material }>(
path.to.material(itemId)
);
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
<VStack spacing={0} className="flex-grow">
@@ -55,6 +64,23 @@ const MaterialHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "parts") ||
@@ -89,6 +115,15 @@ const MaterialHeader = () => {
}}
/>
)}
+ {auditDrawer.isOpen && company?.id && (
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="item"
+ entityId={itemId}
+ companyId={company.id}
+ />
+ )}
</div>
);
};
diff --git a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
index f912bbeac2..ff522b3c21 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartHeader.tsx
@@ -4,6 +4,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -11,11 +12,13 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";
-import { Link, useParams } from "react-router";
+import { Suspense } from "react";
+import { LuEllipsisVertical, LuHistory, LuTrash } from "react-icons/lu";
+import { Await, Link, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { DetailsTopbar } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { PartSummary } from "../../types";
import { usePartNavigation } from "./usePartNavigation";
@@ -25,13 +28,19 @@ const PartHeader = () => {
const { itemId } = useParams();
if (!itemId) throw new Error("itemId not found");
+ const { company } = useUser();
const permissions = usePermissions();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ partSummary: PartSummary }>(
path.to.part(itemId)
);
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
<VStack spacing={0} className="flex-grow">
@@ -53,6 +62,23 @@ const PartHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "parts") ||
@@ -85,6 +111,13 @@ const PartHeader = () => {
}}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="item"
+ entityId={itemId}
+ companyId={company.id}
+ />
</div>
);
};
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
index 24ed5359fc..503a24c8b4 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolHeader.tsx
@@ -4,6 +4,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -11,11 +12,13 @@ import {
useDisclosure,
VStack
} from "@carbon/react";
-import { LuEllipsisVertical, LuTrash } from "react-icons/lu";
-import { Link, useParams } from "react-router";
+import { Suspense } from "react";
+import { LuEllipsisVertical, LuHistory, LuTrash } from "react-icons/lu";
+import { Await, Link, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { DetailsTopbar } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { Tool } from "../../types";
import { useToolNavigation } from "./useToolNavigation";
@@ -25,11 +28,17 @@ const ToolHeader = () => {
const { itemId } = useParams();
if (!itemId) throw new Error("itemId not found");
+ const { company } = useUser();
const permissions = usePermissions();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ toolSummary: Tool }>(path.to.tool(itemId));
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border h-[50px] overflow-x-auto scrollbar-hide dark:border-none dark:shadow-[inset_0_0_1px_rgb(255_255_255_/_0.24),_0_0_0_0.5px_rgb(0,0,0,1),0px_0px_4px_rgba(0,_0,_0,_0.08)]">
<VStack spacing={0} className="flex-grow">
@@ -51,6 +60,23 @@ const ToolHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "parts") ||
@@ -83,6 +109,15 @@ const ToolHeader = () => {
}}
/>
)}
+ {auditDrawer.isOpen && company?.id && (
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="item"
+ entityId={itemId}
+ companyId={company.id}
+ />
+ )}
</div>
);
};
diff --git a/apps/erp/app/modules/people/ui/Person/PersonPreview.tsx b/apps/erp/app/modules/people/ui/Person/PersonPreview.tsx
index a1bd9bd224..8481b40d45 100644
--- a/apps/erp/app/modules/people/ui/Person/PersonPreview.tsx
+++ b/apps/erp/app/modules/people/ui/Person/PersonPreview.tsx
@@ -8,11 +8,14 @@ import {
CardDescription,
CardHeader,
CardTitle,
- HStack
+ HStack,
+ useDisclosure
} from "@carbon/react";
+// import { LuHistory } from "react-icons/lu";
import { useParams } from "react-router";
import { Avatar } from "~/components";
-import { useRouteData } from "~/hooks";
+import { AuditLogDrawer } from "~/components/AuditLog";
+import { useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type { EmployeeSummary } from "../../types";
@@ -20,54 +23,67 @@ const PersonHeader = () => {
const { personId } = useParams();
if (!personId) throw new Error("personId not found");
+ const { company } = useUser();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ employeeSummary: EmployeeSummary }>(
path.to.person(personId)
);
return (
- <Card>
- <HStack className="justify-between items-center p-6 pl-0">
- <CardHeader className="pt-0">
- <CardTitle className="text-2xl">
- {routeData?.employeeSummary?.name}
- </CardTitle>
- <CardDescription>{routeData?.employeeSummary?.title}</CardDescription>
- </CardHeader>
- <Avatar
- size="lg"
- name={routeData?.employeeSummary?.name ?? undefined}
- path={routeData?.employeeSummary?.avatarUrl}
- />
- </HStack>
- <CardContent>
- <CardAttributes>
- <CardAttribute>
- <CardAttributeLabel>Department</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.employeeSummary?.departmentName}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Location</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.employeeSummary?.locationName}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Manager</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.employeeSummary?.managerName}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Start Date</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.employeeSummary?.startDate}
- </CardAttributeValue>
- </CardAttribute>
- </CardAttributes>
- </CardContent>
- </Card>
+ <>
+ <Card>
+ <HStack className="justify-between items-center p-6 pl-0">
+ <CardHeader className="pt-0">
+ <CardTitle className="text-2xl">
+ {routeData?.employeeSummary?.name}
+ </CardTitle>
+ <CardDescription>
+ {routeData?.employeeSummary?.title}
+ </CardDescription>
+ </CardHeader>
+ <Avatar
+ size="lg"
+ name={routeData?.employeeSummary?.name ?? undefined}
+ path={routeData?.employeeSummary?.avatarUrl}
+ />
+ </HStack>
+ <CardContent>
+ <CardAttributes>
+ <CardAttribute>
+ <CardAttributeLabel>Department</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.employeeSummary?.departmentName}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Location</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.employeeSummary?.locationName}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Manager</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.employeeSummary?.managerName}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Start Date</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.employeeSummary?.startDate}
+ </CardAttributeValue>
+ </CardAttribute>
+ </CardAttributes>
+ </CardContent>
+ </Card>
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="employee"
+ entityId={personId}
+ companyId={company.id}
+ />
+ </>
);
};
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index 7267ca1c55..52ee36315f 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -36,7 +36,7 @@ import {
parseDate,
today
} from "@internationalized/date";
-import { useMemo, useState } from "react";
+import { Suspense, useMemo, useState } from "react";
import { flushSync } from "react-dom";
import {
LuCheckCheck,
@@ -48,6 +48,7 @@ import {
LuClipboardList,
LuClock,
LuEllipsisVertical,
+ LuHistory,
LuList,
LuLoaderCircle,
LuPackage,
@@ -63,13 +64,19 @@ import {
} from "react-icons/lu";
import { RiProgress8Line } from "react-icons/ri";
import type { FetcherWithComponents } from "react-router";
-import { Link, useFetcher, useNavigate, useParams } from "react-router";
+import { Await, Link, useFetcher, useNavigate, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { Location, Shelf } from "~/components/Form";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
import Select from "~/components/Select";
import SupplierAvatar from "~/components/SupplierAvatar";
-import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
+import {
+ useOptimisticLocation,
+ usePermissions,
+ useRouteData,
+ useUser
+} from "~/hooks";
import { path } from "~/utils/path";
import { jobCompleteValidator } from "../../production.models";
import type { Job } from "../../types";
@@ -81,6 +88,7 @@ const JobHeader = () => {
const { jobId } = useParams();
if (!jobId) throw new Error("jobId not found");
+ const { company } = useUser();
const location = useOptimisticLocation();
const { toggleExplorer, toggleProperties } = usePanels();
@@ -88,9 +96,14 @@ const JobHeader = () => {
const cancelModal = useDisclosure();
const completeModal = useDisclosure();
const deleteJobModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const statusFetcher = useFetcher<{}>();
const status = routeData?.job?.status;
@@ -147,6 +160,23 @@ const JobHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "production") ||
@@ -410,6 +440,13 @@ const JobHeader = () => {
}}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="productionJob"
+ entityId={jobId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
index ff311ac918..55e4e16aaa 100644
--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx
@@ -14,7 +14,7 @@ import {
SplitButton,
useDisclosure
} from "@carbon/react";
-import { useState } from "react";
+import { Suspense, useState } from "react";
import {
LuCheckCheck,
LuChevronDown,
@@ -25,6 +25,7 @@ import {
LuEye,
LuFile,
LuHandCoins,
+ LuHistory,
LuLoaderCircle,
LuPanelLeft,
LuPanelRight,
@@ -32,11 +33,12 @@ import {
LuTruck,
LuX
} from "react-icons/lu";
-import { Link, useFetcher, useParams } from "react-router";
+import { Await, Link, useFetcher, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { ReceiptStatus } from "~/modules/inventory/ui/Receipts";
import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
import PurchaseInvoicingStatus from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus";
@@ -56,6 +58,7 @@ const PurchaseOrderHeader = () => {
const { orderId } = useParams();
if (!orderId) throw new Error("orderId not found");
+ const { company } = useUser();
const { toggleExplorer, toggleProperties } = usePanels();
const routeData = useRouteData<{
@@ -88,9 +91,14 @@ const PurchaseOrderHeader = () => {
const finalizeDisclosure = useDisclosure();
const deleteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const [approvalDecision, setApprovalDecision] =
useState<ApprovalDecision | null>(null);
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const isOutsideProcessing =
routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing";
const hasShipments = shipments.length > 0;
@@ -130,6 +138,23 @@ const PurchaseOrderHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!permissions.can("delete", "purchasing") ||
@@ -538,6 +563,13 @@ const PurchaseOrderHeader = () => {
defaultCc={routeData?.defaultCc ?? []}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="purchaseOrder"
+ entityId={orderId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
index 9dbbc34173..278130b3f2 100644
--- a/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
+++ b/apps/erp/app/modules/purchasing/ui/Supplier/SupplierHeader.tsx
@@ -1,5 +1,6 @@
import { ValidatedForm } from "@carbon/form";
import {
+ Button,
Card,
CardAction,
CardAttribute,
@@ -10,16 +11,19 @@ import {
CardHeader,
CardTitle,
HStack,
+ useDisclosure,
VStack
} from "@carbon/react";
-import { useCallback } from "react";
-import { useFetcher, useParams } from "react-router";
+import { Suspense, useCallback } from "react";
+import { LuHistory } from "react-icons/lu";
+import { Await, useFetcher, useParams } from "react-router";
import { z } from "zod";
import { EmployeeAvatar } from "~/components";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { Enumerable } from "~/components/Enumerable";
import { Tags } from "~/components/Form";
import { useSupplierTypes } from "~/components/Form/SupplierType";
-import { useRouteData } from "~/hooks";
+import { useRouteData, useUser } from "~/hooks";
import type { SupplierDetail, SupplierStatus } from "~/modules/purchasing";
import type { action } from "~/routes/x+/settings+/tags";
import { path } from "~/utils/path";
@@ -29,11 +33,17 @@ const SupplierHeader = () => {
if (!supplierId) throw new Error("Could not find supplierId");
const fetcher = useFetcher<typeof action>();
+ const { company } = useUser();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{
supplier: SupplierDetail;
tags: { name: string }[];
}>(path.to.supplier(supplierId));
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const supplierTypes = useSupplierTypes();
const supplierType = supplierTypes?.find(
(type) => type.value === routeData?.supplier?.supplierTypeId
@@ -69,68 +79,89 @@ const SupplierHeader = () => {
);
return (
- <VStack>
- <Card>
- <HStack className="justify-between items-start">
- <CardHeader>
- <CardTitle>{routeData?.supplier?.name}</CardTitle>
- </CardHeader>
- <CardAction>
- {/* <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
- Supplier Details
- </Button> */}
- </CardAction>
- </HStack>
- <CardContent>
- <CardAttributes>
- <CardAttribute>
- <CardAttributeLabel>Status</CardAttributeLabel>
- <CardAttributeValue>
- {supplierStatus ? <Enumerable value={supplierStatus!} /> : "-"}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Type</CardAttributeLabel>
- <CardAttributeValue>
- {supplierType ? <Enumerable value={supplierType!} /> : "-"}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Account Manager</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.supplier?.accountManagerId ? (
- <EmployeeAvatar
- employeeId={routeData?.supplier?.accountManagerId ?? null}
- />
- ) : (
- "-"
- )}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeValue>
- <ValidatedForm
- defaultValues={{
- tags: routeData?.supplier?.tags ?? []
- }}
- validator={z.object({
- tags: z.array(z.string()).optional()
- })}
- className="w-full"
- >
- <Tags
- label="Tags"
- name="tags"
- availableTags={routeData?.tags ?? []}
- table="supplier"
- inline
- onChange={onUpdateTags}
- />
- </ValidatedForm>
- </CardAttributeValue>
- </CardAttribute>
+ <>
+ <VStack>
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>{routeData?.supplier?.name}</CardTitle>
+ </CardHeader>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <CardAction>
+ <Button
+ variant="secondary"
+ leftIcon={<LuHistory />}
+ onClick={auditDrawer.onOpen}
+ >
+ History
+ </Button>
+ </CardAction>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ </HStack>
+ <CardContent>
+ <CardAttributes>
+ <CardAttribute>
+ <CardAttributeLabel>Status</CardAttributeLabel>
+ <CardAttributeValue>
+ {supplierStatus ? (
+ <Enumerable value={supplierStatus!} />
+ ) : (
+ "-"
+ )}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Type</CardAttributeLabel>
+ <CardAttributeValue>
+ {supplierType ? <Enumerable value={supplierType!} /> : "-"}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Account Manager</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.supplier?.accountManagerId ? (
+ <EmployeeAvatar
+ employeeId={routeData?.supplier?.accountManagerId ?? null}
+ />
+ ) : (
+ "-"
+ )}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeValue>
+ <ValidatedForm
+ defaultValues={{
+ tags: routeData?.supplier?.tags ?? []
+ }}
+ validator={z.object({
+ tags: z.array(z.string()).optional()
+ })}
+ className="w-full"
+ >
+ <Tags
+ label="Tags"
+ name="tags"
+ availableTags={routeData?.tags ?? []}
+ table="supplier"
+ inline
+ onChange={onUpdateTags}
+ />
+ </ValidatedForm>
+ </CardAttributeValue>
+ </CardAttribute>
- {/* {permissions.is("employee") && (
+ {/* {permissions.is("employee") && (
<CardAttribute>
<CardAttributeLabel>Assignee</CardAttributeLabel>
<CardAttributeValue>
@@ -143,10 +174,18 @@ const SupplierHeader = () => {
</CardAttributeValue>
</CardAttribute>
)} */}
- </CardAttributes>
- </CardContent>
- </Card>
- </VStack>
+ </CardAttributes>
+ </CardContent>
+ </Card>
+ </VStack>
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="supplier"
+ entityId={supplierId}
+ companyId={company.id}
+ />
+ </>
);
};
diff --git a/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx b/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
index 1da201d96a..c7abba1f1f 100644
--- a/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Customer/CustomerHeader.tsx
@@ -1,5 +1,6 @@
import { ValidatedForm } from "@carbon/form";
import {
+ Button,
Card,
CardAction,
CardAttribute,
@@ -10,16 +11,19 @@ import {
CardHeader,
CardTitle,
HStack,
+ useDisclosure,
VStack
} from "@carbon/react";
-import { useCallback } from "react";
-import { useFetcher, useParams } from "react-router";
+import { Suspense, useCallback } from "react";
+import { LuHistory } from "react-icons/lu";
+import { Await, useFetcher, useParams } from "react-router";
import { z } from "zod";
import { EmployeeAvatar } from "~/components";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { Enumerable } from "~/components/Enumerable";
import { Tags } from "~/components/Form";
import { useCustomerTypes } from "~/components/Form/CustomerType";
-import { useRouteData } from "~/hooks";
+import { useRouteData, useUser } from "~/hooks";
import type { action } from "~/routes/x+/settings+/tags";
import { path } from "~/utils/path";
import type { CustomerDetail, CustomerStatus } from "../../types";
@@ -29,11 +33,17 @@ const CustomerHeader = () => {
if (!customerId) throw new Error("Could not find customerId");
const fetcher = useFetcher<typeof action>();
+ const { company } = useUser();
+ const auditDrawer = useDisclosure();
const routeData = useRouteData<{
customer: CustomerDetail;
tags: { name: string }[];
}>(path.to.customer(customerId));
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
const customerTypes = useCustomerTypes();
const customerType = customerTypes?.find(
(type) => type.value === routeData?.customer?.customerTypeId
@@ -68,67 +78,88 @@ const CustomerHeader = () => {
);
return (
- <VStack>
- <Card>
- <HStack className="justify-between items-start">
- <CardHeader>
- <CardTitle>{routeData?.customer?.name}</CardTitle>
- </CardHeader>
- <CardAction>
- {/* <Button onClick={() => alert("TODO")} leftIcon={<FaHistory />}>
- Customer Details
- </Button> */}
- </CardAction>
- </HStack>
- <CardContent>
- <CardAttributes>
- <CardAttribute>
- <CardAttributeLabel>Status</CardAttributeLabel>
- <CardAttributeValue>
- {customerStatus ? <Enumerable value={customerStatus!} /> : "-"}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Type</CardAttributeLabel>
- <CardAttributeValue>
- {customerType ? <Enumerable value={customerType!} /> : "-"}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeLabel>Account Manager</CardAttributeLabel>
- <CardAttributeValue>
- {routeData?.customer?.accountManagerId ? (
- <EmployeeAvatar
- employeeId={routeData?.customer?.accountManagerId ?? null}
- />
- ) : (
- "-"
- )}
- </CardAttributeValue>
- </CardAttribute>
- <CardAttribute>
- <CardAttributeValue>
- <ValidatedForm
- defaultValues={{
- tags: routeData?.customer?.tags ?? []
- }}
- validator={z.object({
- tags: z.array(z.string()).optional()
- })}
- className="w-full"
- >
- <Tags
- label="Tags"
- name="tags"
- availableTags={routeData?.tags ?? []}
- table="customer"
- inline
- onChange={onUpdateTags}
- />
- </ValidatedForm>
- </CardAttributeValue>
- </CardAttribute>
- {/* {permissions.is("employee") && (
+ <>
+ <VStack>
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>{routeData?.customer?.name}</CardTitle>
+ </CardHeader>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <CardAction>
+ <Button
+ variant="secondary"
+ leftIcon={<LuHistory />}
+ onClick={auditDrawer.onOpen}
+ >
+ History
+ </Button>
+ </CardAction>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ </HStack>
+ <CardContent>
+ <CardAttributes>
+ <CardAttribute>
+ <CardAttributeLabel>Status</CardAttributeLabel>
+ <CardAttributeValue>
+ {customerStatus ? (
+ <Enumerable value={customerStatus!} />
+ ) : (
+ "-"
+ )}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Type</CardAttributeLabel>
+ <CardAttributeValue>
+ {customerType ? <Enumerable value={customerType!} /> : "-"}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeLabel>Account Manager</CardAttributeLabel>
+ <CardAttributeValue>
+ {routeData?.customer?.accountManagerId ? (
+ <EmployeeAvatar
+ employeeId={routeData?.customer?.accountManagerId ?? null}
+ />
+ ) : (
+ "-"
+ )}
+ </CardAttributeValue>
+ </CardAttribute>
+ <CardAttribute>
+ <CardAttributeValue>
+ <ValidatedForm
+ defaultValues={{
+ tags: routeData?.customer?.tags ?? []
+ }}
+ validator={z.object({
+ tags: z.array(z.string()).optional()
+ })}
+ className="w-full"
+ >
+ <Tags
+ label="Tags"
+ name="tags"
+ availableTags={routeData?.tags ?? []}
+ table="customer"
+ inline
+ onChange={onUpdateTags}
+ />
+ </ValidatedForm>
+ </CardAttributeValue>
+ </CardAttribute>
+ {/* {permissions.is("employee") && (
<CardAttribute>
<CardAttributeLabel>Assignee</CardAttributeLabel>
<CardAttributeValue>
@@ -141,10 +172,18 @@ const CustomerHeader = () => {
</CardAttributeValue>
</CardAttribute>
)} */}
- </CardAttributes>
- </CardContent>
- </Card>
- </VStack>
+ </CardAttributes>
+ </CardContent>
+ </Card>
+ </VStack>
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="customer"
+ entityId={customerId}
+ companyId={company.id}
+ />
+ </>
);
};
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
index c7608f5e5e..d2ec6fd071 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteHeader.tsx
@@ -5,6 +5,7 @@ import {
DropdownMenuContent,
DropdownMenuIcon,
DropdownMenuItem,
+ DropdownMenuSeparator,
DropdownMenuTrigger,
Heading,
HStack,
@@ -25,7 +26,7 @@ import {
toast,
useDisclosure
} from "@carbon/react";
-import { useEffect, useState } from "react";
+import { Suspense, useEffect, useState } from "react";
import {
LuCheck,
LuCheckCheck,
@@ -38,6 +39,7 @@ import {
LuEye,
LuFile,
LuGitBranchPlus,
+ LuHistory,
LuLoaderCircle,
LuPanelLeft,
LuPanelRight,
@@ -45,10 +47,11 @@ import {
LuTrash,
LuTrophy
} from "react-icons/lu";
-import { Link, useFetcher, useParams } from "react-router";
+import { Await, Link, useFetcher, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { usePanels } from "~/components/Layout";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { path } from "~/utils/path";
import type {
Opportunity,
@@ -66,6 +69,7 @@ const QuoteHeader = () => {
const { quoteId } = useParams();
if (!quoteId) throw new Error("quoteId not found");
+ const { company } = useUser();
const { toggleExplorer, toggleProperties } = usePanels();
const routeData = useRouteData<{
@@ -85,12 +89,17 @@ const QuoteHeader = () => {
const shareModal = useDisclosure();
const createRevisionModal = useDisclosure();
const deleteQuoteModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const [asRevision, setAsRevision] = useState(false);
const finalizeFetcher = useFetcher<{}>();
const statusFetcher = useFetcher<{}>();
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<>
<div className="flex flex-shrink-0 items-center justify-between p-2 bg-card border-b h-[50px] overflow-x-auto scrollbar-hide">
@@ -126,6 +135,23 @@ const QuoteHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => {
setAsRevision(false);
@@ -393,6 +419,13 @@ const QuoteHeader = () => {
}}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="salesQuote"
+ entityId={quoteId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
index f162c625e6..3e87c5e698 100644
--- a/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
+++ b/apps/erp/app/modules/sales/ui/SalesOrder/SalesOrderHeader.tsx
@@ -34,6 +34,7 @@ import {
LuEye,
LuFile,
LuGitCompare,
+ LuHistory,
LuLoaderCircle,
LuPanelLeft,
LuPanelRight,
@@ -42,11 +43,12 @@ import {
} from "react-icons/lu";
import type { FetcherWithComponents } from "react-router";
import { Await, Link, useFetcher, useParams } from "react-router";
+import { AuditLogDrawer } from "~/components/AuditLog";
import { CustomerContact, EmailRecipients } from "~/components/Form";
import { usePanels } from "~/components/Layout";
import Confirm from "~/components/Modals/Confirm/Confirm";
import ConfirmDelete from "~/components/Modals/ConfirmDelete";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useIntegrations } from "~/hooks/useIntegrations";
import type { Shipment } from "~/modules/inventory/types";
import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";
@@ -173,6 +175,7 @@ const SalesOrderHeader = () => {
const { orderId } = useParams();
if (!orderId) throw new Error("orderId not found");
+ const { company } = useUser();
const { toggleExplorer, toggleProperties } = usePanels();
const routeData = useRouteData<{
@@ -198,6 +201,7 @@ const SalesOrderHeader = () => {
const salesOrderToJobsModal = useDisclosure();
const confirmDisclosure = useDisclosure();
const deleteSalesOrderModal = useDisclosure();
+ const auditDrawer = useDisclosure();
const [customers] = useCustomers();
const csvExportData = useMemo(() => {
@@ -232,6 +236,10 @@ const SalesOrderHeader = () => {
routeData?.salesOrder?.salesOrderId
]);
+ const rootRouteData = useRouteData<{
+ auditLogEnabled: Promise<boolean>;
+ }>(path.to.authenticatedRoot);
+
return (
<>
<div className="flex flex-shrink-0 items-center justify-between p-2 bg-card border-b h-[50px] overflow-x-auto scrollbar-hide">
@@ -259,6 +267,23 @@ const SalesOrderHeader = () => {
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
+ <Suspense fallback={null}>
+ <Await resolve={rootRouteData?.auditLogEnabled}>
+ {(auditLogEnabled) => {
+ return (
+ <>
+ {auditLogEnabled && (
+ <DropdownMenuItem onClick={auditDrawer.onOpen}>
+ <DropdownMenuIcon icon={<LuHistory />} />
+ History
+ </DropdownMenuItem>
+ )}
+ </>
+ );
+ }}
+ </Await>
+ </Suspense>
+ <DropdownMenuSeparator />
<DropdownMenuItem
disabled={
!["To Ship and Invoice", "To Ship"].includes(
@@ -619,6 +644,13 @@ const SalesOrderHeader = () => {
}}
/>
)}
+ <AuditLogDrawer
+ isOpen={auditDrawer.isOpen}
+ onClose={auditDrawer.onClose}
+ entityType="salesOrder"
+ entityId={orderId}
+ companyId={company.id}
+ />
</>
);
};
diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx
new file mode 100644
index 0000000000..10beb361c5
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx
@@ -0,0 +1,143 @@
+import { auditConfig } from "@carbon/database/audit.config";
+import type { AuditLogArchive } from "@carbon/database/audit.types";
+import {
+ Button,
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+ HStack,
+ Switch,
+ VStack
+} from "@carbon/react";
+import { formatDate } from "@carbon/utils";
+import { memo, useCallback } from "react";
+import { LuDownload } from "react-icons/lu";
+import { useFetcher } from "react-router";
+
+type AuditLogSettingsProps = {
+ enabled: boolean;
+ archives: AuditLogArchive[];
+};
+
+function formatBytes(bytes: number): string {
+ if (bytes === 0) return "0 B";
+ const k = 1024;
+ const sizes = ["B", "KB", "MB", "GB"];
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(1))} ${sizes[i]}`;
+}
+
+const AuditLogSettings = memo(
+ ({ enabled, archives }: AuditLogSettingsProps) => {
+ const fetcher = useFetcher();
+
+ const isToggling = fetcher.state !== "idle";
+
+ const handleToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { action: checked ? "enable" : "disable" },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
+ const handleDownloadArchive = useCallback(
+ (archiveId: string) => {
+ fetcher.submit({ action: "download", archiveId }, { method: "POST" });
+ },
+ [fetcher]
+ );
+
+ return (
+ <>
+ <Card>
+ <CardHeader>
+ <CardTitle>Audit Logging</CardTitle>
+ <CardDescription>
+ Track changes to key business entities including invoices, orders,
+ customers, suppliers, and more.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <HStack className="justify-between items-center">
+ <VStack className="items-start gap-1">
+ <span className="font-medium">
+ {enabled
+ ? "Audit logging is enabled"
+ : "Audit logging is disabled"}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {enabled
+ ? "All changes to auditable entities are being recorded."
+ : "Enable to start tracking changes to your data."}
+ </span>
+ </VStack>
+ <Switch
+ checked={enabled}
+ onCheckedChange={handleToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ </CardContent>
+ </Card>
+
+ {enabled && (
+ <Card>
+ <CardHeader>
+ <CardTitle>Archived Logs</CardTitle>
+ <CardDescription>
+ Logs older than {auditConfig.retentionDays} days are
+ automatically archived.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ {archives.length > 0 ? (
+ <VStack className="gap-2">
+ {archives.map((archive) => (
+ <HStack
+ key={archive.id}
+ className="justify-between items-center p-6 border rounded-md w-full"
+ >
+ <VStack className="items-start">
+ <span className="font-medium text-sm">
+ {formatDate(archive.startDate)} -{" "}
+ {formatDate(archive.endDate)}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {archive.rowCount.toLocaleString()} records
+ {archive.sizeBytes &&
+ ` (${formatBytes(archive.sizeBytes)})`}
+ </span>
+ </VStack>
+ <Button
+ variant="secondary"
+ size="sm"
+ leftIcon={<LuDownload />}
+ onClick={() => handleDownloadArchive(archive.id)}
+ >
+ Download
+ </Button>
+ </HStack>
+ ))}
+ </VStack>
+ ) : (
+ <p className="text-sm text-muted-foreground text-center text-balance py-8">
+ No archived logs yet. Logs older than{" "}
+ {auditConfig.retentionDays} days will be automatically
+ archived and available for download here.
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ )}
+ </>
+ );
+ }
+);
+
+AuditLogSettings.displayName = "AuditLogSettings";
+export default AuditLogSettings;
diff --git a/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx
new file mode 100644
index 0000000000..5bf6263d3e
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx
@@ -0,0 +1,303 @@
+import {
+ getEntityLabel,
+ getEntityTypes,
+ getTableLabel
+} from "@carbon/database/audit.config";
+import type { AuditDiff, AuditLogEntry } from "@carbon/database/audit.types";
+import { Badge, HStack } from "@carbon/react";
+import { formatDateTime } from "@carbon/utils";
+import type { ColumnDef } from "@tanstack/react-table";
+import { memo, useCallback, useMemo } from "react";
+import { LuFilePen, LuFilePlus, LuFileX } from "react-icons/lu";
+import { Link } from "react-router";
+import { EmployeeAvatar, Table } from "~/components";
+import { path } from "~/utils/path";
+
+type AuditLogTableProps = {
+ entries: AuditLogEntry[];
+ count: number;
+};
+
+const operationConfig: Record<
+ string,
+ { variant: "green" | "blue" | "red"; icon: React.ReactNode; label: string }
+> = {
+ INSERT: {
+ variant: "green",
+ icon: <LuFilePlus className="size-3" />,
+ label: "Created"
+ },
+ UPDATE: {
+ variant: "blue",
+ icon: <LuFilePen className="size-3" />,
+ label: "Updated"
+ },
+ DELETE: {
+ variant: "red",
+ icon: <LuFileX className="size-3" />,
+ label: "Deleted"
+ }
+};
+
+function formatValue(value: unknown): string {
+ if (value === null) return "null";
+ if (value === undefined) return "undefined";
+ if (typeof value === "string") return value;
+ if (typeof value === "number" || typeof value === "boolean")
+ return String(value);
+ return JSON.stringify(value);
+}
+
+function getEntityPath(entityId: string): string | null {
+ const prefix = entityId.split("_")[0];
+ if (!prefix || prefix === entityId) return null;
+
+ const map: Record<string, (id: string) => string> = {
+ pi: path.to.purchaseInvoice,
+ si: path.to.salesInvoice,
+ po: path.to.purchaseOrder,
+ so: path.to.salesOrder,
+ cust: path.to.customer,
+ sup: path.to.supplier,
+ item: path.to.part,
+ job: path.to.job,
+ quote: path.to.quote,
+ emp: path.to.employeeAccount,
+ nc: path.to.issue,
+ sh: path.to.shipment,
+ rec: path.to.receipt,
+ g: path.to.gauge,
+ sq: path.to.supplierQuote,
+ wc: path.to.workCenter,
+ main: path.to.maintenanceDispatch
+ };
+ const pathFn = map[prefix];
+ return pathFn ? pathFn(entityId) : null;
+}
+
+const InlineDiff = memo(
+ ({
+ fieldName,
+ oldValue,
+ newValue
+ }: {
+ fieldName: string;
+ oldValue: unknown;
+ newValue: unknown;
+ }) => (
+ <div className="flex items-center gap-2 font-mono text-sm py-1">
+ <span className="text-muted-foreground font-medium min-w-[120px]">
+ {fieldName}:
+ </span>
+ {oldValue !== undefined && (
+ <span className="px-2 py-0.5 rounded bg-red-500/10 text-red-500">
+ {formatValue(oldValue)}
+ </span>
+ )}
+ {oldValue !== undefined && newValue !== undefined && (
+ <span className="text-muted-foreground">→</span>
+ )}
+ {newValue !== undefined && (
+ <span className="px-2 py-0.5 rounded bg-green-500/10 text-green-500">
+ {formatValue(newValue)}
+ </span>
+ )}
+ </div>
+ )
+);
+InlineDiff.displayName = "InlineDiff";
+
+const ExpandedRowContent = memo(({ entry }: { entry: AuditLogEntry }) => {
+ const hasDiff = entry.diff && Object.keys(entry.diff).length > 0;
+
+ return (
+ <div className="px-6 py-4">
+ <div className="grid grid-cols-4 gap-4 mb-4 text-sm">
+ <div>
+ <span className="text-muted-foreground">Source</span>
+ <div className="text-xs font-medium">
+ {getTableLabel(entry.tableName)}
+ </div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Event ID</span>
+ <div className="font-mono text-xs">{entry.id}</div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Actor ID</span>
+ <div className="font-mono text-xs">{entry.actorId ?? "System"}</div>
+ </div>
+ <div>
+ <span className="text-muted-foreground">Timestamp</span>
+ <div className="font-mono text-xs">{entry.createdAt}</div>
+ </div>
+ </div>
+
+ <div>
+ <h4 className="text-sm font-medium mb-2">Changes</h4>
+ {hasDiff ? (
+ <div className="space-y-1">
+ {Object.entries(entry.diff as AuditDiff).map(
+ ([fieldName, change]) => (
+ <InlineDiff
+ key={fieldName}
+ fieldName={fieldName}
+ oldValue={change.old}
+ newValue={change.new}
+ />
+ )
+ )}
+ </div>
+ ) : (
+ <p className="text-sm text-muted-foreground italic">
+ {entry.operation === "INSERT"
+ ? "New record created"
+ : entry.operation === "DELETE"
+ ? "Record deleted"
+ : "No changes recorded"}
+ </p>
+ )}
+ </div>
+ </div>
+ );
+});
+ExpandedRowContent.displayName = "ExpandedRowContent";
+
+const AuditLogTable = memo(({ entries, count }: AuditLogTableProps) => {
+ const columns = useMemo<ColumnDef<AuditLogEntry>[]>(
+ () => [
+ {
+ accessorKey: "entityType",
+ header: "Entity",
+ cell: ({ row }) => {
+ const entry = row.original;
+ const entityPath = getEntityPath(entry.entityId);
+ return (
+ <div>
+ <div className="font-medium">
+ {getEntityLabel(
+ entry.entityType as Parameters<typeof getEntityLabel>[0]
+ )}
+ </div>
+ {entityPath ? (
+ <Link
+ to={entityPath}
+ className="text-xs text-primary font-mono truncate max-w-[200px] block hover:underline"
+ >
+ {entry.entityId}
+ </Link>
+ ) : (
+ <div className="text-xs text-muted-foreground font-mono truncate max-w-[200px]">
+ {entry.entityId}
+ </div>
+ )}
+ </div>
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: getEntityTypes().map((entityType) => ({
+ label: getEntityLabel(entityType),
+ value: entityType
+ }))
+ },
+ pluralHeader: "Entities"
+ }
+ },
+ {
+ accessorKey: "operation",
+ header: "Operation",
+ cell: ({ row }) => {
+ const config = operationConfig[row.original.operation];
+ return (
+ <Badge
+ variant={config?.variant ?? "secondary"}
+ className="shrink-0"
+ >
+ <HStack className="gap-1">
+ {config?.icon}
+ <span>{config?.label ?? row.original.operation}</span>
+ </HStack>
+ </Badge>
+ );
+ },
+ meta: {
+ filter: {
+ type: "static",
+ options: [
+ { label: "Created", value: "INSERT" },
+ { label: "Updated", value: "UPDATE" },
+ { label: "Deleted", value: "DELETE" }
+ ]
+ }
+ }
+ },
+ {
+ accessorKey: "actorId",
+ header: "Changed By",
+ cell: ({ row }) => {
+ const entry = row.original;
+ return entry.actorId ? (
+ <Link
+ to={path.to.employeeAccount(entry.actorId)}
+ className="hover:underline"
+ >
+ <EmployeeAvatar employeeId={entry.actorId} />
+ </Link>
+ ) : (
+ <span className="text-muted-foreground text-sm">System</span>
+ );
+ }
+ },
+ {
+ id: "changes",
+ header: "Changes",
+ cell: ({ row }) => {
+ const entry = row.original;
+ const hasDiff = entry.diff && Object.keys(entry.diff).length > 0;
+ return (
+ <span className="text-sm text-muted-foreground">
+ {hasDiff
+ ? `${Object.keys(entry.diff!).length} change${
+ Object.keys(entry.diff!).length !== 1 ? "s" : ""
+ }`
+ : "-"}
+ </span>
+ );
+ }
+ },
+ {
+ accessorKey: "createdAt",
+ header: "When",
+ cell: ({ row }) => (
+ <span className="text-sm text-muted-foreground">
+ {formatDateTime(row.original.createdAt)}
+ </span>
+ )
+ }
+ ],
+ []
+ );
+
+ const renderExpandedRow = useCallback(
+ (entry: AuditLogEntry) => <ExpandedRowContent entry={entry} />,
+ []
+ );
+
+ return (
+ <Table
+ data={entries}
+ columns={columns}
+ count={count}
+ title="Audit Log"
+ table="auditLog"
+ withSearch
+ withPagination
+ renderExpandedRow={renderExpandedRow}
+ />
+ );
+});
+
+AuditLogTable.displayName = "AuditLogTable";
+export default AuditLogTable;
diff --git a/apps/erp/app/modules/settings/ui/AuditLog/index.ts b/apps/erp/app/modules/settings/ui/AuditLog/index.ts
new file mode 100644
index 0000000000..b52761efdb
--- /dev/null
+++ b/apps/erp/app/modules/settings/ui/AuditLog/index.ts
@@ -0,0 +1,2 @@
+export { default as AuditLogSettings } from "./AuditLogSettings";
+export { default as AuditLogTable } from "./AuditLogTable";
diff --git a/apps/erp/app/modules/settings/ui/index.ts b/apps/erp/app/modules/settings/ui/index.ts
index b02f1e71ee..4198463c17 100644
--- a/apps/erp/app/modules/settings/ui/index.ts
+++ b/apps/erp/app/modules/settings/ui/index.ts
@@ -2,6 +2,7 @@ import useSettingsSubmodules from "./useSettingsSubmodules";
export * from "./ApiKeys";
export * from "./Approvals";
+export * from "./AuditLog";
export * from "./Company";
export * from "./CustomFields";
export * from "./Integrations";
diff --git a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
index 389c03262e..c27bda858a 100644
--- a/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
+++ b/apps/erp/app/modules/settings/ui/useSettingsSubmodules.tsx
@@ -1,3 +1,5 @@
+import { usePlan } from "@carbon/remix";
+import { Plan } from "@carbon/utils";
import {
LuBarcode,
LuBox,
@@ -6,7 +8,9 @@ import {
LuCreditCard,
LuCrown,
LuFactory,
+ LuHistory,
LuImage,
+ LuKey,
LuLayoutDashboard,
LuSheet,
LuShoppingCart,
@@ -23,6 +27,7 @@ import { path } from "~/utils/path";
const settingsRoutes: AuthenticatedRouteGroup<{
requiresOwnership?: boolean;
requiresCloudEnvironment?: boolean;
+ requiresEnterpriseOrBusiness?: boolean;
}>[] = [
{
name: "Company",
@@ -105,12 +110,25 @@ const settingsRoutes: AuthenticatedRouteGroup<{
{
name: "System",
routes: [
+ {
+ name: "API Keys",
+ to: path.to.apiKeys,
+ role: "employee",
+ icon: <LuKey />
+ },
{
name: "Approval Rules",
to: path.to.approvalRules,
role: "employee",
icon: <LuCircleCheck />
},
+ {
+ name: "Audit Logs",
+ to: path.to.auditLog,
+ role: "employee",
+ icon: <LuHistory />,
+ requiresEnterpriseOrBusiness: true
+ },
{
name: "Custom Fields",
to: path.to.customFields,
@@ -141,7 +159,8 @@ const settingsRoutes: AuthenticatedRouteGroup<{
export default function useSettingsSubmodules() {
const permissions = usePermissions();
- const { isCloud } = useFlags();
+ const { isCloud, isEnterprise, isCommunity } = useFlags();
+ const plan = usePlan();
return {
groups: settingsRoutes
@@ -174,6 +193,15 @@ export default function useSettingsSubmodules() {
return false;
}
+ if (
+ route.requiresEnterpriseOrBusiness &&
+ !isEnterprise &&
+ !isCommunity &&
+ plan !== Plan.Business
+ ) {
+ return false;
+ }
+
return true;
})
}))
diff --git a/apps/erp/app/routes/api+/audit-log.ts b/apps/erp/app/routes/api+/audit-log.ts
new file mode 100644
index 0000000000..4ee65da490
--- /dev/null
+++ b/apps/erp/app/routes/api+/audit-log.ts
@@ -0,0 +1,46 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getEntityAuditLog, isAuditLogEnabled } from "@carbon/database/audit";
+import type { LoaderFunctionArgs } from "react-router";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings"
+ });
+
+ const url = new URL(request.url);
+ const entityType = url.searchParams.get("entityType");
+ const entityId = url.searchParams.get("entityId");
+
+ if (!entityType || !entityId) {
+ return Response.json(
+ { error: "entityType and entityId are required" },
+ { status: 400 }
+ );
+ }
+
+ // Check if audit log is enabled for this company
+ try {
+ const enabled = await isAuditLogEnabled(client, companyId);
+ if (!enabled) {
+ return Response.json({ entries: [] });
+ }
+ } catch {
+ // Table might not exist yet
+ return Response.json({ entries: [] });
+ }
+
+ // Get audit log entries for this entity
+ try {
+ const entries = await getEntityAuditLog(
+ client,
+ companyId,
+ entityType,
+ entityId,
+ { limit: 50, offset: 0 }
+ );
+ return Response.json({ entries });
+ } catch (err) {
+ console.error("Failed to fetch audit log:", err);
+ return Response.json({ entries: [] });
+ }
+}
diff --git a/apps/erp/app/routes/x+/_layout.tsx b/apps/erp/app/routes/x+/_layout.tsx
index 5ff09b7b80..6209997263 100644
--- a/apps/erp/app/routes/x+/_layout.tsx
+++ b/apps/erp/app/routes/x+/_layout.tsx
@@ -10,6 +10,7 @@ import {
requireAuthSession,
updateCompanySession
} from "@carbon/auth/session.server";
+import { isAuditLogEnabled } from "@carbon/database/audit";
import { TooltipProvider, useMount } from "@carbon/react";
import { ItarPopup, useKeyboardWedge, useNProgress } from "@carbon/remix";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
@@ -19,7 +20,13 @@ import type {
LoaderFunctionArgs,
ShouldRevalidateFunction
} from "react-router";
-import { Outlet, redirect, useLoaderData, useNavigate } from "react-router";
+import {
+ data,
+ Outlet,
+ redirect,
+ useLoaderData,
+ useNavigate
+} from "react-router";
import { RealtimeDataProvider } from "~/components";
import { PrimaryNavigation, Topbar } from "~/components/Layout";
import {
@@ -118,12 +125,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
throw redirect(path.to.onboarding.root);
}
- return {
+ return data({
session: {
accessToken,
expiresIn,
expiresAt
},
+ auditLogEnabled: await isAuditLogEnabled(client, companyId),
company,
companies: companies.data ?? [],
companySettings: companySettings.data,
@@ -136,7 +144,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
role: claims?.role,
user: user.data,
savedViews: savedViews.data ?? []
- };
+ });
}
export default function AuthenticatedRoute() {
diff --git a/apps/erp/app/routes/x+/settings+/_layout.tsx b/apps/erp/app/routes/x+/settings+/_layout.tsx
index d9ad415490..f593a82c81 100644
--- a/apps/erp/app/routes/x+/settings+/_layout.tsx
+++ b/apps/erp/app/routes/x+/settings+/_layout.tsx
@@ -1,10 +1,8 @@
import { VStack } from "@carbon/react";
-import { LuKey } from "react-icons/lu";
import type { MetaFunction } from "react-router";
import { Outlet } from "react-router";
import { GroupedContentSidebar } from "~/components/Layout";
import { CollapsibleSidebarProvider } from "~/components/Layout/Navigation";
-import { usePermissions } from "~/hooks";
import { useSettingsSubmodules } from "~/modules/settings";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -20,18 +18,8 @@ export const handle: Handle = {
};
export default function SettingsRoute() {
- const permissions = usePermissions();
const { groups } = useSettingsSubmodules();
- if (permissions.can("update", "users") && permissions.is("employee")) {
- groups?.[2]?.routes.unshift({
- name: "API Keys",
- to: path.to.apiKeys,
- role: "employee",
- icon: <LuKey />
- });
- }
-
return (
<CollapsibleSidebarProvider>
<div className="grid grid-cols-[auto_1fr] w-full h-full bg-card">
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx
new file mode 100644
index 0000000000..5bc69ece1b
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.details.tsx
@@ -0,0 +1,71 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { getGlobalAuditLog } from "@carbon/database/audit";
+import {
+ Drawer,
+ DrawerBody,
+ DrawerContent,
+ DrawerHeader,
+ DrawerTitle
+} from "@carbon/react";
+import type { LoaderFunctionArgs } from "react-router";
+import { useLoaderData, useNavigate } from "react-router";
+import { AuditLogTable } from "~/modules/settings";
+import { path } from "~/utils/path";
+import { getGenericQueryFilters } from "~/utils/query";
+
+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, filters } = getGenericQueryFilters(searchParams);
+
+ const entityTypeFilter = filters?.find((f) => f.column === "entityType")
+ ?.value as string | undefined;
+ const actorIdFilter = filters?.find((f) => f.column === "actorId")?.value;
+ const operationFilter = filters?.find((f) => f.column === "operation")
+ ?.value as "INSERT" | "UPDATE" | "DELETE" | undefined;
+
+ const result = await getGlobalAuditLog(client, companyId, {
+ limit,
+ offset,
+ search: search ?? undefined,
+ entityType: entityTypeFilter as NonNullable<
+ Parameters<typeof getGlobalAuditLog>[2]
+ >["entityType"],
+ actorId: actorIdFilter,
+ operation: operationFilter
+ });
+
+ return {
+ entries: result.data,
+ count: result.count
+ };
+}
+
+export default function AuditLogDetailsRoute() {
+ const { entries, count } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+ return (
+ <Drawer
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ navigate(path.to.auditLog);
+ }
+ }}
+ >
+ <DrawerContent size="full">
+ <DrawerHeader>
+ <DrawerTitle>All Audit Logs</DrawerTitle>
+ </DrawerHeader>
+ <DrawerBody className="p-0">
+ <AuditLogTable entries={entries} count={count} />
+ </DrawerBody>
+ </DrawerContent>
+ </Drawer>
+ );
+}
diff --git a/apps/erp/app/routes/x+/settings+/audit-logs.tsx b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
new file mode 100644
index 0000000000..fa44165461
--- /dev/null
+++ b/apps/erp/app/routes/x+/settings+/audit-logs.tsx
@@ -0,0 +1,157 @@
+import { error, getCarbonServiceRole, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import {
+ disableAuditLog,
+ enableAuditLog,
+ getArchiveDownloadUrl,
+ getAuditLogArchives,
+ isAuditLogEnabled,
+ syncAuditSubscriptions
+} from "@carbon/database/audit";
+import { Button, Heading, ScrollArea, VStack } from "@carbon/react";
+import { LuHistory } from "react-icons/lu";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { Link, Outlet, redirect, useLoaderData } from "react-router";
+import { AuditLogSettings } from "~/modules/settings";
+import type { Handle } from "~/utils/handle";
+import { path } from "~/utils/path";
+
+export const handle: Handle = {
+ breadcrumb: "Audit Log",
+ to: path.to.auditLog
+};
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ view: "settings"
+ });
+
+ // Check if audit log is enabled for this company
+ let enabled = false;
+ try {
+ enabled = await isAuditLogEnabled(client, companyId);
+ } catch {
+ // Table might not exist yet, that's ok
+ }
+
+ // Sync subscriptions to pick up any newly added auditable tables
+ if (enabled) {
+ try {
+ await syncAuditSubscriptions(client, companyId);
+ } catch {
+ // Subscription sync failure is non-critical
+ }
+ }
+
+ // Get archives (uses service role to bypass RLS on auditLogArchive table)
+ let archives: Awaited<ReturnType<typeof getAuditLogArchives>> = [];
+ if (enabled) {
+ try {
+ const serviceRole = getCarbonServiceRole();
+ archives = await getAuditLogArchives(serviceRole, companyId);
+ } catch {
+ // Archives table might not exist
+ }
+ }
+
+ return {
+ enabled,
+ archives
+ };
+}
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const formData = await request.formData();
+ const actionType = formData.get("action") as string;
+
+ switch (actionType) {
+ case "enable": {
+ try {
+ await enableAuditLog(client, companyId);
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, success("Audit logging enabled"))
+ );
+ } catch (err) {
+ if (err instanceof Response) throw err;
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, error(err, "Failed to enable audit logging"))
+ );
+ }
+ }
+
+ case "disable": {
+ try {
+ await disableAuditLog(client, companyId);
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, success("Audit logging disabled"))
+ );
+ } catch (err) {
+ if (err instanceof Response) throw err;
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, error(err, "Failed to disable audit logging"))
+ );
+ }
+ }
+
+ case "download": {
+ const archiveId = formData.get("archiveId") as string;
+ if (!archiveId) {
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, error(null, "Archive ID is required"))
+ );
+ }
+
+ try {
+ const serviceRole = getCarbonServiceRole();
+ const downloadUrl = await getArchiveDownloadUrl(serviceRole, archiveId);
+ // Redirect to the signed URL for download
+ return redirect(downloadUrl);
+ } catch (err) {
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, error(err, "Failed to generate download URL"))
+ );
+ }
+ }
+
+ default:
+ throw redirect(
+ path.to.auditLog,
+ await flash(request, error(null, "Invalid action"))
+ );
+ }
+}
+
+export default function AuditLogRoute() {
+ const { enabled, archives } = useLoaderData<typeof loader>();
+
+ return (
+ <ScrollArea className="w-full h-[calc(100dvh-49px)]">
+ <VStack
+ spacing={4}
+ className="py-12 px-4 max-w-[60rem] h-full mx-auto gap-4"
+ >
+ <div className="flex items-center justify-between w-full">
+ <Heading size="h3">Audit Logs</Heading>
+ {enabled && (
+ <Button leftIcon={<LuHistory />} asChild>
+ <Link to={path.to.auditLogDetails}>View All</Link>
+ </Button>
+ )}
+ </div>
+ <AuditLogSettings enabled={enabled} archives={archives} />
+ {enabled && <Outlet />}
+ </VStack>
+ </ScrollArea>
+ );
+}
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index c87ea27e96..d4859115d8 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -414,6 +414,8 @@ export const path = {
generatePath(`${x}/people/attributes/${id}`),
attributeCategoryList: (id: string) =>
generatePath(`${x}/people/attributes/list/${id}`),
+ auditLog: `${x}/settings/audit-logs`,
+ auditLogDetails: `${x}/settings/audit-logs/details`,
batchProperty: (itemId: string) =>
generatePath(`${x}/inventory/batch-property/${itemId}/property`),
batchPropertyOrder: (itemId: string) =>
@@ -508,7 +510,7 @@ export const path = {
generatePath(`${x}/customer/${id}/locations`),
customerPart: (id: string, customerPartToItemId: string) =>
generatePath(
- `${x}/part/${id}/view/sales/customer-parts/${customerPartToItemId}`
+ `${x}/part/${id}/sales/customer-parts/${customerPartToItemId}`
),
customerPayment: (id: string) =>
generatePath(`${x}/customer/${id}/payments`),
@@ -570,7 +572,7 @@ export const path = {
generatePath(`${x}/customer/${customerId}/locations/delete/${id}`),
deleteCustomerPart: (id: string, customerPartToItemId: string) =>
generatePath(
- `${x}/part/${id}/view/sales/customer-parts/delete/${customerPartToItemId}`
+ `${x}/part/${id}/sales/customer-parts/delete/${customerPartToItemId}`
),
deleteCustomerStatus: (id: string) =>
generatePath(`${x}/sales/customer-statuses/delete/${id}`),
@@ -1021,7 +1023,7 @@ export const path = {
newCustomField: (tableId: string) =>
generatePath(`${x}/settings/custom-fields/${tableId}/new`),
newCustomerPart: (id: string) =>
- generatePath(`${x}/part/${id}/view/sales/customer-parts/new`),
+ generatePath(`${x}/part/${id}/sales/customer-parts/new`),
newDemandProjection: `${x}/production/projections/new`,
newDepartment: `${x}/people/departments/new`,
newDocument: `${x}/documents/new`,
@@ -1076,7 +1078,7 @@ export const path = {
newNote: `${x}/shared/notes/new`,
newPart: `${x}/part/new`,
newPartSupplier: (id: string) =>
- generatePath(`${x}/part/${id}/view/purchasing/new`),
+ generatePath(`${x}/part/${id}/purchasing/new`),
newStockTransfer: `${x}/stock-transfer/new`,
newStockTransferLine: (id: string) =>
generatePath(`${x}/stock-transfer/${id}/line/new`),
@@ -1150,7 +1152,7 @@ export const path = {
newTag: `${x}/settings/tags/new`,
newTool: `${x}/tool/new`,
newToolSupplier: (id: string) =>
- generatePath(`${x}/tool/${id}/view/purchasing/new`),
+ generatePath(`${x}/tool/${id}/purchasing/new`),
newTraining: `${x}/resources/training/new`,
newTrainingAssignment: `${x}/resources/assignments/new`,
newTrainingQuestion: (id: string) =>
@@ -1572,9 +1574,8 @@ export const path = {
toolPurchasing: (id: string) => generatePath(`${x}/tool/${id}/purchasing`),
toolRoot: `${x}/tool`,
toolSupplier: (itemId: string, id: string) =>
- generatePath(`${x}/tool/${itemId}/view/suppliers/${id}`),
- toolSuppliers: (id: string) =>
- generatePath(`${x}/tool/${id}/view/suppliers`),
+ generatePath(`${x}/tool/${itemId}/suppliers/${id}`),
+ toolSuppliers: (id: string) => generatePath(`${x}/tool/${id}/suppliers`),
tools: `${x}/items/tools`,
traceability: `${x}/traceability`,
traceabilityGraph: `${x}/traceability/graph`,
diff --git a/llm/cache/audit-log-system.md b/llm/cache/audit-log-system.md
new file mode 100644
index 0000000000..02a81956a7
--- /dev/null
+++ b/llm/cache/audit-log-system.md
@@ -0,0 +1,101 @@
+# Audit Log System
+
+## Overview
+
+Per-company audit log system that tracks changes to key business entities. Audit logs are stored in dynamically created `auditLog_{companyId}` tables accessed via PostgreSQL RPC functions.
+
+## Schema
+
+Each audit log entry has:
+
+- `id` (TEXT, default `id('aud')`)
+- `companyId` (TEXT)
+- `entityType` (TEXT) — one of the auditable entity types
+- `entityId` (TEXT) — the primary key of the entity that changed
+- `operation` (TEXT) — INSERT, UPDATE, or DELETE
+- `actorId` (TEXT | null) — the user who made the change (null = system)
+- `diff` (JSONB | null) — field-level changes `{ fieldName: { old, new } }`
+- `metadata` (JSONB | null) — ipAddress, userAgent, origin, requestId
+- `createdAt` (TIMESTAMPTZ)
+
+## Auditable Entities
+
+Configured in `packages/database/src/audit.config.ts`:
+
+| Entity Type | UI Label | DB ID Prefix | Linkable Detail Page |
+| ----------------- | ------------------- | --------------------- | ------------------------------- |
+| `purchaseInvoice` | Purchasing Invoice | `pi_` | `/x/purchase-invoice/:id` |
+| `salesInvoice` | Sales Invoice | `si_` | `/x/sales-invoice/:id` |
+| `purchaseOrder` | Purchasing Order | `po_` | `/x/purchase-order/:id` |
+| `salesOrder` | Sales Order | `so_` | `/x/sales-order/:id` |
+| `customer` | Sales Customer | `cust_` | `/x/customer/:id` |
+| `supplier` | Purchasing Supplier | `sup_` | `/x/supplier/:id` |
+| `item` | Inventory Item | `item_` | `/x/part/:id` |
+| `itemCost` | Inventory Item | `item_` (uses itemId) | `/x/part/:id` (via item prefix) |
+| `job` | Production Job | `job_` | `/x/job/:id` |
+| `quote` | Sales Quote | `quote_` | `/x/quote/:id` |
+| `employee` | Employee | `emp_` | `/x/users/employees/:id` |
+
+Labels use domain prefixes to group related entities (e.g., "Inventory Item" for both `item` and `itemCost`).
+
+## Key Files
+
+### Configuration
+
+- `packages/database/src/audit.config.ts` — auditable entities list, labels, skip fields, retention config
+- `packages/database/src/audit.types.ts` — TypeScript types (AuditLogEntry, AuditDiff, AuditLogFilters, etc.)
+
+### Backend
+
+- `packages/database/src/audit.ts` — database query functions (CRUD, enable/disable, archival)
+- `packages/jobs/trigger/event/audit.ts` — Trigger.dev task that processes audit events and inserts entries
+
+### UI Components
+
+- `apps/erp/app/modules/settings/ui/AuditLog/AuditLogTable.tsx` — main audit log table with entity linking, actor linking, expandable diffs
+- `apps/erp/app/modules/settings/ui/AuditLog/AuditLogSettings.tsx` — settings card to enable/disable + archive list
+- `apps/erp/app/components/AuditLog/AuditLogDrawer.tsx` — per-entity history drawer (used on entity detail pages)
+
+### Routes
+
+- `apps/erp/app/routes/x+/settings+/audit-logs.tsx` — settings page (enable/disable/download)
+- `apps/erp/app/routes/x+/settings+/audit-logs.details.tsx` — full-screen table view
+- `apps/erp/app/routes/api+/audit-log.ts` — API endpoint for entity-specific audit logs
+
+### Migrations
+
+- `packages/database/supabase/migrations/20260212152709_audit_log_system.sql` — initial system
+- `packages/database/supabase/migrations/20260212154954_fix_audit_log_table_name_ambiguity.sql` — fix
+- `packages/database/supabase/migrations/20260212174458_remove_actor_name_from_audit_log.sql` — UI resolves from actorId
+
+## Entity Linking
+
+Entity IDs in the audit log table are linked to their detail pages based on the **ID prefix** (the part before the first `_`). The `getEntityPath()` function in `AuditLogTable.tsx` maps prefixes to `path.to.*` helpers:
+
+```
+pi → path.to.purchaseInvoice
+si → path.to.salesInvoice
+po → path.to.purchaseOrder
+so → path.to.salesOrder
+cust → path.to.customer
+sup → path.to.supplier
+item → path.to.part
+job → path.to.job
+quote → path.to.quote
+emp → path.to.employeeAccount
+```
+
+IDs without a recognized prefix render as plain text. The `itemCost` entity uses `itemId` as its key, so its entityId has the `item_` prefix and links to the part page.
+
+## Actor Linking
+
+The "Changed By" column wraps the `<EmployeeAvatar>` in a `<Link>` to `path.to.employeeAccount(actorId)`. System entries (null actorId) display as plain "System" text.
+
+## Architecture Notes
+
+- Per-company tables: `auditLog_{companyId}` accessed via RPC
+- `actorName` column was removed; UI resolves via `<EmployeeAvatar employeeId={actorId} />`
+- Uses `@tanstack/react-table` via shared `<Table>` component with expandable rows, search, pagination, and static column filters
+- Skip fields: `updatedAt`, `updatedBy` are excluded from diff computation
+- Retention: 30 days default before archival
+- Archives stored in `private` bucket at `audit-logs/{companyId}/{year}/{month}.jsonl.gz`
diff --git a/llm/cache/jira-integration.md b/llm/cache/jira-integration.md
new file mode 100644
index 0000000000..3a662468ce
--- /dev/null
+++ b/llm/cache/jira-integration.md
@@ -0,0 +1,29 @@
+# Jira Integration
+
+## Key Implementation Details
+
+### Jira Search API
+
+- The Jira search endpoint was migrated from `/search` to `/search/jql` (the old endpoint was deprecated with a 410 response). See `packages/ee/src/jira/lib/client.ts` `searchIssues` method.
+
+### Unlinking Jira Issues
+
+- `unlinkActionFromJiraIssue` in `packages/ee/src/jira/lib/service.ts` uses `getCarbonServiceRole()` (service role client) to delete from `externalIntegrationMapping` because the table has no DELETE RLS policy for authenticated users.
+- The DELETE handler in `apps/erp/app/routes/api+/integrations.jira.issue.link.ts` unlinks from Carbon's DB first, then does best-effort Jira remote link cleanup.
+- Remote link cleanup fetches actual links via `getRemoteLinks()` and finds the Carbon link by `application.name === "Carbon"` or `globalId.startsWith("carbon-")` rather than reconstructing the globalId from a URL.
+
+### RLS on externalIntegrationMapping
+
+- The table only has SELECT and INSERT RLS policies (defined in migration `20260204001831`). No UPDATE or DELETE policies exist.
+- Any delete operations must use the service role client (`getCarbonServiceRole()`).
+
+### Modal Scroll
+
+- `ModalContent` has `max-h-[85vh]` to prevent modals from exceeding the viewport.
+- `ModalBody` has `overflow-y-auto` so body content scrolls internally.
+
+### Jira Dialog UI
+
+- `IssueDialog.tsx` resets tab to "link" on close, and closes the dialog after unlink.
+- `ModalHeader` uses `pr-10` to prevent close button overlap with tabs.
+- `ModalFooter` inside `ModalBody` uses `className="px-0 pb-0"` to avoid double padding.
diff --git a/packages/database/package.json b/packages/database/package.json
index c90cc74b8d..94a56e4a19 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -18,6 +18,9 @@
".": "./src/index.ts",
"./client": "./src/client.ts",
"./event": "./src/event.ts",
+ "./audit": "./src/audit.ts",
+ "./audit.config": "./src/audit.config.ts",
+ "./audit.types": "./src/audit.types.ts",
"./swagger-docs-schema": "./src/swagger-docs-schema.ts"
},
"private": true,
diff --git a/packages/database/src/audit.config.ts b/packages/database/src/audit.config.ts
new file mode 100644
index 0000000000..d35970515e
--- /dev/null
+++ b/packages/database/src/audit.config.ts
@@ -0,0 +1,463 @@
+/**
+ * Entity-Centric Audit Log Configuration
+ *
+ * Audit logging is organized around business entities (Customer, Sales Order, etc.),
+ * not individual database tables. Each entity is composed of one or more tables.
+ * When a row in any of those tables changes, the audit system attributes the change
+ * to the correct business entity and records the actual field-level diff.
+ *
+ * Table roles:
+ * - "root": The primary table for this entity. Its PK is the entity ID.
+ * - "extension": A 1:1 extension table whose PK equals the parent FK
+ * (e.g., customerPayment PK = customerId). Entity ID resolution
+ * is the same as root, but INSERT events are skipped.
+ * - { entityIdColumn: string }: A child table with its own surrogate PK.
+ * The named column contains the parent entity ID.
+ * - { resolve: { junction, fk, entityIdColumn } }: An indirect child linked
+ * through a junction table. Requires a DB query at audit time.
+ */
+
+// ---------------------------------------------------------------------------
+// Config types
+// ---------------------------------------------------------------------------
+
+type RootTable = { role: "root" };
+
+type ExtensionTable = { role: "extension" };
+
+type ChildTable = { entityIdColumn: string };
+
+type IndirectTable = {
+ resolve: {
+ /** Junction table name (e.g. "customerContact") */
+ junction: string;
+ /** Column in junction table pointing to this table's PK (e.g. "contactId") */
+ fk: string;
+ /** Column in junction table pointing to the parent entity (e.g. "customerId") */
+ entityIdColumn: string;
+ };
+};
+
+type TableConfig = RootTable | ExtensionTable | ChildTable | IndirectTable;
+
+type EntityConfig = {
+ label: string;
+ tables: Record<string, TableConfig>;
+};
+
+// ---------------------------------------------------------------------------
+// Entity definitions
+// ---------------------------------------------------------------------------
+
+export const auditConfig = {
+ entities: {
+ customer: {
+ label: "Customer",
+ tables: {
+ customer: { role: "root" },
+ customerPayment: { role: "extension" }, // PK = customerId
+ customerShipping: { role: "extension" }, // PK = customerId
+ contact: {
+ resolve: {
+ junction: "customerContact",
+ fk: "contactId",
+ entityIdColumn: "customerId"
+ }
+ },
+ address: {
+ resolve: {
+ junction: "customerLocation",
+ fk: "addressId",
+ entityIdColumn: "customerId"
+ }
+ }
+ }
+ },
+
+ supplier: {
+ label: "Supplier",
+ tables: {
+ supplier: { role: "root" },
+ supplierPayment: { role: "extension" }, // PK = supplierId
+ supplierShipping: { role: "extension" }, // PK = supplierId
+ contact: {
+ resolve: {
+ junction: "supplierContact",
+ fk: "contactId",
+ entityIdColumn: "supplierId"
+ }
+ },
+ address: {
+ resolve: {
+ junction: "supplierLocation",
+ fk: "addressId",
+ entityIdColumn: "supplierId"
+ }
+ }
+ }
+ },
+
+ item: {
+ label: "Item",
+ tables: {
+ item: { role: "root" },
+ itemCost: { role: "extension" }, // PK = itemId
+ itemPlanning: { role: "extension" }, // PK = itemId
+ itemReplenishment: { role: "extension" }, // PK = itemId
+ itemUnitSalePrice: { role: "extension" }, // PK = itemId
+ supplierPart: { entityIdColumn: "itemId" },
+ customerPartToItem: { entityIdColumn: "itemId" }
+ }
+ },
+
+ salesOrder: {
+ label: "Sales Order",
+ tables: {
+ salesOrder: { role: "root" },
+ salesOrderLine: { entityIdColumn: "salesOrderId" },
+ salesOrderPayment: { entityIdColumn: "salesOrderId" },
+ salesOrderShipment: { entityIdColumn: "salesOrderId" }
+ }
+ },
+
+ purchaseOrder: {
+ label: "Purchase Order",
+ tables: {
+ purchaseOrder: { role: "root" },
+ purchaseOrderLine: { entityIdColumn: "purchaseOrderId" },
+ purchaseOrderPayment: { entityIdColumn: "purchaseOrderId" },
+ purchaseOrderDelivery: { entityIdColumn: "purchaseOrderId" }
+ }
+ },
+
+ salesInvoice: {
+ label: "Sales Invoice",
+ tables: {
+ salesInvoice: { role: "root" },
+ salesInvoiceLine: { entityIdColumn: "salesInvoiceId" },
+ salesInvoiceShipment: { role: "extension" } // PK = salesInvoiceId
+ }
+ },
+
+ purchaseInvoice: {
+ label: "Purchase Invoice",
+ tables: {
+ purchaseInvoice: { role: "root" },
+ purchaseInvoiceLine: { entityIdColumn: "purchaseInvoiceId" }
+ }
+ },
+
+ salesQuote: {
+ label: "Quote",
+ tables: {
+ quote: { role: "root" },
+ quoteLine: { entityIdColumn: "quoteId" }
+ }
+ },
+
+ supplierQuote: {
+ label: "Supplier Quote",
+ tables: {
+ supplierQuote: { role: "root" },
+ supplierQuoteLine: { entityIdColumn: "supplierQuoteId" }
+ }
+ },
+
+ productionJob: {
+ label: "Job",
+ tables: {
+ job: { role: "root" },
+ jobOperation: { entityIdColumn: "jobId" },
+ jobMaterial: { entityIdColumn: "jobId" },
+ jobMakeMethod: { entityIdColumn: "jobId" }
+ }
+ },
+
+ employee: {
+ label: "Employee",
+ tables: {
+ employee: { role: "root" },
+ employeeJob: { role: "extension" } // PK = employee id
+ }
+ },
+
+ nonConformance: {
+ label: "Non-Conformance",
+ tables: {
+ nonConformance: { role: "root" },
+ nonConformanceItem: { entityIdColumn: "nonConformanceId" },
+ nonConformanceActionTask: { entityIdColumn: "nonConformanceId" },
+ nonConformanceApprovalTask: { entityIdColumn: "nonConformanceId" }
+ }
+ },
+
+ gauge: {
+ label: "Gauge",
+ tables: {
+ gauge: { role: "root" },
+ gaugeCalibrationRecord: { entityIdColumn: "gaugeId" }
+ }
+ },
+
+ shipment: {
+ label: "Shipment",
+ tables: {
+ shipment: { role: "root" },
+ shipmentLine: { entityIdColumn: "shipmentId" }
+ }
+ },
+
+ receipt: {
+ label: "Receipt",
+ tables: {
+ receipt: { role: "root" },
+ receiptLine: { entityIdColumn: "receiptId" }
+ }
+ },
+
+ warehouseTransfer: {
+ label: "Warehouse Transfer",
+ tables: {
+ warehouseTransfer: { role: "root" },
+ warehouseTransferLine: { entityIdColumn: "transferId" }
+ }
+ },
+
+ stockTransfer: {
+ label: "Stock Transfer",
+ tables: {
+ stockTransfer: { role: "root" },
+ stockTransferLine: { entityIdColumn: "stockTransferId" }
+ }
+ },
+
+ workCenter: {
+ label: "Work Center",
+ tables: {
+ workCenter: { role: "root" },
+ workCenterProcess: { entityIdColumn: "workCenterId" }
+ }
+ },
+
+ maintenanceSchedule: {
+ label: "Maintenance Schedule",
+ tables: {
+ maintenanceSchedule: { role: "root" },
+ maintenanceScheduleItem: {
+ entityIdColumn: "maintenanceScheduleId"
+ }
+ }
+ },
+
+ maintenanceDispatch: {
+ label: "Maintenance Dispatch",
+ tables: {
+ maintenanceDispatch: { role: "root" },
+ maintenanceDispatchEvent: { entityIdColumn: "maintenanceDispatchId" },
+ maintenanceDispatchComment: {
+ entityIdColumn: "maintenanceDispatchId"
+ }
+ }
+ }
+ } satisfies Record<string, EntityConfig>,
+
+ /**
+ * Human-readable labels for table names, used in the UI to show
+ * provenance (e.g. "Contact" instead of "customerContact").
+ * Tables not listed here fall back to a camelCase → Title Case conversion.
+ */
+ tableLabels: {
+ customer: "Customer",
+ customerPayment: "Payment",
+ customerShipping: "Shipping",
+ contact: "Contact",
+ address: "Address",
+ supplier: "Supplier",
+ supplierPayment: "Payment",
+ supplierShipping: "Shipping",
+ supplierPart: "Supplier Part",
+ item: "Item",
+ itemCost: "Cost",
+ itemPlanning: "Planning",
+ itemReplenishment: "Replenishment",
+ itemUnitSalePrice: "Unit Sale Price",
+ customerPartToItem: "Customer Part Mapping",
+ salesOrder: "Sales Order",
+ salesOrderLine: "Line Item",
+ salesOrderPayment: "Payment",
+ salesOrderShipment: "Shipment",
+ purchaseOrder: "Purchase Order",
+ purchaseOrderLine: "Line Item",
+ purchaseOrderPayment: "Payment",
+ purchaseOrderDelivery: "Delivery",
+ salesInvoice: "Sales Invoice",
+ salesInvoiceLine: "Line Item",
+ salesInvoiceShipment: "Shipment",
+ purchaseInvoice: "Purchase Invoice",
+ purchaseInvoiceLine: "Line Item",
+ quote: "Quote",
+ quoteLine: "Line Item",
+ supplierQuote: "Supplier Quote",
+ supplierQuoteLine: "Line Item",
+ job: "Job",
+ jobOperation: "Operation",
+ jobMaterial: "Material",
+ jobMakeMethod: "Make Method",
+ employee: "Employee",
+ employeeJob: "Job Info",
+ nonConformance: "Non-Conformance",
+ nonConformanceItem: "Item",
+ nonConformanceActionTask: "Action Task",
+ nonConformanceApprovalTask: "Approval Task",
+ gauge: "Gauge",
+ gaugeCalibrationRecord: "Calibration Record",
+ shipment: "Shipment",
+ shipmentLine: "Line Item",
+ receipt: "Receipt",
+ receiptLine: "Line Item",
+ warehouseTransfer: "Warehouse Transfer",
+ warehouseTransferLine: "Line Item",
+ stockTransfer: "Stock Transfer",
+ stockTransferLine: "Line Item",
+ workCenter: "Work Center",
+ workCenterProcess: "Process",
+ maintenanceSchedule: "Maintenance Schedule",
+ maintenanceScheduleItem: "Schedule Item",
+ maintenanceDispatch: "Dispatch",
+ maintenanceDispatchEvent: "Dispatch Event",
+ maintenanceDispatchComment: "Dispatch Comment"
+ } as Record<string, string>,
+
+ /** Fields to skip in diff computation */
+ skipFields: ["updatedAt", "updatedBy"],
+
+ /** Retention period before archival (days) */
+ retentionDays: 30,
+
+ /** Archive storage path template */
+ archivePath: "audit-logs/{companyId}/{year}/{month}.jsonl.gz",
+
+ /** Storage bucket name for archives */
+ archiveBucket: "private"
+} as const;
+
+// ---------------------------------------------------------------------------
+// Derived types
+// ---------------------------------------------------------------------------
+
+export type AuditEntityType = keyof typeof auditConfig.entities;
+
+export type AuditableTable = string;
+
+/** @deprecated Use AuditableTable or AuditEntityType instead */
+export type AuditableEntity = AuditableTable;
+
+// ---------------------------------------------------------------------------
+// Lookup indexes (computed once at import time)
+// ---------------------------------------------------------------------------
+
+type EntityTableEntry = {
+ entityType: AuditEntityType;
+ label: string;
+ tableConfig: TableConfig;
+};
+
+/** Map from table name → array of entity configs that include it */
+const _tableIndex = new Map<string, EntityTableEntry[]>();
+
+/** Deduplicated set of all auditable table names */
+const _allTables = new Set<string>();
+
+for (const [entityType, entityConfig] of Object.entries(auditConfig.entities)) {
+ for (const [tableName, tableConfig] of Object.entries(entityConfig.tables)) {
+ _allTables.add(tableName);
+
+ const existing = _tableIndex.get(tableName) ?? [];
+ existing.push({
+ entityType: entityType as AuditEntityType,
+ label: entityConfig.label,
+ tableConfig
+ });
+ _tableIndex.set(tableName, existing);
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Public helpers
+// ---------------------------------------------------------------------------
+
+/** Check if a table is tracked by any audit entity */
+export function isAuditableTable(table: string): boolean {
+ return _tableIndex.has(table);
+}
+
+/** @deprecated Use isAuditableTable instead */
+export function isAuditableEntity(table: string): boolean {
+ return isAuditableTable(table);
+}
+
+/**
+ * Get all entity configs that track a given table.
+ * Returns an array because a table can belong to multiple entities
+ * (e.g. `contact` belongs to both `customer` and `supplier`).
+ */
+export function getEntityConfigsForTable(
+ table: string
+): readonly EntityTableEntry[] {
+ return _tableIndex.get(table) ?? [];
+}
+
+/** Get deduplicated list of all auditable table names */
+export function getAuditableTableNames(): string[] {
+ return Array.from(_allTables);
+}
+
+/** Get list of all entity type keys */
+export function getEntityTypes(): AuditEntityType[] {
+ return Object.keys(auditConfig.entities) as AuditEntityType[];
+}
+
+/** Get human-readable label for an entity type */
+export function getEntityLabel(entityType: AuditEntityType): string {
+ return auditConfig.entities[entityType]?.label ?? entityType;
+}
+
+/** Get human-readable label for a table name */
+export function getTableLabel(tableName: string): string {
+ return (
+ auditConfig.tableLabels[tableName] ??
+ tableName.replace(/([A-Z])/g, " $1").trim()
+ );
+}
+
+/**
+ * Check if a table config is a root table (PK = entity ID)
+ */
+export function isRootTable(config: TableConfig): config is RootTable {
+ return "role" in config && config.role === "root";
+}
+
+/**
+ * Check if a table config is a 1:1 extension table (PK = parent FK).
+ * Entity ID resolution is the same as root (use recordId), but
+ * INSERT events are skipped since they are just empty default rows.
+ */
+export function isExtensionTable(
+ config: TableConfig
+): config is ExtensionTable {
+ return "role" in config && config.role === "extension";
+}
+
+/**
+ * Check if a table config is a direct child (has entityIdColumn)
+ */
+export function isChildTable(config: TableConfig): config is ChildTable {
+ return "entityIdColumn" in config && !("resolve" in config);
+}
+
+/**
+ * Check if a table config requires junction table resolution
+ */
+export function isIndirectTable(config: TableConfig): config is IndirectTable {
+ return "resolve" in config;
+}
diff --git a/packages/database/src/audit.ts b/packages/database/src/audit.ts
new file mode 100644
index 0000000000..5006c5763a
--- /dev/null
+++ b/packages/database/src/audit.ts
@@ -0,0 +1,438 @@
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { auditConfig, getAuditableTableNames } from "./audit.config.ts";
+import type {
+ AuditLogArchive,
+ AuditLogEntry,
+ AuditLogFilters,
+ AuditLogResponse,
+ CreateAuditLogEntry
+} from "./audit.types.ts";
+import {
+ createEventSystemSubscription,
+ deleteEventSystemSubscriptionsByName
+} from "./event.ts";
+
+// Type for Supabase client with our custom RPC functions
+type AuditRpcClient = {
+ rpc(
+ fn: "create_audit_log_table",
+ params: { p_company_id: string }
+ ): Promise<{ data: null; error: any }>;
+ rpc(
+ fn: "drop_audit_log_table",
+ params: { p_company_id: string }
+ ): Promise<{ data: null; error: any }>;
+ rpc(
+ fn: "insert_audit_log_batch",
+ params: { p_company_id: string; p_entries: CreateAuditLogEntry[] }
+ ): Promise<{ data: number | null; error: any }>;
+ rpc(
+ fn: "get_entity_audit_log",
+ params: {
+ p_company_id: string;
+ p_entity_type: string;
+ p_entity_id: string;
+ p_limit?: number;
+ p_offset?: number;
+ }
+ ): Promise<{ data: AuditLogEntry[] | null; error: any }>;
+ rpc(
+ fn: "get_audit_log",
+ params: {
+ p_company_id: string;
+ p_entity_type?: string | null;
+ p_actor_id?: string | null;
+ p_operation?: string | null;
+ p_start_date?: string | null;
+ p_end_date?: string | null;
+ p_search?: string | null;
+ p_limit?: number;
+ p_offset?: number;
+ }
+ ): Promise<{ data: AuditLogEntry[] | null; error: any }>;
+ rpc(
+ fn: "get_audit_log_count",
+ params: {
+ p_company_id: string;
+ p_entity_type?: string | null;
+ p_actor_id?: string | null;
+ p_operation?: string | null;
+ p_start_date?: string | null;
+ p_end_date?: string | null;
+ p_search?: string | null;
+ }
+ ): Promise<{ data: number | null; error: any }>;
+ rpc(
+ fn: "get_audit_logs_for_archive",
+ params: { p_company_id: string; p_before_date: string }
+ ): Promise<{ data: AuditLogEntry[] | null; error: any }>;
+ rpc(
+ fn: "delete_old_audit_logs",
+ params: { p_company_id: string; p_cutoff_date: string }
+ ): Promise<{ data: number | null; error: any }>;
+};
+
+/**
+ * Get audit log entries for a specific entity.
+ * Queries by entityType (semantic grouping) so that child table changes
+ * (e.g., customerPayment, customerShipping) roll up into the parent entity view.
+ */
+export async function getEntityAuditLog(
+ client: SupabaseClient,
+ companyId: string,
+ entityType: string,
+ entityId: string,
+ options?: { limit?: number; offset?: number }
+): Promise<AuditLogEntry[]> {
+ const limit = options?.limit ?? 50;
+ const offset = options?.offset ?? 0;
+
+ const { data, error } = await (client as unknown as AuditRpcClient).rpc(
+ "get_entity_audit_log",
+ {
+ p_company_id: companyId,
+ p_entity_type: entityType,
+ p_entity_id: entityId,
+ p_limit: limit,
+ p_offset: offset
+ }
+ );
+
+ if (error) {
+ throw new Error(`Failed to fetch audit log: ${error.message}`);
+ }
+
+ return data ?? [];
+}
+
+/**
+ * Get audit log entries with filters (for global audit log view)
+ */
+export async function getGlobalAuditLog(
+ client: SupabaseClient,
+ companyId: string,
+ filters?: AuditLogFilters
+): Promise<AuditLogResponse> {
+ const limit = filters?.limit ?? 50;
+ const offset = filters?.offset ?? 0;
+
+ // Get data
+ const { data, error } = await (client as unknown as AuditRpcClient).rpc(
+ "get_audit_log",
+ {
+ p_company_id: companyId,
+ p_entity_type: filters?.entityType ?? null,
+ p_actor_id: filters?.actorId ?? null,
+ p_operation: filters?.operation ?? null,
+ p_start_date: filters?.startDate ?? null,
+ p_end_date: filters?.endDate ?? null,
+ p_search: filters?.search ?? null,
+ p_limit: limit,
+ p_offset: offset
+ }
+ );
+
+ if (error) {
+ throw new Error(`Failed to fetch audit log: ${error.message}`);
+ }
+
+ // Get count
+ const { data: count, error: countError } = await (
+ client as unknown as AuditRpcClient
+ ).rpc("get_audit_log_count", {
+ p_company_id: companyId,
+ p_entity_type: filters?.entityType ?? null,
+ p_actor_id: filters?.actorId ?? null,
+ p_operation: filters?.operation ?? null,
+ p_start_date: filters?.startDate ?? null,
+ p_end_date: filters?.endDate ?? null,
+ p_search: filters?.search ?? null
+ });
+
+ if (countError) {
+ throw new Error(`Failed to fetch audit log count: ${countError.message}`);
+ }
+
+ return {
+ data: data ?? [],
+ count: count ?? 0
+ };
+}
+
+/**
+ * Insert audit log entries (used by the audit handler task)
+ */
+export async function insertAuditLogEntries(
+ client: SupabaseClient,
+ companyId: string,
+ entries: CreateAuditLogEntry[]
+): Promise<number> {
+ if (entries.length === 0) return 0;
+
+ const { data, error } = await (client as unknown as AuditRpcClient).rpc(
+ "insert_audit_log_batch",
+ {
+ p_company_id: companyId,
+ p_entries: entries
+ }
+ );
+
+ if (error) {
+ throw new Error(`Failed to insert audit log entries: ${error.message}`);
+ }
+
+ return data ?? 0;
+}
+
+/**
+ * Enable audit logging for a company
+ * Creates the per-company audit log table and event subscriptions
+ */
+export async function enableAuditLog(
+ client: SupabaseClient,
+ companyId: string
+): Promise<void> {
+ // Create the per-company audit log table
+ const { error: createError } = await (
+ client as unknown as AuditRpcClient
+ ).rpc("create_audit_log_table", {
+ p_company_id: companyId
+ });
+
+ if (createError) {
+ throw new Error(`Failed to create audit log table: ${createError.message}`);
+ }
+
+ // Update company flag
+ const { error: updateError } = await client
+ .from("company")
+ .update({ auditLogEnabled: true })
+ .eq("id", companyId);
+
+ if (updateError) {
+ throw new Error(`Failed to enable audit log: ${updateError.message}`);
+ }
+
+ // Create AUDIT subscriptions for all auditable tables
+ for (const table of getAuditableTableNames()) {
+ await createEventSystemSubscription(client, {
+ name: `audit-${table}`,
+ table,
+ companyId,
+ operations: ["INSERT", "UPDATE", "DELETE"],
+ type: "AUDIT",
+ config: {},
+ filter: {},
+ active: true
+ });
+ }
+}
+
+/**
+ * Disable audit logging for a company
+ * Removes event subscriptions but keeps existing audit logs
+ */
+export async function disableAuditLog(
+ client: SupabaseClient,
+ companyId: string
+): Promise<void> {
+ // Update company flag
+ const { error: updateError } = await client
+ .from("company")
+ .update({ auditLogEnabled: false })
+ .eq("id", companyId);
+
+ if (updateError) {
+ throw new Error(`Failed to disable audit log: ${updateError.message}`);
+ }
+
+ // Delete AUDIT subscriptions for all auditable tables
+ for (const table of getAuditableTableNames()) {
+ await deleteEventSystemSubscriptionsByName(
+ client,
+ companyId,
+ `audit-${table}`
+ );
+ }
+
+ // Note: We don't drop the table - keep the data for compliance
+}
+
+/**
+ * Check if audit logging is enabled for a company
+ */
+export async function isAuditLogEnabled(
+ client: SupabaseClient,
+ companyId: string
+): Promise<boolean> {
+ const { data, error } = await client
+ .from("company")
+ .select("auditLogEnabled")
+ .eq("id", companyId)
+ .single();
+
+ if (error) {
+ throw new Error(`Failed to check audit log status: ${error.message}`);
+ }
+
+ return (
+ (data as { auditLogEnabled: boolean } | null)?.auditLogEnabled ?? false
+ );
+}
+
+/**
+ * Get list of archived audit log periods for a company
+ */
+export async function getAuditLogArchives(
+ client: SupabaseClient,
+ companyId: string
+): Promise<AuditLogArchive[]> {
+ const { data, error } = await client
+ .from("auditLogArchive")
+ .select("*")
+ .eq("companyId", companyId)
+ .order("endDate", { ascending: false });
+
+ if (error) {
+ throw new Error(`Failed to fetch audit log archives: ${error.message}`);
+ }
+
+ return data as AuditLogArchive[];
+}
+
+/**
+ * Get a signed URL for downloading an archived audit log
+ */
+export async function getArchiveDownloadUrl(
+ client: SupabaseClient,
+ archiveId: string
+): Promise<string> {
+ // First get the archive record to get the path
+ const { data: archive, error: fetchError } = await client
+ .from("auditLogArchive")
+ .select("archivePath")
+ .eq("id", archiveId)
+ .single();
+
+ if (fetchError || !archive) {
+ throw new Error(`Archive not found: ${fetchError?.message}`);
+ }
+
+ // Generate signed URL (1 hour expiry)
+ const { data, error } = await client.storage
+ .from(auditConfig.archiveBucket)
+ .createSignedUrl((archive as { archivePath: string }).archivePath, 3600);
+
+ if (error || !data?.signedUrl) {
+ throw new Error(`Failed to generate download URL: ${error?.message}`);
+ }
+
+ return data.signedUrl;
+}
+
+/**
+ * Get audit logs for archival
+ */
+export async function getAuditLogsForArchive(
+ client: SupabaseClient,
+ companyId: string,
+ cutoffDate: Date
+): Promise<AuditLogEntry[]> {
+ const { data, error } = await (client as unknown as AuditRpcClient).rpc(
+ "get_audit_logs_for_archive",
+ {
+ p_company_id: companyId,
+ p_before_date: cutoffDate.toISOString()
+ }
+ );
+
+ if (error) {
+ throw new Error(`Failed to get audit logs for archive: ${error.message}`);
+ }
+
+ return data ?? [];
+}
+
+/**
+ * Delete audit log entries older than a certain date
+ * Used by the archive task after successful export
+ */
+export async function deleteOldAuditLogs(
+ client: SupabaseClient,
+ companyId: string,
+ cutoffDate: Date
+): Promise<number> {
+ const { data, error } = await (client as unknown as AuditRpcClient).rpc(
+ "delete_old_audit_logs",
+ {
+ p_company_id: companyId,
+ p_cutoff_date: cutoffDate.toISOString()
+ }
+ );
+
+ if (error) {
+ throw new Error(`Failed to delete old audit logs: ${error.message}`);
+ }
+
+ return data ?? 0;
+}
+
+/**
+ * Record an archive in the tracking table
+ */
+export async function recordAuditLogArchive(
+ client: SupabaseClient,
+ archive: Omit<AuditLogArchive, "id" | "createdAt">
+): Promise<void> {
+ const { error } = await client.from("auditLogArchive").insert(archive);
+
+ if (error) {
+ throw new Error(`Failed to record audit log archive: ${error.message}`);
+ }
+}
+
+/**
+ * Sync audit subscriptions for a company.
+ * Ensures subscriptions exist for all auditable tables defined in the config.
+ * This handles the case where new tables are added to the config after a
+ * company has already enabled audit logging.
+ */
+export async function syncAuditSubscriptions(
+ client: SupabaseClient,
+ companyId: string
+): Promise<void> {
+ const allTables = getAuditableTableNames();
+
+ // Get existing AUDIT subscriptions for this company
+ const { data: existing, error: fetchError } = await client
+ .from("eventSystemSubscription" as any)
+ .select("name")
+ .eq("companyId", companyId)
+ .eq("handlerType", "AUDIT");
+
+ if (fetchError) {
+ // Table might not exist, silently return
+ return;
+ }
+
+ const existingNames = new Set(
+ ((existing as { name: string }[] | null) ?? []).map((s) => s.name)
+ );
+
+ // Create subscriptions for any tables that don't have one yet
+ for (const table of allTables) {
+ const subName = `audit-${table}`;
+ if (!existingNames.has(subName)) {
+ await createEventSystemSubscription(client, {
+ name: subName,
+ table,
+ companyId,
+ operations: ["INSERT", "UPDATE", "DELETE"],
+ type: "AUDIT",
+ config: {},
+ filter: {},
+ active: true
+ });
+ }
+ }
+}
diff --git a/packages/database/src/audit.types.ts b/packages/database/src/audit.types.ts
new file mode 100644
index 0000000000..db0ce8b485
--- /dev/null
+++ b/packages/database/src/audit.types.ts
@@ -0,0 +1,103 @@
+import type { AuditableTable, AuditEntityType } from "./audit.config";
+
+/**
+ * Operation types for audit log entries
+ */
+export type AuditOperation = "INSERT" | "UPDATE" | "DELETE";
+
+/**
+ * Metadata captured with each audit log entry
+ */
+export interface AuditMetadata {
+ ipAddress?: string;
+ userAgent?: string;
+ origin?: "web" | "api" | "import" | "system";
+ requestId?: string;
+}
+
+/**
+ * Represents a single field change in the diff
+ */
+export interface AuditDiffEntry {
+ old: unknown;
+ new: unknown;
+}
+
+/**
+ * The diff object showing what changed
+ * Keys are field names (can be nested like "customFields.myField")
+ */
+export type AuditDiff = Record<string, AuditDiffEntry>;
+
+/**
+ * A single audit log entry as stored in the database
+ */
+export interface AuditLogEntry {
+ id: string;
+ companyId: string;
+ tableName: AuditableTable;
+ entityType: AuditEntityType;
+ entityId: string;
+ operation: AuditOperation;
+ actorId: string | null;
+ diff: AuditDiff | null;
+ metadata: AuditMetadata | null;
+ createdAt: string;
+}
+
+/**
+ * Input for creating an audit log entry
+ * Note: companyId is passed separately to the RPC function
+ */
+export interface CreateAuditLogEntry {
+ tableName: AuditableTable;
+ entityType: AuditEntityType;
+ entityId: string;
+ operation: AuditOperation;
+ actorId: string | null;
+ diff?: AuditDiff | null;
+ metadata?: AuditMetadata | null;
+}
+
+/**
+ * Filters for querying audit logs
+ */
+export interface AuditLogFilters {
+ entityType?: AuditEntityType;
+ actorId?: string;
+ operation?: AuditOperation;
+ startDate?: string;
+ endDate?: string;
+ search?: string;
+ limit?: number;
+ offset?: number;
+}
+
+/**
+ * Response from getGlobalAuditLog with pagination info
+ */
+export interface AuditLogResponse {
+ data: AuditLogEntry[];
+ count: number;
+}
+
+/**
+ * An archived audit log period
+ */
+export interface AuditLogArchive {
+ id: string;
+ companyId: string;
+ archivePath: string;
+ startDate: string;
+ endDate: string;
+ rowCount: number;
+ sizeBytes: number | null;
+ createdAt: string;
+}
+
+/**
+ * Configuration for enabling audit logs
+ */
+export interface AuditLogConfig {
+ enabled: boolean;
+}
diff --git a/packages/database/src/event.ts b/packages/database/src/event.ts
index ddc501e951..347ac9eb13 100644
--- a/packages/database/src/event.ts
+++ b/packages/database/src/event.ts
@@ -8,7 +8,13 @@ export const OperationSchema = z.enum([
"TRUNCATE"
]);
-const HandlerTypeSchema = z.enum(["WEBHOOK", "WORKFLOW", "SYNC", "SEARCH"]);
+const HandlerTypeSchema = z.enum([
+ "WEBHOOK",
+ "WORKFLOW",
+ "SYNC",
+ "SEARCH",
+ "AUDIT"
+]);
export const EventSchema = z.discriminatedUnion("operation", [
z.object({
@@ -43,6 +49,7 @@ export const QueueMessageSchema = z.object({
handlerType: HandlerTypeSchema,
handlerConfig: z.record(z.any()),
companyId: z.string(),
+ actorId: z.string().nullish(), // Captured from auth.uid() at trigger time
event: EventSchema
});
diff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.ts
index f68e64f7c4..243fefaebd 100644
--- a/packages/database/src/seed-dev.ts
+++ b/packages/database/src/seed-dev.ts
@@ -11,7 +11,7 @@
import { parseArgs } from "node:util";
import { createClient } from "@supabase/supabase-js";
import * as dotenv from "dotenv";
-import { getPostgresConnectionPool } from "./client";
+import { getPostgresConnectionPool } from "./client.ts";
import {
accountCategories,
accountDefaults,
@@ -34,8 +34,8 @@ import {
sequences,
supplierStatuses,
unitOfMeasures
-} from "./seed/seed.data";
-import type { Database } from "./types";
+} from "./seed/seed.data.ts";
+import type { Database } from "./types.ts";
// Load environment variables
dotenv.config();
@@ -43,6 +43,19 @@ dotenv.config();
const DEV_PASSWORD = "password";
const DEV_COMPANY_NAME = "Carbon Development";
+/**
+ * Infers a first name from an email address.
+ * Takes the local part (before @), splits on common delimiters (., +, _),
+ * takes the first segment, and capitalizes it.
+ */
+function inferFirstNameFromEmail(email: string): string {
+ const localPart = email.split("@")[0];
+ // Split on common delimiters and take the first part
+ const firstName = localPart.split(/[.+_-]/)[0];
+ // Capitalize first letter, lowercase the rest
+ return firstName.charAt(0).toUpperCase() + firstName.slice(1).toLowerCase();
+}
+
// Parse CLI arguments
const { values } = parseArgs({
options: {
@@ -151,19 +164,27 @@ async function seedDev() {
console.log(` User created with ID: ${userId}`);
}
- // Step 2: Begin transaction for all database operations
- console.log("2. Starting database transaction...");
+ // Step 2: Update user's first name (inferred from email)
+ const firstName = inferFirstNameFromEmail(email);
+ console.log(`2. Updating user first name to "${firstName}"...`);
+ await client.query(`UPDATE "user" SET "firstName" = $1 WHERE id = $2`, [
+ firstName,
+ userId
+ ]);
+
+ // Step 3: Begin transaction for all database operations
+ console.log("3. Starting database transaction...");
await client.query("BEGIN");
try {
// Generate company ID using xid() function
- console.log("3. Generating company ID...");
+ console.log("4. Generating company ID...");
const xidResult = await client.query("SELECT xid() as id");
const companyId = xidResult.rows[0].id as string;
console.log(` Company ID: ${companyId}`);
// Create the company
- console.log("4. Creating company...");
+ console.log("5. Creating company...");
await client.query(
`INSERT INTO company (id, name, "baseCurrencyCode") VALUES ($1, $2, 'USD')`,
[companyId, DEV_COMPANY_NAME]
@@ -171,7 +192,7 @@ async function seedDev() {
console.log(` Company "${DEV_COMPANY_NAME}" created.`);
// Seed the company with all default data
- console.log("5. Seeding company with default data...");
+ console.log("6. Seeding company with default data...");
// Create storage bucket
await client.query(
@@ -541,7 +562,7 @@ async function seedDev() {
);
// Update user permissions
- console.log("6. Updating user permissions...");
+ console.log("7. Updating user permissions...");
// Build permissions object
const newPermissions: Record<string, string[]> = {};
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0fef4854ba..3de43bae98 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -6444,6 +6444,168 @@ export default {
tags: ["productionQuantity"],
},
},
+ "/auditLogArchive": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.archivePath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.endDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.rowCount",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.sizeBytes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.createdAt",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/auditLogArchive",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["auditLogArchive"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.auditLogArchive",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["auditLogArchive"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.archivePath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.endDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.rowCount",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.sizeBytes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.createdAt",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["auditLogArchive"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.archivePath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.endDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.rowCount",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.sizeBytes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.auditLogArchive.createdAt",
+ },
+ {
+ $ref: "#/parameters/body.auditLogArchive",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["auditLogArchive"],
+ },
+ },
"/nonConformanceActionTask": {
get: {
parameters: [
@@ -48987,6 +49149,9 @@ export default {
{
$ref: "#/parameters/rowFilter.company.suggestionNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.company.auditLogEnabled",
+ },
{
$ref: "#/parameters/select",
},
@@ -49115,6 +49280,9 @@ export default {
{
$ref: "#/parameters/rowFilter.company.suggestionNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.company.auditLogEnabled",
+ },
{
$ref: "#/parameters/preferReturn",
},
@@ -49197,6 +49365,9 @@ export default {
{
$ref: "#/parameters/rowFilter.company.suggestionNotificationGroup",
},
+ {
+ $ref: "#/parameters/rowFilter.company.auditLogEnabled",
+ },
{
$ref: "#/parameters/body.company",
},
@@ -63154,6 +63325,41 @@ export default {
tags: ["(rpc) has_company_permission"],
},
},
+ "/rpc/create_audit_log_table": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["p_company_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) create_audit_log_table"],
+ },
+ },
"/rpc/get_training_assignments_by_user": {
post: {
parameters: [
@@ -63772,6 +63978,46 @@ export default {
tags: ["(rpc) get_direct_descendants_of_tracked_entity_strict"],
},
},
+ "/rpc/insert_audit_log_batch": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_entries: {
+ format: "jsonb[]",
+ items: {},
+ type: "array",
+ },
+ },
+ required: ["p_company_id", "p_entries"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) insert_audit_log_batch"],
+ },
+ },
"/rpc/create_rfq_from_models_v1": {
post: {
parameters: [
@@ -65250,6 +65496,57 @@ export default {
tags: ["(rpc) prevent_posted_sales_invoice_deletion"],
},
},
+ "/rpc/get_entity_audit_log": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_entity_id: {
+ format: "text",
+ type: "string",
+ },
+ p_entity_type: {
+ format: "text",
+ type: "string",
+ },
+ p_limit: {
+ format: "integer",
+ type: "integer",
+ },
+ p_offset: {
+ format: "integer",
+ type: "integer",
+ },
+ },
+ required: ["p_company_id", "p_entity_type", "p_entity_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_entity_audit_log"],
+ },
+ },
"/rpc/get_active_job_count": {
post: {
parameters: [
@@ -65328,6 +65625,63 @@ export default {
tags: ["(rpc) delete_event_system_subscriptions_by_name"],
},
},
+ "/rpc/get_primary_key_column": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "p_table_name",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_primary_key_column"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_table_name: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["p_table_name"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_primary_key_column"],
+ },
+ },
"/rpc/groups_for_user": {
post: {
parameters: [
@@ -65590,6 +65944,77 @@ export default {
tags: ["(rpc) uuid_to_base58"],
},
},
+ "/rpc/get_audit_log": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_actor_id: {
+ format: "text",
+ type: "string",
+ },
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_end_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ p_entity_id: {
+ format: "text",
+ type: "string",
+ },
+ p_entity_type: {
+ format: "text",
+ type: "string",
+ },
+ p_limit: {
+ format: "integer",
+ type: "integer",
+ },
+ p_offset: {
+ format: "integer",
+ type: "integer",
+ },
+ p_operation: {
+ format: "text",
+ type: "string",
+ },
+ p_search: {
+ format: "text",
+ type: "string",
+ },
+ p_start_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ required: ["p_company_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_audit_log"],
+ },
+ },
"/rpc/get_assigned_job_operations": {
post: {
parameters: [
@@ -66080,6 +66505,45 @@ export default {
tags: ["(rpc) increment_webhook_error"],
},
},
+ "/rpc/get_audit_logs_for_archive": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_before_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["p_company_id", "p_before_date"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_audit_logs_for_archive"],
+ },
+ },
"/rpc/journalLinesByAccountNumber": {
post: {
parameters: [
@@ -66188,6 +66652,45 @@ export default {
tags: ["(rpc) get_my_claim"],
},
},
+ "/rpc/delete_old_audit_logs": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_cutoff_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ required: ["p_company_id", "p_cutoff_date"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) delete_old_audit_logs"],
+ },
+ },
"/rpc/get_job_quantity_on_hand": {
post: {
parameters: [
@@ -66288,6 +66791,41 @@ export default {
tags: ["(rpc) get_material_naming_details"],
},
},
+ "/rpc/drop_audit_log_table": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["p_company_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) drop_audit_log_table"],
+ },
+ },
"/rpc/get_job_method": {
get: {
parameters: [
@@ -66967,6 +67505,65 @@ export default {
tags: ["(rpc) groups_query"],
},
},
+ "/rpc/get_audit_log_count": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_actor_id: {
+ format: "text",
+ type: "string",
+ },
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_end_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ p_entity_type: {
+ format: "text",
+ type: "string",
+ },
+ p_operation: {
+ format: "text",
+ type: "string",
+ },
+ p_search: {
+ format: "text",
+ type: "string",
+ },
+ p_start_date: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ required: ["p_company_id"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_audit_log_count"],
+ },
+ },
"/rpc/get_next_prefixed_sequence": {
post: {
parameters: [
@@ -67355,6 +67952,74 @@ export default {
tags: ["(rpc) update_receipt_line_batch_tracking"],
},
},
+ "/rpc/insert_audit_log": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ p_actor_id: {
+ format: "text",
+ type: "string",
+ },
+ p_actor_name: {
+ format: "text",
+ type: "string",
+ },
+ p_company_id: {
+ format: "text",
+ type: "string",
+ },
+ p_diff: {
+ format: "jsonb",
+ },
+ p_entity_id: {
+ format: "text",
+ type: "string",
+ },
+ p_entity_type: {
+ format: "text",
+ type: "string",
+ },
+ p_metadata: {
+ format: "jsonb",
+ },
+ p_operation: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: [
+ "p_company_id",
+ "p_entity_type",
+ "p_entity_id",
+ "p_operation",
+ "p_actor_id",
+ "p_actor_name",
+ ],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) insert_audit_log"],
+ },
+ },
"/rpc/get_purchasing_planning": {
post: {
parameters: [
@@ -70640,6 +71305,57 @@ export default {
},
type: "object",
},
+ auditLogArchive: {
+ required: [
+ "id",
+ "companyId",
+ "archivePath",
+ "startDate",
+ "endDate",
+ "rowCount",
+ "createdAt",
+ ],
+ properties: {
+ id: {
+ default: "public.id('arc'::text)",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ archivePath: {
+ format: "text",
+ type: "string",
+ },
+ startDate: {
+ format: "date",
+ type: "string",
+ },
+ endDate: {
+ format: "date",
+ type: "string",
+ },
+ rowCount: {
+ format: "integer",
+ type: "integer",
+ },
+ sizeBytes: {
+ format: "bigint",
+ type: "integer",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
nonConformanceActionTask: {
required: [
"id",
@@ -90850,6 +91566,7 @@ export default {
"baseCurrencyCode",
"createdAt",
"suggestionNotificationGroup",
+ "auditLogEnabled",
],
properties: {
id: {
@@ -90954,6 +91671,11 @@ export default {
},
type: "array",
},
+ auditLogEnabled: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
},
type: "object",
},
@@ -101064,6 +101786,63 @@ export default {
in: "query",
type: "string",
},
+ "body.auditLogArchive": {
+ name: "auditLogArchive",
+ description: "auditLogArchive",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/auditLogArchive",
+ },
+ },
+ "rowFilter.auditLogArchive.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.archivePath": {
+ name: "archivePath",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.startDate": {
+ name: "startDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.endDate": {
+ name: "endDate",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.rowCount": {
+ name: "rowCount",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.sizeBytes": {
+ name: "sizeBytes",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.auditLogArchive.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.nonConformanceActionTask": {
name: "nonConformanceActionTask",
description: "nonConformanceActionTask",
@@ -123983,6 +124762,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.company.auditLogEnabled": {
+ name: "auditLogEnabled",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.salesOrderLocations": {
name: "salesOrderLocations",
description: "salesOrderLocations",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index d16c78f09a..846df8ff0d 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -2133,6 +2133,68 @@ export type Database = {
}
Relationships: []
}
+ auditLogArchive: {
+ Row: {
+ archivePath: string
+ companyId: string
+ createdAt: string
+ endDate: string
+ id: string
+ rowCount: number
+ sizeBytes: number | null
+ startDate: string
+ }
+ Insert: {
+ archivePath: string
+ companyId: string
+ createdAt?: string
+ endDate: string
+ id?: string
+ rowCount: number
+ sizeBytes?: number | null
+ startDate: string
+ }
+ Update: {
+ archivePath?: string
+ companyId?: string
+ createdAt?: string
+ endDate?: string
+ id?: string
+ rowCount?: number
+ sizeBytes?: number | null
+ startDate?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
batchProperty: {
Row: {
companyId: string
@@ -2383,6 +2445,7 @@ export type Database = {
Row: {
addressLine1: string | null
addressLine2: string | null
+ auditLogEnabled: boolean
baseCurrencyCode: string
city: string | null
countryCode: string | null
@@ -2408,6 +2471,7 @@ export type Database = {
Insert: {
addressLine1?: string | null
addressLine2?: string | null
+ auditLogEnabled?: boolean
baseCurrencyCode: string
city?: string | null
countryCode?: string | null
@@ -2433,6 +2497,7 @@ export type Database = {
Update: {
addressLine1?: string | null
addressLine2?: string | null
+ auditLogEnabled?: boolean
baseCurrencyCode?: string
city?: string | null
countryCode?: string | null
@@ -51891,14 +51956,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55469,6 +55534,10 @@ export type Database = {
Args: { operation_id: string }
Returns: boolean
}
+ create_audit_log_table: {
+ Args: { p_company_id: string }
+ Returns: undefined
+ }
create_company_search_index: {
Args: { p_company_id: string }
Returns: undefined
@@ -55553,6 +55622,14 @@ export type Database = {
}
Returns: undefined
}
+ delete_old_audit_logs: {
+ Args: { p_company_id: string; p_cutoff_date: string }
+ Returns: number
+ }
+ drop_audit_log_table: {
+ Args: { p_company_id: string }
+ Returns: undefined
+ }
drop_company_search_index: {
Args: { p_company_id: string }
Returns: undefined
@@ -55689,6 +55766,58 @@ export type Database = {
workCenterId: string
}[]
}
+ get_audit_log: {
+ Args: {
+ p_actor_id?: string
+ p_company_id: string
+ p_end_date?: string
+ p_entity_id?: string
+ p_entity_type?: string
+ p_limit?: number
+ p_offset?: number
+ p_operation?: string
+ p_search?: string
+ p_start_date?: string
+ }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ totalCount: number
+ }[]
+ }
+ get_audit_log_count: {
+ Args: {
+ p_actor_id?: string
+ p_company_id: string
+ p_end_date?: string
+ p_entity_type?: string
+ p_operation?: string
+ p_search?: string
+ p_start_date?: string
+ }
+ Returns: number
+ }
+ get_audit_logs_for_archive: {
+ Args: { p_before_date: string; p_company_id: string }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ }[]
+ }
get_claims: { Args: { company: string; uid: string }; Returns: Json }
get_companies_with_any_role: { Args: never; Returns: string[] }
get_companies_with_employee_permission: {
@@ -55813,6 +55942,26 @@ export type Database = {
trackedActivityId: string
}[]
}
+ get_entity_audit_log: {
+ Args: {
+ p_company_id: string
+ p_entity_id: string
+ p_entity_type: string
+ p_limit?: number
+ p_offset?: number
+ }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ }[]
+ }
get_inventory_quantities: {
Args: { company_id: string; location_id: string }
Returns: {
@@ -56325,6 +56474,10 @@ export type Database = {
get_period_end_date: { Args: { period: string }; Returns: string }
get_period_start_date: { Args: { period: string }; Returns: string }
get_permission_companies: { Args: { claim: string }; Returns: string[] }
+ get_primary_key_column: {
+ Args: { p_table_name: string }
+ Returns: string
+ }
get_production_planning: {
Args: { company_id: string; location_id: string; periods: string[] }
Returns: {
@@ -56903,6 +57056,23 @@ export type Database = {
Args: { webhook_id: string }
Returns: undefined
}
+ insert_audit_log: {
+ Args: {
+ p_actor_id: string
+ p_actor_name: string
+ p_company_id: string
+ p_diff?: Json
+ p_entity_id: string
+ p_entity_type: string
+ p_metadata?: Json
+ p_operation: string
+ }
+ Returns: string
+ }
+ insert_audit_log_batch: {
+ Args: { p_company_id: string; p_entries: Json[] }
+ Returns: number
+ }
is_claims_admin: { Args: never; Returns: boolean }
is_last_job_operation: {
Args: { operation_id: string }
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index d16c78f09a..846df8ff0d 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -2133,6 +2133,68 @@ export type Database = {
}
Relationships: []
}
+ auditLogArchive: {
+ Row: {
+ archivePath: string
+ companyId: string
+ createdAt: string
+ endDate: string
+ id: string
+ rowCount: number
+ sizeBytes: number | null
+ startDate: string
+ }
+ Insert: {
+ archivePath: string
+ companyId: string
+ createdAt?: string
+ endDate: string
+ id?: string
+ rowCount: number
+ sizeBytes?: number | null
+ startDate: string
+ }
+ Update: {
+ archivePath?: string
+ companyId?: string
+ createdAt?: string
+ endDate?: string
+ id?: string
+ rowCount?: number
+ sizeBytes?: number | null
+ startDate?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "auditLogArchive_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
batchProperty: {
Row: {
companyId: string
@@ -2383,6 +2445,7 @@ export type Database = {
Row: {
addressLine1: string | null
addressLine2: string | null
+ auditLogEnabled: boolean
baseCurrencyCode: string
city: string | null
countryCode: string | null
@@ -2408,6 +2471,7 @@ export type Database = {
Insert: {
addressLine1?: string | null
addressLine2?: string | null
+ auditLogEnabled?: boolean
baseCurrencyCode: string
city?: string | null
countryCode?: string | null
@@ -2433,6 +2497,7 @@ export type Database = {
Update: {
addressLine1?: string | null
addressLine2?: string | null
+ auditLogEnabled?: boolean
baseCurrencyCode?: string
city?: string | null
countryCode?: string | null
@@ -51891,14 +51956,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["invoiceCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["invoiceCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["alpha2"]
@@ -55469,6 +55534,10 @@ export type Database = {
Args: { operation_id: string }
Returns: boolean
}
+ create_audit_log_table: {
+ Args: { p_company_id: string }
+ Returns: undefined
+ }
create_company_search_index: {
Args: { p_company_id: string }
Returns: undefined
@@ -55553,6 +55622,14 @@ export type Database = {
}
Returns: undefined
}
+ delete_old_audit_logs: {
+ Args: { p_company_id: string; p_cutoff_date: string }
+ Returns: number
+ }
+ drop_audit_log_table: {
+ Args: { p_company_id: string }
+ Returns: undefined
+ }
drop_company_search_index: {
Args: { p_company_id: string }
Returns: undefined
@@ -55689,6 +55766,58 @@ export type Database = {
workCenterId: string
}[]
}
+ get_audit_log: {
+ Args: {
+ p_actor_id?: string
+ p_company_id: string
+ p_end_date?: string
+ p_entity_id?: string
+ p_entity_type?: string
+ p_limit?: number
+ p_offset?: number
+ p_operation?: string
+ p_search?: string
+ p_start_date?: string
+ }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ totalCount: number
+ }[]
+ }
+ get_audit_log_count: {
+ Args: {
+ p_actor_id?: string
+ p_company_id: string
+ p_end_date?: string
+ p_entity_type?: string
+ p_operation?: string
+ p_search?: string
+ p_start_date?: string
+ }
+ Returns: number
+ }
+ get_audit_logs_for_archive: {
+ Args: { p_before_date: string; p_company_id: string }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ }[]
+ }
get_claims: { Args: { company: string; uid: string }; Returns: Json }
get_companies_with_any_role: { Args: never; Returns: string[] }
get_companies_with_employee_permission: {
@@ -55813,6 +55942,26 @@ export type Database = {
trackedActivityId: string
}[]
}
+ get_entity_audit_log: {
+ Args: {
+ p_company_id: string
+ p_entity_id: string
+ p_entity_type: string
+ p_limit?: number
+ p_offset?: number
+ }
+ Returns: {
+ actorId: string
+ createdAt: string
+ diff: Json
+ entityId: string
+ entityType: string
+ id: string
+ metadata: Json
+ operation: string
+ tableName: string
+ }[]
+ }
get_inventory_quantities: {
Args: { company_id: string; location_id: string }
Returns: {
@@ -56325,6 +56474,10 @@ export type Database = {
get_period_end_date: { Args: { period: string }; Returns: string }
get_period_start_date: { Args: { period: string }; Returns: string }
get_permission_companies: { Args: { claim: string }; Returns: string[] }
+ get_primary_key_column: {
+ Args: { p_table_name: string }
+ Returns: string
+ }
get_production_planning: {
Args: { company_id: string; location_id: string; periods: string[] }
Returns: {
@@ -56903,6 +57056,23 @@ export type Database = {
Args: { webhook_id: string }
Returns: undefined
}
+ insert_audit_log: {
+ Args: {
+ p_actor_id: string
+ p_actor_name: string
+ p_company_id: string
+ p_diff?: Json
+ p_entity_id: string
+ p_entity_type: string
+ p_metadata?: Json
+ p_operation: string
+ }
+ Returns: string
+ }
+ insert_audit_log_batch: {
+ Args: { p_company_id: string; p_entries: Json[] }
+ Returns: number
+ }
is_claims_admin: { Args: never; Returns: boolean }
is_last_job_operation: {
Args: { operation_id: string }
diff --git a/packages/database/supabase/migrations/20260212152709_audit_log_system.sql b/packages/database/supabase/migrations/20260212152709_audit_log_system.sql
new file mode 100644
index 0000000000..c69fc180cb
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212152709_audit_log_system.sql
@@ -0,0 +1,433 @@
+-- Add audit log enabled column to company table
+ALTER TABLE "company"
+ ADD COLUMN IF NOT EXISTS "auditLogEnabled" BOOLEAN NOT NULL DEFAULT false;
+
+-- Create audit log archive tracking table (shared - tracks all company archives)
+CREATE TABLE "auditLogArchive" (
+ "id" TEXT NOT NULL DEFAULT id('arc'),
+ "companyId" TEXT NOT NULL,
+ "archivePath" TEXT NOT NULL,
+ "startDate" DATE NOT NULL,
+ "endDate" DATE NOT NULL,
+ "rowCount" INTEGER NOT NULL,
+ "sizeBytes" BIGINT,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT "auditLogArchive_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "auditLogArchive_companyId_fkey"
+ FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE
+);
+
+CREATE INDEX "auditLogArchive_companyId_idx" ON "auditLogArchive"("companyId");
+
+ALTER TABLE "auditLogArchive" ENABLE ROW LEVEL SECURITY;
+-- No RLS policies = service role only
+
+-- Update event system subscription handler type constraint to include AUDIT
+ALTER TABLE "eventSystemSubscription"
+DROP CONSTRAINT IF EXISTS "eventSystemSubscription_handlerType_check";
+
+ALTER TABLE "eventSystemSubscription"
+ADD CONSTRAINT "eventSystemSubscription_handlerType_check"
+CHECK ("handlerType" IN ('WEBHOOK', 'WORKFLOW', 'SYNC', 'SEARCH', 'AUDIT'));
+
+-- Function to create a per-company audit log table
+CREATE OR REPLACE FUNCTION create_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ table_name TEXT;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table already exists
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name = table_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Create the audit log table for this company
+ EXECUTE format('
+ CREATE TABLE %I (
+ "id" TEXT NOT NULL DEFAULT id(''aud''),
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "operation" TEXT NOT NULL,
+ "actorId" TEXT NOT NULL,
+ "actorName" TEXT NOT NULL,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT %I PRIMARY KEY ("id"),
+ CONSTRAINT %I
+ FOREIGN KEY ("actorId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT %I
+ CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE''))
+ )',
+ table_name,
+ table_name || '_pkey',
+ table_name || '_actorId_fkey',
+ table_name || '_operation_check'
+ );
+
+ -- Create indexes
+ EXECUTE format('CREATE INDEX %I ON %I("entityType", "entityId")',
+ table_name || '_entityType_entityId_idx', table_name);
+ EXECUTE format('CREATE INDEX %I ON %I("createdAt" DESC)',
+ table_name || '_createdAt_idx', table_name);
+ EXECUTE format('CREATE INDEX %I ON %I("actorId")',
+ table_name || '_actorId_idx', table_name);
+ EXECUTE format('CREATE INDEX %I ON %I("operation")',
+ table_name || '_operation_idx', table_name);
+
+ -- Enable RLS (no policies = service role only)
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', table_name);
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to drop a per-company audit log table
+CREATE OR REPLACE FUNCTION drop_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ table_name TEXT;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', table_name);
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to insert into a per-company audit log table
+CREATE OR REPLACE FUNCTION insert_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_operation TEXT,
+ p_actor_id TEXT,
+ p_actor_name TEXT,
+ p_diff JSONB DEFAULT NULL,
+ p_metadata JSONB DEFAULT NULL
+)
+RETURNS TEXT AS $$
+DECLARE
+ table_name TEXT;
+ new_id TEXT;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING "id"
+ ', table_name)
+ USING p_entity_type, p_entity_id, p_operation, p_actor_id, p_actor_name, p_diff, p_metadata
+ INTO new_id;
+
+ RETURN new_id;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to batch insert into a per-company audit log table
+CREATE OR REPLACE FUNCTION insert_audit_log_batch(
+ p_company_id TEXT,
+ p_entries JSONB
+)
+RETURNS INTEGER AS $$
+DECLARE
+ table_name TEXT;
+ entry JSONB;
+ inserted_count INTEGER := 0;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ FOR entry IN SELECT * FROM jsonb_array_elements(p_entries)
+ LOOP
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ ', table_name)
+ USING
+ entry->>'entityType',
+ entry->>'entityId',
+ entry->>'operation',
+ entry->>'actorId',
+ entry->>'actorName',
+ entry->'diff',
+ entry->'metadata';
+
+ inserted_count := inserted_count + 1;
+ END LOOP;
+
+ RETURN inserted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to query audit logs for an entity
+CREATE OR REPLACE FUNCTION get_entity_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ table_name TEXT;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = table_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', table_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to query all audit logs for a company with filters
+CREATE OR REPLACE FUNCTION get_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_end_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_search TEXT DEFAULT NULL,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ table_name TEXT;
+ query TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = table_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Build WHERE clauses
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format(
+ '("actorName" ILIKE %L OR "entityId" ILIKE %L)',
+ '%' || p_search || '%',
+ '%' || p_search || '%'
+ ));
+ END IF;
+
+ -- Build query
+ query := format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ ', table_name);
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ query := query || ' WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ query := query || format(' ORDER BY "createdAt" DESC LIMIT %s OFFSET %s', p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to get count of audit logs with filters
+CREATE OR REPLACE FUNCTION get_audit_log_count(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_end_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS INTEGER AS $$
+DECLARE
+ table_name TEXT;
+ query TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ result INTEGER;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = table_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ -- Build WHERE clauses (same as get_audit_log)
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format(
+ '("actorName" ILIKE %L OR "entityId" ILIKE %L)',
+ '%' || p_search || '%',
+ '%' || p_search || '%'
+ ));
+ END IF;
+
+ -- Build query
+ query := format('SELECT COUNT(*)::INTEGER FROM %I', table_name);
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ query := query || ' WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ EXECUTE query INTO result;
+ RETURN result;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to delete old audit logs (for archival)
+CREATE OR REPLACE FUNCTION delete_old_audit_logs(
+ p_company_id TEXT,
+ p_cutoff_date TIMESTAMP WITH TIME ZONE
+)
+RETURNS INTEGER AS $$
+DECLARE
+ table_name TEXT;
+ deleted_count INTEGER;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = table_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ EXECUTE format('
+ WITH deleted AS (
+ DELETE FROM %I
+ WHERE "createdAt" < $1
+ RETURNING *
+ )
+ SELECT COUNT(*) FROM deleted
+ ', table_name)
+ USING p_cutoff_date
+ INTO deleted_count;
+
+ RETURN deleted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to get all audit logs for archival
+CREATE OR REPLACE FUNCTION get_audit_logs_for_archive(
+ p_company_id TEXT,
+ p_cutoff_date TIMESTAMP WITH TIME ZONE
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ table_name TEXT;
+BEGIN
+ table_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = table_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', table_name)
+ USING p_cutoff_date;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260212153753_event_system_add_actor.sql b/packages/database/supabase/migrations/20260212153753_event_system_add_actor.sql
new file mode 100644
index 0000000000..e75ddc4c46
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212153753_event_system_add_actor.sql
@@ -0,0 +1,148 @@
+-- Add auth.uid() capture to event system
+-- This allows event handlers (like audit log) to know who triggered the event
+
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, pgmq, extensions
+AS $$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+BEGIN
+ -- Guard: Skip if we're in a sync operation (prevents circular triggers)
+ -- Set this via: SET LOCAL "app.sync_in_progress" = 'true';
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- Capture the current authenticated user (will be NULL for service role operations)
+ current_actor_id := auth.uid()::TEXT;
+
+ -- A. Extract Company ID (Partition Key)
+ -- We need this to efficiently filter subscriptions.
+ -- NOTE: For STATEMENT-level triggers, OLD/NEW are not available.
+ -- We must query the transition tables (batched_new/batched_old) instead.
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE -- UPDATE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ -- Performance Guard: If record has no companyId, we can't match any subscriptions.
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ -- B. Fast Check: Any active subscriptions for this Company + Table + Op?
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id -- Use the Index!
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+
+ -- C. Iterate Subscriptions (Filtered by Company)
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id -- Use the Index!
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ LOOP
+
+ -- D. Build Batch Payload
+ -- Filter rows using the subscription's JSONB filter
+ -- Only include rows belonging to the correct companyId (Redundant but safe)
+
+ IF TG_OP = 'INSERT' THEN
+ SELECT array_agg(
+ jsonb_build_object(
+ 'subscriptionId', sub.id,
+ 'triggerType', TG_LEVEL,
+ 'handlerType', sub."handlerType",
+ 'handlerConfig', sub."config",
+ 'companyId', rec_company_id,
+ 'actorId', current_actor_id,
+ 'event', jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'operation', TG_OP,
+ 'recordId', t.id,
+ 'new', row_to_json(t)::jsonb,
+ 'old', null,
+ 'timestamp', NOW()
+ )
+ )
+ ) INTO msg_batch
+ FROM batched_new t
+ WHERE t."companyId" = rec_company_id
+ AND (sub.filter = '{}'::jsonb OR row_to_json(t)::jsonb @> sub.filter);
+
+ ELSIF TG_OP = 'DELETE' THEN
+ SELECT array_agg(
+ jsonb_build_object(
+ 'subscriptionId', sub.id,
+ 'triggerType', TG_LEVEL,
+ 'handlerType', sub."handlerType",
+ 'handlerConfig', sub."config",
+ 'companyId', rec_company_id,
+ 'actorId', current_actor_id,
+ 'event', jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'operation', TG_OP,
+ 'recordId', t.id,
+ 'new', null,
+ 'old', row_to_json(t)::jsonb,
+ 'timestamp', NOW()
+ )
+ )
+ ) INTO msg_batch
+ FROM batched_old t
+ WHERE t."companyId" = rec_company_id
+ AND (sub.filter = '{}'::jsonb OR row_to_json(t)::jsonb @> sub.filter);
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ SELECT array_agg(
+ jsonb_build_object(
+ 'subscriptionId', sub.id,
+ 'triggerType', TG_LEVEL,
+ 'handlerType', sub."handlerType",
+ 'handlerConfig', sub."config",
+ 'companyId', rec_company_id,
+ 'actorId', current_actor_id,
+ 'event', jsonb_build_object(
+ 'table', TG_TABLE_NAME,
+ 'operation', TG_OP,
+ 'recordId', n.id,
+ 'new', row_to_json(n)::jsonb,
+ 'old', row_to_json(o)::jsonb,
+ 'timestamp', NOW()
+ )
+ )
+ ) INTO msg_batch
+ FROM batched_new n
+ JOIN batched_old o ON n.id = o.id
+ WHERE n."companyId" = rec_company_id
+ AND (sub.filter = '{}'::jsonb OR row_to_json(n)::jsonb @> sub.filter);
+ END IF;
+
+ -- E. Send Batch (PGMQ)
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ END IF;
+
+ END LOOP;
+
+ RETURN NULL;
+END;
+$$;
+
+COMMENT ON FUNCTION public.dispatch_event_batch() IS 'Dispatches database events to PGMQ with auth.uid() captured as actorId for audit purposes';
diff --git a/packages/database/supabase/migrations/20260212154954_fix_audit_log_table_name_ambiguity.sql b/packages/database/supabase/migrations/20260212154954_fix_audit_log_table_name_ambiguity.sql
new file mode 100644
index 0000000000..84f6c06713
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212154954_fix_audit_log_table_name_ambiguity.sql
@@ -0,0 +1,403 @@
+-- Fix ambiguous table_name reference in audit log functions
+-- Rename the variable to tbl_name to avoid conflict with information_schema.tables.table_name
+
+-- Function to create a per-company audit log table
+CREATE OR REPLACE FUNCTION create_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table already exists
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Create the audit log table for this company
+ EXECUTE format('
+ CREATE TABLE %I (
+ "id" TEXT NOT NULL DEFAULT id(''aud''),
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "operation" TEXT NOT NULL,
+ "actorId" TEXT NOT NULL,
+ "actorName" TEXT NOT NULL,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT %I PRIMARY KEY ("id"),
+ CONSTRAINT %I
+ FOREIGN KEY ("actorId") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+ CONSTRAINT %I
+ CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE''))
+ )',
+ tbl_name,
+ tbl_name || '_pkey',
+ tbl_name || '_actorId_fkey',
+ tbl_name || '_operation_check'
+ );
+
+ -- Create indexes
+ EXECUTE format('CREATE INDEX %I ON %I("entityType", "entityId")',
+ tbl_name || '_entityType_entityId_idx', tbl_name);
+ EXECUTE format('CREATE INDEX %I ON %I("createdAt" DESC)',
+ tbl_name || '_createdAt_idx', tbl_name);
+ EXECUTE format('CREATE INDEX %I ON %I("actorId")',
+ tbl_name || '_actorId_idx', tbl_name);
+ EXECUTE format('CREATE INDEX %I ON %I("operation")',
+ tbl_name || '_operation_idx', tbl_name);
+
+ -- Enable RLS (no policies = service role only)
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to drop a per-company audit log table
+CREATE OR REPLACE FUNCTION drop_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('DROP TABLE IF EXISTS %I CASCADE', tbl_name);
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to insert into a per-company audit log table
+CREATE OR REPLACE FUNCTION insert_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_operation TEXT,
+ p_actor_id TEXT,
+ p_actor_name TEXT,
+ p_diff JSONB DEFAULT NULL,
+ p_metadata JSONB DEFAULT NULL
+)
+RETURNS TEXT AS $$
+DECLARE
+ tbl_name TEXT;
+ new_id TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ RETURNING "id"
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_operation, p_actor_id, p_actor_name, p_diff, p_metadata
+ INTO new_id;
+
+ RETURN new_id;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to batch insert into a per-company audit log table
+CREATE OR REPLACE FUNCTION insert_audit_log_batch(
+ p_company_id TEXT,
+ p_entries JSONB
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ entry JSONB;
+ inserted_count INTEGER := 0;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ FOR entry IN SELECT * FROM jsonb_array_elements(p_entries)
+ LOOP
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ ', tbl_name)
+ USING
+ entry->>'entityType',
+ entry->>'entityId',
+ entry->>'operation',
+ entry->>'actorId',
+ entry->>'actorName',
+ entry->'diff',
+ entry->'metadata';
+
+ inserted_count := inserted_count + 1;
+ END LOOP;
+
+ RETURN inserted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to query audit logs for an entity
+CREATE OR REPLACE FUNCTION get_entity_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to query all audit logs for a company with filters
+CREATE OR REPLACE FUNCTION get_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_end_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_search TEXT DEFAULT NULL,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ tbl_name TEXT;
+ query TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Build WHERE clauses
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format(
+ '("actorName" ILIKE %L OR "entityId" ILIKE %L)',
+ '%' || p_search || '%',
+ '%' || p_search || '%'
+ ));
+ END IF;
+
+ -- Build query
+ query := format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ ', tbl_name);
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ query := query || ' WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ query := query || format(' ORDER BY "createdAt" DESC LIMIT %s OFFSET %s', p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to get count of audit logs with filters
+CREATE OR REPLACE FUNCTION get_audit_log_count(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_end_date TIMESTAMP WITH TIME ZONE DEFAULT NULL,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ query TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ result INTEGER;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ -- Build WHERE clauses (same as get_audit_log)
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format(
+ '("actorName" ILIKE %L OR "entityId" ILIKE %L)',
+ '%' || p_search || '%',
+ '%' || p_search || '%'
+ ));
+ END IF;
+
+ -- Build query
+ query := format('SELECT COUNT(*)::INTEGER FROM %I', tbl_name);
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ query := query || ' WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ EXECUTE query INTO result;
+ RETURN result;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to delete old audit logs (for archival)
+CREATE OR REPLACE FUNCTION delete_old_audit_logs(
+ p_company_id TEXT,
+ p_cutoff_date TIMESTAMP WITH TIME ZONE
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ deleted_count INTEGER;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ EXECUTE format('
+ WITH deleted AS (
+ DELETE FROM %I
+ WHERE "createdAt" < $1
+ RETURNING *
+ )
+ SELECT COUNT(*) FROM deleted
+ ', tbl_name)
+ USING p_cutoff_date
+ INTO deleted_count;
+
+ RETURN deleted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Function to get all audit logs for archival
+CREATE OR REPLACE FUNCTION get_audit_logs_for_archive(
+ p_company_id TEXT,
+ p_cutoff_date TIMESTAMP WITH TIME ZONE
+)
+RETURNS TABLE (
+ id TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ operation TEXT,
+ "actorId" TEXT,
+ "actorName" TEXT,
+ diff JSONB,
+ metadata JSONB,
+ "createdAt" TIMESTAMP WITH TIME ZONE
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "actorName", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', tbl_name)
+ USING p_cutoff_date;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260212164223_attach_audit_table_triggers.sql b/packages/database/supabase/migrations/20260212164223_attach_audit_table_triggers.sql
new file mode 100644
index 0000000000..4d838a78a0
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212164223_attach_audit_table_triggers.sql
@@ -0,0 +1,4 @@
+-- Attach event triggers to tables needed for audit logging
+
+-- itemCost - stores cost/pricing data for items (unit price changes)
+SELECT attach_event_trigger('itemCost', ARRAY[]::TEXT[]);
diff --git a/packages/database/supabase/migrations/20260212165827_fix_event_system_dynamic_pk.sql b/packages/database/supabase/migrations/20260212165827_fix_event_system_dynamic_pk.sql
new file mode 100644
index 0000000000..7d5335b854
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212165827_fix_event_system_dynamic_pk.sql
@@ -0,0 +1,199 @@
+-- Fix dispatch_event_batch to dynamically find primary key column
+-- instead of hardcoding 'id'
+
+-- Helper function to get primary key column name for a table
+CREATE OR REPLACE FUNCTION public.get_primary_key_column(p_table_name TEXT)
+RETURNS TEXT AS $$
+DECLARE
+ pk_column TEXT;
+BEGIN
+ -- First try to get primary key
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ AND i.indisprimary
+ LIMIT 1;
+
+ -- If no primary key, try to get any unique index column
+ IF pk_column IS NULL THEN
+ SELECT a.attname INTO pk_column
+ FROM pg_index i
+ JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)
+ WHERE i.indrelid = ('"' || p_table_name || '"')::regclass
+ LIMIT 1;
+ END IF;
+
+ RETURN COALESCE(pk_column, 'id');
+END;
+$$ LANGUAGE plpgsql STABLE;
+
+-- Updated dispatch_event_batch function with dynamic primary key support
+CREATE OR REPLACE FUNCTION public.dispatch_event_batch()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+SECURITY DEFINER
+SET search_path = public, pgmq, extensions
+AS $$
+DECLARE
+ sub RECORD;
+ msg_batch JSONB[];
+ rec_company_id TEXT;
+ has_subs BOOLEAN;
+ current_actor_id TEXT;
+ pk_column TEXT;
+ query_text TEXT;
+BEGIN
+ -- Guard: Skip if we're in a sync operation (prevents circular triggers)
+ -- Set this via: SET LOCAL "app.sync_in_progress" = 'true';
+ IF current_setting('app.sync_in_progress', true) = 'true' THEN
+ RETURN NULL;
+ END IF;
+
+ -- Capture the current authenticated user (will be NULL for service role operations)
+ current_actor_id := auth.uid()::TEXT;
+
+ -- Get the primary key column for this table
+ pk_column := public.get_primary_key_column(TG_TABLE_NAME);
+
+ -- A. Extract Company ID (Partition Key)
+ -- We need this to efficiently filter subscriptions.
+ -- NOTE: For STATEMENT-level triggers, OLD/NEW are not available.
+ -- We must query the transition tables (batched_new/batched_old) instead.
+ IF TG_OP = 'DELETE' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_old t LIMIT 1;
+ ELSIF TG_OP = 'INSERT' THEN
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ ELSE -- UPDATE
+ SELECT t."companyId" INTO rec_company_id FROM batched_new t LIMIT 1;
+ END IF;
+
+ -- Performance Guard: If record has no companyId, we can't match any subscriptions.
+ IF rec_company_id IS NULL THEN RETURN NULL; END IF;
+
+ -- B. Fast Check: Any active subscriptions for this Company + Table + Op?
+ SELECT EXISTS (
+ SELECT 1 FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id -- Use the Index!
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ ) INTO has_subs;
+
+ IF NOT has_subs THEN RETURN NULL; END IF;
+
+
+ -- C. Iterate Subscriptions (Filtered by Company)
+ FOR sub IN
+ SELECT * FROM "eventSystemSubscription"
+ WHERE "table" = TG_TABLE_NAME
+ AND "companyId" = rec_company_id -- Use the Index!
+ AND "active" = TRUE
+ AND TG_OP = ANY("operations")
+ LOOP
+
+ -- D. Build Batch Payload
+ -- Filter rows using the subscription's JSONB filter
+ -- Only include rows belonging to the correct companyId (Redundant but safe)
+
+ IF TG_OP = 'INSERT' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', row_to_json(t)::jsonb,
+ ''old'', null,
+ ''timestamp'', NOW()
+ )
+ )
+ )
+ FROM batched_new t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'DELETE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', t.%I::TEXT,
+ ''new'', null,
+ ''old'', row_to_json(t)::jsonb,
+ ''timestamp'', NOW()
+ )
+ )
+ )
+ FROM batched_old t
+ WHERE t."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(t)::jsonb @> $9)
+ ', pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+
+ ELSIF TG_OP = 'UPDATE' THEN
+ query_text := format('
+ SELECT array_agg(
+ jsonb_build_object(
+ ''subscriptionId'', $1,
+ ''triggerType'', $2,
+ ''handlerType'', $3,
+ ''handlerConfig'', $4,
+ ''companyId'', $5,
+ ''actorId'', $6,
+ ''event'', jsonb_build_object(
+ ''table'', $7,
+ ''operation'', $8,
+ ''recordId'', n.%I::TEXT,
+ ''new'', row_to_json(n)::jsonb,
+ ''old'', row_to_json(o)::jsonb,
+ ''timestamp'', NOW()
+ )
+ )
+ )
+ FROM batched_new n
+ JOIN batched_old o ON n.%I = o.%I
+ WHERE n."companyId" = $5
+ AND ($9 = ''{}''::jsonb OR row_to_json(n)::jsonb @> $9)
+ ', pk_column, pk_column, pk_column);
+
+ EXECUTE query_text INTO msg_batch
+ USING sub.id, TG_LEVEL, sub."handlerType", sub."config", rec_company_id,
+ current_actor_id, TG_TABLE_NAME, TG_OP, sub.filter;
+ END IF;
+
+ -- E. Send Batch (PGMQ)
+ IF msg_batch IS NOT NULL AND array_length(msg_batch, 1) > 0 THEN
+ PERFORM pgmq.send_batch('event_system', msg_batch);
+ END IF;
+
+ END LOOP;
+
+ RETURN NULL;
+END;
+$$;
+
+COMMENT ON FUNCTION public.dispatch_event_batch() IS 'Dispatches database events to PGMQ with dynamic primary key support and auth.uid() captured as actorId';
diff --git a/packages/database/supabase/migrations/20260212174458_remove_actor_name_from_audit_log.sql b/packages/database/supabase/migrations/20260212174458_remove_actor_name_from_audit_log.sql
new file mode 100644
index 0000000000..87c1b7ae56
--- /dev/null
+++ b/packages/database/supabase/migrations/20260212174458_remove_actor_name_from_audit_log.sql
@@ -0,0 +1,274 @@
+-- Remove actorName from audit log tables and functions
+-- The UI will resolve actor info from actorId instead
+
+-- Drop existing functions first (they have different return types or conflicting signatures)
+-- Use CASCADE to handle any dependencies
+DROP FUNCTION IF EXISTS public.get_entity_audit_log CASCADE;
+DROP FUNCTION IF EXISTS public.get_audit_log CASCADE;
+DROP FUNCTION IF EXISTS public.get_audit_logs_for_archive CASCADE;
+DROP FUNCTION IF EXISTS public.insert_audit_log_batch CASCADE;
+DROP FUNCTION IF EXISTS public.create_audit_log_table CASCADE;
+
+-- Update create_audit_log_table to not include actorName
+CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table already exists
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Create the audit log table for this company
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" TEXT PRIMARY KEY DEFAULT id(''aud''),
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ ', tbl_name);
+
+ -- Create indexes for common queries
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',
+ 'idx_' || tbl_name || '_entity', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',
+ 'idx_' || tbl_name || '_actor', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',
+ 'idx_' || tbl_name || '_created', tbl_name);
+
+ -- Enable RLS
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+
+ -- Create RLS policy (company isolation is implicit via table name)
+ EXECUTE format('
+ CREATE POLICY "audit_log_access" ON %I
+ FOR ALL
+ USING (true)
+ WITH CHECK (true)
+ ', tbl_name);
+
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Update insert_audit_log_batch to not require actorName
+CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(
+ p_company_id TEXT,
+ p_entries JSONB[]
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ entry JSONB;
+ inserted_count INTEGER := 0;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Ensure table exists
+ PERFORM create_audit_log_table(p_company_id);
+
+ -- Insert each entry
+ FOREACH entry IN ARRAY p_entries
+ LOOP
+ EXECUTE format('
+ INSERT INTO %I ("entityType", "entityId", "operation", "actorId", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ', tbl_name)
+ USING
+ entry->>'entityType',
+ entry->>'entityId',
+ entry->>'operation',
+ entry->>'actorId',
+ entry->'diff',
+ entry->'metadata';
+
+ inserted_count := inserted_count + 1;
+ END LOOP;
+
+ RETURN inserted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Update get_entity_audit_log to not return actorName
+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Update get_audit_log to not return actorName
+CREATE OR REPLACE FUNCTION public.get_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_entity_id TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMPTZ DEFAULT NULL,
+ p_end_date TIMESTAMPTZ DEFAULT NULL,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ,
+ "totalCount" BIGINT
+) AS $$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ query_text TEXT;
+ count_query TEXT;
+ total BIGINT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ -- Build WHERE clauses
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_entity_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ -- Combine WHERE clauses
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ -- Get total count
+ count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);
+ EXECUTE count_query INTO total;
+
+ -- Build and execute main query
+ query_text := format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"
+ FROM %I
+ %s
+ ORDER BY "createdAt" DESC
+ LIMIT %s OFFSET %s
+ ', total, tbl_name, where_clause, p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query_text;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Update get_audit_logs_for_archive to not return actorName
+CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(
+ p_company_id TEXT,
+ p_before_date TIMESTAMPTZ
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ -- Check if table exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', tbl_name)
+ USING p_before_date;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260217120000_audit_log_add_table_name.sql b/packages/database/supabase/migrations/20260217120000_audit_log_add_table_name.sql
new file mode 100644
index 0000000000..59d33c3220
--- /dev/null
+++ b/packages/database/supabase/migrations/20260217120000_audit_log_add_table_name.sql
@@ -0,0 +1,422 @@
+-- Add tableName column to audit log tables
+-- Separates the raw DB table name from the semantic entity type
+--
+-- tableName = raw DB table name (e.g., "item", "itemCost", "purchaseOrder")
+-- entityType = semantic domain entity (e.g., "item", "purchaseOrder", "salesCustomer")
+--
+-- This allows grouping related tables under one entity type
+-- (e.g., both "item" and "itemCost" tables map to entityType "item")
+
+-- Drop existing functions first
+DROP FUNCTION IF EXISTS public.create_audit_log_table CASCADE;
+DROP FUNCTION IF EXISTS public.insert_audit_log_batch CASCADE;
+DROP FUNCTION IF EXISTS public.get_entity_audit_log CASCADE;
+DROP FUNCTION IF EXISTS public.get_audit_log CASCADE;
+DROP FUNCTION IF EXISTS public.get_audit_log_count CASCADE;
+DROP FUNCTION IF EXISTS public.get_audit_logs_for_archive CASCADE;
+DROP FUNCTION IF EXISTS public.delete_old_audit_logs CASCADE;
+
+-- Helper function to map table name to entity type
+CREATE OR REPLACE FUNCTION public.audit_table_to_entity_type(p_table_name TEXT)
+RETURNS TEXT AS $$
+BEGIN
+ RETURN CASE p_table_name
+ WHEN 'customer' THEN 'salesCustomer'
+ WHEN 'supplier' THEN 'purchaseSupplier'
+ WHEN 'itemCost' THEN 'item'
+ WHEN 'job' THEN 'productionJob'
+ WHEN 'quote' THEN 'salesQuote'
+ ELSE p_table_name
+ END;
+END;
+$$ LANGUAGE plpgsql IMMUTABLE;
+
+-- Migrate existing per-company tables: add tableName column and backfill
+DO $$
+DECLARE
+ tbl RECORD;
+BEGIN
+ FOR tbl IN
+ SELECT table_name FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name LIKE 'auditLog_%'
+ AND table_name != 'auditLogArchive'
+ LOOP
+ -- Add tableName column if not exists
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND information_schema.columns.table_name = tbl.table_name AND column_name = 'tableName'
+ ) THEN
+ EXECUTE format('ALTER TABLE %I ADD COLUMN "tableName" TEXT', tbl.table_name);
+ END IF;
+
+ -- Backfill tableName from existing entityType (which currently holds the table name)
+ EXECUTE format('UPDATE %I SET "tableName" = "entityType" WHERE "tableName" IS NULL', tbl.table_name);
+
+ -- Update entityType to the new semantic domain values
+ EXECUTE format('UPDATE %I SET "entityType" = audit_table_to_entity_type("tableName")', tbl.table_name);
+
+ -- Make tableName NOT NULL after backfill
+ EXECUTE format('ALTER TABLE %I ALTER COLUMN "tableName" SET NOT NULL', tbl.table_name);
+ END LOOP;
+END;
+$$;
+
+-- Recreate create_audit_log_table with tableName column
+CREATE OR REPLACE FUNCTION public.create_audit_log_table(p_company_id TEXT)
+RETURNS VOID AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ -- Table exists; ensure tableName column is present (for tables created before this migration)
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.columns
+ WHERE table_schema = 'public' AND information_schema.columns.table_name = tbl_name AND column_name = 'tableName'
+ ) THEN
+ EXECUTE format('ALTER TABLE %I ADD COLUMN "tableName" TEXT', tbl_name);
+ EXECUTE format('UPDATE %I SET "tableName" = "entityType" WHERE "tableName" IS NULL', tbl_name);
+ EXECUTE format('UPDATE %I SET "entityType" = audit_table_to_entity_type("tableName")', tbl_name);
+ EXECUTE format('ALTER TABLE %I ALTER COLUMN "tableName" SET NOT NULL', tbl_name);
+ END IF;
+ RETURN;
+ END IF;
+
+ EXECUTE format('
+ CREATE TABLE IF NOT EXISTS %I (
+ "id" TEXT PRIMARY KEY DEFAULT id(''aud''),
+ "tableName" TEXT NOT NULL,
+ "entityType" TEXT NOT NULL,
+ "entityId" TEXT NOT NULL,
+ "operation" TEXT NOT NULL CHECK ("operation" IN (''INSERT'', ''UPDATE'', ''DELETE'')),
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()
+ )
+ ', tbl_name);
+
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("entityType", "entityId")',
+ 'idx_' || tbl_name || '_entity', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("tableName")',
+ 'idx_' || tbl_name || '_table', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("actorId")',
+ 'idx_' || tbl_name || '_actor', tbl_name);
+ EXECUTE format('CREATE INDEX IF NOT EXISTS %I ON %I ("createdAt" DESC)',
+ 'idx_' || tbl_name || '_created', tbl_name);
+
+ EXECUTE format('ALTER TABLE %I ENABLE ROW LEVEL SECURITY', tbl_name);
+
+ EXECUTE format('
+ CREATE POLICY "audit_log_access" ON %I
+ FOR ALL
+ USING (true)
+ WITH CHECK (true)
+ ', tbl_name);
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate insert_audit_log_batch with tableName
+CREATE OR REPLACE FUNCTION public.insert_audit_log_batch(
+ p_company_id TEXT,
+ p_entries JSONB[]
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ entry JSONB;
+ inserted_count INTEGER := 0;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ PERFORM create_audit_log_table(p_company_id);
+
+ FOREACH entry IN ARRAY p_entries
+ LOOP
+ EXECUTE format('
+ INSERT INTO %I ("tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata")
+ VALUES ($1, $2, $3, $4, $5, $6, $7)
+ ', tbl_name)
+ USING
+ entry->>'tableName',
+ entry->>'entityType',
+ entry->>'entityId',
+ entry->>'operation',
+ entry->>'actorId',
+ CASE WHEN entry->'diff' = 'null'::jsonb THEN NULL ELSE entry->'diff' END,
+ CASE WHEN entry->'metadata' = 'null'::jsonb THEN NULL ELSE entry->'metadata' END;
+
+ inserted_count := inserted_count + 1;
+ END LOOP;
+
+ RETURN inserted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate get_entity_audit_log — queries by tableName (raw table) + entityId
+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(
+ p_company_id TEXT,
+ p_table_name TEXT,
+ p_entity_id TEXT,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "tableName" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "tableName" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_table_name, p_entity_id, p_limit, p_offset;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate get_audit_log with tableName support
+CREATE OR REPLACE FUNCTION public.get_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_entity_id TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMPTZ DEFAULT NULL,
+ p_end_date TIMESTAMPTZ DEFAULT NULL,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "tableName" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ,
+ "totalCount" BIGINT
+) AS $$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ query_text TEXT;
+ count_query TEXT;
+ total BIGINT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_entity_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityId" = %L', p_entity_id));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ count_query := format('SELECT COUNT(*) FROM %I %s', tbl_name, where_clause);
+ EXECUTE count_query INTO total;
+
+ query_text := format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt", %s::BIGINT as "totalCount"
+ FROM %I
+ %s
+ ORDER BY "createdAt" DESC
+ LIMIT %s OFFSET %s
+ ', total, tbl_name, where_clause, p_limit, p_offset);
+
+ RETURN QUERY EXECUTE query_text;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate get_audit_log_count
+CREATE OR REPLACE FUNCTION public.get_audit_log_count(
+ p_company_id TEXT,
+ p_entity_type TEXT DEFAULT NULL,
+ p_actor_id TEXT DEFAULT NULL,
+ p_operation TEXT DEFAULT NULL,
+ p_start_date TIMESTAMPTZ DEFAULT NULL,
+ p_end_date TIMESTAMPTZ DEFAULT NULL,
+ p_search TEXT DEFAULT NULL
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ where_clauses TEXT[] := ARRAY[]::TEXT[];
+ where_clause TEXT := '';
+ count_val INTEGER;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ IF p_entity_type IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"entityType" = %L', p_entity_type));
+ END IF;
+
+ IF p_actor_id IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"actorId" = %L', p_actor_id));
+ END IF;
+
+ IF p_operation IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"operation" = %L', p_operation));
+ END IF;
+
+ IF p_start_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" >= %L', p_start_date));
+ END IF;
+
+ IF p_end_date IS NOT NULL THEN
+ where_clauses := array_append(where_clauses, format('"createdAt" <= %L', p_end_date));
+ END IF;
+
+ IF p_search IS NOT NULL AND p_search != '' THEN
+ where_clauses := array_append(where_clauses,
+ format('"entityId" ILIKE %L', '%' || p_search || '%'));
+ END IF;
+
+ IF array_length(where_clauses, 1) > 0 THEN
+ where_clause := 'WHERE ' || array_to_string(where_clauses, ' AND ');
+ END IF;
+
+ EXECUTE format('SELECT COUNT(*)::INTEGER FROM %I %s', tbl_name, where_clause) INTO count_val;
+ RETURN count_val;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate get_audit_logs_for_archive with tableName
+CREATE OR REPLACE FUNCTION public.get_audit_logs_for_archive(
+ p_company_id TEXT,
+ p_before_date TIMESTAMPTZ
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "tableName" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "createdAt" < $1
+ ORDER BY "createdAt" ASC
+ ', tbl_name)
+ USING p_before_date;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+-- Recreate delete_old_audit_logs (unchanged logic)
+CREATE OR REPLACE FUNCTION public.delete_old_audit_logs(
+ p_company_id TEXT,
+ p_cutoff_date TIMESTAMP WITH TIME ZONE
+)
+RETURNS INTEGER AS $$
+DECLARE
+ tbl_name TEXT;
+ deleted_count INTEGER;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN 0;
+ END IF;
+
+ EXECUTE format('
+ WITH deleted AS (
+ DELETE FROM %I
+ WHERE "createdAt" < $1
+ RETURNING *
+ )
+ SELECT COUNT(*) FROM deleted
+ ', tbl_name)
+ USING p_cutoff_date
+ INTO deleted_count;
+
+ RETURN deleted_count;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
diff --git a/packages/database/supabase/migrations/20260218000000_expand_audit_log_entities.sql b/packages/database/supabase/migrations/20260218000000_expand_audit_log_entities.sql
new file mode 100644
index 0000000000..e281009aca
--- /dev/null
+++ b/packages/database/supabase/migrations/20260218000000_expand_audit_log_entities.sql
@@ -0,0 +1,156 @@
+-- Expand audit log to cover ~60 tables across 21 entity types
+-- Key changes:
+-- 1. Drop audit_table_to_entity_type() — entity resolution is now in TypeScript
+-- 2. Update get_entity_audit_log() to query by entityType (not tableName)
+-- so child table changes roll up into parent entity views
+-- 3. Backfill existing entityType values (salesCustomer -> customer, etc.)
+-- 4. Attach event triggers to all new auditable tables
+-- 5. Create audit subscriptions for existing companies that have audit enabled
+
+
+-- ============================================================================
+-- 1. Drop audit_table_to_entity_type — entity type resolution is now done
+-- entirely in the TypeScript audit event processor using audit.config.ts
+-- ============================================================================
+DROP FUNCTION IF EXISTS public.audit_table_to_entity_type(TEXT);
+
+
+-- ============================================================================
+-- 2. Backfill existing audit log tables: rename old entity type values
+-- ============================================================================
+DO $$
+DECLARE
+ tbl RECORD;
+BEGIN
+ FOR tbl IN
+ SELECT table_name FROM information_schema.tables
+ WHERE table_schema = 'public' AND table_name LIKE 'auditLog_%'
+ AND table_name != 'auditLogArchive'
+ LOOP
+ EXECUTE format('UPDATE %I SET "entityType" = ''customer'' WHERE "entityType" = ''salesCustomer''', tbl.table_name);
+ EXECUTE format('UPDATE %I SET "entityType" = ''supplier'' WHERE "entityType" = ''purchaseSupplier''', tbl.table_name);
+ END LOOP;
+END;
+$$;
+
+
+-- ============================================================================
+-- 3. Update get_entity_audit_log to query by entityType instead of tableName
+-- Must DROP first because we renamed the parameter (p_table_name -> p_entity_type)
+-- ============================================================================
+DROP FUNCTION IF EXISTS public.get_entity_audit_log(TEXT, TEXT, TEXT, INTEGER, INTEGER);
+
+CREATE OR REPLACE FUNCTION public.get_entity_audit_log(
+ p_company_id TEXT,
+ p_entity_type TEXT,
+ p_entity_id TEXT,
+ p_limit INTEGER DEFAULT 50,
+ p_offset INTEGER DEFAULT 0
+)
+RETURNS TABLE (
+ "id" TEXT,
+ "tableName" TEXT,
+ "entityType" TEXT,
+ "entityId" TEXT,
+ "operation" TEXT,
+ "actorId" TEXT,
+ "diff" JSONB,
+ "metadata" JSONB,
+ "createdAt" TIMESTAMPTZ
+) AS $$
+DECLARE
+ tbl_name TEXT;
+BEGIN
+ tbl_name := 'auditLog_' || p_company_id;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = 'public' AND information_schema.tables.table_name = tbl_name
+ ) THEN
+ RETURN;
+ END IF;
+
+ RETURN QUERY EXECUTE format('
+ SELECT "id", "tableName", "entityType", "entityId", "operation", "actorId", "diff", "metadata", "createdAt"
+ FROM %I
+ WHERE "entityType" = $1 AND "entityId" = $2
+ ORDER BY "createdAt" DESC
+ LIMIT $3 OFFSET $4
+ ', tbl_name)
+ USING p_entity_type, p_entity_id, p_limit, p_offset;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+
+-- ============================================================================
+-- 4. Attach event triggers to new auditable tables
+-- Note: The following already have event triggers from previous migrations:
+-- customer, employee, gauge, item, itemCost, job, nonConformance,
+-- purchaseInvoice, purchaseOrder, purchaseOrderLine, quote, salesInvoice,
+-- salesOrder, salesOrderLine, supplier, supplierQuote, contact, address
+-- ============================================================================
+
+-- CRM child tables
+SELECT attach_event_trigger('customerPayment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('customerShipping', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('supplierPayment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('supplierShipping', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('supplierPart', ARRAY[]::TEXT[]);
+
+-- Item child tables
+SELECT attach_event_trigger('itemPlanning', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('itemReplenishment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('itemUnitSalePrice', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('customerPartToItem', ARRAY[]::TEXT[]);
+
+-- Job child tables
+SELECT attach_event_trigger('jobOperation', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('jobMaterial', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('jobMakeMethod', ARRAY[]::TEXT[]);
+
+-- Sales child tables
+SELECT attach_event_trigger('salesOrderPayment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('salesOrderShipment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('quoteLine', ARRAY[]::TEXT[]);
+
+-- Purchasing child tables
+SELECT attach_event_trigger('purchaseOrderPayment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('purchaseOrderDelivery', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('supplierQuoteLine', ARRAY[]::TEXT[]);
+
+-- Finance child tables
+SELECT attach_event_trigger('salesInvoiceLine', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('salesInvoiceShipment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('purchaseInvoiceLine', ARRAY[]::TEXT[]);
+
+-- Quality child tables
+SELECT attach_event_trigger('nonConformanceItem', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('nonConformanceActionTask', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('nonConformanceApprovalTask', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('gaugeCalibrationRecord', ARRAY[]::TEXT[]);
+
+-- Shipping / Receiving (new root entities)
+SELECT attach_event_trigger('shipment', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('shipmentLine', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('receipt', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('receiptLine', ARRAY[]::TEXT[]);
+
+-- Inventory movement tables (new root entities)
+SELECT attach_event_trigger('warehouseTransfer', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('warehouseTransferLine', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('stockTransfer', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('stockTransferLine', ARRAY[]::TEXT[]);
+
+-- Production tables (new root entities)
+SELECT attach_event_trigger('workCenter', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('workCenterProcess', ARRAY[]::TEXT[]);
+
+-- Maintenance tables
+SELECT attach_event_trigger('maintenanceSchedule', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('maintenanceScheduleItem', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('maintenanceDispatch', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('maintenanceDispatchEvent', ARRAY[]::TEXT[]);
+SELECT attach_event_trigger('maintenanceDispatchComment', ARRAY[]::TEXT[]);
+
+-- HR child tables
+SELECT attach_event_trigger('employeeJob', ARRAY[]::TEXT[]);
\ No newline at end of file
diff --git a/packages/jobs/trigger/audit-archive.ts b/packages/jobs/trigger/audit-archive.ts
new file mode 100644
index 0000000000..99e65a6a33
--- /dev/null
+++ b/packages/jobs/trigger/audit-archive.ts
@@ -0,0 +1,173 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import { auditConfig } from "@carbon/database/audit.config";
+import type { AuditLogEntry } from "@carbon/database/audit.types";
+import { logger, schedules } from "@trigger.dev/sdk/v3";
+import { gzipSync } from "node:zlib";
+
+// Type for RPC calls
+type AuditArchiveRpcClient = {
+ rpc(
+ fn: "get_audit_logs_for_archive",
+ params: { p_company_id: string; p_before_date: string }
+ ): Promise<{ data: AuditLogEntry[] | null; error: any }>;
+ rpc(
+ fn: "delete_old_audit_logs",
+ params: { p_company_id: string; p_cutoff_date: string }
+ ): Promise<{ data: number | null; error: any }>;
+};
+
+/**
+ * Scheduled task to archive old audit logs
+ * Runs daily at 2 AM UTC
+ * Exports audit logs older than retentionDays to gzipped JSONL files
+ * Stores them in the private storage bucket and records in auditLogArchive table
+ */
+export const auditLogArchiveTask = schedules.task({
+ id: "audit-log-archive",
+ cron: "0 2 * * *", // Daily at 2 AM UTC
+ retry: {
+ maxAttempts: 3,
+ factor: 2,
+ randomize: true,
+ },
+ run: async () => {
+ const client = getCarbonServiceRole();
+
+ // Calculate cutoff date
+ const cutoffDate = new Date();
+ cutoffDate.setDate(cutoffDate.getDate() - auditConfig.retentionDays);
+
+ logger.info(`Archiving audit logs older than ${cutoffDate.toISOString()}`);
+
+ // Get companies with audit logs enabled
+ const { data: companies, error: companiesError } = await client
+ .from("company")
+ .select("id")
+ .eq("auditLogEnabled", true);
+
+ if (companiesError) {
+ logger.error("Failed to fetch companies", { error: companiesError });
+ throw new Error(`Failed to fetch companies: ${companiesError.message}`);
+ }
+
+ const results = {
+ companiesProcessed: 0,
+ recordsArchived: 0,
+ recordsDeleted: 0,
+ errors: 0,
+ };
+
+ for (const company of (companies as { id: string }[]) ?? []) {
+ try {
+ const archived = await archiveCompanyLogs(
+ client as unknown as AuditArchiveRpcClient &
+ ReturnType<typeof getCarbonServiceRole>,
+ company.id,
+ cutoffDate
+ );
+ results.companiesProcessed++;
+ results.recordsArchived += archived.recordsArchived;
+ results.recordsDeleted += archived.recordsDeleted;
+ } catch (error) {
+ logger.error(`Failed to archive logs for company ${company.id}`, {
+ error,
+ });
+ results.errors++;
+ }
+ }
+
+ logger.info("Audit log archive task completed", results);
+ return results;
+ },
+});
+
+async function archiveCompanyLogs(
+ client: AuditArchiveRpcClient & ReturnType<typeof getCarbonServiceRole>,
+ companyId: string,
+ cutoffDate: Date
+): Promise<{ recordsArchived: number; recordsDeleted: number }> {
+ // Fetch old records using RPC
+ const { data: records, error: fetchError } = await client.rpc(
+ "get_audit_logs_for_archive",
+ {
+ p_company_id: companyId,
+ p_before_date: cutoffDate.toISOString(),
+ }
+ );
+
+ if (fetchError) {
+ throw new Error(`Failed to fetch audit logs: ${fetchError.message}`);
+ }
+
+ if (!records || records.length === 0) {
+ return { recordsArchived: 0, recordsDeleted: 0 };
+ }
+
+ logger.info(`Archiving ${records.length} records for company ${companyId}`);
+
+ // Convert to JSONL format
+ const jsonl = records.map((r) => JSON.stringify(r)).join("\n");
+ const gzipped = gzipSync(Buffer.from(jsonl));
+
+ // Generate archive path
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, "0");
+ const day = String(now.getDate()).padStart(2, "0");
+ const timestamp = `${year}-${month}-${day}`;
+ const archivePath = `audit-logs/${companyId}/${year}/${month}/${timestamp}.jsonl.gz`;
+
+ // Upload to storage
+ const { error: uploadError } = await client.storage
+ .from(auditConfig.archiveBucket)
+ .upload(archivePath, gzipped, {
+ contentType: "application/gzip",
+ upsert: true,
+ });
+
+ if (uploadError) {
+ throw new Error(`Failed to upload archive: ${uploadError.message}`);
+ }
+
+ // Get date range from records
+ const startDate = records[0].createdAt;
+ const endDate = records[records.length - 1].createdAt;
+
+ // Record archive metadata
+ const { error: archiveError } = await client.from("auditLogArchive").insert({
+ companyId,
+ archivePath,
+ startDate: startDate.split("T")[0], // Extract date part
+ endDate: endDate.split("T")[0],
+ rowCount: records.length,
+ sizeBytes: gzipped.length,
+ });
+
+ if (archiveError) {
+ // Try to clean up uploaded file
+ await client.storage.from(auditConfig.archiveBucket).remove([archivePath]);
+ throw new Error(`Failed to record archive: ${archiveError.message}`);
+ }
+
+ // Delete archived records using RPC
+ const { data: deletedCount, error: deleteError } = await client.rpc(
+ "delete_old_audit_logs",
+ {
+ p_company_id: companyId,
+ p_cutoff_date: cutoffDate.toISOString(),
+ }
+ );
+
+ if (deleteError) {
+ logger.error(`Failed to delete archived records for ${companyId}`, {
+ error: deleteError,
+ });
+ // Don't throw - archive was successful, just couldn't clean up
+ return { recordsArchived: records.length, recordsDeleted: 0 };
+ }
+
+ return {
+ recordsArchived: records.length,
+ recordsDeleted: deletedCount ?? records.length,
+ };
+}
diff --git a/packages/jobs/trigger/event/audit.ts b/packages/jobs/trigger/event/audit.ts
new file mode 100644
index 0000000000..2932d459d1
--- /dev/null
+++ b/packages/jobs/trigger/event/audit.ts
@@ -0,0 +1,366 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ auditConfig,
+ getEntityConfigsForTable,
+ isAuditableTable,
+ isChildTable,
+ isExtensionTable,
+ isIndirectTable,
+ isRootTable,
+} from "@carbon/database/audit.config";
+import type { AuditEntityType } from "@carbon/database/audit.config";
+import type {
+ AuditDiff,
+ CreateAuditLogEntry,
+} from "@carbon/database/audit.types";
+import { groupBy } from "@carbon/utils";
+import { logger, task } from "@trigger.dev/sdk/v3";
+import { z } from "zod";
+
+const AuditRecordSchema = z.object({
+ event: z.object({
+ table: z.string(),
+ operation: z.enum(["INSERT", "UPDATE", "DELETE", "TRUNCATE"]),
+ recordId: z.string(),
+ new: z.record(z.any()).nullable(),
+ old: z.record(z.any()).nullable(),
+ timestamp: z.string(),
+ }),
+ companyId: z.string(),
+ actorId: z.string().nullish(),
+ handlerConfig: z.record(z.any()),
+});
+
+const AuditPayloadSchema = z.object({
+ records: z.array(AuditRecordSchema),
+});
+
+export type AuditPayload = z.infer<typeof AuditPayloadSchema>;
+
+/**
+ * Compute the diff between old and new record values.
+ * Supports deep diffing for JSONB fields.
+ */
+function computeDiff(
+ old: Record<string, unknown>,
+ newRecord: Record<string, unknown>
+): AuditDiff | null {
+ const diff: AuditDiff = {};
+ const skipFields = auditConfig.skipFields;
+
+ const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);
+
+ for (const key of allKeys) {
+ if ((skipFields as readonly string[]).includes(key)) continue;
+
+ const oldValue = old[key];
+ const newValue = newRecord[key];
+
+ if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
+ if (
+ typeof oldValue === "object" &&
+ oldValue !== null &&
+ typeof newValue === "object" &&
+ newValue !== null &&
+ !Array.isArray(oldValue) &&
+ !Array.isArray(newValue)
+ ) {
+ const nestedDiff = computeNestedDiff(
+ oldValue as Record<string, unknown>,
+ newValue as Record<string, unknown>,
+ key
+ );
+ Object.assign(diff, nestedDiff);
+ } else {
+ diff[key] = { old: oldValue, new: newValue };
+ }
+ }
+ }
+
+ return Object.keys(diff).length > 0 ? diff : null;
+}
+
+/**
+ * Compute nested diff for object fields (like customFields).
+ */
+function computeNestedDiff(
+ old: Record<string, unknown>,
+ newRecord: Record<string, unknown>,
+ prefix: string
+): AuditDiff {
+ const diff: AuditDiff = {};
+
+ const allKeys = new Set([...Object.keys(old), ...Object.keys(newRecord)]);
+
+ for (const key of allKeys) {
+ const oldValue = old[key];
+ const newValue = newRecord[key];
+
+ if (JSON.stringify(oldValue) !== JSON.stringify(newValue)) {
+ diff[`${prefix}.${key}`] = { old: oldValue, new: newValue };
+ }
+ }
+
+ return diff;
+}
+
+// Type for RPC call
+type AuditRpcClient = {
+ rpc(
+ fn: "insert_audit_log_batch",
+ params: { p_company_id: string; p_entries: object[] }
+ ): Promise<{ data: number | null; error: any }>;
+};
+
+export const auditTask = task({
+ id: "event-handler-audit",
+ retry: {
+ maxAttempts: 3,
+ factor: 2,
+ randomize: true,
+ },
+ run: async (input: unknown) => {
+ const payload = AuditPayloadSchema.parse(input);
+
+ logger.info(`Processing ${payload.records.length} audit log events`);
+
+ const results = {
+ inserted: 0,
+ skipped: 0,
+ failed: 0,
+ };
+
+ const client = getCarbonServiceRole();
+
+ // Group by companyId for efficient processing
+ type AuditRecord = (typeof payload.records)[number];
+ const byCompany = groupBy(payload.records, (r) => r.companyId);
+
+ for (const [companyId, records] of Object.entries(byCompany) as [
+ string,
+ AuditRecord[]
+ ][]) {
+ if (!companyId || companyId === "undefined") {
+ logger.info(`Skipping ${records.length} records: missing companyId`);
+ results.skipped += records.length;
+ continue;
+ }
+
+ // Check if company has audit logs enabled
+ const { data: company } = await client
+ .from("company")
+ .select("auditLogEnabled")
+ .eq("id", companyId)
+ .single();
+
+ if (!(company as { auditLogEnabled: boolean } | null)?.auditLogEnabled) {
+ logger.info(
+ `Skipping ${records.length} records: audit logging disabled for company ${companyId}`
+ );
+ results.skipped += records.length;
+ continue;
+ }
+
+ // Process records and build entries
+ const entries: CreateAuditLogEntry[] = [];
+
+ for (const record of records) {
+ const tableName = record.event.table;
+
+ // Skip non-auditable tables
+ if (!isAuditableTable(tableName)) {
+ logger.info(`Skipping: table "${tableName}" is not auditable`);
+ results.skipped++;
+ continue;
+ }
+
+ // Skip TRUNCATE operations
+ if (record.event.operation === "TRUNCATE") {
+ logger.info(`Skipping: TRUNCATE on "${tableName}" is not meaningful`);
+ results.skipped++;
+ continue;
+ }
+
+ try {
+ // Resolve actorId: event payload first, fallback to record data
+ const actorId =
+ record.actorId ??
+ record.event.new?.updatedBy ??
+ record.event.new?.createdBy ??
+ record.event.old?.updatedBy ??
+ record.event.old?.createdBy;
+
+ // Compute diff for UPDATE operations
+ let diff: AuditDiff | null = null;
+ if (
+ record.event.operation === "UPDATE" &&
+ record.event.old &&
+ record.event.new
+ ) {
+ diff = computeDiff(
+ record.event.old as Record<string, unknown>,
+ record.event.new as Record<string, unknown>
+ );
+
+ if (!diff) {
+ logger.info(
+ `Skipping: no meaningful diff for UPDATE on "${tableName}" record ${record.event.recordId}`
+ );
+ results.skipped++;
+ continue;
+ }
+ }
+
+ const operation = record.event
+ .operation as CreateAuditLogEntry["operation"];
+ const entryActorId = (actorId as string) ?? null;
+ const entryMetadata = record.handlerConfig.metadata ?? null;
+
+ // Get all entity configs that track this table
+ const entityConfigs = getEntityConfigsForTable(tableName);
+
+ if (entityConfigs.length === 0) {
+ logger.info(
+ `Skipping: no entity config found for table "${tableName}"`
+ );
+ results.skipped++;
+ continue;
+ }
+
+ let entriesCreatedForRecord = 0;
+
+ for (const entityEntry of entityConfigs) {
+ const { entityType, tableConfig } = entityEntry;
+
+ // Skip INSERT events for non-root tables — these are just
+ // default rows created alongside the parent entity (extensions)
+ // or child rows that will get meaningful UPDATEs later.
+ if (
+ record.event.operation === "INSERT" &&
+ !isRootTable(tableConfig)
+ ) {
+ logger.info(
+ `Skipping: INSERT on non-root table "${tableName}" for entity "${entityType}"`
+ );
+ continue;
+ }
+
+ if (isRootTable(tableConfig)) {
+ // Root table: recordId IS the entity ID
+ entries.push({
+ tableName,
+ entityType,
+ entityId: record.event.recordId,
+ operation,
+ actorId: entryActorId,
+ diff,
+ metadata: entryMetadata,
+ });
+ entriesCreatedForRecord++;
+ } else if (isExtensionTable(tableConfig)) {
+ // Extension table: PK = parent FK, so recordId IS the entity ID
+ // (same resolution as root, but INSERT is already skipped above)
+ entries.push({
+ tableName,
+ entityType,
+ entityId: record.event.recordId,
+ operation,
+ actorId: entryActorId,
+ diff,
+ metadata: entryMetadata,
+ });
+ entriesCreatedForRecord++;
+ } else if (isChildTable(tableConfig)) {
+ // Child table: extract entity ID from the named column
+ const recordData = record.event.new ?? record.event.old;
+ const entityId = recordData?.[tableConfig.entityIdColumn];
+
+ if (!entityId) {
+ logger.info(
+ `Skipping: could not resolve entity ID from column "${tableConfig.entityIdColumn}" for "${tableName}" record ${record.event.recordId}`
+ );
+ continue;
+ }
+
+ entries.push({
+ tableName,
+ entityType,
+ entityId: String(entityId),
+ operation,
+ actorId: entryActorId,
+ diff,
+ metadata: entryMetadata,
+ });
+ entriesCreatedForRecord++;
+ } else if (isIndirectTable(tableConfig)) {
+ // Indirect table: resolve via junction table query
+ const { junction, fk, entityIdColumn } = tableConfig.resolve;
+
+ const { data: junctionRow } = await client
+ .from(junction as any)
+ .select(entityIdColumn)
+ .eq(fk, record.event.recordId)
+ .limit(1)
+ .maybeSingle();
+
+ const row = junctionRow as unknown as Record<
+ string,
+ unknown
+ > | null;
+ if (row && row[entityIdColumn]) {
+ entries.push({
+ tableName,
+ entityType,
+ entityId: String(row[entityIdColumn]),
+ operation,
+ actorId: entryActorId,
+ diff,
+ metadata: entryMetadata,
+ });
+ entriesCreatedForRecord++;
+ } else {
+ logger.info(
+ `Skipping: no parent entity found via junction "${junction}" for "${tableName}" record ${record.event.recordId} (entity: ${entityType})`
+ );
+ }
+ }
+ }
+
+ if (entriesCreatedForRecord === 0) {
+ logger.info(
+ `Skipping: could not resolve any entity for "${tableName}" record ${record.event.recordId}`
+ );
+ results.skipped++;
+ }
+ } catch (error) {
+ logger.error(`Failed to process audit record:`, {
+ error,
+ record,
+ });
+ results.failed++;
+ }
+ }
+
+ // Batch insert entries using RPC
+ if (entries.length > 0) {
+ const { data: insertedCount, error } = await (
+ client as unknown as AuditRpcClient
+ ).rpc("insert_audit_log_batch", {
+ p_company_id: companyId,
+ p_entries: entries,
+ });
+
+ if (error) {
+ logger.error(`Failed to insert audit log entries:`, { error });
+ results.failed += entries.length;
+ } else {
+ results.inserted += insertedCount ?? entries.length;
+ }
+ }
+ }
+
+ logger.info("Audit task completed", results);
+
+ return results;
+ },
+});
diff --git a/packages/jobs/trigger/event/queue.ts b/packages/jobs/trigger/event/queue.ts
index cab00f1e42..dd05b12187 100644
--- a/packages/jobs/trigger/event/queue.ts
+++ b/packages/jobs/trigger/event/queue.ts
@@ -7,6 +7,7 @@ import { HandlerType, QueueMessage } from "@carbon/database/event";
import { all } from "@carbon/utils";
import { schedules } from "@trigger.dev/sdk";
import { Kysely, PostgresDriver, sql } from "kysely";
+import { auditTask } from "./audit.ts";
import { searchTask } from "./search.ts";
import { syncTask } from "./sync.ts";
import { webhookTask } from "./webhook.ts";
@@ -56,6 +57,7 @@ export const eventQueueTask = schedules.task({
WORKFLOW: [],
SYNC: [],
SEARCH: [],
+ AUDIT: [],
};
// 2. Sort into Buckets
@@ -63,7 +65,7 @@ export const eventQueueTask = schedules.task({
grouped[job.message.handlerType].push(job);
}
- const { webhooks, syncs, workflows, searches } = await all({
+ const { webhooks, syncs, workflows, searches, audits } = await all({
async webhooks() {
let queue: number[] = [];
@@ -156,11 +158,33 @@ export const eventQueueTask = schedules.task({
records,
});
+ return queue;
+ },
+ async audits() {
+ let queue: number[] = [];
+
+ if (grouped.AUDIT.length === 0) return queue;
+
+ const records = grouped.AUDIT.map((job) => {
+ queue.push(job.msg_id);
+
+ return {
+ event: job.message.event,
+ companyId: job.message.companyId,
+ actorId: job.message.actorId,
+ handlerConfig: job.message.handlerConfig,
+ };
+ });
+
+ await auditTask.trigger({
+ records,
+ });
+
return queue;
},
});
- total = total.concat(webhooks, workflows, syncs, searches);
+ total = total.concat(webhooks, workflows, syncs, searches, audits);
// 5. Delete from PGMQ
// We delete immediately because we have successfully offloaded
diff --git a/packages/utils/src/date.ts b/packages/utils/src/date.ts
index 4113923114..e15361a311 100644
--- a/packages/utils/src/date.ts
+++ b/packages/utils/src/date.ts
@@ -5,7 +5,9 @@ import {
toZoned
} from "@internationalized/date";
-const relativeFormatter = new Intl.RelativeTimeFormat(undefined, {
+const LOCALE = "en-US";
+
+const relativeFormatter = new Intl.RelativeTimeFormat(LOCALE, {
numeric: "auto"
});
@@ -43,14 +45,14 @@ export function formatDate(
const date = parseAbsolute(_dateString);
return new Intl.DateTimeFormat(
- undefined,
+ LOCALE,
options || defaultFormatOptions
).format(date.toDate());
} catch {
try {
const date = new Date(dateString);
return new Intl.DateTimeFormat(
- undefined, // TODO: use locale
+ LOCALE,
options || defaultFormatOptions
).format(date);
} catch {