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.

External Accounting and Event Engine (#451)

Sid6ac029e9d32b
diff --git a/.vscode/launch.json b/.vscode/launch.json
new file mode 100644
index 0000000000..d0bdd6a371
--- /dev/null
+++ b/.vscode/launch.json
@@ -0,0 +1,15 @@
+{
+ "version": "0.2.0",
+ "configurations": [
+ {
+ "name": "Trigger.dev: Dev",
+ "type": "node",
+ "request": "launch",
+ "cwd": "${workspaceFolder}",
+ "runtimeExecutable": "npm",
+ "runtimeArgs": ["run", "dev:jobs"],
+ "skipFiles": ["<node_internals>/**"],
+ "sourceMaps": true
+ }
+ ]
+}
diff --git a/apps/academy/app/root.tsx b/apps/academy/app/root.tsx
index 2dc650d693..a6195c6427 100644
--- a/apps/academy/app/root.tsx
+++ b/apps/academy/app/root.tsx
@@ -26,7 +26,8 @@ import { modeValidator } from "@carbon/utils";
import { I18nProvider } from "@react-aria/i18n";
import { Analytics } from "@vercel/analytics/react";
import { motion } from "framer-motion";
-import React, { useEffect } from "react";
+import type React from "react";
+import { useEffect } from "react";
import { LuChevronDown, LuFingerprint, LuMoon, LuSun } from "react-icons/lu";
import type {
ActionFunctionArgs,
diff --git a/apps/academy/app/routes.ts b/apps/academy/app/routes.ts
index 66d6f7384c..1b20b9ace7 100644
--- a/apps/academy/app/routes.ts
+++ b/apps/academy/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { remixRoutesOptionAdapter } from "@react-router/remix-routes-option-adapter";
import { flatRoutes } from "remix-flat-routes";
diff --git a/apps/academy/app/routes/_index.tsx b/apps/academy/app/routes/_index.tsx
index bdecc3786d..3bb348abbc 100644
--- a/apps/academy/app/routes/_index.tsx
+++ b/apps/academy/app/routes/_index.tsx
@@ -1,4 +1,5 @@
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { modules } from "~/config";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/components/AnimatedSizeContainer.tsx b/apps/erp/app/components/AnimatedSizeContainer.tsx
index 7a682f7a48..76a574c6d2 100644
--- a/apps/erp/app/components/AnimatedSizeContainer.tsx
+++ b/apps/erp/app/components/AnimatedSizeContainer.tsx
@@ -1,9 +1,11 @@
import { cn } from "@carbon/react";
import { motion } from "framer-motion";
+import type {
+ ComponentPropsWithoutRef,
+ PropsWithChildren
+} from "react";
import {
- type ComponentPropsWithoutRef,
forwardRef,
- type PropsWithChildren
} from "react";
import useMeasure from "react-use-measure";
diff --git a/apps/erp/app/components/Chat/AnimatedSizeContainer.tsx b/apps/erp/app/components/Chat/AnimatedSizeContainer.tsx
index 2f2fee8cf9..45bcbf3c28 100644
--- a/apps/erp/app/components/Chat/AnimatedSizeContainer.tsx
+++ b/apps/erp/app/components/Chat/AnimatedSizeContainer.tsx
@@ -1,9 +1,11 @@
import { cn } from "@carbon/react";
import { motion } from "framer-motion";
+import type {
+ ComponentPropsWithoutRef,
+ PropsWithChildren,
+} from "react";
import {
- type ComponentPropsWithoutRef,
forwardRef,
- type PropsWithChildren,
useRef
} from "react";
import { useResizeObserver } from "~/hooks/useResizeObserver";
diff --git a/apps/erp/app/components/Chat/ChatInput.tsx b/apps/erp/app/components/Chat/ChatInput.tsx
index 479603c25e..4da104d63a 100644
--- a/apps/erp/app/components/Chat/ChatInput.tsx
+++ b/apps/erp/app/components/Chat/ChatInput.tsx
@@ -8,19 +8,22 @@ import { cn } from "@carbon/react";
import { forwardRef, useRef } from "react";
import { CommandMenu } from "./CommandMenu";
import { useChatStore } from "./lib/store";
+import type {
+ PromptInputMessage,
+} from "./PromptInput";
import {
PromptInput,
PromptInputActionAddAttachments,
PromptInputAttachment,
PromptInputAttachments,
PromptInputBody,
- type PromptInputMessage,
PromptInputSubmit,
PromptInputTextarea,
PromptInputToolbar,
PromptInputTools
} from "./PromptInput";
-import { RecordButton, type RecordButtonRef } from "./RecordButton";
+import type { RecordButtonRef } from "./RecordButton";
+import { RecordButton, } from "./RecordButton";
import { SuggestedActionsButton } from "./SuggestedActions";
import { SuggestedPrompts } from "./SuggestedPrompts";
import { WebSearchButton } from "./WebSearch";
diff --git a/apps/erp/app/components/Chat/CommandMenu.tsx b/apps/erp/app/components/Chat/CommandMenu.tsx
index cac2c162ab..dcadedb1c6 100644
--- a/apps/erp/app/components/Chat/CommandMenu.tsx
+++ b/apps/erp/app/components/Chat/CommandMenu.tsx
@@ -1,6 +1,7 @@
import { useChatActions, useChatId } from "@ai-sdk-tools/store";
import { cn } from "@carbon/react";
-import { type RefObject, useEffect, useRef } from "react";
+import type { RefObject, } from "react";
+import { useEffect, useRef } from "react";
import { LuArrowRight } from "react-icons/lu";
import { useOnClickOutside } from "~/hooks/useOnClickOutside";
import { AnimatedSizeContainer } from "./AnimatedSizeContainer";
diff --git a/apps/erp/app/components/Chat/Markdown/utils.ts b/apps/erp/app/components/Chat/Markdown/utils.ts
index a90de0adc6..81cace28a1 100644
--- a/apps/erp/app/components/Chat/Markdown/utils.ts
+++ b/apps/erp/app/components/Chat/Markdown/utils.ts
@@ -1,7 +1,10 @@
import rehypeRaw from "rehype-raw";
-import rehypeSanitize, {
+import type rehypeSanitize from "rehype-sanitize";
+import type {
+ Options as RehypeSanitizeOptions
+} from "rehype-sanitize";
+import {
defaultSchema,
- type Options as RehypeSanitizeOptions
} from "rehype-sanitize";
import remarkGfm from "remark-gfm";
import type { PluggableList, Plugin } from "unified";
diff --git a/apps/erp/app/components/Chat/PromptInput.tsx b/apps/erp/app/components/Chat/PromptInput.tsx
index 81fbbbaf56..94354b638c 100644
--- a/apps/erp/app/components/Chat/PromptInput.tsx
+++ b/apps/erp/app/components/Chat/PromptInput.tsx
@@ -16,17 +16,20 @@ import {
} from "@carbon/react";
import type { ChatStatus, FileUIPart } from "ai";
import { nanoid } from "nanoid";
+import type {
+ ChangeEventHandler,
+ ComponentProps,
+ FormEvent,
+ FormEventHandler,
+ HTMLAttributes,
+ KeyboardEventHandler,
+ RefObject
+} from "react";
import {
- type ChangeEventHandler,
Children,
- type ComponentProps,
createContext,
- type FormEvent,
- type FormEventHandler,
Fragment,
- type HTMLAttributes,
- type KeyboardEventHandler,
- type RefObject,
+ forwardRef,
useCallback,
useContext,
useEffect,
@@ -441,52 +444,56 @@ export const PromptInputBody = ({
export type PromptInputTextareaProps = ComponentProps<typeof Textarea>;
-export const PromptInputTextarea = ({
- onChange,
- className,
- placeholder = "You can just do things",
- ...props
-}: PromptInputTextareaProps) => {
- const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
- if (e.key === "Enter") {
- // Don't submit if IME composition is in progress
- if (e.nativeEvent.isComposing) {
- return;
- }
+export const PromptInputTextarea = forwardRef<
+ HTMLTextAreaElement,
+ PromptInputTextareaProps
+>(
+ (
+ { onChange, className, placeholder = "You can just do things", ...props },
+ ref
+ ) => {
+ const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
+ if (e.key === "Enter") {
+ // Don't submit if IME composition is in progress
+ if (e.nativeEvent.isComposing) {
+ return;
+ }
- if (e.shiftKey) {
- // Allow newline
- return;
- }
+ if (e.shiftKey) {
+ // Allow newline
+ return;
+ }
- // Submit on Enter (without Shift)
- e.preventDefault();
- const form = e.currentTarget.form;
- if (form) {
- form.requestSubmit();
+ // Submit on Enter (without Shift)
+ e.preventDefault();
+ const form = e.currentTarget.form;
+ if (form) {
+ form.requestSubmit();
+ }
}
- }
- };
+ };
- return (
- <Textarea
- className={cn(
- "w-full resize-none rounded-none border-none p-3 pt-4 shadow-none outline-none ring-0 text-base",
- "field-sizing-content bg-transparent placeholder:text-muted-foreground",
- "max-h-[55px] min-h-[55px]",
- "focus-visible:ring-0",
- className
- )}
- name="message"
- onChange={(e) => {
- onChange?.(e);
- }}
- onKeyDown={handleKeyDown}
- placeholder={placeholder}
- {...props}
- />
- );
-};
+ return (
+ <Textarea
+ ref={ref}
+ className={cn(
+ "w-full resize-none rounded-none border-none p-3 pt-4 shadow-none outline-none ring-0 text-base",
+ "field-sizing-content bg-transparent placeholder:text-muted-foreground",
+ "max-h-[55px] min-h-[55px]",
+ "focus-visible:ring-0",
+ className
+ )}
+ name="message"
+ onChange={(e) => {
+ onChange?.(e);
+ }}
+ onKeyDown={handleKeyDown}
+ placeholder={placeholder}
+ {...props}
+ />
+ );
+ }
+);
export type PromptInputToolbarProps = HTMLAttributes<HTMLDivElement>;
diff --git a/apps/erp/app/components/Chat/messages/Messages.tsx b/apps/erp/app/components/Chat/messages/Messages.tsx
index b1a16339d0..184793acc8 100644
--- a/apps/erp/app/components/Chat/messages/Messages.tsx
+++ b/apps/erp/app/components/Chat/messages/Messages.tsx
@@ -9,8 +9,10 @@ import {
ConversationScrollButton
} from "../Conversation";
import { Markdown } from "../Markdown/Markdown";
+import type {
+ SupportedToolName,
+} from "../ToolCallIndicator";
import {
- type SupportedToolName,
ToolCallIndicator
} from "../ToolCallIndicator";
import { WebSearchSources } from "../WebSearch";
diff --git a/apps/erp/app/components/EmployeeAvatarGroup.tsx b/apps/erp/app/components/EmployeeAvatarGroup.tsx
index 81d92da642..486b389d0a 100644
--- a/apps/erp/app/components/EmployeeAvatarGroup.tsx
+++ b/apps/erp/app/components/EmployeeAvatarGroup.tsx
@@ -1,8 +1,10 @@
+import type {
+ AvatarProps
+} from "@carbon/react";
import {
AvatarGroup,
AvatarGroupList,
AvatarOverflowIndicator,
- type AvatarProps
} from "@carbon/react";
import { usePeople } from "~/stores";
import Avatar from "./Avatar";
diff --git a/apps/erp/app/components/FileDropzone.tsx b/apps/erp/app/components/FileDropzone.tsx
index 868c270b7d..a40c25481f 100644
--- a/apps/erp/app/components/FileDropzone.tsx
+++ b/apps/erp/app/components/FileDropzone.tsx
@@ -1,4 +1,4 @@
-import React from "react";
+import type React from "react";
import { useDropzone } from "react-dropzone";
import { LuCloudUpload } from "react-icons/lu";
diff --git a/apps/erp/app/components/Form/CustomerLocation.tsx b/apps/erp/app/components/Form/CustomerLocation.tsx
index 67a65ea601..f9bb6f317c 100644
--- a/apps/erp/app/components/Form/CustomerLocation.tsx
+++ b/apps/erp/app/components/Form/CustomerLocation.tsx
@@ -4,9 +4,9 @@ import { useDisclosure } from "@carbon/react";
import { formatAddress } from "@carbon/utils";
import { useEffect, useMemo, useRef, useState } from "react";
import { useFetcher } from "react-router";
-import {
- type CustomerLocation as CustomerLocationType,
- type getCustomerLocations
+import type {
+ CustomerLocation as CustomerLocationType,
+ getCustomerLocations
} from "~/modules/sales";
import CustomerLocationForm from "~/modules/sales/ui/Customer/CustomerLocationForm";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/components/Form/ExchangeRate.tsx b/apps/erp/app/components/Form/ExchangeRate.tsx
index ad76f57b95..7780174ef9 100644
--- a/apps/erp/app/components/Form/ExchangeRate.tsx
+++ b/apps/erp/app/components/Form/ExchangeRate.tsx
@@ -8,7 +8,8 @@ import {
VStack
} from "@carbon/react";
import { useLocale } from "@react-aria/i18n";
-import React, { useMemo } from "react";
+import type React from "react";
+import { useMemo } from "react";
import { LuInfo, LuLoaderCircle } from "react-icons/lu";
import { NumberControlled } from "~/components/Form";
diff --git a/apps/erp/app/components/Form/Item.tsx b/apps/erp/app/components/Form/Item.tsx
index 2636028e67..4f7229cb60 100644
--- a/apps/erp/app/components/Form/Item.tsx
+++ b/apps/erp/app/components/Form/Item.tsx
@@ -33,7 +33,8 @@ import ConsumableForm from "~/modules/items/ui/Consumables/ConsumableForm";
import MaterialForm from "~/modules/items/ui/Materials/MaterialForm";
import PartForm from "~/modules/items/ui/Parts/PartForm";
import ToolForm from "~/modules/items/ui/Tools/ToolForm";
-import { type MethodItemType, methodItemType } from "~/modules/shared";
+import type { MethodItemType } from "~/modules/shared";
+import { methodItemType } from "~/modules/shared";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
import { MethodItemTypeIcon } from "../Icons";
diff --git a/apps/erp/app/components/Form/SupplierLocation.tsx b/apps/erp/app/components/Form/SupplierLocation.tsx
index 479b4963cf..bc06c75c68 100644
--- a/apps/erp/app/components/Form/SupplierLocation.tsx
+++ b/apps/erp/app/components/Form/SupplierLocation.tsx
@@ -4,9 +4,9 @@ import { useDisclosure } from "@carbon/react";
import { formatAddress } from "@carbon/utils";
import { useEffect, useMemo, useRef } from "react";
import { useFetcher } from "react-router";
-import {
- type getSupplierLocations,
- type SupplierLocation as SupplierLocationType
+import type {
+ getSupplierLocations,
+ SupplierLocation as SupplierLocationType
} from "~/modules/purchasing";
import { SupplierLocationForm } from "~/modules/purchasing/ui/Supplier";
import { path } from "~/utils/path";
@@ -43,7 +43,6 @@ const SupplierLocation = (props: SupplierLocationSelectProps) => {
path.to.api.supplierLocations(props.supplier)
);
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.supplier]);
const options = useMemo(
diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
index 395982bddc..dc70bbace6 100644
--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
@@ -4,8 +4,10 @@ import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { useFetcher } from "react-router";
import { z } from "zod";
+import type {
+ fieldMappings,
+} from "~/modules/shared/imports.models";
import {
- type fieldMappings,
importSchemas
} from "~/modules/shared/imports.models";
import type { action } from "~/routes/x+/shared+/import.$tableId";
diff --git a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
index 633ca21026..b99629dcb0 100644
--- a/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
+++ b/apps/erp/app/components/Layout/Navigation/CollapsibleSidebar.tsx
@@ -1,5 +1,5 @@
import { cn, IconButton, useDisclosure } from "@carbon/react";
-import { motion } from "framer-motion";
+import { motion, useReducedMotion } from "framer-motion";
import type { ComponentProps, PropsWithChildren } from "react";
import { createContext, forwardRef, useContext, useMemo } from "react";
import { LuPanelLeft } from "react-icons/lu";
@@ -62,19 +62,25 @@ export const CollapsibleSidebarTrigger = forwardRef<
CollapsibleSidebarTrigger.displayName = "CollapsibleSidebarTrigger";
+// ease-out-quart: feels snappy and responsive for sidebar expand/collapse
+const easeOutQuart = [0.165, 0.84, 0.44, 1] as const;
+
export const CollapsibleSidebar = ({
children,
width = 180
}: PropsWithChildren<{ width?: number }>) => {
const { isOpen } = useCollapsibleSidebar();
+ const shouldReduceMotion = useReducedMotion();
const variants = useMemo(() => {
return {
visible: {
- width
+ width,
+ opacity: 1
},
hidden: {
- width: 0
+ width: 0,
+ opacity: 0
}
};
}, [width]);
@@ -82,8 +88,16 @@ export const CollapsibleSidebar = ({
return (
<motion.div
animate={isOpen ? "visible" : "hidden"}
- initial={variants.visible}
- transition={{ duration: 0.2, ease: "easeInOut" }}
+ initial={shouldReduceMotion ? false : variants.visible}
+ transition={
+ shouldReduceMotion
+ ? { duration: 0 }
+ : {
+ duration: 0.2,
+ ease: easeOutQuart,
+ opacity: { duration: 0.15 }
+ }
+ }
variants={variants}
className="relative flex h-[calc(100dvh-49px)]"
>
diff --git a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
index 0273d2489d..00901ac356 100644
--- a/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
+++ b/apps/erp/app/components/Layout/Navigation/PrimaryNavigation.tsx
@@ -1,5 +1,6 @@
import { cn, useDisclosure, VStack } from "@carbon/react";
-import { type AnchorHTMLAttributes, forwardRef, memo } from "react";
+import type { AnchorHTMLAttributes, } from "react";
+import { forwardRef, memo } from "react";
import { Link, useMatches } from "react-router";
import { useModules, useOptimisticLocation } from "~/hooks";
import type { Authenticated, NavItem } from "~/types";
diff --git a/apps/erp/app/components/Layout/Topbar/Search.tsx b/apps/erp/app/components/Layout/Topbar/Search.tsx
index fea08d7177..3b88e440f8 100644
--- a/apps/erp/app/components/Layout/Topbar/Search.tsx
+++ b/apps/erp/app/components/Layout/Topbar/Search.tsx
@@ -297,7 +297,7 @@ const SearchModal = () => {
},
result.entityType,
undefined,
- result.description
+ result.description!
)
}
className="flex items-center gap-3 px-3 py-3 rounded-lg group"
diff --git a/apps/erp/app/components/OnshapeSync.tsx b/apps/erp/app/components/OnshapeSync.tsx
index c26d425556..6dac8bdc61 100644
--- a/apps/erp/app/components/OnshapeSync.tsx
+++ b/apps/erp/app/components/OnshapeSync.tsx
@@ -72,16 +72,18 @@ export const OnshapeSync = ({
return;
}
carbon
- ?.from("item")
- .select("externalId")
- .eq("id", itemId)
- .single()
+ .from("externalIntegrationMapping")
+ .select("metadata, lastSyncedAt")
+ .eq("entityType", "item")
+ .eq("entityId", itemId)
+ .eq("integration", "onshape")
+ .maybeSingle()
.then(({ data }) => {
- const externalId = data?.externalId as Record<string, any>;
- setDocumentId(externalId.onshape?.documentId);
- setVersionId(externalId.onshape?.versionId);
- setElementId(externalId.onshape?.elementId);
- setLastSyncedAt(externalId.onshape?.lastSyncedAt);
+ const metadata = data?.metadata as Record<string, any> | null;
+ setDocumentId(metadata?.documentId ?? null);
+ setVersionId(metadata?.versionId ?? null);
+ setElementId(metadata?.elementId ?? null);
+ setLastSyncedAt(data?.lastSyncedAt ?? null);
});
});
diff --git a/apps/erp/app/components/Table/components/TableHeader.tsx b/apps/erp/app/components/Table/components/TableHeader.tsx
index dbb16c3263..e58525f33f 100644
--- a/apps/erp/app/components/Table/components/TableHeader.tsx
+++ b/apps/erp/app/components/Table/components/TableHeader.tsx
@@ -27,7 +27,8 @@ import type {
ColumnOrderState,
ColumnPinningState
} from "@tanstack/react-table";
-import { type ReactNode, useEffect, useState } from "react";
+import type { ReactNode, } from "react";
+import { useEffect, useState } from "react";
import { BsThreeDotsVertical } from "react-icons/bs";
import {
LuCheck,
diff --git a/apps/erp/app/hooks/useResizeObserver.tsx b/apps/erp/app/hooks/useResizeObserver.tsx
index 4b03f40567..208e4564a2 100644
--- a/apps/erp/app/hooks/useResizeObserver.tsx
+++ b/apps/erp/app/hooks/useResizeObserver.tsx
@@ -1,4 +1,5 @@
-import { type RefObject, useEffect, useState } from "react";
+import type { RefObject, } from "react";
+import { useEffect, useState } from "react";
export function useResizeObserver(
elementRef: RefObject<Element>
diff --git a/apps/erp/app/modules/documents/ui/Documents/DocumentView.tsx b/apps/erp/app/modules/documents/ui/Documents/DocumentView.tsx
index b37e0803b5..d8fd595a79 100644
--- a/apps/erp/app/modules/documents/ui/Documents/DocumentView.tsx
+++ b/apps/erp/app/modules/documents/ui/Documents/DocumentView.tsx
@@ -11,7 +11,7 @@ import { Document, Page, pdfjs } from "react-pdf";
import { useNavigate } from "react-router";
import DocumentIcon from "~/components/DocumentIcon";
import { path } from "~/utils/path";
-import { type Document as DocumentType } from "../../types";
+import type { Document as DocumentType } from "../../types";
import { useDocument } from "./useDocument";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.ts
index a7e75cfeb7..5ffc3489df 100644
--- a/apps/erp/app/modules/inventory/inventory.service.ts
+++ b/apps/erp/app/modules/inventory/inventory.service.ts
@@ -1,4 +1,5 @@
-import { type Database, fetchAllFromTable, type Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
+import { fetchAllFromTable, } from "@carbon/database";
import { getLocalTimeZone, today } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
diff --git a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
index 709fc67694..0bd3f616fb 100644
--- a/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
+++ b/apps/erp/app/modules/inventory/ui/Receipts/ReceiptLines.tsx
@@ -65,11 +65,13 @@ import { useShelves } from "~/components/Form/Shelf";
import { useUnitOfMeasure } from "~/components/Form/UnitOfMeasure";
import { ConfirmDelete } from "~/components/Modals";
import { useRouteData, useUser } from "~/hooks";
+import type {
+ BatchProperty,
+ ItemTracking,
+ Receipt,
+ ReceiptLine,
+} from "~/modules/inventory";
import {
- type BatchProperty,
- type ItemTracking,
- type Receipt,
- type ReceiptLine,
ShelfForm,
splitValidator
} from "~/modules/inventory";
diff --git a/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx b/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
index 382d1e8bd7..57a03c475f 100644
--- a/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/ShippingMethods/ShippingMethodsTable.tsx
@@ -14,7 +14,8 @@ import { Hyperlink, New, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import { type ShippingMethod, shippingCarrierType } from "~/modules/inventory";
+import type { ShippingMethod, } from "~/modules/inventory";
+import { shippingCarrierType } from "~/modules/inventory";
import { path } from "~/utils/path";
type ShippingMethodsTableProps = {
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
index f4ac0261c4..61fbf3111c 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransferWizard.tsx
@@ -44,8 +44,8 @@ import {
VStack
} from "@carbon/react";
import { useNumberFormatter } from "@react-aria/i18n";
+import type { ColumnDef } from "@tanstack/react-table";
import {
- type ColumnDef,
flexRender,
getCoreRowModel,
useReactTable
diff --git a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
index 36459f3f81..85177d4108 100644
--- a/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StockTransfers/StockTransfersTable.tsx
@@ -6,7 +6,7 @@ import {
useDisclosure
} from "@carbon/react";
import { formatDate } from "@carbon/utils";
-import { type ColumnDef } from "@tanstack/react-table";
+import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo, useState } from "react";
import {
LuBookMarked,
diff --git a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
index 4d522906d6..f05b94b489 100644
--- a/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/Traceability/TrackedEntitiesTable.tsx
@@ -14,7 +14,8 @@ import { useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions } from "~/hooks";
-import { type TrackedEntity, trackedEntityStatus } from "~/modules/inventory";
+import type { TrackedEntity, } from "~/modules/inventory";
+import { trackedEntityStatus } from "~/modules/inventory";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { Item } from "~/stores/items";
import { useItems } from "~/stores/items";
diff --git a/apps/erp/app/modules/invoicing/invoicing.service.ts b/apps/erp/app/modules/invoicing/invoicing.service.ts
index 69232544d3..837c9c755c 100644
--- a/apps/erp/app/modules/invoicing/invoicing.service.ts
+++ b/apps/erp/app/modules/invoicing/invoicing.service.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import { getLocalTimeZone, now, today } from "@internationalized/date";
-import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion, } from "@supabase/supabase-js";
import type { z } from "zod";
import {
getSupplierPayment,
diff --git a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
index 467dec8332..e268cdef5b 100644
--- a/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
+++ b/apps/erp/app/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicePostModal.tsx
@@ -25,7 +25,7 @@ import { useEffect, useMemo } from "react";
import { LuTriangleAlert } from "react-icons/lu";
import { useFetcher, useNavigate } from "react-router";
import { useItems } from "~/stores";
-import { Result } from "~/types";
+import type { Result } from "~/types";
import { path } from "~/utils/path";
type PurchaseInvoicePostModalProps = {
diff --git a/apps/erp/app/modules/items/items.service.ts b/apps/erp/app/modules/items/items.service.ts
index 3d6bd0709e..2914eaa21d 100644
--- a/apps/erp/app/modules/items/items.service.ts
+++ b/apps/erp/app/modules/items/items.service.ts
@@ -1,9 +1,10 @@
import type { Database, Json } from "@carbon/database";
import { fetchAllFromTable } from "@carbon/database";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
-import { type z } from "zod";
+import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index bcb6a7cd75..04c1cf42d1 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -78,12 +78,12 @@ import type {
} from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
-import {
- type MethodItemType,
- type MethodType,
- methodType
-} from "~/modules/shared";
-import { type Item as ItemType, useItems } from "~/stores";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { methodType } from "~/modules/shared";
+
+import type { Item as ItemType } from "~/stores";
+import { useItems } from "~/stores";
+
import { path } from "~/utils/path";
import type { methodOperationValidator } from "../../items.models";
import { methodMaterialValidator } from "../../items.models";
diff --git a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
index c08b223f2d..853212b732 100644
--- a/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BoMExplorer.tsx
@@ -41,7 +41,7 @@ import { OnshapeSync } from "~/components/OnshapeSync";
import type { FlatTreeItem } from "~/components/TreeView";
import { LevelLine, TreeView, useTree } from "~/components/TreeView";
import { useIntegrations } from "~/hooks/useIntegrations";
-import { type MethodItemType } from "~/modules/shared";
+import type { MethodItemType } from "~/modules/shared";
import { generateBomIds } from "~/utils/bom";
import { path } from "~/utils/path";
import type { MakeMethod, Method, MethodOperation } from "../../types";
diff --git a/apps/erp/app/modules/people/ui/Person/PersonAbilities.tsx b/apps/erp/app/modules/people/ui/Person/PersonAbilities.tsx
index 49167380e3..4f47301b12 100644
--- a/apps/erp/app/modules/people/ui/Person/PersonAbilities.tsx
+++ b/apps/erp/app/modules/people/ui/Person/PersonAbilities.tsx
@@ -5,9 +5,11 @@ import type { IconType } from "react-icons";
import { BsBarChartFill, BsCheckLg } from "react-icons/bs";
import { FaThumbsUp } from "react-icons/fa";
import { Link } from "react-router";
+import type {
+ EmployeeAbility,
+} from "~/modules/resources/types";
import {
AbilityEmployeeStatus,
- type EmployeeAbility,
getTrainingStatus
} from "~/modules/resources/types";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 38b7b348fd..1ea9feb724 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -1,13 +1,11 @@
import { getCarbonServiceRole } from "@carbon/auth";
-import { type Database, fetchAllFromTable, type Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
+import { fetchAllFromTable } from "@carbon/database";
import type { JSONContent } from "@carbon/react";
import { parseDate } from "@internationalized/date";
import type { FileObject, StorageError } from "@supabase/storage-js";
-import {
- FunctionRegion,
- type PostgrestError,
- type SupabaseClient
-} from "@supabase/supabase-js";
+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import type { z } from "zod";
import type { StorageItem } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index 7c62905260..a9ec1ed348 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -68,7 +68,8 @@ import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
-import { type Item as ItemType, useItems } from "~/stores";
+import type { Item as ItemType } from "~/stores";
+import { useItems } from "~/stores";
import { path } from "~/utils/path";
import type { jobOperationValidator } from "../../production.models";
import {
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
index a933ebe146..60ddf61649 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobForm.tsx
@@ -40,7 +40,7 @@ import type {
ConfigurationParameter,
ConfigurationParameterGroup
} from "~/modules/items/types";
-import { type MethodItemType } from "~/modules/shared";
+import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
import type { jobStatus } from "../../production.models";
import {
diff --git a/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx b/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
index d4e27dc99c..6688258c17 100644
--- a/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
+++ b/apps/erp/app/modules/production/ui/Schedule/Kanban/context/KanbanContext.tsx
@@ -1,4 +1,5 @@
-import { createContext, type ReactNode, useContext } from "react";
+import type { ReactNode, } from "react";
+import { createContext, useContext } from "react";
import type { DisplaySettings } from "../types";
interface KanbanContextType {
diff --git a/apps/erp/app/modules/purchasing/purchasing.service.ts b/apps/erp/app/modules/purchasing/purchasing.service.ts
index 5a34da420f..43275d7024 100644
--- a/apps/erp/app/modules/purchasing/purchasing.service.ts
+++ b/apps/erp/app/modules/purchasing/purchasing.service.ts
@@ -1,11 +1,12 @@
-import { type Database, fetchAllFromTable, type Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
+import { fetchAllFromTable } from "@carbon/database";
import { getPurchaseOrderStatus } from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
-import {
- FunctionRegion,
- type PostgrestSingleResponse,
- type SupabaseClient
+import type {
+ PostgrestSingleResponse,
+ SupabaseClient
} from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import type { z } from "zod";
import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
@@ -14,25 +15,25 @@ import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting/accounting.service";
import type { PurchaseInvoice } from "../invoicing/types";
import { upsertExternalLink } from "../shared/shared.service";
-import {
- type purchaseOrderDeliveryValidator,
- type purchaseOrderLineValidator,
- type purchaseOrderPaymentValidator,
- type purchaseOrderStatusType,
- type purchaseOrderValidator,
+import type {
+ purchaseOrderDeliveryValidator,
+ purchaseOrderLineValidator,
+ purchaseOrderPaymentValidator,
+ purchaseOrderStatusType,
+ purchaseOrderValidator,
purchasingRfqStatusType,
- type selectedLinesValidator,
- type supplierAccountingValidator,
- type supplierContactValidator,
- type supplierPaymentValidator,
- type supplierProcessValidator,
- type supplierQuoteLineValidator,
- type supplierQuoteStatusType,
- type supplierQuoteValidator,
- type supplierShippingValidator,
- type supplierStatusValidator,
- type supplierTypeValidator,
- type supplierValidator
+ selectedLinesValidator,
+ supplierAccountingValidator,
+ supplierContactValidator,
+ supplierPaymentValidator,
+ supplierProcessValidator,
+ supplierQuoteLineValidator,
+ supplierQuoteStatusType,
+ supplierQuoteValidator,
+ supplierShippingValidator,
+ supplierStatusValidator,
+ supplierTypeValidator,
+ supplierValidator
} from "./purchasing.models";
import type { PurchaseOrder, PurchasingRFQ, SupplierQuote } from "./types";
@@ -581,14 +582,14 @@ export async function getSupplierQuoteByInteractionId(
.single();
}
-export async function getSupplierQuoteByExternalId(
+export async function getSupplierQuoteByExternalLinkId(
client: SupabaseClient<Database>,
- externalId: string
+ externalLinkId: string
) {
return client
.from("supplierQuote")
.select("*")
- .eq("externalLinkId", externalId)
+ .eq("externalLinkId", externalLinkId)
.single();
}
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 5434cab46f..99ad4ba653 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -1,4 +1,5 @@
-import { type Database, fetchAllFromTable, type Json } from "@carbon/database";
+import type { Database, Json } from "@carbon/database";
+import { fetchAllFromTable } from "@carbon/database";
import type { JSONContent } from "@carbon/react";
import { parseDate } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
@@ -408,7 +409,37 @@ export async function getIssueActionTasks(
if (supplierId) {
query = query.eq("supplierId", supplierId);
}
- return query;
+
+ const result = await query;
+
+ if (result.error || !result.data) {
+ return result;
+ }
+
+ // Fetch Linear mappings for all action task IDs
+ const taskIds = result.data.map((t) => t.id);
+ let linearMappings: Map<string, unknown> = new Map();
+
+ if (taskIds.length > 0) {
+ const { data: mappings } = await client
+ .from("externalIntegrationMapping")
+ .select("entityId, metadata")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("integration", "linear")
+ .in("entityId", taskIds);
+
+ linearMappings = new Map(
+ (mappings ?? []).map((m) => [m.entityId, m.metadata])
+ );
+ }
+
+ return {
+ ...result,
+ data: result.data.map((task) => ({
+ ...task,
+ linearIssue: linearMappings.get(task.id) ?? null
+ }))
+ };
}
export async function getIssueApprovalTasks(
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueContent.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueContent.tsx
index ed5839857c..027ba1e64c 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueContent.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueContent.tsx
@@ -1,4 +1,7 @@
import { useCarbon } from "@carbon/auth";
+import type {
+ JSONContent,
+} from "@carbon/react";
import {
Card,
CardContent,
@@ -6,7 +9,6 @@ import {
CardHeader,
CardTitle,
generateHTML,
- type JSONContent,
toast,
useDebounce
} from "@carbon/react";
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
index 7d77f33c6b..c4ca9c6c3f 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx
@@ -278,9 +278,7 @@ export function TaskItem({
// Check if this action task has a linked Linear issue
const hasLinearLink =
- type === "action" &&
- !!(task as IssueActionTask & { externalId?: { linear?: unknown } })
- .externalId?.linear;
+ type === "action" && !!(task as IssueActionTask).linearIssue;
const { content, setContent, onUpdateContent, onUploadImage } = useTaskNotes({
initialContent: (task.notes ?? {}) as JSONContent,
diff --git a/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx b/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx
index 43b0615803..8a2e63fcfc 100644
--- a/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/Linear/IssueDialog.tsx
@@ -1,4 +1,4 @@
-import { type LinearIssue, LinearIssueSchema } from "@carbon/ee/linear";
+import { LinearIssueSchema } from "@carbon/ee/linear";
import {
Badge,
Button,
@@ -29,9 +29,7 @@ import { CreateIssue } from "./CreateIssue";
import { LinkIssue } from "./LinkIssue";
interface Props {
- task: IssueActionTask & {
- externalId: { linear: LinearIssue } | undefined;
- };
+ task: IssueActionTask;
}
export const LinearIssueDialog = ({ task }: Props) => {
@@ -44,7 +42,7 @@ export const LinearIssueDialog = ({ task }: Props) => {
}
});
- const { data: linked } = LinearIssueSchema.safeParse(task.externalId?.linear);
+ const { data: linked } = LinearIssueSchema.safeParse(task.linearIssue);
const fetcher = useAsyncFetcher();
const onUnlink = async () => {
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
index a1ae4d5ed7..8b264832c7 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceAddPartModal.tsx
@@ -40,7 +40,7 @@ import {
import { useFetcher } from "react-router";
import { z } from "zod";
import { Item, UnitOfMeasure } from "~/components/Form";
-import { MethodItemType } from "~/modules/shared/types";
+import type { MethodItemType } from "~/modules/shared/types";
import { path } from "~/utils/path";
export const maintenanceAddPartValidator = z.object({
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
index aa79bbe587..9d426c12cb 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchNotes.tsx
@@ -1,4 +1,7 @@
import { useCarbon } from "@carbon/auth";
+import type {
+ JSONContent,
+} from "@carbon/react";
import {
Card,
CardAction,
@@ -14,7 +17,6 @@ import {
generateHTML,
HStack,
IconButton,
- type JSONContent,
Skeleton,
Table,
Tbody,
@@ -29,7 +31,8 @@ import { Editor } from "@carbon/react/Editor";
import { convertKbToString } from "@carbon/utils";
import type { FileObject } from "@supabase/storage-js";
import { nanoid } from "nanoid";
-import { type ChangeEvent, Suspense, useCallback, useState } from "react";
+import type { ChangeEvent, } from "react";
+import { Suspense, useCallback, useState } from "react";
import { LuEllipsisVertical, LuUpload } from "react-icons/lu";
import { Await, useRevalidator } from "react-router";
import { DocumentPreview, FileDropzone } from "~/components";
diff --git a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
index 9e828dcc60..92987b3371 100644
--- a/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Maintenance/MaintenanceDispatchesTable.tsx
@@ -20,7 +20,7 @@ import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenters";
import { usePermissions, useUrlParams } from "~/hooks";
import { usePeople } from "~/stores";
-import { ListItem } from "~/types";
+import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import {
maintenanceDispatchPriority,
diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
index d271d6624b..82bee9a486 100644
--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -31,7 +31,7 @@ import { Enumerable } from "~/components/Enumerable";
import { useWorkCenters } from "~/components/Form/WorkCenter";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import { type Process } from "~/modules/resources";
+import type { Process } from "~/modules/resources";
import { standardFactorType } from "~/modules/shared";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx
index 97e8e3b096..8ba8cae46e 100644
--- a/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx
+++ b/apps/erp/app/modules/resources/ui/Training/TrainingProperties.tsx
@@ -17,8 +17,10 @@ import Assignee, { useOptimisticAssignment } from "~/components/Assignee";
import { InputControlled, Tags } from "~/components/Form";
import { usePermissions, useRouteData } from "~/hooks";
import { useTags } from "~/hooks/useTags";
+import type {
+ Training,
+} from "~/modules/resources";
import {
- type Training,
trainingFrequency,
trainingStatus,
trainingType
diff --git a/apps/erp/app/modules/sales/sales.service.ts b/apps/erp/app/modules/sales/sales.service.ts
index 9b266e26f5..3a16733ba4 100644
--- a/apps/erp/app/modules/sales/sales.service.ts
+++ b/apps/erp/app/modules/sales/sales.service.ts
@@ -1,12 +1,13 @@
-import { type Database, fetchAllFromTable, type Json } from "@carbon/database";
-import { PickPartial } from "@carbon/utils";
+import type { Database, Json } from "@carbon/database";
+import { fetchAllFromTable } from "@carbon/database";
+import type { PickPartial } from "@carbon/utils";
import { getLocalTimeZone, now, today } from "@internationalized/date";
-import {
- FunctionRegion,
- type PostgrestError,
- type PostgrestSingleResponse,
- type SupabaseClient
+import type {
+ PostgrestError,
+ PostgrestSingleResponse,
+ SupabaseClient
} from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import type { z } from "zod";
import { getEmployeeJob } from "~/modules/people";
import type { GenericQueryFilters } from "~/utils/query";
diff --git a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
index 92798f18b3..c5e8eb1ccf 100644
--- a/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
+++ b/apps/erp/app/modules/sales/ui/Quotes/QuoteBillOfMaterial.tsx
@@ -69,7 +69,8 @@ import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
import type { MethodItemType, MethodType } from "~/modules/shared";
-import { type Item as ItemType, useItems } from "~/stores";
+import type { Item as ItemType } from "~/stores";
+import { useItems } from "~/stores";
import { path } from "~/utils/path";
import type { quoteOperationValidator } from "../../sales.models";
import { quoteMaterialValidator } from "../../sales.models";
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index b86d022b64..12f1b706f8 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -1,9 +1,9 @@
import type { Database, Json } from "@carbon/database";
-import { integrations } from "@carbon/ee";
+import { getIntegrationConfigById } from "@carbon/ee";
import { redis } from "@carbon/kv";
import type { SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
-import { Integration } from "~/modules/settings/types";
+import type { Integration } from "~/modules/settings/types";
import { sanitize } from "~/utils/supabase";
import type { customFieldValidator } from "./settings.models";
@@ -351,9 +351,9 @@ export async function getIntegrationHealth(
};
}
- const check = integrations.find((i) => i.id === integration.id);
+ const check = getIntegrationConfigById(integration.id!);
- if (!check || !check.healthcheck) {
+ if (!check || !check.onHealthcheck) {
return {
...integration,
health: "healthy"
@@ -362,23 +362,23 @@ export async function getIntegrationHealth(
const key = `integrations:${companyId}:${integration.id}:health`;
- const cached = await redis.get<string>(key);
+ const cached = await redis.get<number>(key);
- if (cached && parseInt(cached)) {
+ // Only cache healthy status
+ if (cached && cached == 1) {
return {
...integration,
- health: cached === "1" ? "healthy" : "unhealthy"
+ health: "healthy"
};
}
- const status = await check.healthcheck(
+ const status = await check.onHealthcheck(
companyId,
integration.metadata as Record<string, any>
);
await redis.set(key, status ? "1" : "0", {
- nx: true, // Only set if not exists
- ex: INTEGRATION_CACHE_TTL // Cache for 5 minutes
+ ex: INTEGRATION_CACHE_TTL * 5 // Cache for 5 minutes
});
return {
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 72bc7d6e20..69782239e8 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -1,7 +1,8 @@
import { SUPABASE_URL } from "@carbon/auth";
import type { Database } from "@carbon/database";
-import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type { z } from "zod";
import type { GenericQueryFilters } from "~/utils/query";
diff --git a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
index 47f57d3d40..6cd3767307 100644
--- a/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
+++ b/apps/erp/app/modules/settings/ui/ApiKeys/ApiKeysTable.tsx
@@ -14,7 +14,7 @@ import {
import { Link, Outlet, useNavigate } from "react-router";
import { EmployeeAvatar, Hyperlink, New, Table } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
-import { type ApiKey } from "~/modules/settings";
+import type { ApiKey } from "~/modules/settings";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
index 429e1cb292..9b0fb1621f 100644
--- a/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Company/CompanyLogoForm.tsx
@@ -8,7 +8,7 @@ import {
toast,
VStack
} from "@carbon/react";
-import { type ChangeEvent } from "react";
+import type { ChangeEvent } from "react";
import { useSubmit } from "react-router";
import type { Company } from "~/modules/settings";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
index 25809ec01e..85d60ea5dd 100644
--- a/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
+++ b/apps/erp/app/modules/settings/ui/CustomFields/CustomFieldsTable.tsx
@@ -8,7 +8,8 @@ import { Link, useNavigate } from "react-router";
import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions, useUrlParams } from "~/hooks";
-import { type CustomFieldsTableType, modulesType } from "~/modules/settings";
+import type { CustomFieldsTableType, } from "~/modules/settings";
+import { modulesType } from "~/modules/settings";
import { tablesWithTags } from "~/modules/shared";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
index 152243e0df..ac684d3eba 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationCard.tsx
@@ -1,4 +1,4 @@
-import type { IntegrationConfig } from "@carbon/ee";
+import type { Integration } from "@carbon/ee";
import {
Badge,
Button,
@@ -23,14 +23,14 @@ export function IntegrationCard({
integration,
installed
}: {
- integration: IntegrationConfig;
+ integration: Integration;
installed: IntegrationHealth | null;
}) {
const fetcher = useFetcher<{}>();
const navigate = useNavigate();
const routeData = useRouteData<{ state: string }>(path.to.integrations);
- const getOauthUrl = (integration: IntegrationConfig) => {
+ const getOauthUrl = (integration: Integration) => {
if ("oauth" in integration && !!integration.oauth) {
const { clientId, redirectUri, scopes } = integration.oauth;
const encodedRedirectUri = encodeURIComponent(
@@ -53,8 +53,8 @@ export function IntegrationCard({
window.open(oauthUrl);
} else if (integration.settings.some((setting) => setting.required)) {
navigate(path.to.integration(integration.id));
- } else if (integration.onInitialize) {
- await integration.onInitialize?.();
+ } else if (integration.onClientInstall) {
+ await integration.onClientInstall?.();
} else {
const formData = new FormData();
fetcher.submit(formData, {
@@ -65,7 +65,7 @@ export function IntegrationCard({
};
const handleUninstall = async () => {
- await integration?.onUninstall?.();
+ await integration?.onClientUninstall?.();
};
return (
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
index 48b807d6a8..0cca81265f 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
@@ -1,3 +1,8 @@
+import type {
+ IntegrationAction,
+ IntegrationSetting,
+ IntegrationSettingOption
+} from "@carbon/ee";
import { integrations as availableIntegrations } from "@carbon/ee";
import {
// biome-ignore lint/suspicious/noShadowRestrictedNames: suppressed due to migration
@@ -12,6 +17,9 @@ import {
import {
Badge,
Button,
+ Collapsible,
+ CollapsibleContent,
+ CollapsibleTrigger,
Drawer,
DrawerBody,
DrawerContent,
@@ -24,12 +32,232 @@ import {
VStack
} from "@carbon/react";
import { SUPPORT_EMAIL } from "@carbon/utils";
+import { useCallback, useMemo, useState } from "react";
+import { LuChevronDown } from "react-icons/lu";
import { useParams } from "react-router";
import { Processes } from "~/components/Form";
import { MethodIcon, TrackingTypeIcon } from "~/components/Icons";
import { usePermissions, useUser } from "~/hooks";
import { path } from "~/utils/path";
+function IntegrationActionButton({
+ action,
+ isDisabled
+}: {
+ action: IntegrationAction;
+ isDisabled: boolean;
+}) {
+ const [isLoading, setIsLoading] = useState(false);
+ const [status, setStatus] = useState<"idle" | "running" | "completed">(
+ "idle"
+ );
+
+ const handleClick = useCallback(async () => {
+ setIsLoading(true);
+ setStatus("running");
+
+ try {
+ const response = await fetch(action.endpoint, { method: "POST" });
+ const data = await response.json();
+
+ if (data.success) {
+ toast.success(`${action.label} started`);
+ setStatus("completed");
+ } else {
+ setStatus("idle");
+ toast.error(data.error || `Failed to start ${action.label}`);
+ }
+ } catch {
+ setStatus("idle");
+ toast.error(`Failed to start ${action.label}`);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [action]);
+
+ return (
+ <div className="flex items-center justify-between gap-4 p-3 border rounded-lg w-full">
+ <div className="flex flex-col flex-1 min-w-0">
+ <p className="text-sm font-medium">{action.label}</p>
+ <p className="text-xs text-muted-foreground">{action.description}</p>
+ </div>
+ <div className="shrink-0">
+ <Button
+ variant="secondary"
+ size="sm"
+ onClick={handleClick}
+ isLoading={isLoading}
+ isDisabled={isDisabled || status === "running"}
+ >
+ {status === "completed" ? "Started" : "Run"}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Helper to normalize option to consistent format
+ */
+function normalizeOption(option: IntegrationSettingOption): {
+ value: string;
+ label: string;
+ description?: string;
+} {
+ if (typeof option === "string") {
+ return { value: option, label: option };
+ }
+ return option;
+}
+
+/**
+ * Renders a single setting field based on its type
+ */
+function SettingField({ setting }: { setting: IntegrationSetting }) {
+ switch (setting.type) {
+ case "text":
+ return (
+ <div className="w-full">
+ <Input
+ name={setting.name}
+ label={setting.label}
+ isOptional={!setting.required}
+ />
+ {setting.description && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {setting.description}
+ </p>
+ )}
+ </div>
+ );
+
+ case "switch":
+ return (
+ <div className="flex items-center justify-between gap-4 w-full py-2">
+ <div className="flex flex-col flex-1">
+ <span className="text-sm font-medium">{setting.label}</span>
+ {setting.description && (
+ <span className="text-xs text-muted-foreground">
+ {setting.description}
+ </span>
+ )}
+ </div>
+ <div className="shrink-0">
+ <Boolean name={setting.name} />
+ </div>
+ </div>
+ );
+
+ case "processes":
+ return (
+ <div className="w-full">
+ <Processes name={setting.name} label={setting.label} />
+ {setting.description && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {setting.description}
+ </p>
+ )}
+ </div>
+ );
+
+ case "array":
+ return (
+ <div className="w-full">
+ <Array name={setting.name} label={setting.label} />
+ {setting.description && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {setting.description}
+ </p>
+ )}
+ </div>
+ );
+
+ case "options": {
+ const options =
+ setting.listOptions?.map((option) => {
+ const normalized = normalizeOption(option);
+ let icon: JSX.Element | null = null;
+
+ // Legacy icon support for specific field names
+ if (setting.name === "methodType") {
+ // @ts-ignore
+ icon = <MethodIcon type={normalized.value} />;
+ } else if (setting.name === "trackingType") {
+ // @ts-ignore
+ icon = <TrackingTypeIcon type={normalized.value} />;
+ }
+
+ // Build a simpler label that works well with Radix Select
+ const label = (
+ <span className="flex items-center gap-2">
+ {icon}
+ <span className="font-medium">{normalized.label}</span>
+ {normalized.description && (
+ <span className="text-muted-foreground text-xs">
+ — {normalized.description}
+ </span>
+ )}
+ </span>
+ );
+
+ return {
+ label,
+ value: normalized.value
+ };
+ }) ?? [];
+
+ return (
+ <div className="w-full">
+ <Select name={setting.name} label={setting.label} options={options} />
+ {setting.description && (
+ <p className="text-xs text-muted-foreground mt-1">
+ {setting.description}
+ </p>
+ )}
+ </div>
+ );
+ }
+
+ default:
+ return null;
+ }
+}
+
+/**
+ * Renders a collapsible group of settings
+ */
+function SettingsGroup({
+ name,
+ settings
+}: {
+ name: string;
+ settings: IntegrationSetting[];
+}) {
+ const [isOpen, setIsOpen] = useState(true);
+
+ return (
+ <Collapsible open={isOpen} onOpenChange={setIsOpen} className="w-full">
+ <CollapsibleTrigger className="flex items-center justify-between w-full py-2 group">
+ <Heading size="h4" className="text-left">
+ {name}
+ </Heading>
+ <LuChevronDown
+ className={`h-4 w-4 text-muted-foreground transition-transform duration-200 ${
+ isOpen ? "rotate-180" : ""
+ }`}
+ />
+ </CollapsibleTrigger>
+ <CollapsibleContent>
+ <VStack spacing={4} className="pt-2">
+ {settings.map((setting) => (
+ <SettingField key={setting.name} setting={setting} />
+ ))}
+ </VStack>
+ </CollapsibleContent>
+ </Collapsible>
+ );
+}
+
interface IntegrationFormProps {
metadata: Record<string, unknown>;
installed: boolean;
@@ -48,24 +276,67 @@ export function IntegrationForm({
} = useUser();
const { id: integrationId } = useParams();
+
+ const integration = integrationId
+ ? availableIntegrations.find((i) => i.id === integrationId)
+ : undefined;
+
+ // Extract connected organisation name from metadata (e.g. Xero tenant name)
+ const connectedOrgName = (metadata?.credentials as Record<string, unknown>)
+ ?.tenantName as string | undefined;
+
+ // Group settings by their group property
+ // Settings without a group appear first (ungrouped)
+ const { ungroupedSettings, groupedSettings, groupNames } = useMemo(() => {
+ if (!integration) {
+ return {
+ ungroupedSettings: [] as IntegrationSetting[],
+ groupedSettings: new Map<string, IntegrationSetting[]>(),
+ groupNames: [] as string[]
+ };
+ }
+
+ const ungrouped: IntegrationSetting[] = [];
+ const grouped = new Map<string, IntegrationSetting[]>();
+
+ for (const setting of integration.settings) {
+ if (!setting.group) {
+ ungrouped.push(setting);
+ } else {
+ const existing = grouped.get(setting.group) ?? [];
+ grouped.set(setting.group, [...existing, setting]);
+ }
+ }
+
+ return {
+ ungroupedSettings: ungrouped,
+ groupedSettings: grouped,
+ groupNames: [...grouped.keys()]
+ };
+ }, [integration]);
+
+ const initialValues = useMemo(() => {
+ if (!integration) return {};
+ return integration.settings.reduce(
+ (acc, setting) => {
+ return {
+ ...acc,
+ [setting.name]: metadata[setting.name] ?? setting.value
+ };
+ },
+ {} as Record<string, unknown>
+ );
+ }, [integration, metadata]);
+
if (!integrationId) {
throw new Error("Integration ID is required");
}
- const integration = availableIntegrations.find((i) => i.id === integrationId);
-
if (!integration) {
toast.error("Integration not found");
return null;
}
- const initialValues = integration.settings.reduce((acc, setting) => {
- return {
- ...acc,
- [setting.name]: metadata[setting.name]
- };
- }, {});
-
return (
<Drawer
open
@@ -89,12 +360,21 @@ export function IntegrationForm({
<Heading size="h3">{integration.name}</Heading>
{installed && <Badge variant="green">Installed</Badge>}
+
+ <span className="text-xs text-[#878787] text-right">
+ <Badge variant="secondary">{integration.category}</Badge> •
+ Published by Carbon
+ </span>
</div>
- <span className="text-xs text-[#878787] text-right">
- <Badge variant="secondary">{integration.category}</Badge> •
- Published by Carbon
- </span>
+ {installed && connectedOrgName && (
+ <div className="text-sm text-muted-foreground">
+ Connected to{" "}
+ <span className="font-medium text-foreground">
+ {connectedOrgName}
+ </span>
+ </div>
+ )}
</div>
</VStack>
</DrawerHeader>
@@ -113,78 +393,40 @@ export function IntegrationForm({
</>
)}
- {integration.settings.map((setting) => {
- switch (setting.type) {
- case "text":
- return (
- <Input
- key={setting.name}
- name={setting.name}
- label={setting.label}
- isOptional={!setting.required}
- />
- );
- case "switch":
- return (
- <Boolean
- key={setting.name}
- name={setting.name}
- label={setting.label}
- description={setting.label}
- />
- );
- case "processes":
- return (
- <Processes
- key={setting.name}
- name={setting.name}
- label={setting.label}
- />
- );
- case "array":
- return (
- <Array
- key={setting.name}
- name={setting.name}
- label={setting.label}
- />
- );
- case "options":
- return (
- <Select
- key={setting.name}
- name={setting.name}
- label={setting.label}
- options={
- setting.listOptions?.map((option) => {
- let icon: JSX.Element | null = null;
- if (setting.name === "methodType") {
- // @ts-ignore
- icon = <MethodIcon type={option} />;
- } else if (setting.name === "trackingType") {
- // @ts-ignore
- icon = <TrackingTypeIcon type={option} />;
- }
-
- return {
- label: (
- <Badge
- variant="secondary"
- className="flex items-center gap-2"
- >
- {icon ? icon : null} {option}
- </Badge>
- ),
- value: option
- };
- }) ?? []
- }
- />
- );
- default:
- return null;
- }
- })}
+ {/* Ungrouped settings appear first */}
+ {ungroupedSettings.length > 0 && (
+ <VStack spacing={4} className="w-full">
+ {ungroupedSettings.map((setting) => (
+ <SettingField key={setting.name} setting={setting} />
+ ))}
+ </VStack>
+ )}
+
+ {/* Grouped settings in collapsible sections */}
+ {groupNames.map((groupName) => (
+ <SettingsGroup
+ key={groupName}
+ name={groupName}
+ settings={groupedSettings.get(groupName) ?? []}
+ />
+ ))}
+
+ {installed &&
+ integration.actions &&
+ integration.actions.length > 0 && (
+ <>
+ <Heading size="h3">Actions</Heading>
+ <VStack spacing={2} className="w-full">
+ {integration.actions.map((action) => (
+ <IntegrationActionButton
+ key={action.id}
+ action={action}
+ isDisabled={isDisabled}
+ />
+ ))}
+ </VStack>
+ </>
+ )}
</VStack>
</ScrollArea>
<p className="text-sm text-muted-foreground">
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
index 9a756cd256..428830ca83 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationsList.tsx
@@ -1,4 +1,4 @@
-import type { IntegrationConfig } from "@carbon/ee";
+import type { Integration } from "@carbon/ee";
import {
Select,
@@ -10,10 +10,11 @@ import {
import { useUrlParams } from "@carbon/remix";
import { useMemo, useState } from "react";
import { SearchFilter } from "~/components";
-import { IntegrationCard, IntegrationHealth } from "./IntegrationCard";
+import type { IntegrationHealth } from "./IntegrationCard";
+import { IntegrationCard } from "./IntegrationCard";
type IntegrationsListProps = {
- availableIntegrations: IntegrationConfig[];
+ availableIntegrations: Integration[];
integrations: Array<IntegrationHealth>;
};
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index b1723e24a1..35c83538be 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1,6 +1,7 @@
import type { Database } from "@carbon/database";
import { getPurchaseOrderStatus, supportedModelTypes } from "@carbon/utils";
-import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion } from "@supabase/supabase-js";
import { getPurchaseOrderLines } from "~/modules/purchasing";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
diff --git a/apps/erp/app/root.tsx b/apps/erp/app/root.tsx
index 2232c993c9..8999aa6efb 100644
--- a/apps/erp/app/root.tsx
+++ b/apps/erp/app/root.tsx
@@ -15,7 +15,8 @@ import { modeValidator, themes } from "@carbon/utils";
import { I18nProvider } from "@react-aria/i18n";
import { QueryClient } from "@tanstack/react-query";
import { Analytics } from "@vercel/analytics/react";
-import React, { useEffect } from "react";
+import type React from "react";
+import { useEffect } from "react";
import type {
ActionFunctionArgs,
LinksFunction,
diff --git a/apps/erp/app/routes.ts b/apps/erp/app/routes.ts
index 66d6f7384c..1b20b9ace7 100644
--- a/apps/erp/app/routes.ts
+++ b/apps/erp/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { remixRoutesOptionAdapter } from "@react-router/remix-routes-option-adapter";
import { flatRoutes } from "remix-flat-routes";
diff --git a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
index b843a00804..d245252339 100644
--- a/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
+++ b/apps/erp/app/routes/api+/ai+/chat+/agents/shared/agent.ts
@@ -1,5 +1,6 @@
import { openai } from "@ai-sdk/openai";
-import { Agent, type AgentConfig } from "@ai-sdk-tools/agents";
+import type { AgentConfig } from "@ai-sdk-tools/agents";
+import { Agent, } from "@ai-sdk-tools/agents";
import { UpstashProvider } from "@ai-sdk-tools/memory/upstash";
import { UPSTASH_REDIS_REST_TOKEN, UPSTASH_REDIS_REST_URL } from "@carbon/auth";
import { Redis } from "@upstash/redis";
diff --git a/apps/erp/app/routes/api+/assign.ts b/apps/erp/app/routes/api+/assign.ts
index 8eba3d241b..ab98bd46fc 100644
--- a/apps/erp/app/routes/api+/assign.ts
+++ b/apps/erp/app/routes/api+/assign.ts
@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { assign } from "~/modules/shared/shared.server";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.create.ts b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
index f7dc207d46..c378dba3bd 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.create.ts
@@ -5,7 +5,8 @@ import {
getLinearClient,
linkActionToLinearIssue
} from "@carbon/ee/linear";
-import { type ActionFunction, data, type LoaderFunction } from "react-router";
+import type { ActionFunction, LoaderFunction } from "react-router";
+import { data, } from "react-router";
import { getIssueAction } from "~/modules/quality/quality.service";
const linear = getLinearClient();
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.link.ts b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
index eaf06971bb..9de5e19cb1 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.link.ts
@@ -5,7 +5,8 @@ import {
linkActionToLinearIssue,
unlinkActionFromLinearIssue
} from "@carbon/ee/linear";
-import { type ActionFunction, data, type LoaderFunction } from "react-router";
+import type { ActionFunction, LoaderFunction } from "react-router";
+import { data, } from "react-router";
import { getIssueAction } from "~/modules/quality/quality.service";
const linear = getLinearClient();
diff --git a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
index f1047c7c6a..e1f5e66b41 100644
--- a/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
+++ b/apps/erp/app/routes/api+/integrations.linear.issue.sync-notes.ts
@@ -1,11 +1,14 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import type {
+ TiptapDocument,
+} from "@carbon/ee/linear";
import {
getLinearClient,
getLinearIssueFromExternalId,
- type TiptapDocument,
tiptapToMarkdown
} from "@carbon/ee/linear";
-import { type ActionFunction, data } from "react-router";
+import type { ActionFunction, } from "react-router";
+import { data } from "react-router";
const linear = getLinearClient();
diff --git a/apps/erp/app/routes/api+/integrations.onshape.sync.ts b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
index 80d4f75d3d..0939c22b87 100644
--- a/apps/erp/app/routes/api+/integrations.onshape.sync.ts
+++ b/apps/erp/app/routes/api+/integrations.onshape.sync.ts
@@ -2,7 +2,8 @@ import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { onShapeDataValidator } from "@carbon/ee/onshape";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
@@ -41,23 +42,16 @@ export async function action({ request }: ActionFunctionArgs) {
const parsed = onShapeDataValidator.parse(JSON.parse(rows as string));
const serviceRole = await getCarbonServiceRole();
- const [sync, item] = await Promise.all([
- serviceRole.functions.invoke("sync", {
- body: {
- type: "onshape",
- makeMethodId,
- data: parsed,
- companyId,
- userId
- },
- region: FunctionRegion.UsEast1
- }),
- serviceRole
- .from("item")
- .select("externalId")
- .eq("id", record.data?.itemId as string)
- .single()
- ]);
+ const sync = await serviceRole.functions.invoke("sync", {
+ body: {
+ type: "onshape",
+ makeMethodId,
+ data: parsed,
+ companyId,
+ userId
+ },
+ region: FunctionRegion.UsEast1
+ });
if (sync.error) {
return data(
@@ -66,31 +60,28 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- if (item.error) {
- return data(
- { success: false, message: "Failed to get item" },
- { status: 400 }
- );
- }
-
- const currentExternalId =
- (item.data?.externalId as Record<string, any>) ?? {};
-
- // biome-ignore lint/complexity/useLiteralKeys: suppressed due to migration
- currentExternalId["onshape"] = {
- documentId,
- versionId,
- elementId,
- lastSyncedAt: new Date().toISOString()
- };
+ const itemId = record.data?.itemId as string;
+ // Upsert the OnShape mapping in externalIntegrationMapping
await client
- .from("item")
- .update({
- externalId: currentExternalId
- })
- .eq("id", record.data?.itemId as string);
- // biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", "item")
+ .eq("entityId", itemId)
+ .eq("integration", "onshape");
+
+ await client.from("externalIntegrationMapping").insert({
+ entityType: "item",
+ entityId: itemId,
+ integration: "onshape",
+ metadata: {
+ documentId,
+ versionId,
+ elementId
+ },
+ lastSyncedAt: new Date().toISOString(),
+ companyId
+ });
} catch (error) {
console.error("Failed to sync onshape data");
return data(
diff --git a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts b/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts
deleted file mode 100644
index 733df45e9d..0000000000
--- a/apps/erp/app/routes/api+/integrations.quickbooks.oauth.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import {
- QUICKBOOKS_CLIENT_ID,
- QUICKBOOKS_CLIENT_SECRET,
- VERCEL_URL
-} from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { QuickBooks } from "@carbon/ee";
-import { QuickBooksProvider } from "@carbon/ee/quickbooks";
-import { data, type LoaderFunctionArgs, redirect } from "react-router";
-import z from "zod";
-import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
-import { oAuthCallbackSchema } from "~/modules/shared";
-import { path } from "~/utils/path";
-
-export const config = {
- runtime: "nodejs"
-};
-
-export async function loader({ request }: LoaderFunctionArgs) {
- const { client, userId, companyId } = await requirePermissions(request, {
- update: "settings"
- });
-
- const url = new URL(request.url);
- const searchParams = Object.fromEntries(url.searchParams.entries());
-
- const quickbooksAuthResponse = oAuthCallbackSchema
- .extend({
- realmId: z.string()
- })
- .safeParse(searchParams);
-
- if (!quickbooksAuthResponse.success) {
- return data({ error: "Invalid QuickBooks auth response" }, { status: 400 });
- }
-
- const { data: d } = quickbooksAuthResponse;
-
- // TODO: Verify state parameter
- if (!d.state) {
- return data({ error: "Invalid state parameter" }, { status: 400 });
- }
-
- if (!QUICKBOOKS_CLIENT_ID || !QUICKBOOKS_CLIENT_SECRET) {
- return data({ error: "QuickBooks OAuth not configured" }, { status: 500 });
- }
-
- try {
- // Use the QuickBooksProvider to handle the OAuth flow
- const provider = new QuickBooksProvider({
- companyId,
- clientId: QUICKBOOKS_CLIENT_ID,
- clientSecret: QUICKBOOKS_CLIENT_SECRET,
- redirectUri: `${url.origin}/api/integrations/quickbooks/oauth`,
- environment:
- process.env.NODE_ENV === "production" ? "production" : "sandbox"
- });
-
- // Exchange the authorization code for tokens
-
- const auth = await provider.authenticate(
- d.code,
- provider.config.redirectUri!
- );
-
- if (!auth) {
- return data(
- { error: "Failed to exchange code for token" },
- { status: 500 }
- );
- }
-
- const createdQuickBooksIntegration = await upsertCompanyIntegration(
- client,
- {
- id: QuickBooks.id,
- active: true,
- // @ts-ignore
- metadata: {
- ...auth,
- tenantId: d.realmId
- },
- updatedBy: userId,
- companyId: companyId
- }
- );
-
- if (createdQuickBooksIntegration?.data?.metadata) {
- const requestUrl = new URL(request.url);
-
- if (!VERCEL_URL || VERCEL_URL.includes("localhost")) {
- requestUrl.protocol = "http";
- }
-
- const redirectUrl = `${requestUrl.origin}${path.to.integrations}`;
-
- return redirect(redirectUrl);
- } else {
- return data(
- { error: "Failed to save QuickBooks integration" },
- { status: 500 }
- );
- }
- } catch (err) {
- return data(
- { error: "Failed to exchange code for token" },
- { status: 500 }
- );
- }
-}
diff --git a/apps/erp/app/routes/api+/integrations.slack.install.ts b/apps/erp/app/routes/api+/integrations.slack.install.ts
index 98e404f14e..5cdfdb21f6 100644
--- a/apps/erp/app/routes/api+/integrations.slack.install.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.install.ts
@@ -1,6 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getSlackInstallUrl } from "@carbon/ee/slack.server";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
export async function loader({ request }: LoaderFunctionArgs) {
const { userId, companyId } = await requirePermissions(request, {});
diff --git a/apps/erp/app/routes/api+/integrations.slack.interactive.ts b/apps/erp/app/routes/api+/integrations.slack.interactive.ts
index 01fd21ee8d..f59bc1ce25 100644
--- a/apps/erp/app/routes/api+/integrations.slack.interactive.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.interactive.ts
@@ -8,7 +8,8 @@ import {
} from "@carbon/ee/slack.server";
import type { SupabaseClient } from "@supabase/supabase-js";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import {
getIssueTypesList,
diff --git a/apps/erp/app/routes/api+/integrations.slack.oauth.ts b/apps/erp/app/routes/api+/integrations.slack.oauth.ts
index 56850acaa7..2f62489b08 100644
--- a/apps/erp/app/routes/api+/integrations.slack.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.slack.oauth.ts
@@ -11,7 +11,8 @@ import {
getSlackInstaller,
slackOAuthTokenResponseSchema
} from "@carbon/ee/slack.server";
-import { data, type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import { z } from "zod";
import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
import { oAuthCallbackSchema } from "~/modules/shared";
diff --git a/apps/erp/app/routes/api+/integrations.xero.backfill.ts b/apps/erp/app/routes/api+/integrations.xero.backfill.ts
new file mode 100644
index 0000000000..45dd163cdc
--- /dev/null
+++ b/apps/erp/app/routes/api+/integrations.xero.backfill.ts
@@ -0,0 +1,104 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { ProviderID } from "@carbon/ee/accounting";
+import { runs, tasks } from "@trigger.dev/sdk/v3";
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
+import { data } from "react-router";
+import { z } from "zod";
+
+const BackfillSettingsSchema = z.object({
+ backfillCustomers: z.boolean().optional().default(true),
+ backfillVendors: z.boolean().optional().default(true),
+ backfillItems: z.boolean().optional().default(true),
+ conflictResolution: z
+ .enum(["skip", "overwrite", "merge"])
+ .optional()
+ .default("merge")
+});
+
+export const config = {
+ runtime: "nodejs"
+};
+
+// GET: Check backfill status
+export async function loader({ request }: LoaderFunctionArgs) {
+ await requirePermissions(request, {
+ update: "settings"
+ });
+
+ const url = new URL(request.url);
+ const runId = url.searchParams.get("runId");
+
+ if (runId) {
+ try {
+ const run = await runs.retrieve(runId);
+ return data({
+ status: run.status,
+ metadata: run.metadata,
+ output: run.output
+ });
+ } catch {
+ return data({ error: "Failed to retrieve run status" }, { status: 500 });
+ }
+ }
+
+ return data({ status: "idle" });
+}
+
+// POST: Start backfill
+export async function action({ request }: ActionFunctionArgs) {
+ const { client, companyId } = await requirePermissions(request, {
+ update: "settings"
+ });
+
+ // Verify Xero integration exists and is active
+ const integration = await client
+ .from("companyIntegration")
+ .select("*")
+ .eq("companyId", companyId)
+ .eq("id", "xero")
+ .single();
+
+ if (integration.error || !integration.data?.active) {
+ return data(
+ { error: "Xero integration not found or inactive" },
+ { status: 400 }
+ );
+ }
+
+ // Parse settings from integration metadata
+ const settings = BackfillSettingsSchema.parse(
+ integration.data.metadata || {}
+ );
+
+ try {
+ // Trigger the backfill task with settings
+ const handle = await tasks.trigger(
+ "accounting-backfill",
+ {
+ companyId,
+ provider: ProviderID.XERO,
+ batchSize: 50,
+ pageSize: 100,
+ entityTypes: {
+ customers: settings.backfillCustomers,
+ vendors: settings.backfillVendors,
+ items: settings.backfillItems
+ },
+ conflictResolution: settings.conflictResolution
+ },
+ {
+ idempotencyKey: `backfill_${companyId}_${Date.now()}`,
+ tags: [`company_${companyId}`, "backfill", "xero"]
+ }
+ );
+
+ return data({
+ success: true,
+ runId: handle.id,
+ message: "Contact import started"
+ });
+ } catch (error) {
+ console.error("Failed to start backfill:", error);
+ return data({ error: "Failed to start contact import" }, { status: 500 });
+ }
+}
diff --git a/apps/erp/app/routes/api+/integrations.xero.oauth.ts b/apps/erp/app/routes/api+/integrations.xero.oauth.ts
index b05ccdb3de..90c903196a 100644
--- a/apps/erp/app/routes/api+/integrations.xero.oauth.ts
+++ b/apps/erp/app/routes/api+/integrations.xero.oauth.ts
@@ -1,9 +1,13 @@
import { VERCEL_URL, XERO_CLIENT_ID, XERO_CLIENT_SECRET } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { Xero } from "@carbon/ee";
-import { getProviderIntegration, ProviderID } from "@carbon/ee/accounting";
-import { XeroProvider } from "@carbon/ee/xero";
-import { data, type LoaderFunctionArgs, redirect } from "react-router";
+import { getIntegrationConfigById, Xero } from "@carbon/ee";
+import {
+ DEFAULT_SYNC_CONFIG,
+ getProviderIntegration,
+ ProviderID
+} from "@carbon/ee/accounting";
+import type { LoaderFunctionArgs } from "react-router";
+import { data, redirect } from "react-router";
import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
import { oAuthCallbackSchema } from "~/modules/shared";
import { path } from "~/utils/path";
@@ -78,8 +82,9 @@ export async function loader({ request }: LoaderFunctionArgs) {
return data({ error: "No Xero connections found" }, { status: 500 });
}
- // Get the first connection's tenant ID
+ // Get the first connection's tenant ID and name
const tenantId = connections[0].tenantId;
+ const tenantName = connections[0].tenantName;
if (!tenantId) {
return data(
@@ -93,13 +98,22 @@ export async function loader({ request }: LoaderFunctionArgs) {
active: true,
// @ts-ignore
metadata: {
- ...auth,
- tenantId
+ syncConfig: DEFAULT_SYNC_CONFIG,
+ credentials: {
+ ...auth,
+ tenantId,
+ tenantName: tenantName ?? undefined
+ }
},
updatedBy: userId,
companyId: companyId
});
+ const config = getIntegrationConfigById(Xero.id);
+
+ typeof config?.onInstall === "function" &&
+ (await config.onInstall(companyId));
+
if (createdXeroIntegration?.data?.metadata) {
const requestUrl = new URL(request.url);
@@ -117,6 +131,7 @@ export async function loader({ request }: LoaderFunctionArgs) {
);
}
} catch (err) {
+ console.error("Xero OAuth Error:", err);
return data(
{ error: "Failed to exchange code for token" },
{ status: 500 }
diff --git a/apps/erp/app/routes/api+/item.$type.ts b/apps/erp/app/routes/api+/item.$type.ts
index 96216a2b32..29a1f71887 100644
--- a/apps/erp/app/routes/api+/item.$type.ts
+++ b/apps/erp/app/routes/api+/item.$type.ts
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { itemValidator, updateItem } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
index 5f01b4a14b..9d65a5bb40 100644
--- a/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
+++ b/apps/erp/app/routes/api+/items.$id.$locationId.forecast.ts
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { getLocalTimeZone, startOfWeek, today } from "@internationalized/date";
-import { data, type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { data, } from "react-router";
import {
getItemDemand,
getItemQuantities,
diff --git a/apps/erp/app/routes/api+/kanban.$id.tsx b/apps/erp/app/routes/api+/kanban.$id.tsx
index 7b7de329cc..3966d5cb83 100644
--- a/apps/erp/app/routes/api+/kanban.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.$id.tsx
@@ -3,10 +3,12 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import type { Database } from "@carbon/database";
import { Loading } from "@carbon/react";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import { FunctionRegion, } from "@supabase/supabase-js";
import { tasks } from "@trigger.dev/sdk";
import { Suspense } from "react";
-import { Await, type LoaderFunctionArgs, useLoaderData } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { Await, useLoaderData } from "react-router";
import { Redirect } from "~/components/Redirect";
import { getDefaultShelfForJob, getKanban } from "~/modules/inventory";
diff --git a/apps/erp/app/routes/api+/kanban.complete.$id.tsx b/apps/erp/app/routes/api+/kanban.complete.$id.tsx
index f8c0a96d2c..42aae794ee 100644
--- a/apps/erp/app/routes/api+/kanban.complete.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.complete.$id.tsx
@@ -2,7 +2,8 @@ import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { data, type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import { getKanban } from "~/modules/inventory";
import { getActiveJobOperationByJobId } from "~/modules/production";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/api+/kanban.link.$id.tsx b/apps/erp/app/routes/api+/kanban.link.$id.tsx
index f4dbb881d8..6e2fd260e5 100644
--- a/apps/erp/app/routes/api+/kanban.link.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.link.$id.tsx
@@ -1,6 +1,7 @@
import { notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getKanban } from "~/modules/inventory";
import { getActiveJobOperationByJobId } from "~/modules/production";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/api+/kanban.start.$id.tsx b/apps/erp/app/routes/api+/kanban.start.$id.tsx
index 657e9e9078..413871aafa 100644
--- a/apps/erp/app/routes/api+/kanban.start.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.start.$id.tsx
@@ -4,7 +4,8 @@ import type { Database } from "@carbon/database";
import { Loading } from "@carbon/react";
import type { SupabaseClient } from "@supabase/supabase-js";
import { Suspense } from "react";
-import { Await, type LoaderFunctionArgs, useLoaderData } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { Await, useLoaderData } from "react-router";
import { Redirect } from "~/components/Redirect";
import { getKanban } from "~/modules/inventory";
import { getActiveJobOperationByJobId } from "~/modules/production";
diff --git a/apps/erp/app/routes/api+/messaging.notify.ts b/apps/erp/app/routes/api+/messaging.notify.ts
index 49a60f40fd..714deae498 100644
--- a/apps/erp/app/routes/api+/messaging.notify.ts
+++ b/apps/erp/app/routes/api+/messaging.notify.ts
@@ -4,7 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import type { notifyTask } from "@carbon/jobs/trigger/notify";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
export const messagingNotifySchema = z.discriminatedUnion("type", [
diff --git a/apps/erp/app/routes/api+/model.upload.ts b/apps/erp/app/routes/api+/model.upload.ts
index f5664c5aab..8c397874f9 100644
--- a/apps/erp/app/routes/api+/model.upload.ts
+++ b/apps/erp/app/routes/api+/model.upload.ts
@@ -2,7 +2,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { modelThumbnailTask } from "@carbon/jobs/trigger/model-thumbnail";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/api+/production.kpi.$key.ts b/apps/erp/app/routes/api+/production.kpi.$key.ts
index 0450b9e33e..3fbd28e342 100644
--- a/apps/erp/app/routes/api+/production.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/production.kpi.$key.ts
@@ -4,7 +4,7 @@ import {
parseDateTime,
toCalendarDateTime
} from "@internationalized/date";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { KPIs } from "~/modules/production/production.models";
import { makeDurations } from "~/utils/duration";
diff --git a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
index 923c6f5c75..b3de5ce455 100644
--- a/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
+++ b/apps/erp/app/routes/api+/purchasing.digital-quote.$id.tsx
@@ -9,7 +9,7 @@ import {
externalSupplierQuoteValidator,
selectedLineSchema
} from "~/modules/purchasing/purchasing.models";
-import { getSupplierQuoteByExternalId } from "~/modules/purchasing/purchasing.service";
+import { getSupplierQuoteByExternalLinkId } from "~/modules/purchasing/purchasing.service";
import { getCompanySettings } from "~/modules/settings";
export async function action({ request, params }: ActionFunctionArgs) {
@@ -22,7 +22,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
const intent = String(formData.get("intent"));
const serviceRole = getCarbonServiceRole();
- const quote = await getSupplierQuoteByExternalId(serviceRole, id);
+ const quote = await getSupplierQuoteByExternalLinkId(serviceRole, id);
if (quote.error || !quote.data) {
console.error("Quote not found", quote.error);
diff --git a/apps/erp/app/routes/api+/purchasing.kpi.$key.ts b/apps/erp/app/routes/api+/purchasing.kpi.$key.ts
index c37b78167d..59f0bcbcd8 100644
--- a/apps/erp/app/routes/api+/purchasing.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/purchasing.kpi.$key.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { parseDateTime, toCalendarDateTime } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { KPIs } from "~/modules/purchasing/purchasing.models";
import { months } from "~/modules/shared/shared.models";
import { groupDataByDay, groupDataByMonth } from "~/utils/chart";
diff --git a/apps/erp/app/routes/api+/quality.documents.seed.ts b/apps/erp/app/routes/api+/quality.documents.seed.ts
index c6317f1553..9ed6565d45 100644
--- a/apps/erp/app/routes/api+/quality.documents.seed.ts
+++ b/apps/erp/app/routes/api+/quality.documents.seed.ts
@@ -1,7 +1,8 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import template from "lodash.template";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { documents } from "./data/quality";
function interpolateContent(
diff --git a/apps/erp/app/routes/api+/resources.kpi.$key.ts b/apps/erp/app/routes/api+/resources.kpi.$key.ts
index 00a69c982c..32ad7992a4 100644
--- a/apps/erp/app/routes/api+/resources.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/resources.kpi.$key.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { parseDateTime, toCalendarDateTime } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { MaintenanceKPIs } from "~/modules/resources/resources.models";
import { months } from "~/modules/shared/shared.models";
import { groupDataByDay, groupDataByMonth } from "~/utils/chart";
diff --git a/apps/erp/app/routes/api+/sales.kpi.$key.ts b/apps/erp/app/routes/api+/sales.kpi.$key.ts
index 9f59233ee3..28b9df7acc 100644
--- a/apps/erp/app/routes/api+/sales.kpi.$key.ts
+++ b/apps/erp/app/routes/api+/sales.kpi.$key.ts
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { parseDateTime, toCalendarDateTime } from "@internationalized/date";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { KPIs } from "~/modules/sales/sales.models";
import { months } from "~/modules/shared/shared.models";
import { groupDataByDay, groupDataByMonth } from "~/utils/chart";
diff --git a/apps/erp/app/routes/api+/webhook.quickbooks.ts b/apps/erp/app/routes/api+/webhook.quickbooks.ts
deleted file mode 100644
index 386efd9f54..0000000000
--- a/apps/erp/app/routes/api+/webhook.quickbooks.ts
+++ /dev/null
@@ -1,265 +0,0 @@
-/**
- * QuickBooks Webhook Handler
- *
- * This endpoint receives webhook notifications from QuickBooks when entities
- * (customers, vendors, etc.) are created, updated, or deleted in QuickBooks.
- *
- * The webhook handler:
- * 1. Validates the webhook payload structure
- * 2. Verifies the webhook signature for security
- * 3. Looks up the company integration by QuickBooks realm ID
- * 4. Triggers background sync jobs to process the entity changes
- *
- * Supported entity types:
- * - Customer: Synced to Carbon's customer table
- * - Vendor: Synced to Carbon's supplier table
- *
- * The actual sync logic is handled asynchronously by the accounting-sync
- * background job to prevent webhook timeouts and ensure reliability.
- */
-
-import { getCarbonServiceRole, QUICKBOOKS_WEBHOOK_SECRET } from "@carbon/auth";
-import { tasks } from "@trigger.dev/sdk/v3";
-import crypto from "crypto";
-import { type ActionFunctionArgs, data } from "react-router";
-import { z } from "zod";
-
-export const config = {
- runtime: "nodejs"
-};
-
-const quickbooksEventValidator = z.object({
- eventNotifications: z.array(
- z.object({
- realmId: z.string(),
- dataChangeEvent: z.object({
- entities: z.array(
- z.object({
- id: z.string(),
- name: z.string(),
- operation: z.enum(["Create", "Update", "Delete"])
- })
- )
- })
- })
- )
-});
-
-function verifyQuickBooksSignature(
- payload: string,
- signature: string
-): boolean {
- if (!QUICKBOOKS_WEBHOOK_SECRET) {
- console.warn("QUICKBOOKS_WEBHOOK_SECRET is not set");
- return true;
- }
-
- const expectedSignature = crypto
- .createHmac("sha256", QUICKBOOKS_WEBHOOK_SECRET)
- .update(payload)
- .digest("base64");
-
- return crypto.timingSafeEqual(
- Buffer.from(signature),
- Buffer.from(expectedSignature)
- );
-}
-
-async function triggerAccountingSync(
- companyId: string,
- realmId: string,
- entities: Array<{
- entityType: "customer" | "vendor";
- entityId: string;
- operation: "Create" | "Update" | "Delete";
- }>
-) {
- // Prepare the payload for the accounting sync job
- const payload = {
- companyId,
- provider: "quickbooks" as const,
- syncType: "webhook" as const,
- syncDirection: "fromAccounting" as const,
- entities: entities.map((entity) => ({
- entityType: entity.entityType,
- entityId: entity.entityId,
- operation: entity.operation.toLowerCase() as
- | "create"
- | "update"
- | "delete",
- externalId: entity.entityId // In QuickBooks, the entity ID is the external ID
- })),
- metadata: {
- tenantId: realmId,
- webhookId: crypto.randomUUID(),
- timestamp: new Date().toISOString()
- }
- };
-
- // Trigger the background job using Trigger.dev
- const handle = await tasks.trigger("accounting-sync", payload);
-
- console.log(
- `Triggered accounting sync job ${handle.id} for ${entities.length} entities`
- );
-
- return handle;
-}
-
-export async function action({ request, params }: ActionFunctionArgs) {
- const serviceRole = await getCarbonServiceRole();
-
- // Parse and validate the webhook payload
- const payload = await request.clone().json();
- const parsedPayload = quickbooksEventValidator.safeParse(payload);
-
- if (!parsedPayload.success) {
- console.error("Invalid QuickBooks webhook payload:", parsedPayload.error);
- return data(
- {
- success: false,
- error: "Invalid payload format"
- },
- { status: 400 }
- );
- }
-
- // Verify webhook signature for security
- const payloadText = await request.text();
- const signatureHeader = request.headers.get("intuit-signature");
-
- if (!signatureHeader) {
- console.warn("QuickBooks webhook received without signature");
- return data(
- {
- success: false,
- error: "Missing signature"
- },
- { status: 401 }
- );
- }
-
- const requestIsValid = verifyQuickBooksSignature(
- payloadText,
- signatureHeader
- );
-
- if (!requestIsValid) {
- console.error("QuickBooks webhook signature verification failed");
- return data(
- {
- success: false,
- error: "Invalid signature"
- },
- { status: 401 }
- );
- }
-
- console.log(
- "Processing QuickBooks webhook with",
- parsedPayload.data.eventNotifications.length,
- "events"
- );
-
- const events = parsedPayload.data.eventNotifications;
- const syncJobs = [];
- const errors = [];
-
- // Process each event notification
- for (const event of events) {
- try {
- const { realmId, dataChangeEvent } = event;
-
- // Find the company integration for this QuickBooks realm
- const companyIntegration = await serviceRole
- .from("companyIntegration")
- .select("*")
- .eq("metadata->>tenantId", realmId)
- .eq("id", "quickbooks")
- .single();
-
- if (companyIntegration.error || !companyIntegration.data.companyId) {
- console.error(`No QuickBooks integration found for realm ${realmId}`);
- errors.push({
- realmId,
- error: "Integration not found"
- });
- continue;
- }
-
- const companyId = companyIntegration.data.companyId;
- const { entities } = dataChangeEvent;
-
- // Group entities by type for efficient batch processing
- const entitiesToSync: Array<{
- entityType: "customer" | "vendor";
- entityId: string;
- operation: "Create" | "Update" | "Delete";
- }> = [];
-
- for (const entity of entities) {
- const { id, name, operation } = entity;
-
- // Log each entity change for debugging
- console.log(
- `QuickBooks ${operation}: ${name} ${id} (realm: ${realmId})`
- );
-
- // Map QuickBooks entity types to our internal types
- if (name === "Customer") {
- entitiesToSync.push({
- entityType: "customer",
- entityId: id,
- operation
- });
- } else if (name === "Vendor") {
- entitiesToSync.push({
- entityType: "vendor",
- entityId: id,
- operation
- });
- } else {
- console.log(`Skipping unsupported entity type: ${name}`);
- }
- }
-
- // Trigger background sync job if there are entities to process
- if (entitiesToSync.length > 0) {
- try {
- const jobHandle = await triggerAccountingSync(
- companyId,
- realmId,
- entitiesToSync
- );
- syncJobs.push({
- id: jobHandle.id,
- companyId,
- realmId,
- entityCount: entitiesToSync.length
- });
- } catch (error) {
- console.error("Failed to trigger sync job:", error);
- errors.push({
- realmId,
- error:
- error instanceof Error ? error.message : "Failed to trigger job"
- });
- }
- }
- } catch (error) {
- console.error("Error processing event:", error);
- errors.push({
- error: error instanceof Error ? error.message : "Unknown error"
- });
- }
- }
-
- // Return detailed response
- return {
- success: errors.length === 0,
- jobsTriggered: syncJobs.length,
- jobs: syncJobs,
- errors: errors.length > 0 ? errors : undefined,
- timestamp: new Date().toISOString()
- };
-}
diff --git a/apps/erp/app/routes/api+/webhook.xero.ts b/apps/erp/app/routes/api+/webhook.xero.ts
index bf3e034b53..e20506f63a 100644
--- a/apps/erp/app/routes/api+/webhook.xero.ts
+++ b/apps/erp/app/routes/api+/webhook.xero.ts
@@ -19,23 +19,21 @@
* background job to prevent webhook timeouts and ensure reliability.
*/
-import {
- getCarbonServiceRole,
- XERO_CLIENT_ID,
- XERO_CLIENT_SECRET,
- XERO_WEBHOOK_SECRET
-} from "@carbon/auth";
-import {
+import { getCarbonServiceRole, XERO_WEBHOOK_SECRET } from "@carbon/auth";
+import type {
AccountingEntity,
- AccountingSyncPayload,
+ AccountingProvider,
+ AccountingSyncPayload
+} from "@carbon/ee/accounting";
+import {
+ getAccountingIntegration,
getProviderIntegration,
- ProviderCredentials,
ProviderID
} from "@carbon/ee/accounting";
-import { XeroProvider } from "@carbon/ee/xero";
import { tasks } from "@trigger.dev/sdk/v3";
import crypto from "crypto";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
export const config = {
@@ -47,7 +45,7 @@ const WebhookSchema = z.object({
events: z.array(
z.object({
tenantId: z.string(),
- eventCategory: z.enum(["INVOICE", "CONTACT"]),
+ eventCategory: z.enum(["CONTACT", "INVOICE"]),
eventType: z.enum(["CREATE", "UPDATE", "DELETE"]),
resourceId: z.string(),
eventDateUtc: z.string()
@@ -57,7 +55,7 @@ const WebhookSchema = z.object({
lastEventSequence: z.number()
});
-async function verifySignature(payload: string, header: string) {
+function verifySignature(payload: string, header: string) {
if (!XERO_WEBHOOK_SECRET) {
console.warn("XERO_WEBHOOK_SECRET is not configured");
return payload;
@@ -71,165 +69,6 @@ async function verifySignature(payload: string, header: string) {
return crypto.timingSafeEqual(Buffer.from(hmac), Buffer.from(header));
}
-async function fetchInvoiceAndDetermineContactType(
- companyId: string,
- tenantId: string,
- invoiceId: string,
- serviceRole: any
-): Promise<{
- contactId: string;
- entityType: "customer" | "vendor" | "both";
- isCustomer: boolean;
- isSupplier: boolean;
- invoiceType: "ACCREC" | "ACCPAY";
-}> {
- try {
- // Get the Xero integration credentials
- const integration = await serviceRole
- .from("companyIntegration")
- .select("*")
- .eq("companyId", companyId)
- .eq("id", "xero")
- .single();
-
- if (integration.error || !integration.data) {
- throw new Error("Xero integration not found");
- }
-
- const { accessToken, tenantId } = integration.data.metadata || {};
-
- if (!accessToken) {
- throw new Error("No access token available for Xero integration");
- }
-
- const provider = new XeroProvider({
- clientId: XERO_CLIENT_ID!,
- clientSecret: XERO_CLIENT_SECRET!,
- tenantId,
- companyId
- });
-
- // Fetch the invoice to get the contact ID and type
- const invoiceData = await provider.invoices.get(invoiceId);
- const xeroInvoice = invoiceData.Invoices?.[0];
-
- if (!xeroInvoice) {
- throw new Error(`Invoice ${invoiceId} not found`);
- }
-
- const contactId = xeroInvoice.Contact?.ContactID;
- const invoiceType = xeroInvoice.Type; // ACCREC (receivable/customer) or ACCPAY (payable/supplier)
-
- if (!contactId) {
- throw new Error(`No contact found for invoice ${invoiceId}`);
- }
-
- // Now fetch the contact details
- const xeroContact = await provider.contacts.get(contactId);
-
- if (!xeroContact) {
- throw new Error(`Contact ${contactId} not found`);
- }
-
- // Check IsCustomer and IsSupplier fields from Xero
- const isCustomer = xeroContact.IsCustomer === true;
- const isSupplier = xeroContact.IsSupplier === true;
-
- console.log(
- `Invoice ${invoiceId} (${invoiceType}) - Contact ${contactId} (${xeroContact.Name}) - IsCustomer: ${isCustomer}, IsSupplier: ${isSupplier}`
- );
-
- // Determine entity type based on flags and invoice type
- let entityType: "customer" | "vendor" | "both";
-
- if (isCustomer && isSupplier) {
- entityType = "both";
- } else if (invoiceType === "ACCPAY" || isSupplier) {
- // Accounts payable (bills) or supplier flag = vendor
- entityType = "vendor";
- } else {
- // Accounts receivable (invoices) or customer flag = customer (default)
- entityType = "customer";
- }
-
- return { contactId, entityType, isCustomer, isSupplier, invoiceType };
- } catch (error) {
- console.error(`Error fetching invoice ${invoiceId}:`, error);
- // Default based on typical patterns
- throw error;
- }
-}
-
-async function fetchContactAndDetermineType(
- companyId: string,
- tenantId: string,
- contactId: string,
- serviceRole: any
-): Promise<{
- entityType: "customer" | "vendor" | "both";
- isCustomer: boolean;
- isSupplier: boolean;
-}> {
- try {
- // Get the Xero integration credentials
- const integration = await serviceRole
- .from("companyIntegration")
- .select("*")
- .eq("companyId", companyId)
- .eq("id", XeroProvider.id)
- .single();
-
- if (integration.error || !integration.data) {
- throw new Error("Xero integration not found");
- }
-
- const metadata = integration.data.metadata || {};
-
- const { accessToken, refreshToken } = metadata;
-
- if (!accessToken) {
- throw new Error("No access token available for Xero integration");
- }
-
- const creds: ProviderCredentials = {
- type: "oauth2",
- accessToken,
- refreshToken,
- tenantId
- };
-
- const provider = getProviderIntegration(
- serviceRole,
- companyId,
- XeroProvider.id,
- creds
- );
-
- const contact = await provider.contacts.get(contactId);
-
- const isCustomer = contact.isCustomer;
- const isSupplier = contact.isVendor;
-
- // Determine entity type based on flags
- let entityType: "customer" | "vendor" | "both";
-
- if (isCustomer && isSupplier) {
- entityType = "both";
- } else if (isSupplier) {
- entityType = "vendor";
- } else {
- // Default to customer if only customer or neither flag is set
- entityType = "customer";
- }
-
- return { entityType, isCustomer, isSupplier };
- } catch (error) {
- console.error(`Error fetching contact ${contactId}:`, error);
- // Default to customer if we can't fetch the contact
- return { entityType: "customer", isCustomer: true, isSupplier: false };
- }
-}
-
export async function action({ request }: ActionFunctionArgs) {
// Get the raw payload for signature verification
const payloadText = await request.text();
@@ -274,7 +113,7 @@ export async function action({ request }: ActionFunctionArgs) {
success: false,
error: "Invalid JSON payload"
},
- { status: 400 }
+ { status: 401 }
);
}
@@ -287,7 +126,7 @@ export async function action({ request }: ActionFunctionArgs) {
success: false,
error: "Invalid payload format"
},
- { status: 400 }
+ { status: 401 }
);
}
@@ -297,7 +136,7 @@ export async function action({ request }: ActionFunctionArgs) {
"events"
);
- const serviceRole = await getCarbonServiceRole();
+ const serviceRole = getCarbonServiceRole();
const events = parsed.data.events;
const syncJobs = [];
const errors = [];
@@ -317,27 +156,13 @@ export async function action({ request }: ActionFunctionArgs) {
// Process events for each tenant
for (const [tenantId, tenantEvents] of Object.entries(eventsByTenant)) {
try {
- // Find the company integration for this Xero tenant by checking metadata
- const { data: integrations } = await serviceRole
- .from("companyIntegration")
- .select("*")
- .eq("id", "xero" as any);
-
- if (!integrations || integrations.length === 0) {
- console.error(`No Xero integration found for tenant ${tenantId}`);
- errors.push({
- tenantId,
- error: "Integration not found"
- });
- continue;
- }
-
- // Find the integration that matches this tenant ID
- const found = integrations.find(
- (integration: any) => integration.metadata?.tenantId === tenantId
+ const integration = await getAccountingIntegration(
+ serviceRole,
+ tenantId,
+ ProviderID.XERO
);
- if (!found) {
+ if (!integration) {
console.error(`No Xero integration found for tenant ${tenantId}`);
errors.push({
tenantId,
@@ -346,7 +171,14 @@ export async function action({ request }: ActionFunctionArgs) {
continue;
}
- const companyId = found.companyId;
+ const companyId = integration.companyId;
+
+ const provider = getProviderIntegration(
+ serviceRole,
+ companyId,
+ ProviderID.XERO,
+ integration.metadata
+ );
// Group entities by type for efficient batch processing
const entities: Array<AccountingEntity> = [];
@@ -364,43 +196,51 @@ export async function action({ request }: ActionFunctionArgs) {
);
switch (eventCategory) {
- case "CONTACT": {
- // Fetch the contact from Xero to determine if it's a customer or vendor
- const contactInfo = await fetchContactAndDetermineType(
- companyId,
- tenantId,
- resourceId,
- serviceRole
- );
-
- // If the contact is both customer and supplier, sync to both tables
- if (contactInfo.entityType === "both") {
+ case "CONTACT":
+ const contactType = await fetchContactType(provider, resourceId);
+
+ if (!contactType) {
console.log(
- `Contact ${resourceId} is both customer and supplier, syncing to both`
+ `Skipping contact ${resourceId} with no customer/supplier role`
);
+ continue;
+ }
- // Add as customer
+ if (contactType === "customer" || contactType === "both") {
entities.push({
- operation,
entityType: "customer",
- entityId: resourceId
+ entityId: resourceId,
+ operation: operation
});
+ }
- // Add as vendor
+ if (contactType === "supplier" || contactType === "both") {
entities.push({
- operation,
entityType: "vendor",
- entityId: resourceId
- });
- } else {
- // Add as either customer or vendor based on the determination
- entities.push({
- operation,
- entityType: contactInfo.entityType,
- entityId: resourceId
+ entityId: resourceId,
+ operation: operation
});
}
- }
+
+ break;
+
+ case "INVOICE":
+ const invoiceType = await fetchInvoiceType(provider, resourceId);
+
+ if (!invoiceType) {
+ console.log(
+ `Skipping invoice ${resourceId} - could not determine type`
+ );
+ continue;
+ }
+
+ entities.push({
+ entityType: invoiceType,
+ entityId: resourceId,
+ operation: operation
+ });
+
+ break;
}
}
@@ -412,7 +252,7 @@ export async function action({ request }: ActionFunctionArgs) {
companyId,
provider: ProviderID.XERO,
syncType: "webhook",
- syncDirection: "from-accounting",
+ syncDirection: "pull-from-accounting",
entities,
metadata: {
tenantId: tenantId,
@@ -423,9 +263,14 @@ export async function action({ request }: ActionFunctionArgs) {
console.dir(payload, { depth: null });
// Trigger the background job using Trigger.dev
- const handle = await tasks.trigger("from-accounting-sync", payload, {
- tags: [ProviderID.XERO, payload.syncType]
- });
+ const handle = await tasks.trigger(
+ "sync-external-accounting",
+ payload,
+ {
+ tags: [ProviderID.XERO, payload.syncType],
+ concurrencyKey: `sync-external-accounting:${companyId}`
+ }
+ );
console.log(
`Triggered accounting sync job ${handle.id} for ${entities.length} entities`
@@ -455,6 +300,8 @@ export async function action({ request }: ActionFunctionArgs) {
}
}
+ console.log(`Processed Xero webhook: ${syncJobs.length} sync jobs triggered`);
+
// Return detailed response
return {
success: errors.length === 0,
@@ -464,3 +311,52 @@ export async function action({ request }: ActionFunctionArgs) {
timestamp: new Date().toISOString()
};
}
+
+const fetchContactType = async (
+ provider: AccountingProvider,
+ resourceId: string
+) => {
+ const res = await provider.request<{
+ Contacts: { IsSupplier: boolean; IsCustomer: boolean }[];
+ }>("GET", `/Contacts/${resourceId}`);
+
+ if (res.error || !res.data || res.data.Contacts.length === 0) {
+ throw new Error(`Failed to fetch contact ${resourceId}: ${res.message}`);
+ }
+
+ const contact = res.data.Contacts[0];
+
+ if (contact.IsSupplier && contact.IsCustomer) {
+ return "both";
+ } else if (contact.IsSupplier) {
+ return "supplier";
+ } else if (contact.IsCustomer) {
+ return "customer";
+ }
+
+ return null;
+};
+
+/**
+ * Fetches invoice from Xero to determine if it's a sales invoice or bill.
+ * - ACCREC (Accounts Receivable) = Sales Invoice -> maps to "invoice"
+ * - ACCPAY (Accounts Payable) = Purchase Invoice/Bill -> maps to "bill"
+ */
+const fetchInvoiceType = async (
+ provider: AccountingProvider,
+ resourceId: string
+): Promise<"invoice" | "bill" | null> => {
+ const res = await provider.request<{
+ Invoices: { Type: "ACCREC" | "ACCPAY" }[];
+ }>("GET", `/Invoices/${resourceId}`);
+
+ if (res.error || !res.data || res.data.Invoices.length === 0) {
+ throw new Error(`Failed to fetch invoice ${resourceId}: ${res.message}`);
+ }
+
+ const invoice = res.data.Invoices[0];
+
+ // ACCREC = Accounts Receivable = Sales Invoice
+ // ACCPAY = Accounts Payable = Bill/Purchase Invoice
+ return invoice.Type === "ACCREC" ? "invoice" : "bill";
+};
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
index f3baae0b42..aabb44521d 100644
--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]pdf.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
import { getEntityLabelData } from "./labels.server";
diff --git a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
index cfb0590e56..051a6072d2 100644
--- a/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/entity+/$id.labels[.]zpl.tsx
@@ -1,7 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
import { getEntityLabelData } from "./labels.server";
diff --git a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx
index 4d87241a0d..f30125e19c 100644
--- a/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/issue+/$id[.]pdf.tsx
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { IssuePDF } from "@carbon/documents/pdf";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import {
getIssue,
getIssueActionTasks,
diff --git a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
index b1ff68dbab..a593742183 100644
--- a/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/job+/$jobId.traveler[.]pdf.tsx
@@ -10,7 +10,7 @@ import {
renderToStream,
StyleSheet
} from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import {
getJob,
getJobMethodTree,
diff --git a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
index f647b405be..8516eabb73 100644
--- a/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
+++ b/apps/erp/app/routes/file+/kanban+/$id.$action[.]png.tsx
@@ -1,6 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateQRCodeBuffer } from "@carbon/documents/qr";
-import { data, type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { data, } from "react-router";
import { getKanban } from "~/modules/inventory/inventory.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
index 5ef20e854f..7f4bd07a49 100644
--- a/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/kanban+/labels.$action[.]pdf.tsx
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { KanbanLabelPDF } from "@carbon/documents/pdf";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getBase64ImageFromSupabase } from "~/modules/shared";
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index 7b7b9fb000..ecea4640b9 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole, notFound } from "@carbon/auth";
import { supportedModelTypes } from "@carbon/utils";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
const supportedFileTypes: Record<string, string> = {
pdf: "application/pdf",
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
index 18e4807791..83c31938aa 100644
--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
index 228b74e594..8e9d63f581 100644
--- a/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -1,7 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getTrackedEntitiesByMakeMethodId } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings";
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 8e7e9b8ec8..fc0bf4071e 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
const supportedFileTypes: Record<string, string> = {
pdf: "application/pdf",
diff --git a/apps/erp/app/routes/file+/preview+/image.tsx b/apps/erp/app/routes/file+/preview+/image.tsx
index 129f91f905..57cfb57913 100644
--- a/apps/erp/app/routes/file+/preview+/image.tsx
+++ b/apps/erp/app/routes/file+/preview+/image.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { path } from "~/utils/path";
// this route exists so we can apply some styles to the preview iframe
diff --git a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
index 9275b986d5..b2597056ae 100644
--- a/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/purchase-order+/$orderId[.]pdf.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { PurchaseOrderPDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import {
getPurchaseOrder,
getPurchaseOrderLines,
diff --git a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
index 2caa040331..9f8e26d8fd 100644
--- a/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/quote+/$id[.]pdf.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { QuotePDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getCurrencyByCode, getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import {
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
index 03abf22da9..9d33d02182 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]pdf.tsx
@@ -3,7 +3,8 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getReceiptTracking } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
index 362a6214da..3329c9fee1 100644
--- a/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/receipt+/$id.labels[.]zpl.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getReceiptTracking } from "~/modules/inventory/inventory.service";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
index ccbed3fc78..26364085f2 100644
--- a/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/sales-invoice+/$id[.]pdf.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { SalesInvoicePDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import {
diff --git a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
index 9914ec5bba..be722057a6 100644
--- a/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/sales-order+/$id[.]pdf.tsx
@@ -2,7 +2,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { SalesOrderPDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import { getShippingMethodsList } from "~/modules/inventory";
import {
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
index 7e3f4ddce1..90ea4f3ced 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]pdf.tsx
@@ -3,7 +3,8 @@ import { ProductLabelPDF } from "@carbon/documents/pdf";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getShipmentTracking } from "~/modules/inventory";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
index bab5a3f7a4..50ddac557c 100644
--- a/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id.labels[.]zpl.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import type { TrackedEntityAttributes } from "@carbon/utils";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getShipmentTracking } from "~/modules/inventory/inventory.service";
import { getCompanySettings } from "~/modules/settings/settings.service";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
index 206f8e201c..f37508e7d3 100644
--- a/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/shipment+/$id[.]pdf.tsx
@@ -3,7 +3,7 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { PackingSlipPDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getPaymentTerm } from "~/modules/accounting";
import {
getShipment,
diff --git a/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx
index 34bb62e19f..ff29051000 100644
--- a/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/stock-transfer+/$id[.]pdf.tsx
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { StockTransferPDF } from "@carbon/documents/pdf";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getStockTransfer, getStockTransferLines } from "~/modules/inventory";
import { getCompany } from "~/modules/settings";
import { getBase64ImageFromSupabase } from "~/modules/shared";
diff --git a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx
index dde2065c17..774ef3f86e 100644
--- a/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx
+++ b/apps/erp/app/routes/file+/traveler+/$id[.]pdf.tsx
@@ -4,7 +4,7 @@ import { JobTravelerPDF } from "@carbon/documents/pdf";
import type { JSONContent } from "@carbon/react";
import { flattenTree, generateBomIds } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import {
getJob,
getJobMakeMethodById,
diff --git a/apps/erp/app/routes/oauth+/token.tsx b/apps/erp/app/routes/oauth+/token.tsx
index 4dc3add653..73eb6c7924 100644
--- a/apps/erp/app/routes/oauth+/token.tsx
+++ b/apps/erp/app/routes/oauth+/token.tsx
@@ -1,6 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
const oauthTokenValidator = z.object({
diff --git a/apps/erp/app/routes/onboarding+/_layout.tsx b/apps/erp/app/routes/onboarding+/_layout.tsx
index f6efb1c83e..9121245a68 100644
--- a/apps/erp/app/routes/onboarding+/_layout.tsx
+++ b/apps/erp/app/routes/onboarding+/_layout.tsx
@@ -4,7 +4,8 @@ import { VStack } from "@carbon/react";
import { getStripeCustomerByCompanyId } from "@carbon/stripe/stripe.server";
import { Edition } from "@carbon/utils";
import type { ShouldRevalidateFunction } from "react-router";
-import { type LoaderFunctionArgs, Outlet, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { Outlet, redirect } from "react-router";
import { getLocationsList } from "~/modules/resources";
import { getCompany } from "~/modules/settings";
import { onboardingSequence, path } from "~/utils/path";
diff --git a/apps/erp/app/routes/onboarding+/company.tsx b/apps/erp/app/routes/onboarding+/company.tsx
index c223c100ff..7280b5f023 100644
--- a/apps/erp/app/routes/onboarding+/company.tsx
+++ b/apps/erp/app/routes/onboarding+/company.tsx
@@ -20,8 +20,10 @@ import {
import { Edition } from "@carbon/utils";
import { getLocalTimeZone } from "@internationalized/date";
import { tasks } from "@trigger.dev/sdk";
+import type {
+ ActionFunctionArgs,
+} from "react-router";
import {
- type ActionFunctionArgs,
Link,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/onboarding+/plan.tsx b/apps/erp/app/routes/onboarding+/plan.tsx
index c8266541db..693b108367 100644
--- a/apps/erp/app/routes/onboarding+/plan.tsx
+++ b/apps/erp/app/routes/onboarding+/plan.tsx
@@ -17,8 +17,10 @@ import { Edition } from "@carbon/utils";
import { useLocale } from "@react-aria/i18n";
import { useMemo } from "react";
import { LuGraduationCap, LuMoveLeft, LuPhoneCall } from "react-icons/lu";
+import type {
+ ActionFunctionArgs,
+} from "react-router";
import {
- type ActionFunctionArgs,
Form,
redirect,
useFetcher,
diff --git a/apps/erp/app/routes/onboarding+/theme.tsx b/apps/erp/app/routes/onboarding+/theme.tsx
index 6b1f9f3373..6e4f907091 100644
--- a/apps/erp/app/routes/onboarding+/theme.tsx
+++ b/apps/erp/app/routes/onboarding+/theme.tsx
@@ -14,7 +14,8 @@ import {
VStack
} from "@carbon/react";
import { useMode } from "@carbon/remix";
-import { type Theme, themes } from "@carbon/utils";
+import type { Theme, } from "@carbon/utils";
+import { themes } from "@carbon/utils";
import { useEffect, useRef, useState } from "react";
import { BiMoon, BiSun } from "react-icons/bi";
import { RxCheck } from "react-icons/rx";
@@ -28,7 +29,8 @@ import {
useSubmit
} from "react-router";
import { useOnboarding } from "~/hooks";
-import { type Theme as ThemeValue, themeValidator } from "~/modules/settings";
+import type { Theme as ThemeValue, } from "~/modules/settings";
+import { themeValidator } from "~/modules/settings";
import type { action as modeAction } from "~/root";
import { getTheme, setTheme } from "~/services/theme.server";
import type { Handle } from "~/utils/handle";
diff --git a/apps/erp/app/routes/onboarding+/user.tsx b/apps/erp/app/routes/onboarding+/user.tsx
index 5dfdcdd52f..c56667de0c 100644
--- a/apps/erp/app/routes/onboarding+/user.tsx
+++ b/apps/erp/app/routes/onboarding+/user.tsx
@@ -12,8 +12,10 @@ import {
HStack,
VStack
} from "@carbon/react";
+import type {
+ ActionFunctionArgs,
+} from "react-router";
import {
- type ActionFunctionArgs,
Link,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index 77dccdfc53..856aef1c18 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -2,7 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth";
import { redis } from "@carbon/kv";
import { supportedModelTypes } from "@carbon/utils";
import { Ratelimit } from "@upstash/ratelimit";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { getJobByOperationId } from "~/modules/production";
import { getCustomerPortal } from "~/modules/shared/shared.service";
diff --git a/apps/erp/app/routes/share+/supplier-quote.$id.tsx b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
index 7f0c676741..16ec207eb0 100644
--- a/apps/erp/app/routes/share+/supplier-quote.$id.tsx
+++ b/apps/erp/app/routes/share+/supplier-quote.$id.tsx
@@ -50,7 +50,7 @@ import type { LoaderFunctionArgs } from "react-router";
import { useFetcher, useLoaderData, useParams } from "react-router";
import { externalSupplierQuoteValidator } from "~/modules/purchasing/purchasing.models";
import {
- getSupplierQuoteByExternalId,
+ getSupplierQuoteByExternalLinkId,
getSupplierQuoteLinePricesByQuoteId,
getSupplierQuoteLines
} from "~/modules/purchasing/purchasing.service";
@@ -95,7 +95,7 @@ export async function loader({ params, request }: LoaderFunctionArgs) {
}
const serviceRole = getCarbonServiceRole();
- const quote = await getSupplierQuoteByExternalId(serviceRole, id);
+ const quote = await getSupplierQuoteByExternalLinkId(serviceRole, id);
if (quote.error) {
return {
diff --git a/apps/erp/app/routes/x+/_index.tsx b/apps/erp/app/routes/x+/_index.tsx
index 1ad04e591c..75990797bf 100644
--- a/apps/erp/app/routes/x+/_index.tsx
+++ b/apps/erp/app/routes/x+/_index.tsx
@@ -2,7 +2,8 @@ import { Provider as ChatProvider } from "@ai-sdk-tools/store";
import { cn } from "@carbon/react";
import { getLocalTimeZone } from "@internationalized/date";
import { useLocale } from "@react-aria/i18n";
-import { type ComponentProps, useMemo } from "react";
+import type { ComponentProps, } from "react";
+import { useMemo } from "react";
import { Link } from "react-router";
import { ChatInterface } from "~/components/Chat";
// import { DevTools } from "~/components/Chat/DevTools.client";
diff --git a/apps/erp/app/routes/x+/customer+/$customerId.risks.tsx b/apps/erp/app/routes/x+/customer+/$customerId.risks.tsx
index 389dd8dea8..85ae57afe2 100644
--- a/apps/erp/app/routes/x+/customer+/$customerId.risks.tsx
+++ b/apps/erp/app/routes/x+/customer+/$customerId.risks.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { data, type LoaderFunctionArgs, useParams } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { data, useParams } from "react-router";
import CustomerRiskRegister from "~/modules/sales/ui/Customer/CustomerRiskRegister";
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/documents+/favorite.tsx b/apps/erp/app/routes/x+/documents+/favorite.tsx
index 47d4f171c9..c8b3aff673 100644
--- a/apps/erp/app/routes/x+/documents+/favorite.tsx
+++ b/apps/erp/app/routes/x+/documents+/favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateDocumentFavorite } from "~/modules/documents";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/feedback.tsx b/apps/erp/app/routes/x+/feedback.tsx
index f5bc746084..7f9543ff2b 100644
--- a/apps/erp/app/routes/x+/feedback.tsx
+++ b/apps/erp/app/routes/x+/feedback.tsx
@@ -2,7 +2,7 @@ import { getCarbonServiceRole, SUPABASE_URL } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { getSlackClient } from "@carbon/lib/slack.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { feedbackValidator } from "~/modules/shared";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.order.tsx b/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.order.tsx
index b36c973170..5202a7e295 100644
--- a/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.order.tsx
+++ b/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.order.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
batchPropertyOrderValidator,
updateBatchPropertyOrder
diff --git a/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.tsx b/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.tsx
index 80551b7210..401bd41c21 100644
--- a/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.tsx
+++ b/apps/erp/app/routes/x+/inventory+/batch-property+/$itemId.property.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
batchPropertyValidator,
upsertBatchProperty
diff --git a/apps/erp/app/routes/x+/issue+/$id.association.delete.$type.$associationId.tsx b/apps/erp/app/routes/x+/issue+/$id.association.delete.$type.$associationId.tsx
index e628a3c97c..ff0690058b 100644
--- a/apps/erp/app/routes/x+/issue+/$id.association.delete.$type.$associationId.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.association.delete.$type.$associationId.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import {
deleteIssueAssociation,
nonConformanceAssociationType
diff --git a/apps/erp/app/routes/x+/issue+/$id.details.tsx b/apps/erp/app/routes/x+/issue+/$id.details.tsx
index 3b18d886b4..d6ca040484 100644
--- a/apps/erp/app/routes/x+/issue+/$id.details.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.details.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type JSONContent, Spinner, VStack } from "@carbon/react";
+import type { JSONContent, } from "@carbon/react";
+import { Spinner, VStack } from "@carbon/react";
import { Suspense } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import { Await, redirect, useLoaderData, useParams } from "react-router";
diff --git a/apps/erp/app/routes/x+/issue+/$id.review.tsx b/apps/erp/app/routes/x+/issue+/$id.review.tsx
index cabc516be1..2b37f6f555 100644
--- a/apps/erp/app/routes/x+/issue+/$id.review.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.review.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
insertIssueReviewer,
nonConformanceReviewerValidator
diff --git a/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx b/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx
index f80cded0fb..dc2ec7d5eb 100644
--- a/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx
+++ b/apps/erp/app/routes/x+/issue+/action-tasks.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
diff --git a/apps/erp/app/routes/x+/issue+/action.$id.due-date.tsx b/apps/erp/app/routes/x+/issue+/action.$id.due-date.tsx
index 122c98ec7f..ce0ce9792d 100644
--- a/apps/erp/app/routes/x+/issue+/action.$id.due-date.tsx
+++ b/apps/erp/app/routes/x+/issue+/action.$id.due-date.tsx
@@ -1,6 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import { zfd } from "zod-form-data";
diff --git a/apps/erp/app/routes/x+/issue+/action.$id.processes.tsx b/apps/erp/app/routes/x+/issue+/action.$id.processes.tsx
index 6199dc2ad1..e13b243b9b 100644
--- a/apps/erp/app/routes/x+/issue+/action.$id.processes.tsx
+++ b/apps/erp/app/routes/x+/issue+/action.$id.processes.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import { updateIssueActionProcesses } from "~/modules/quality/quality.service";
diff --git a/apps/erp/app/routes/x+/issue+/item+/update.tsx b/apps/erp/app/routes/x+/issue+/item+/update.tsx
index 3661c88904..93f592e913 100644
--- a/apps/erp/app/routes/x+/issue+/item+/update.tsx
+++ b/apps/erp/app/routes/x+/issue+/item+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { disposition } from "~/modules/quality/quality.models";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/issue+/task.$id.status.tsx b/apps/erp/app/routes/x+/issue+/task.$id.status.tsx
index c385f6bbbc..d5175c9045 100644
--- a/apps/erp/app/routes/x+/issue+/task.$id.status.tsx
+++ b/apps/erp/app/routes/x+/issue+/task.$id.status.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { notifyTaskStatusChanged } from "@carbon/ee/notifications";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import type { IssueInvestigationTask } from "~/modules/quality";
import { updateIssueTaskStatus } from "~/modules/quality";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
diff --git a/apps/erp/app/routes/x+/issue+/task.supplier.tsx b/apps/erp/app/routes/x+/issue+/task.supplier.tsx
index 7e21d74c9e..0db152ed5d 100644
--- a/apps/erp/app/routes/x+/issue+/task.supplier.tsx
+++ b/apps/erp/app/routes/x+/issue+/task.supplier.tsx
@@ -1,7 +1,8 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
export async function action({ request, params }: ActionFunctionArgs) {
const { client, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/issue+/update.tsx b/apps/erp/app/routes/x+/issue+/update.tsx
index 5b70d9408d..8587e0161f 100644
--- a/apps/erp/app/routes/x+/issue+/update.tsx
+++ b/apps/erp/app/routes/x+/issue+/update.tsx
@@ -1,7 +1,7 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/issue-workflow+/update.tsx b/apps/erp/app/routes/x+/issue-workflow+/update.tsx
index d2600b607b..0ed3be2e64 100644
--- a/apps/erp/app/routes/x+/issue-workflow+/update.tsx
+++ b/apps/erp/app/routes/x+/issue-workflow+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/items+/cost.$itemId.tsx b/apps/erp/app/routes/x+/items+/cost.$itemId.tsx
index 4b8188f5d5..ad71b5285c 100644
--- a/apps/erp/app/routes/x+/items+/cost.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/cost.$itemId.tsx
@@ -1,6 +1,6 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { updateItemCost } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
index 8e6c6ed40a..f33e562783 100644
--- a/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
+++ b/apps/erp/app/routes/x+/items+/delete.$itemId.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { deleteItem } from "~/modules/items";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/items+/methods+/get.tsx b/apps/erp/app/routes/x+/items+/methods+/get.tsx
index ec7b7f6ac2..d157bb51f2 100644
--- a/apps/erp/app/routes/x+/items+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/get.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { copyItem, getMethodValidator } from "~/modules/items";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
index 8bf74547f7..f12a9ee50f 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { methodMaterialValidator, upsertMethodMaterial } from "~/modules/items";
import { setCustomFields } from "~/utils/form";
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx
index 128a37b30e..b2e33685a6 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteMethodMaterial } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx b/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
index d6a3ee498c..562893db63 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { methodMaterialValidator, upsertMethodMaterial } from "~/modules/items";
import { setCustomFields } from "~/utils/form";
diff --git a/apps/erp/app/routes/x+/items+/methods+/material.order.tsx b/apps/erp/app/routes/x+/items+/methods+/material.order.tsx
index 591556b96b..ebc9ee49f9 100644
--- a/apps/erp/app/routes/x+/items+/methods+/material.order.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/material.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateMaterialOrder } from "~/modules/items";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx
index da0388108f..eff688820b 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
methodOperationValidator,
upsertMethodOperation
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx
index d390a1eacd..8d72042540 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.$operationId.step.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateMethodOperationStepOrder } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx
index c6122d9692..595df633a6 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
methodOperationValidator,
upsertMethodOperation
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx
index 07e54a6230..6fea25cff6 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateOperationOrder } from "~/modules/items";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx
index 33768990df..709ea429a6 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationParameter } from "~/modules/items";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx
index fad238d7c5..d3a24d30bc 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteMethodOperationParameter } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx
index ee3583790e..f2344fde45 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.parameter.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationParameter } from "~/modules/items";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx
index ee23f13ed4..f3fdacbd9e 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationStep } from "~/modules/items";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx
index 8f2c78187e..80515a0e5c 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteMethodOperationStep } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx
index 445221792d..95cf4257ec 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.step.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationStep } from "~/modules/items";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
index 297bfc372b..7ae97ec85a 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationTool } from "~/modules/items";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx
index cb5736b7e9..a7d526cf00 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteMethodOperationTool } from "~/modules/items";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
index 7eff652a16..b68afb3818 100644
--- a/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/operation.tool.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertMethodOperationTool } from "~/modules/items";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/items+/methods+/save.tsx b/apps/erp/app/routes/x+/items+/methods+/save.tsx
index be0ac1cdc1..4a63e58458 100644
--- a/apps/erp/app/routes/x+/items+/methods+/save.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/save.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { copyItem, getMethodValidator } from "~/modules/items";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
index 52a80418cd..ad822374fd 100644
--- a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
copyMakeMethod,
makeMethodVersionValidator,
diff --git a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
index 6499fbdad5..4f0a68b6d2 100644
--- a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
@@ -1,6 +1,7 @@
import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { activateMethodVersion } from "~/modules/items/items.service";
import { requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/items+/update.tsx b/apps/erp/app/routes/x+/items+/update.tsx
index 3e3160c99f..e9d981d02f 100644
--- a/apps/erp/app/routes/x+/items+/update.tsx
+++ b/apps/erp/app/routes/x+/items+/update.tsx
@@ -1,7 +1,7 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { Database } from "@carbon/database";
import { getMaterialDescription, getMaterialId } from "@carbon/utils";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCompanySettings } from "~/modules/settings";
diff --git a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
index eb5a24014b..671971eacc 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.configure.tsx
@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { upsertJobMethod } from "~/modules/production";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/job+/$jobId.recalculate.tsx b/apps/erp/app/routes/x+/job+/$jobId.recalculate.tsx
index 76feb8a5fc..f3cbf5e7a1 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.recalculate.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.recalculate.tsx
@@ -1,7 +1,8 @@
import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { recalculateJobRequirements } from "~/modules/production";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/job+/bulk.new.tsx b/apps/erp/app/routes/x+/job+/bulk.new.tsx
index 65f9f68150..694784cd3d 100644
--- a/apps/erp/app/routes/x+/job+/bulk.new.tsx
+++ b/apps/erp/app/routes/x+/job+/bulk.new.tsx
@@ -13,7 +13,8 @@ import {
toCalendarDateTime
} from "@internationalized/date";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getDefaultShelfForJob } from "~/modules/inventory";
import { getItemReplenishment } from "~/modules/items";
import {
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
index 7883d685a6..4286d52821 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
index e392a3a6db..11d8bd9a52 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
deleteJobMaterial,
recalculateJobOperationDependencies
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
index b1f4c7c3bb..c6bee26263 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
jobMaterialValidator,
recalculateJobMakeMethodRequirements,
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx
index c7d801696a..f1f704588a 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
jobOperationValidator,
upsertJobOperation
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
index 703c6c8ca2..421d6dac50 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
jobOperationValidator,
recalculateJobMakeMethodRequirements,
diff --git a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx
index 913796460b..729fa477d6 100644
--- a/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/$jobId.operation.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
recalculateJobOperationDependencies,
updateJobOperationOrder
diff --git a/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
index f9147e10ec..f563e2c182 100644
--- a/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/event.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { deleteProductionEvent } from "~/modules/production";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/job+/methods+/get.tsx b/apps/erp/app/routes/x+/job+/methods+/get.tsx
index 96ad036f2a..6aa3ff994d 100644
--- a/apps/erp/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/get.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
getJobMethodValidator,
recalculateJobOperationDependencies,
diff --git a/apps/erp/app/routes/x+/job+/methods+/material.order.tsx b/apps/erp/app/routes/x+/job+/methods+/material.order.tsx
index 324fbe1fc4..7cc3f5bd2d 100644
--- a/apps/erp/app/routes/x+/job+/methods+/material.order.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/material.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateJobMaterialOrder } from "~/modules/production";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.$operationId.step.order.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.$operationId.step.order.tsx
index 1082f3d412..cd0fd9da3a 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.$operationId.step.order.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.$operationId.step.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateJobOperationStepOrder } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.$id.tsx
index e24c7ade51..442f71ddf7 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationParameter } from "~/modules/production";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.delete.$id.tsx
index a9a0e8f4e2..4947a4b2f9 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteJobOperationParameter } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.new.tsx
index a91dfbd64b..fb341d5fab 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.parameter.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.parameter.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationParameter } from "~/modules/production";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx
index 984521360a..8a6c61881f 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.procedure.sync.tsx
@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { procedureSyncValidator } from "~/modules/production";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx
index 87b1f5c8ee..a6835e5222 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.status.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import type { JobOperation } from "~/modules/production";
import { updateJobOperationStatus } from "~/modules/production";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.$id.tsx
index 00d37212cc..f8ade5848d 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.step.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationStep } from "~/modules/production";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.delete.$id.tsx
index 72cabc97aa..fd422f84af 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.step.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteJobOperationStep } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.step.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.step.new.tsx
index ca83c0451d..15fe0a1f2e 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.step.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.step.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationStep } from "~/modules/production";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
index 909c298b90..5dcc7f3669 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.tool.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationTool } from "~/modules/production";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx
index b4c0191282..f5fd9f9327 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteJobOperationTool } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
index 14405e292f..9ff5069c53 100644
--- a/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/operation.tool.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertJobOperationTool } from "~/modules/production";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/job+/methods+/quantity.delete.$id.tsx b/apps/erp/app/routes/x+/job+/methods+/quantity.delete.$id.tsx
index b6347a7bd1..8b8f1afb7d 100644
--- a/apps/erp/app/routes/x+/job+/methods+/quantity.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/quantity.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { deleteProductionQuantity } from "~/modules/production";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/job+/methods+/save.tsx b/apps/erp/app/routes/x+/job+/methods+/save.tsx
index 582639d82a..242a5588ea 100644
--- a/apps/erp/app/routes/x+/job+/methods+/save.tsx
+++ b/apps/erp/app/routes/x+/job+/methods+/save.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
getJobMethodValidator,
upsertMakeMethodFromJob,
diff --git a/apps/erp/app/routes/x+/job+/update.tsx b/apps/erp/app/routes/x+/job+/update.tsx
index 177497e257..0d2ea1c1a4 100644
--- a/apps/erp/app/routes/x+/job+/update.tsx
+++ b/apps/erp/app/routes/x+/job+/update.tsx
@@ -2,7 +2,7 @@ import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { recalculateTask } from "@carbon/jobs/trigger/recalculate";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
calculateJobPriority,
recalculateJobRequirements,
diff --git a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
index 6e54cf7e8a..44ce1512ba 100644
--- a/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/$dispatchId.tsx
@@ -1,7 +1,8 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type JSONContent, VStack } from "@carbon/react";
+import type { JSONContent, } from "@carbon/react";
+import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { Outlet, redirect, useLoaderData, useParams } from "react-router";
import { PanelProvider, ResizablePanels } from "~/components/Layout/Panels";
diff --git a/apps/erp/app/routes/x+/maintenance+/update.tsx b/apps/erp/app/routes/x+/maintenance+/update.tsx
index 3929d9054d..2704168e0a 100644
--- a/apps/erp/app/routes/x+/maintenance+/update.tsx
+++ b/apps/erp/app/routes/x+/maintenance+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { upsertMaintenanceDispatch } from "~/modules/resources";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
index 4f718323af..e5b9f88911 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.make.$makeMethodId.tsx
@@ -22,12 +22,8 @@ import {
BillOfProcess,
MakeMethodTools
} from "~/modules/items/ui/Item";
-import {
- getModelByItemId,
- getTagsList,
- type MethodItemType,
- type MethodType
-} from "~/modules/shared";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { getModelByItemId, getTagsList } from "~/modules/shared";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/part+/$itemId.parameter.group.order.tsx b/apps/erp/app/routes/x+/part+/$itemId.parameter.group.order.tsx
index 54f4c4e653..cc3403aa9d 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.parameter.group.order.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.parameter.group.order.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
configurationParameterGroupOrderValidator,
updateConfigurationParameterGroupOrder
diff --git a/apps/erp/app/routes/x+/part+/$itemId.parameter.group.tsx b/apps/erp/app/routes/x+/part+/$itemId.parameter.group.tsx
index 29c473ea1d..400f0da33e 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.parameter.group.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.parameter.group.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
configurationParameterGroupValidator,
upsertConfigurationParameterGroup
diff --git a/apps/erp/app/routes/x+/part+/$itemId.parameter.order.tsx b/apps/erp/app/routes/x+/part+/$itemId.parameter.order.tsx
index fc10dff8f0..5f5c6bb82a 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.parameter.order.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.parameter.order.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
configurationParameterOrderValidator,
updateConfigurationParameterOrder
diff --git a/apps/erp/app/routes/x+/part+/$itemId.parameter.tsx b/apps/erp/app/routes/x+/part+/$itemId.parameter.tsx
index 8bb903c1d8..85e461ed72 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.parameter.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.parameter.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
configurationParameterValidator,
upsertConfigurationParameter
diff --git a/apps/erp/app/routes/x+/part+/$itemId.rule.tsx b/apps/erp/app/routes/x+/part+/$itemId.rule.tsx
index 145289e6c7..eb49c8f6d1 100644
--- a/apps/erp/app/routes/x+/part+/$itemId.rule.tsx
+++ b/apps/erp/app/routes/x+/part+/$itemId.rule.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
configurationRuleValidator,
upsertConfigurationRule
diff --git a/apps/erp/app/routes/x+/person+/_layout.tsx b/apps/erp/app/routes/x+/person+/_layout.tsx
index 8ebb009357..330cf33537 100644
--- a/apps/erp/app/routes/x+/person+/_layout.tsx
+++ b/apps/erp/app/routes/x+/person+/_layout.tsx
@@ -1,8 +1,10 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { VStack } from "@carbon/react";
+import type {
+ LoaderFunctionArgs,
+ MetaFunction,
+} from "react-router";
import {
- type LoaderFunctionArgs,
- type MetaFunction,
Outlet
} from "react-router";
diff --git a/apps/erp/app/routes/x+/procedure+/$id.parameters.new.tsx b/apps/erp/app/routes/x+/procedure+/$id.parameters.new.tsx
index 9e3b54f952..51e10d774b 100644
--- a/apps/erp/app/routes/x+/procedure+/$id.parameters.new.tsx
+++ b/apps/erp/app/routes/x+/procedure+/$id.parameters.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { procedureParameterValidator } from "~/modules/production/production.models";
import { upsertProcedureParameter } from "~/modules/production/production.service";
diff --git a/apps/erp/app/routes/x+/procedure+/$id.steps.new.tsx b/apps/erp/app/routes/x+/procedure+/$id.steps.new.tsx
index 04f20f9ae7..dfaaceac61 100644
--- a/apps/erp/app/routes/x+/procedure+/$id.steps.new.tsx
+++ b/apps/erp/app/routes/x+/procedure+/$id.steps.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { procedureStepValidator } from "~/modules/production/production.models";
import { upsertProcedureStep } from "~/modules/production/production.service";
diff --git a/apps/erp/app/routes/x+/procedure+/update.tsx b/apps/erp/app/routes/x+/procedure+/update.tsx
index 5003be1603..1dfe41a004 100644
--- a/apps/erp/app/routes/x+/procedure+/update.tsx
+++ b/apps/erp/app/routes/x+/procedure+/update.tsx
@@ -1,6 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import type { ClientActionFunctionArgs } from "react-router";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCompanyId, proceduresQuery } from "~/utils/react-query";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/production+/_index.tsx b/apps/erp/app/routes/x+/production+/_index.tsx
index 7f39e26ae8..fdf97a637f 100644
--- a/apps/erp/app/routes/x+/production+/_index.tsx
+++ b/apps/erp/app/routes/x+/production+/_index.tsx
@@ -28,8 +28,10 @@ import {
TooltipTrigger,
useRealtimeChannel
} from "@carbon/react";
+import type {
+ ChartConfig,
+} from "@carbon/react/Chart";
import {
- type ChartConfig,
ChartContainer,
ChartLegend,
ChartLegendContent,
diff --git a/apps/erp/app/routes/x+/production+/planning.update.tsx b/apps/erp/app/routes/x+/production+/planning.update.tsx
index 8ebc2e2eb2..f2efbbce5c 100644
--- a/apps/erp/app/routes/x+/production+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/production+/planning.update.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import { getDefaultShelfForJob } from "~/modules/inventory";
import {
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
index 166859432a..209e2ac8d7 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/$invoiceId.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updatePurchaseInvoiceExchangeRate } from "~/modules/invoicing";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
index fd78996257..5518d9dfb6 100644
--- a/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-invoice+/update.tsx
@@ -1,6 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { parseDate } from "@internationalized/date";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx
index 0c9a4fff7d..bae6a75226 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updatePurchaseOrderExchangeRate } from "~/modules/purchasing";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
index e811419634..686456f72f 100644
--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx
@@ -14,7 +14,8 @@ import { renderAsync } from "@react-email/components";
import { FunctionRegion } from "@supabase/supabase-js";
import { tasks } from "@trigger.dev/sdk";
import { parseAcceptLanguage } from "intl-parse-accept-language";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
diff --git a/apps/erp/app/routes/x+/purchase-order+/update.tsx b/apps/erp/app/routes/x+/purchase-order+/update.tsx
index 98d28e0f8d..9afe55802b 100644
--- a/apps/erp/app/routes/x+/purchase-order+/update.tsx
+++ b/apps/erp/app/routes/x+/purchase-order+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/purchasing+/_index.tsx b/apps/erp/app/routes/x+/purchasing+/_index.tsx
index c043c38162..6bdf5e0987 100644
--- a/apps/erp/app/routes/x+/purchasing+/_index.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/_index.tsx
@@ -29,8 +29,8 @@ import {
Thead,
Tr
} from "@carbon/react";
+import type { ChartConfig } from "@carbon/react/Chart";
import {
- type ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent
@@ -54,13 +54,8 @@ import {
LuLayoutList,
LuPackageSearch
} from "react-icons/lu";
-import {
- Await,
- Link,
- type LoaderFunctionArgs,
- useFetcher,
- useLoaderData
-} from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { Await, Link, useFetcher, useLoaderData } from "react-router";
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { Empty, Hyperlink, SupplierAvatar } from "~/components";
import { useUser } from "~/hooks";
diff --git a/apps/erp/app/routes/x+/purchasing+/orders.favorite.tsx b/apps/erp/app/routes/x+/purchasing+/orders.favorite.tsx
index dad66fa2a7..7939baefaa 100644
--- a/apps/erp/app/routes/x+/purchasing+/orders.favorite.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/orders.favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updatePurchaseOrderFavorite } from "~/modules/purchasing";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
index a8f7984884..7919df5c18 100644
--- a/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/planning.update.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import { getCurrencyByCode } from "~/modules/accounting/accounting.service";
import {
diff --git a/apps/erp/app/routes/x+/purchasing+/quotes.favorite.tsx b/apps/erp/app/routes/x+/purchasing+/quotes.favorite.tsx
index c4682e7960..16d7eb0aa1 100644
--- a/apps/erp/app/routes/x+/purchasing+/quotes.favorite.tsx
+++ b/apps/erp/app/routes/x+/purchasing+/quotes.favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateSupplierQuoteFavorite } from "~/modules/purchasing";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/quality+/risks.$id.tsx b/apps/erp/app/routes/x+/quality+/risks.$id.tsx
index 9d1a73c0f5..f707d56925 100644
--- a/apps/erp/app/routes/x+/quality+/risks.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/risks.$id.tsx
@@ -4,10 +4,12 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { NotificationEvent } from "@carbon/notifications";
import { tasks } from "@trigger.dev/sdk";
+import type {
+ ActionFunctionArgs,
+ LoaderFunctionArgs,
+} from "react-router";
import {
- type ActionFunctionArgs,
data,
- type LoaderFunctionArgs,
useLoaderData,
useNavigate
} from "react-router";
diff --git a/apps/erp/app/routes/x+/quality+/risks.delete.$id.tsx b/apps/erp/app/routes/x+/quality+/risks.delete.$id.tsx
index def809925d..83a5e1447b 100644
--- a/apps/erp/app/routes/x+/quality+/risks.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quality+/risks.delete.$id.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import invariant from "tiny-invariant";
import { deleteRisk } from "~/modules/quality/quality.service";
diff --git a/apps/erp/app/routes/x+/quality+/risks.new.tsx b/apps/erp/app/routes/x+/quality+/risks.new.tsx
index a5957f6877..6746f6f608 100644
--- a/apps/erp/app/routes/x+/quality+/risks.new.tsx
+++ b/apps/erp/app/routes/x+/quality+/risks.new.tsx
@@ -5,7 +5,8 @@ import { validationError, validator } from "@carbon/form";
import { NotificationEvent } from "@carbon/notifications";
import { useDisclosure } from "@carbon/react";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, data, useNavigate } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, useNavigate } from "react-router";
import { riskRegisterValidator } from "~/modules/quality/quality.models";
import { upsertRisk } from "~/modules/quality/quality.service";
import RiskRegisterForm from "~/modules/quality/ui/RiskRegister/RiskRegisterForm";
diff --git a/apps/erp/app/routes/x+/quality+/risks.tsx b/apps/erp/app/routes/x+/quality+/risks.tsx
index 33e0b66787..9d3091711a 100644
--- a/apps/erp/app/routes/x+/quality+/risks.tsx
+++ b/apps/erp/app/routes/x+/quality+/risks.tsx
@@ -2,9 +2,11 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { VStack } from "@carbon/react";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
data,
- type LoaderFunctionArgs,
Outlet,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/x+/quality-document+/$id.steps.new.tsx b/apps/erp/app/routes/x+/quality-document+/$id.steps.new.tsx
index 3b998c63ef..13978564ce 100644
--- a/apps/erp/app/routes/x+/quality-document+/$id.steps.new.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/$id.steps.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { qualityDocumentStepValidator } from "~/modules/quality/quality.models";
import { upsertQualityDocumentStep } from "~/modules/quality/quality.service";
diff --git a/apps/erp/app/routes/x+/quality-document+/update.tsx b/apps/erp/app/routes/x+/quality-document+/update.tsx
index df1f35d15d..9421c0eecd 100644
--- a/apps/erp/app/routes/x+/quality-document+/update.tsx
+++ b/apps/erp/app/routes/x+/quality-document+/update.tsx
@@ -4,7 +4,7 @@ import type { Database } from "@carbon/database";
import { NotificationEvent } from "@carbon/notifications";
import type { SupabaseClient } from "@supabase/supabase-js";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { qualityDocumentStatus } from "~/modules/quality/quality.models";
import {
canApproveRequest,
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
index 4f556c81e1..6664442a87 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.configure.tsx
@@ -1,7 +1,8 @@
import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { upsertQuoteLineMethod } from "~/modules/sales/sales.service";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.delete.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.delete.tsx
index b5f6edbf30..c18004919f 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.delete.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.delete.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
quoteLineAdditionalChargesValidator,
upsertQuoteLineAdditionalCharges
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.new.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.new.tsx
index da9ea688fa..61d7e4231d 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.cost.new.tsx
@@ -1,7 +1,8 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { nanoid } from "nanoid";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
quoteLineAdditionalChargesValidator,
upsertQuoteLineAdditionalCharges
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
index 5d7f292f5b..c7f446cee7 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.recalculate-price.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { z } from "zod";
import { upsertQuoteLinePrices } from "~/modules/sales";
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx
index 3edb956b3f..0f0e27b5b0 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.$lineId.update-precision.tsx
@@ -1,6 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
updateQuoteLinePrecision,
upsertQuoteLinePrices
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
index 1df017d31c..d749a6dc67 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.convert.tsx
@@ -6,7 +6,8 @@ import {
} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { convertQuoteToOrder, selectedLinesValidator } from "~/modules/sales";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx
index 646b1bd15c..ccd2382fe3 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updateQuoteExchangeRate } from "~/modules/sales";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
index 59b54f580f..fe6c67bc03 100644
--- a/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
+++ b/apps/erp/app/routes/x+/quote+/$quoteId.finalize.tsx
@@ -7,7 +7,8 @@ import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend
import { getLocalTimeZone, now } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
import { upsertDocument } from "~/modules/documents";
import {
finalizeQuote,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
index a3712570bd..93268de216 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { quoteMaterialValidator, upsertQuoteMaterial } from "~/modules/sales";
import { setCustomFields } from "~/utils/form";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
index ccfd882554..c9113f2347 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteQuoteMaterial } from "~/modules/sales";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
index 8075da0d12..638cf8f1c3 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.material.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
quoteMaterialValidator,
upsertQuoteMaterial,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
index 48e918e7bc..2ef70758b4 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { quoteOperationValidator, upsertQuoteOperation } from "~/modules/sales";
import { setCustomFields } from "~/utils/form";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
index e759d04902..8ff8baa6bd 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/$quoteId.$lineId.operation.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { quoteOperationValidator, upsertQuoteOperation } from "~/modules/sales";
import { setCustomFields } from "~/utils/form";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/get.tsx b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
index ef4dbf734a..1c6ed147e1 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/get.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/get.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
copyQuoteLine,
getMethodValidator,
diff --git a/apps/erp/app/routes/x+/quote+/methods+/material.order.tsx b/apps/erp/app/routes/x+/quote+/methods+/material.order.tsx
index 7b791ed883..c743217da3 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/material.order.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/material.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateQuoteMaterialOrder } from "~/modules/sales";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.$operationId.step.order.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.$operationId.step.order.tsx
index a4f4efb938..6c80c778f2 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.$operationId.step.order.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.$operationId.step.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateQuoteOperationStepOrder } from "~/modules/production";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.order.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.order.tsx
index 06a7d6a020..851f747898 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.order.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateQuoteOperationOrder } from "~/modules/sales";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.$id.tsx
index c34b896dc3..616c19ea7a 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationParameter } from "~/modules/sales";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.delete.$id.tsx
index f27a0b4692..60ea1348e3 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteQuoteOperationParameter } from "~/modules/sales";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.new.tsx
index 9dbcbf059a..dc4b959116 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.parameter.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationParameter } from "~/modules/sales";
import { operationParameterValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.step.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.step.$id.tsx
index fae0a71ee2..ad3ab7135e 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.step.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.step.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationStep } from "~/modules/sales";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.step.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.step.delete.$id.tsx
index 100820ceb3..79c745afce 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.step.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.step.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteQuoteOperationStep } from "~/modules/sales";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.step.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.step.new.tsx
index 921c43ce11..7cfa1daa1f 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.step.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.step.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationStep } from "~/modules/sales";
import { operationStepValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.$id.tsx
index b2fd35afbc..f571f63aa9 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.$id.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationTool } from "~/modules/sales";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx
index f6d2d6f69a..784ba71074 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { deleteQuoteOperationTool } from "~/modules/sales";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.new.tsx b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.new.tsx
index 7a393cc6ba..c3892af75b 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/operation.tool.new.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/operation.tool.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { upsertQuoteOperationTool } from "~/modules/sales";
import { operationToolValidator } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/quote+/methods+/save.tsx b/apps/erp/app/routes/x+/quote+/methods+/save.tsx
index 03ec5cb26c..c5e83d3e7b 100644
--- a/apps/erp/app/routes/x+/quote+/methods+/save.tsx
+++ b/apps/erp/app/routes/x+/quote+/methods+/save.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
getMethodValidator,
upsertMakeMethodFromQuoteLine,
diff --git a/apps/erp/app/routes/x+/quote+/update.tsx b/apps/erp/app/routes/x+/quote+/update.tsx
index 67040c7c13..e8a27fe355 100644
--- a/apps/erp/app/routes/x+/quote+/update.tsx
+++ b/apps/erp/app/routes/x+/quote+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/receipt+/lines.split.tsx b/apps/erp/app/routes/x+/receipt+/lines.split.tsx
index 83edff08c4..75942f5ef4 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.split.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.split.tsx
@@ -2,7 +2,7 @@ import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { splitValidator } from "~/modules/inventory";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
index 777cc08e48..c230d5c73f 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.tracking.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import type { TrackedEntityAttributes } from "@carbon/utils";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
export async function action({ request, context }: ActionFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/receipt+/lines.update.tsx b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
index a818f1b73f..cfeaab41fd 100644
--- a/apps/erp/app/routes/x+/receipt+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/receipt+/lines.update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/receipt+/new.tsx b/apps/erp/app/routes/x+/receipt+/new.tsx
index 4c65a3cf21..64da97089b 100644
--- a/apps/erp/app/routes/x+/receipt+/new.tsx
+++ b/apps/erp/app/routes/x+/receipt+/new.tsx
@@ -2,7 +2,8 @@ import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import type { ReceiptSourceDocument } from "~/modules/inventory";
import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
diff --git a/apps/erp/app/routes/x+/resources+/_index.tsx b/apps/erp/app/routes/x+/resources+/_index.tsx
index a45bf65a6c..aadf7a5fd9 100644
--- a/apps/erp/app/routes/x+/resources+/_index.tsx
+++ b/apps/erp/app/routes/x+/resources+/_index.tsx
@@ -28,8 +28,10 @@ import {
Thead,
Tr
} from "@carbon/react";
+import type {
+ ChartConfig,
+} from "@carbon/react/Chart";
import {
- type ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent
@@ -49,10 +51,12 @@ import {
LuTriangleAlert,
LuWrench
} from "react-icons/lu";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
Await,
Link,
- type LoaderFunctionArgs,
useFetcher,
useLoaderData
} from "react-router";
@@ -60,9 +64,11 @@ import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts";
import { Empty, Hyperlink } from "~/components";
import { useWorkCenters } from "~/components/Form/WorkCenters";
import { useCurrencyFormatter } from "~/hooks/useCurrencyFormatter";
+import type {
+ maintenanceSource
+} from "~/modules/resources/resources.models";
import {
MaintenanceKPIs,
- maintenanceSource
} from "~/modules/resources/resources.models";
import MaintenanceSource from "~/modules/resources/ui/Maintenance/MaintenanceSource";
import MaintenanceStatus from "~/modules/resources/ui/Maintenance/MaintenanceStatus";
diff --git a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
index e39eb8b0d7..686395d300 100644
--- a/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
+++ b/apps/erp/app/routes/x+/resources+/scheduled-maintenance.tsx
@@ -5,10 +5,12 @@ import { VStack } from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
import { data, Outlet, useLoaderData } from "react-router";
+import type {
+ MaintenanceSchedule
+} from "~/modules/resources";
import {
getLocationsList,
getMaintenanceSchedulesByLocation,
- MaintenanceSchedule
} from "~/modules/resources";
import MaintenanceSchedulesTable from "~/modules/resources/ui/MaintenanceSchedule/MaintenanceSchedulesTable";
import type { Handle } from "~/utils/handle";
diff --git a/apps/erp/app/routes/x+/sales+/_index.tsx b/apps/erp/app/routes/x+/sales+/_index.tsx
index 790a2780c3..6a8025dfe6 100644
--- a/apps/erp/app/routes/x+/sales+/_index.tsx
+++ b/apps/erp/app/routes/x+/sales+/_index.tsx
@@ -29,8 +29,10 @@ import {
Thead,
Tr
} from "@carbon/react";
+import type {
+ ChartConfig,
+} from "@carbon/react/Chart";
import {
- type ChartConfig,
ChartContainer,
ChartTooltip,
ChartTooltipContent
@@ -52,10 +54,12 @@ import {
RiProgress4Line,
RiProgress8Line
} from "react-icons/ri";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
Await,
Link,
- type LoaderFunctionArgs,
useFetcher,
useLoaderData
} from "react-router";
diff --git a/apps/erp/app/routes/x+/sales+/quotes.favorite.tsx b/apps/erp/app/routes/x+/sales+/quotes.favorite.tsx
index 26ed7db377..2923af923e 100644
--- a/apps/erp/app/routes/x+/sales+/quotes.favorite.tsx
+++ b/apps/erp/app/routes/x+/sales+/quotes.favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateQuoteFavorite } from "~/modules/sales";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/sales+/rfqs.favorite.tsx b/apps/erp/app/routes/x+/sales+/rfqs.favorite.tsx
index 8636aee6c1..5d08a0df9c 100644
--- a/apps/erp/app/routes/x+/sales+/rfqs.favorite.tsx
+++ b/apps/erp/app/routes/x+/sales+/rfqs.favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateSalesRFQFavorite } from "~/modules/sales";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
index 8e1c573fb1..7116253c9f 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updateSalesInvoiceExchangeRate } from "~/modules/invoicing";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
index 05da307ee2..a60933077f 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/$invoiceId.post.tsx
@@ -7,7 +7,7 @@ import { renderAsync } from "@react-email/components";
import { FunctionRegion } from "@supabase/supabase-js";
import { tasks } from "@trigger.dev/sdk";
import { parseAcceptLanguage } from "intl-parse-accept-language";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import {
diff --git a/apps/erp/app/routes/x+/sales-invoice+/update.tsx b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
index 9ab39edbe6..4e461e36dc 100644
--- a/apps/erp/app/routes/x+/sales-invoice+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-invoice+/update.tsx
@@ -1,6 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { parseDate } from "@internationalized/date";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
index 295f65800c..4746e0b016 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.confirm.tsx
@@ -8,7 +8,7 @@ import { getLocalTimeZone, today } from "@internationalized/date";
import { renderAsync } from "@react-email/components";
import { tasks } from "@trigger.dev/sdk";
import { parseAcceptLanguage } from "intl-parse-accept-language";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getPaymentTermsList } from "~/modules/accounting";
import { upsertDocument } from "~/modules/documents";
import { runMRP } from "~/modules/production/production.service";
diff --git a/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx b/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx
index 77b6b3c5c3..dd4d6da9b6 100644
--- a/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/$orderId.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updateSalesOrderExchangeRate } from "~/modules/sales";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-order+/orders.favorite.tsx b/apps/erp/app/routes/x+/sales-order+/orders.favorite.tsx
index 42acd0290d..7da4b63cb4 100644
--- a/apps/erp/app/routes/x+/sales-order+/orders.favorite.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/orders.favorite.tsx
@@ -2,7 +2,8 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateSalesOrderFavorite } from "~/modules/sales";
import { favoriteSchema } from "~/types/validators";
diff --git a/apps/erp/app/routes/x+/sales-order+/update.tsx b/apps/erp/app/routes/x+/sales-order+/update.tsx
index 00eb28561f..297073f891 100644
--- a/apps/erp/app/routes/x+/sales-order+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-order+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
index e8bd4ec423..dad5590574 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { deleteSalesRFQLine } from "~/modules/sales";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
index 3a65a7cefd..f4414b661e 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.convert.tsx
@@ -6,7 +6,8 @@ import {
} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { convertSalesRfqToQuote } from "~/modules/sales";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
index ae73753d29..e85466a32c 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -4,7 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import type { modelThumbnailTask } from "@carbon/jobs/trigger/model-thumbnail";
import { tasks } from "@trigger.dev/sdk";
import { nanoid } from "nanoid";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { salesRfqDragValidator, upsertSalesRFQLine } from "~/modules/sales";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.new.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.new.tsx
index fc53ca8572..e8db01c0cd 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.new.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { salesRfqLineValidator, upsertSalesRFQLine } from "~/modules/sales";
import { setCustomFields } from "~/utils/form";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
index 33de0c069f..1b43f02418 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -1,7 +1,8 @@
import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type JSONContent, VStack } from "@carbon/react";
+import type { JSONContent, } from "@carbon/react";
+import { VStack } from "@carbon/react";
import { supportedModelTypes } from "@carbon/utils";
import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/update.tsx b/apps/erp/app/routes/x+/sales-rfq+/update.tsx
index d7cd973bd7..0ca8f0a34a 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/update.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/schedule+/dates.tsx b/apps/erp/app/routes/x+/schedule+/dates.tsx
index 50ff8ba282..5302a85e56 100644
--- a/apps/erp/app/routes/x+/schedule+/dates.tsx
+++ b/apps/erp/app/routes/x+/schedule+/dates.tsx
@@ -33,8 +33,10 @@ import {
} from "@internationalized/date";
import { useCallback, useEffect, useMemo, useState } from "react";
import { LuChevronLeft, LuChevronRight, LuSettings2 } from "react-icons/lu";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
- type LoaderFunctionArgs,
redirect,
useLoaderData,
useNavigate,
diff --git a/apps/erp/app/routes/x+/schedule+/operations.tsx b/apps/erp/app/routes/x+/schedule+/operations.tsx
index c711ba60e2..c1049ba98e 100644
--- a/apps/erp/app/routes/x+/schedule+/operations.tsx
+++ b/apps/erp/app/routes/x+/schedule+/operations.tsx
@@ -28,12 +28,8 @@ import {
} from "@internationalized/date";
import { useCallback, useEffect, useMemo, useState } from "react";
import { LuCirclePlus, LuSettings2, LuTriangleAlert } from "react-icons/lu";
-import {
- Link,
- type LoaderFunctionArgs,
- redirect,
- useLoaderData
-} from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { Link, redirect, useLoaderData } from "react-router";
import { SearchFilter } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import { useLocations } from "~/components/Form/Location";
diff --git a/apps/erp/app/routes/x+/scheduling+/gantt.tsx b/apps/erp/app/routes/x+/scheduling+/gantt.tsx
index 9aadd5fb1c..dd624bc190 100644
--- a/apps/erp/app/routes/x+/scheduling+/gantt.tsx
+++ b/apps/erp/app/routes/x+/scheduling+/gantt.tsx
@@ -8,7 +8,8 @@ import {
useDebounce
} from "@carbon/react";
import type { LoaderFunctionArgs } from "react-router";
-import { type Location, useLoaderData } from "react-router";
+import type { Location, } from "react-router";
+import { useLoaderData } from "react-router";
import type { GanttEvent } from "~/components/Gantt";
import { Gantt } from "~/components/Gantt";
import { useReplaceLocation } from "~/hooks/useReplaceLocation";
diff --git a/apps/erp/app/routes/x+/settings+/api-keys.tsx b/apps/erp/app/routes/x+/settings+/api-keys.tsx
index f1b76ac8c2..13e25bf862 100644
--- a/apps/erp/app/routes/x+/settings+/api-keys.tsx
+++ b/apps/erp/app/routes/x+/settings+/api-keys.tsx
@@ -1,8 +1,10 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
- type LoaderFunctionArgs,
Outlet,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx b/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx
index 3df784dfc9..c42a9afd63 100644
--- a/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx
+++ b/apps/erp/app/routes/x+/settings+/company.switch.$companyId.tsx
@@ -6,7 +6,8 @@ import {
flash,
updateCompanySession
} from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCompanies } from "~/modules/settings";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index 7ed0378d05..c8c02b153f 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -63,10 +63,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { active, ...d } = validation.data;
+ // Fetch existing metadata so we merge form settings without
+ // overwriting credentials and syncConfig
+ const existing = await getIntegration(client, integrationId, companyId);
+ const existingMetadata =
+ (existing.data?.metadata as Record<string, unknown>) ?? {};
+
const update = await upsertCompanyIntegration(client, {
id: integrationId,
active: true,
metadata: {
+ ...existingMetadata,
...d
},
companyId,
diff --git a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
index 9af3d6a239..b5e9772561 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.deactivate.$id.tsx
@@ -1,7 +1,10 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { integrations as availableIntegrations } from "@carbon/ee";
+import {
+ integrations as availableIntegrations,
+ getIntegrationConfigById
+} from "@carbon/ee";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
import { deactivateIntegration } from "~/modules/settings/settings.server";
@@ -36,6 +39,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Call the onUninstall hook if defined
+ const config = getIntegrationConfigById(integrationId);
+ if (config && typeof config.onUninstall === "function") {
+ await config.onUninstall(companyId);
+ }
+
throw redirect(
path.to.integrations,
await flash(
diff --git a/apps/erp/app/routes/x+/settings+/integrations.tsx b/apps/erp/app/routes/x+/settings+/integrations.tsx
index 674d3b359c..153d6799cf 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.tsx
@@ -2,8 +2,10 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { integrations as availableIntegrations } from "@carbon/ee";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
- type LoaderFunctionArgs,
Outlet,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/x+/settings+/logos.tsx b/apps/erp/app/routes/x+/settings+/logos.tsx
index 42bab41da7..50e686b7ce 100644
--- a/apps/erp/app/routes/x+/settings+/logos.tsx
+++ b/apps/erp/app/routes/x+/settings+/logos.tsx
@@ -10,7 +10,8 @@ import {
VStack
} from "@carbon/react";
import { LuMoon, LuSun } from "react-icons/lu";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { useRouteData } from "~/hooks";
import type { Company } from "~/modules/settings";
import {
diff --git a/apps/erp/app/routes/x+/settings+/tags.new.tsx b/apps/erp/app/routes/x+/settings+/tags.new.tsx
index 56ae09d4c5..b4204faffc 100644
--- a/apps/erp/app/routes/x+/settings+/tags.new.tsx
+++ b/apps/erp/app/routes/x+/settings+/tags.new.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { insertTag } from "~/modules/shared";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/settings+/tags.tsx b/apps/erp/app/routes/x+/settings+/tags.tsx
index 2e3db6f424..58448d9390 100644
--- a/apps/erp/app/routes/x+/settings+/tags.tsx
+++ b/apps/erp/app/routes/x+/settings+/tags.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, userId } = await requirePermissions(request, {});
diff --git a/apps/erp/app/routes/x+/settings+/webhooks.tsx b/apps/erp/app/routes/x+/settings+/webhooks.tsx
index 3bf041efa3..ba0a1a6d06 100644
--- a/apps/erp/app/routes/x+/settings+/webhooks.tsx
+++ b/apps/erp/app/routes/x+/settings+/webhooks.tsx
@@ -1,8 +1,10 @@
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import type {
+ LoaderFunctionArgs,
+} from "react-router";
import {
- type LoaderFunctionArgs,
Outlet,
redirect,
useLoaderData
diff --git a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
index 6498e770af..26605e3506 100644
--- a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
+++ b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
@@ -1,7 +1,7 @@
import { getCarbonServiceRole, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { z } from "zod";
import { importCsv, importPermissions, importSchemas } from "~/modules/shared";
diff --git a/apps/erp/app/routes/x+/shared+/view.order.tsx b/apps/erp/app/routes/x+/shared+/view.order.tsx
index a2e20c0a37..d8a16d020b 100644
--- a/apps/erp/app/routes/x+/shared+/view.order.tsx
+++ b/apps/erp/app/routes/x+/shared+/view.order.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { updateSavedViewOrder } from "~/modules/shared/shared.service";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/shared+/views.delete.$id.tsx b/apps/erp/app/routes/x+/shared+/views.delete.$id.tsx
index e4d8ef31b3..400c725c34 100644
--- a/apps/erp/app/routes/x+/shared+/views.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/shared+/views.delete.$id.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import { deleteSavedView } from "~/modules/shared";
import { path } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/shared+/views.tsx b/apps/erp/app/routes/x+/shared+/views.tsx
index 0ead45525e..f2ae8a57e1 100644
--- a/apps/erp/app/routes/x+/shared+/views.tsx
+++ b/apps/erp/app/routes/x+/shared+/views.tsx
@@ -1,7 +1,7 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
savedViewStateValidator,
savedViewValidator
diff --git a/apps/erp/app/routes/x+/shipment+/lines.split.tsx b/apps/erp/app/routes/x+/shipment+/lines.split.tsx
index 96f5a8aaa5..fe3e387f53 100644
--- a/apps/erp/app/routes/x+/shipment+/lines.split.tsx
+++ b/apps/erp/app/routes/x+/shipment+/lines.split.tsx
@@ -2,7 +2,7 @@ import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { splitValidator } from "~/modules/inventory";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx b/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
index 53dfbe6007..053f22f1f3 100644
--- a/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
+++ b/apps/erp/app/routes/x+/shipment+/lines.tracking.tsx
@@ -1,7 +1,8 @@
import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/shipment+/lines.update.tsx b/apps/erp/app/routes/x+/shipment+/lines.update.tsx
index 1ff45cbaec..b6fc5e12a8 100644
--- a/apps/erp/app/routes/x+/shipment+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/shipment+/lines.update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/shipment+/new.tsx b/apps/erp/app/routes/x+/shipment+/new.tsx
index da1c9e0f32..0e500a045c 100644
--- a/apps/erp/app/routes/x+/shipment+/new.tsx
+++ b/apps/erp/app/routes/x+/shipment+/new.tsx
@@ -2,7 +2,8 @@ import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import type { ShipmentSourceDocument } from "~/modules/inventory";
import { getUserDefaults } from "~/modules/users/users.server";
import type { Handle } from "~/utils/handle";
diff --git a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx
index 570dbe76aa..d4ecc46096 100644
--- a/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx
+++ b/apps/erp/app/routes/x+/stock-transfer+/lines.update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, companyId, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx
index c4701c0f1a..9d3ca39670 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx
@@ -8,10 +8,12 @@ import type {
import { redirect, useNavigate, useParams } from "react-router";
import { ConfirmDelete } from "~/components/Modals";
import { useRouteData } from "~/hooks";
+import type {
+ SupplierProcess
+} from "~/modules/purchasing";
import {
deleteSupplierProcess,
getSupplierProcessById,
- type SupplierProcess
} from "~/modules/purchasing";
import { path } from "~/utils/path";
import { supplierProcessesQuery } from "~/utils/react-query";
diff --git a/apps/erp/app/routes/x+/supplier+/$supplierId.risks.tsx b/apps/erp/app/routes/x+/supplier+/$supplierId.risks.tsx
index aa2d3791b2..5b111ad774 100644
--- a/apps/erp/app/routes/x+/supplier+/$supplierId.risks.tsx
+++ b/apps/erp/app/routes/x+/supplier+/$supplierId.risks.tsx
@@ -1,5 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { data, type LoaderFunctionArgs, useParams } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { data, useParams } from "react-router";
import SupplierRiskRegister from "~/modules/purchasing/ui/Supplier/SupplierRiskRegister";
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
index 84f2791d05..fc0463b24c 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.convert.tsx
@@ -6,7 +6,8 @@ import {
} from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import {
convertSupplierQuoteToOrder,
selectedLinesValidator
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx
index 949687931c..a3465854b6 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.exchange-rate.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
import { updateSupplierQuoteExchangeRate } from "~/modules/purchasing";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
index ae942d5874..f5093976ee 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.finalize.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import {
finalizeSupplierQuote,
getSupplierQuote,
diff --git a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
index 4b933c05af..201b28fc78 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/$id.send.tsx
@@ -4,7 +4,8 @@ import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
+import { redirect } from "react-router";
import {
getSupplierContact,
getSupplierInteractionLineDocuments,
diff --git a/apps/erp/app/routes/x+/supplier-quote+/update.tsx b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
index 3f28924806..8f7d810a6e 100644
--- a/apps/erp/app/routes/x+/supplier-quote+/update.tsx
+++ b/apps/erp/app/routes/x+/supplier-quote+/update.tsx
@@ -1,6 +1,6 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { getLocalTimeZone, today } from "@internationalized/date";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { getCurrencyByCode } from "~/modules/accounting";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
index cdf12adc0c..b460950013 100644
--- a/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
+++ b/apps/erp/app/routes/x+/tool+/$itemId.make.$makeMethodId.tsx
@@ -19,12 +19,8 @@ import {
BillOfProcess,
MakeMethodTools
} from "~/modules/items/ui/Item";
-import {
- getModelByItemId,
- getTagsList,
- type MethodItemType,
- type MethodType
-} from "~/modules/shared";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { getModelByItemId, getTagsList } from "~/modules/shared";
import { path } from "~/utils/path";
export async function loader({ request, params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/training+/$id.questions.$questionId.tsx b/apps/erp/app/routes/x+/training+/$id.questions.$questionId.tsx
index a63276208d..7c82d0a1e1 100644
--- a/apps/erp/app/routes/x+/training+/$id.questions.$questionId.tsx
+++ b/apps/erp/app/routes/x+/training+/$id.questions.$questionId.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error, notFound } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
trainingQuestionValidator,
upsertTrainingQuestion
diff --git a/apps/erp/app/routes/x+/training+/$id.questions.new.tsx b/apps/erp/app/routes/x+/training+/$id.questions.new.tsx
index d7538a1931..b1645d8d31 100644
--- a/apps/erp/app/routes/x+/training+/$id.questions.new.tsx
+++ b/apps/erp/app/routes/x+/training+/$id.questions.new.tsx
@@ -2,7 +2,8 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validator } from "@carbon/form";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import {
trainingQuestionValidator,
upsertTrainingQuestion
diff --git a/apps/erp/app/routes/x+/training+/update.tsx b/apps/erp/app/routes/x+/training+/update.tsx
index c8acdba725..4dd313bbef 100644
--- a/apps/erp/app/routes/x+/training+/update.tsx
+++ b/apps/erp/app/routes/x+/training+/update.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
export async function action({ request }: ActionFunctionArgs) {
const { client, userId } = await requirePermissions(request, {
diff --git a/apps/erp/app/routes/x+/users+/revoke-invite.tsx b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
index f6f49d7f81..c07dd85169 100644
--- a/apps/erp/app/routes/x+/users+/revoke-invite.tsx
+++ b/apps/erp/app/routes/x+/users+/revoke-invite.tsx
@@ -12,7 +12,8 @@ import type { userAdminTask } from "@carbon/jobs/trigger/user-admin";
import { updateSubscriptionQuantityForCompany } from "@carbon/stripe/stripe.server";
import { Edition } from "@carbon/utils";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { revokeInviteValidator } from "~/modules/users";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx
index 6af460fa1a..8e21a266e1 100644
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.receive.tsx
@@ -1,4 +1,5 @@
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
export async function loader({ params }: LoaderFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx
index 50d0cac48c..287f2454b3 100644
--- a/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx
+++ b/apps/erp/app/routes/x+/warehouse-transfer+/$transferId.ship.tsx
@@ -1,4 +1,5 @@
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
export async function loader({ params }: LoaderFunctionArgs) {
diff --git a/apps/mes/app/components/AppSidebar.tsx b/apps/mes/app/components/AppSidebar.tsx
index 009b683fd8..b23d03d8ee 100644
--- a/apps/mes/app/components/AppSidebar.tsx
+++ b/apps/mes/app/components/AppSidebar.tsx
@@ -1,6 +1,7 @@
"use client";
-import { CONTROLLED_ENVIRONMENT, type Company } from "@carbon/auth";
+import type { Company } from "@carbon/auth";
+import { CONTROLLED_ENVIRONMENT, } from "@carbon/auth";
import {
Avatar,
cn,
@@ -32,7 +33,8 @@ import {
useSidebar
} from "@carbon/react";
import { ItarDisclosure, useMode } from "@carbon/remix";
-import { type ComponentProps, useRef } from "react";
+import type { ComponentProps, } from "react";
+import { useRef } from "react";
import { BsFillHexagonFill } from "react-icons/bs";
import {
LuActivity,
diff --git a/apps/mes/app/components/FileDropzone.tsx b/apps/mes/app/components/FileDropzone.tsx
index 051230b456..6e036e04dc 100644
--- a/apps/mes/app/components/FileDropzone.tsx
+++ b/apps/mes/app/components/FileDropzone.tsx
@@ -1,5 +1,5 @@
import { cn } from "@carbon/react";
-import React from "react";
+import type React from "react";
import { useDropzone } from "react-dropzone";
import { LuCloudUpload } from "react-icons/lu";
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index ea9ef35a04..2febf0389c 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -1,6 +1,7 @@
import type { Result } from "@carbon/auth";
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import type { JSONContent } from "@carbon/react";
import {
Badge,
Button,
@@ -15,7 +16,6 @@ import {
Heading,
HStack,
IconButton,
- type JSONContent,
ModelViewer,
Progress,
ScrollArea,
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index fb1e53f9c4..4eaadc34a7 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -1686,11 +1686,11 @@ function useSerialNumbers(itemId?: string) {
const serialNumbersFetcher =
useFetcher<Awaited<ReturnType<typeof getSerialNumbersForItem>>>();
+ // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
useEffect(() => {
if (itemId) {
serialNumbersFetcher.load(path.to.api.serialNumbers(itemId));
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [itemId]);
return { data: serialNumbersFetcher.data };
@@ -1705,8 +1705,7 @@ function useBatchNumbers(itemId?: string) {
if (itemId) {
batchNumbersFetcher.load(path.to.api.batchNumbers(itemId));
}
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [itemId]);
+ }, [itemId, batchNumbersFetcher.load]);
return { data: batchNumbersFetcher.data };
}
diff --git a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
index e6ea20d0bf..9bfa1671c6 100644
--- a/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
+++ b/apps/mes/app/components/JobOperation/components/MaintenanceDispatch.tsx
@@ -26,7 +26,7 @@ import {
VStack
} from "@carbon/react";
import { Editor } from "@carbon/react/Editor";
-import { PostgrestResponse } from "@supabase/supabase-js";
+import type { PostgrestResponse } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { useEffect, useState } from "react";
import { BsExclamationSquareFill } from "react-icons/bs";
diff --git a/apps/mes/app/components/JobOperation/components/Step.tsx b/apps/mes/app/components/JobOperation/components/Step.tsx
index 36d24b893a..5cb26fccd1 100644
--- a/apps/mes/app/components/JobOperation/components/Step.tsx
+++ b/apps/mes/app/components/JobOperation/components/Step.tsx
@@ -10,6 +10,9 @@ import {
Submit,
ValidatedForm
} from "@carbon/form";
+import type {
+ JSONContent,
+} from "@carbon/react";
import {
Button,
Checkbox,
@@ -17,7 +20,6 @@ import {
generateHTML,
HStack,
IconButton,
- type JSONContent,
Modal,
ModalBody,
ModalContent,
diff --git a/apps/mes/app/root.tsx b/apps/mes/app/root.tsx
index b9894c189f..e847337490 100644
--- a/apps/mes/app/root.tsx
+++ b/apps/mes/app/root.tsx
@@ -13,7 +13,8 @@ import type { Theme } from "@carbon/utils";
import { modeValidator, themes } from "@carbon/utils";
import { I18nProvider } from "@react-aria/i18n";
import { Analytics } from "@vercel/analytics/react";
-import React, { useEffect } from "react";
+import type React from "react";
+import { useEffect } from "react";
import type {
ActionFunctionArgs,
LoaderFunctionArgs,
diff --git a/apps/mes/app/routes.ts b/apps/mes/app/routes.ts
index 66d6f7384c..1b20b9ace7 100644
--- a/apps/mes/app/routes.ts
+++ b/apps/mes/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { remixRoutesOptionAdapter } from "@react-router/remix-routes-option-adapter";
import { flatRoutes } from "remix-flat-routes";
diff --git a/apps/mes/app/routes/_index.tsx b/apps/mes/app/routes/_index.tsx
index 40207019ac..28ac58b332 100644
--- a/apps/mes/app/routes/_index.tsx
+++ b/apps/mes/app/routes/_index.tsx
@@ -1,5 +1,6 @@
import { requireAuthSession } from "@carbon/auth/session.server";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
index d3001672f9..8dcf9121fa 100644
--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]pdf.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntity } from "~/services/operations.service";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
index dc2d152c6d..739d407eb4 100644
--- a/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
+++ b/apps/mes/app/routes/file+/entity+/$id.labels[.]zpl.tsx
@@ -1,7 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntity } from "~/services/operations.service";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
index 2fb4be61d1..b5ead102df 100644
--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]pdf.tsx
@@ -2,7 +2,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { ProductLabelPDF } from "@carbon/documents/pdf";
import { labelSizes } from "@carbon/utils";
import { renderToStream } from "@react-pdf/renderer";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntitiesByOperationId } from "~/services/operations.service";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
index e4d0b10478..1c2b4a5ca8 100644
--- a/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
+++ b/apps/mes/app/routes/file+/operation+/$id.labels[.]zpl.tsx
@@ -1,7 +1,8 @@
import { requirePermissions } from "@carbon/auth/auth.server";
import { generateProductLabelZPL } from "@carbon/documents/zpl";
import { labelSizes } from "@carbon/utils";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getCompanySettings } from "~/services/inventory.service";
import { getTrackedEntitiesByMakeMethodId } from "~/services/operations.service";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
index 8e7e9b8ec8..fc0bf4071e 100644
--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
const supportedFileTypes: Record<string, string> = {
pdf: "application/pdf",
diff --git a/apps/mes/app/routes/file+/preview+/image.tsx b/apps/mes/app/routes/file+/preview+/image.tsx
index e1ff07b94a..85c38a74f4 100644
--- a/apps/mes/app/routes/file+/preview+/image.tsx
+++ b/apps/mes/app/routes/file+/preview+/image.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { type LoaderFunctionArgs } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
import { path } from "~/utils/path";
// this route exists so we can apply some styles to the preview iframe
diff --git a/apps/mes/app/routes/x+/adjustment.tsx b/apps/mes/app/routes/x+/adjustment.tsx
index 823b65c282..dcd0e45b83 100644
--- a/apps/mes/app/routes/x+/adjustment.tsx
+++ b/apps/mes/app/routes/x+/adjustment.tsx
@@ -1,7 +1,7 @@
import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validationError, validator } from "@carbon/form";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import {
insertManualInventoryAdjustment,
inventoryAdjustmentValidator
diff --git a/apps/mes/app/routes/x+/company.switch.$companyId.tsx b/apps/mes/app/routes/x+/company.switch.$companyId.tsx
index 1113d696c6..09f90587ac 100644
--- a/apps/mes/app/routes/x+/company.switch.$companyId.tsx
+++ b/apps/mes/app/routes/x+/company.switch.$companyId.tsx
@@ -6,7 +6,8 @@ import {
flash,
updateCompanySession
} from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getLocation, setLocation } from "~/services/location.server";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
index 05f394a3d0..8264c6e88c 100644
--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.item.tsx
@@ -7,7 +7,8 @@ import {
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { addMaintenanceDispatchItem } from "~/services/maintenance.service";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
index 53eb63324e..cf564d6b42 100644
--- a/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
+++ b/apps/mes/app/routes/x+/dispatch.$dispatchId.tsx
@@ -1,5 +1,5 @@
import { requirePermissions } from "@carbon/auth/auth.server";
-import { Database } from "@carbon/database";
+import type { Database } from "@carbon/database";
import { Hidden, ValidatedForm } from "@carbon/form";
import {
Button,
diff --git a/apps/mes/app/routes/x+/dispatch.new.tsx b/apps/mes/app/routes/x+/dispatch.new.tsx
index cf314b8c94..e92e78d5c2 100644
--- a/apps/mes/app/routes/x+/dispatch.new.tsx
+++ b/apps/mes/app/routes/x+/dispatch.new.tsx
@@ -11,7 +11,8 @@ import type { notifyTask } from "@carbon/jobs/trigger/notify";
import { NotificationEvent } from "@carbon/notifications";
import { getLocalTimeZone, now } from "@internationalized/date";
import { tasks } from "@trigger.dev/sdk";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import { maintenanceDispatchValidator } from "~/services/models";
import { endProductionEventsByWorkCenter } from "~/services/operations.service";
import { path } from "~/utils/path";
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index 61005c6487..b476f6fdb5 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -2,7 +2,8 @@ import { error, getCarbonServiceRole, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs } from "react-router";
+import { redirect } from "react-router";
import {
finishJobOperation,
getTrackedEntitiesByMakeMethodId,
diff --git a/apps/mes/app/routes/x+/entity+/$id.convert.tsx b/apps/mes/app/routes/x+/entity+/$id.convert.tsx
index be1260d9da..511f04a350 100644
--- a/apps/mes/app/routes/x+/entity+/$id.convert.tsx
+++ b/apps/mes/app/routes/x+/entity+/$id.convert.tsx
@@ -1,7 +1,8 @@
import { assertIsPost, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { convertEntityValidator } from "~/services/models";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx b/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx
index 1f22c23550..0fe3af9611 100644
--- a/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx
+++ b/apps/mes/app/routes/x+/entity+/$materialId.$trackedEntityId.scrap.tsx
@@ -1,7 +1,8 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { getTrackedEntity } from "~/services/operations.service";
export async function action({ request, params }: ActionFunctionArgs) {
diff --git a/apps/mes/app/routes/x+/event.tsx b/apps/mes/app/routes/x+/event.tsx
index 00fc938b24..daa0cc583c 100644
--- a/apps/mes/app/routes/x+/event.tsx
+++ b/apps/mes/app/routes/x+/event.tsx
@@ -3,7 +3,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { getLocalTimeZone, now } from "@internationalized/date";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { productionEventValidator } from "~/services/models";
import {
endProductionEvent,
diff --git a/apps/mes/app/routes/x+/feedback.tsx b/apps/mes/app/routes/x+/feedback.tsx
index 89bc30e465..7d0410955f 100644
--- a/apps/mes/app/routes/x+/feedback.tsx
+++ b/apps/mes/app/routes/x+/feedback.tsx
@@ -2,7 +2,7 @@ import { getCarbonServiceRole, SUPABASE_URL } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { validator } from "@carbon/form";
import { getSlackClient } from "@carbon/lib/slack.server";
-import { type ActionFunctionArgs } from "react-router";
+import type { ActionFunctionArgs } from "react-router";
import { feedbackValidator } from "~/services/models";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/mes/app/routes/x+/maintenance-event.tsx b/apps/mes/app/routes/x+/maintenance-event.tsx
index efb7a8e052..36f9e1a4fa 100644
--- a/apps/mes/app/routes/x+/maintenance-event.tsx
+++ b/apps/mes/app/routes/x+/maintenance-event.tsx
@@ -7,7 +7,8 @@ import {
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { getLocalTimeZone, now } from "@internationalized/date";
-import { type ActionFunctionArgs, data, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data, redirect } from "react-router";
import {
endMaintenanceEvent,
startMaintenanceEvent,
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
index 70a11a5175..e626966ba6 100644
--- a/apps/mes/app/routes/x+/scrap.tsx
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -8,7 +8,8 @@ import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { validationError, validator } from "@carbon/form";
import { FunctionRegion } from "@supabase/supabase-js";
-import { type ActionFunctionArgs, data } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { data } from "react-router";
import { scrapQuantityValidator } from "~/services/models";
import { insertScrapQuantity } from "~/services/operations.service";
diff --git a/apps/mes/app/routes/x+/start.$operationId.tsx b/apps/mes/app/routes/x+/start.$operationId.tsx
index 2dcc689c59..0c0a8ebc5b 100644
--- a/apps/mes/app/routes/x+/start.$operationId.tsx
+++ b/apps/mes/app/routes/x+/start.$operationId.tsx
@@ -2,7 +2,8 @@ import { error, getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { getLocalTimeZone, now } from "@internationalized/date";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { getWorkCenterWithBlockingStatus } from "~/services/maintenance.service";
import {
getTrackedEntitiesByMakeMethodId,
diff --git a/apps/starter/app/root.tsx b/apps/starter/app/root.tsx
index 8f97ae2d5a..9bdf918eef 100644
--- a/apps/starter/app/root.tsx
+++ b/apps/starter/app/root.tsx
@@ -6,7 +6,8 @@ import { useMode } from "@carbon/remix";
import type { Theme } from "@carbon/utils";
import { modeValidator, themes } from "@carbon/utils";
import { Analytics } from "@vercel/analytics/react";
-import React, { useEffect } from "react";
+import type React from "react";
+import { useEffect } from "react";
import type {
ActionFunctionArgs,
LoaderFunctionArgs,
diff --git a/apps/starter/app/routes.ts b/apps/starter/app/routes.ts
index 66d6f7384c..1b20b9ace7 100644
--- a/apps/starter/app/routes.ts
+++ b/apps/starter/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { remixRoutesOptionAdapter } from "@react-router/remix-routes-option-adapter";
import { flatRoutes } from "remix-flat-routes";
diff --git a/apps/starter/app/routes/_index.tsx b/apps/starter/app/routes/_index.tsx
index c08d984afb..05a953fa1d 100644
--- a/apps/starter/app/routes/_index.tsx
+++ b/apps/starter/app/routes/_index.tsx
@@ -1,5 +1,6 @@
import { requireAuthSession } from "@carbon/auth/session.server";
-import { type LoaderFunctionArgs, redirect } from "react-router";
+import type { LoaderFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
export async function loader({ request }: LoaderFunctionArgs) {
diff --git a/apps/starter/app/routes/x+/_index.tsx b/apps/starter/app/routes/x+/_index.tsx
index 45250f8df0..41be04abc8 100644
--- a/apps/starter/app/routes/x+/_index.tsx
+++ b/apps/starter/app/routes/x+/_index.tsx
@@ -1,7 +1,8 @@
import { cn, Heading } from "@carbon/react";
import { getLocalTimeZone } from "@internationalized/date";
import { useLocale } from "@react-aria/i18n";
-import { type ComponentProps, useMemo } from "react";
+import type { ComponentProps, } from "react";
+import { useMemo } from "react";
import { useUser } from "~/hooks";
export default function AppIndexRoute() {
diff --git a/apps/starter/app/routes/x+/company.switch.$companyId.tsx b/apps/starter/app/routes/x+/company.switch.$companyId.tsx
index 64d0e7a14d..8f804c1649 100644
--- a/apps/starter/app/routes/x+/company.switch.$companyId.tsx
+++ b/apps/starter/app/routes/x+/company.switch.$companyId.tsx
@@ -6,7 +6,8 @@ import {
flash,
updateCompanySession
} from "@carbon/auth/session.server";
-import { type ActionFunctionArgs, redirect } from "react-router";
+import type { ActionFunctionArgs, } from "react-router";
+import { redirect } from "react-router";
import { path, requestReferrer } from "~/utils/path";
diff --git a/biome.jsonc b/biome.jsonc
index 99f5afa03e..0fb0eaaac9 100644
--- a/biome.jsonc
+++ b/biome.jsonc
@@ -72,7 +72,15 @@
"noDangerouslySetInnerHtmlWithChildren": "warn",
"noGlobalEval": "error"
},
- "style": { "useArrayLiterals": "warn" },
+ "style": {
+ "useArrayLiterals": "warn",
+ "useImportType": {
+ "level": "error",
+ "options": {
+ "style": "auto"
+ }
+ }
+ },
"suspicious": {
"noCatchAssign": "warn",
"noCommentText": "warn",
diff --git a/examples/quote-configurator/app/root.tsx b/examples/quote-configurator/app/root.tsx
index 30bb7961eb..52199b19ee 100644
--- a/examples/quote-configurator/app/root.tsx
+++ b/examples/quote-configurator/app/root.tsx
@@ -1,5 +1,5 @@
import { Toaster } from "@carbon/react";
-import React from "react";
+import type React from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
isRouteErrorResponse,
diff --git a/examples/quote-configurator/app/routes.ts b/examples/quote-configurator/app/routes.ts
index 4c05936cb6..30b5e6f3d7 100644
--- a/examples/quote-configurator/app/routes.ts
+++ b/examples/quote-configurator/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export default flatRoutes() satisfies RouteConfig;
diff --git a/examples/quote-configurator/vite.config.ts b/examples/quote-configurator/vite.config.ts
index 848e68ec42..ec667330dd 100644
--- a/examples/quote-configurator/vite.config.ts
+++ b/examples/quote-configurator/vite.config.ts
@@ -1,5 +1,6 @@
import { reactRouter } from "@react-router/dev/vite";
-import { defineConfig, PluginOption } from "vite";
+import type { PluginOption } from "vite";
+import { defineConfig, } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
diff --git a/examples/upload-3d-model/app/root.tsx b/examples/upload-3d-model/app/root.tsx
index 75d6f28f5f..1b311ef32d 100644
--- a/examples/upload-3d-model/app/root.tsx
+++ b/examples/upload-3d-model/app/root.tsx
@@ -1,5 +1,5 @@
import { Toaster } from "@carbon/react";
-import React from "react";
+import type React from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
import {
isRouteErrorResponse,
diff --git a/examples/upload-3d-model/app/routes.ts b/examples/upload-3d-model/app/routes.ts
index 4c05936cb6..30b5e6f3d7 100644
--- a/examples/upload-3d-model/app/routes.ts
+++ b/examples/upload-3d-model/app/routes.ts
@@ -1,4 +1,4 @@
-import { type RouteConfig } from "@react-router/dev/routes";
+import type { RouteConfig } from "@react-router/dev/routes";
import { flatRoutes } from "@react-router/fs-routes";
export default flatRoutes() satisfies RouteConfig;
diff --git a/examples/upload-3d-model/vite.config.ts b/examples/upload-3d-model/vite.config.ts
index 9f50b5fab4..35cc2147ee 100644
--- a/examples/upload-3d-model/vite.config.ts
+++ b/examples/upload-3d-model/vite.config.ts
@@ -1,5 +1,6 @@
import { reactRouter } from "@react-router/dev/vite";
-import { defineConfig, PluginOption } from "vite";
+import type { PluginOption } from "vite";
+import { defineConfig, } from "vite";
import tsconfigPaths from "vite-tsconfig-paths";
export default defineConfig({
diff --git a/llm/cache/accounting-sync-handlers.md b/llm/cache/accounting-sync-handlers.md
new file mode 100644
index 0000000000..f177a8af0f
--- /dev/null
+++ b/llm/cache/accounting-sync-handlers.md
@@ -0,0 +1,356 @@
+# Accounting Sync Handlers
+
+## Overview
+
+The accounting sync system in Carbon uses trigger.dev tasks to synchronize data between accounting providers (like Xero) and the Carbon ERP system. Two main sync tasks exist:
+- `from-accounting-sync`: Syncs data FROM accounting provider TO Carbon
+- `to-accounting-sync`: Syncs data FROM Carbon TO accounting provider
+
+## Handler Structure
+
+### Handler Architecture
+
+Both sync tasks use a **handler map pattern** where handlers are organized by entity type and operation:
+
+```typescript
+// UPSERT_MAP: handles create/update/sync operations
+const UPSERT_MAP: Record<keyof EntityMap, SyncFn> = {
+ async customer({ client, entity, payload, provider }) { ... },
+ async vendor({ client, entity, payload, provider }) { ... },
+};
+
+// DELETE_MAP: handles delete operations
+const DELETE_MAP: Record<keyof EntityMap, SyncFn> = {
+ async customer({ client, entity, payload, provider }) { ... },
+ async vendor({ client, entity, payload, provider }) { ... },
+};
+```
+
+### SyncFn Type Definition
+
+```typescript
+type SyncFn = (input: {
+ client: SupabaseClient<Database>; // Supabase client for database queries
+ kysely: ReturnType<typeof getPostgresClient>; // Kysely ORM client
+ entity: AccountingEntity; // The entity being synced
+ provider: AccountingProvider; // The provider integration instance
+ payload: AccountingSyncPayload; // Full sync payload with metadata
+}) => Promise<any> | any;
+```
+
+### EntityMap
+
+```typescript
+type AccountingEntityType = "customer" | "vendor";
+
+interface EntityMap {
+ customer: Accounting.Contact;
+ vendor: Accounting.Contact;
+}
+
+// Both entity types map to Accounting.Contact schema
+namespace Accounting {
+ export type Contact = z.infer<typeof ContactSchema>;
+}
+```
+
+## Entity Types
+
+### Currently Implemented
+
+- **customer**: Maps to accounting provider contacts (with `isCustomer: true`)
+- **vendor**: Maps to accounting provider contacts (with `isVendor: true`)
+
+### Commented/Future Support
+
+- bill (Purchase Invoice)
+- employee
+- invoice
+- item
+- purchase_order
+- sales_order
+- inventory_adjustment
+
+## AccountingEntity Structure
+
+```typescript
+interface AccountingEntity<T extends AccountingEntityType = AccountingEntityType> {
+ entityType: T; // "customer" | "vendor"
+ entityId: string; // External ID from provider
+ operation: "create" | "update" | "delete" | "sync";
+ lastSyncedAt?: string; // Optional timestamp of last sync
+}
+```
+
+## AccountingSyncPayload
+
+```typescript
+interface AccountingSyncPayload {
+ companyId: string;
+ provider: ProviderID; // "xero" (QuickBooks commented out)
+ syncType: "webhook" | "scheduled" | "trigger";
+ syncDirection: "from-accounting" | "to-accounting" | "bi-directional";
+ entities: AccountingEntity[];
+ metadata?: {
+ tenantId?: string;
+ webhookId?: string;
+ userId?: string;
+ [key: string]: any;
+ };
+}
+```
+
+## Handler Invocation Flow
+
+1. **Parse & Validate**: PayloadSchema validates input
+2. **Get Integration**: `getAccountingIntegration()` fetches integration metadata
+3. **Get Provider**: `getProviderIntegration()` instantiates provider class (XeroProvider)
+4. **Iterate Entities**: For each entity in payload:
+ - Determine operation type (upsert vs delete)
+ - Select handler from UPSERT_MAP or DELETE_MAP based on entityType
+ - Execute handler with context
+ - Collect results (success/failed)
+5. **Return Results**: Returns object with success[] and failed[] arrays
+
+## From-Accounting-Sync Task
+
+**File**: `/Users/sidwebworks/Documents/work/carbon/packages/jobs/trigger/from-accounting-sync.ts`
+
+**Task ID**: `from-accounting-sync`
+
+**Sync Direction**: Only accepts "from-accounting" (not "to-accounting")
+
+### Customer Handler (Implemented)
+
+```typescript
+async customer({ client, entity, payload, provider }) {
+ try {
+ // 1. Check if customer already exists by external ID
+ const customer = await getEntityWithExternalId(
+ client,
+ "customer",
+ payload.companyId,
+ provider.id,
+ { externalId: entity.entityId }
+ );
+
+ // 2. Fetch full contact data from provider
+ const remote = await provider.contacts.get(entity.entityId);
+
+ // 3. Atomic transaction:
+ // - Upsert customer
+ const customerId = await upsertCustomerFromAccounting(
+ tx,
+ remote,
+ { companyId: payload.companyId, provider: provider.id },
+ customer?.id
+ );
+
+ // - Upsert contact and link to customer
+ await upsertContactAndLinkToCustomer(tx, remote, customerId, {
+ companyId: payload.companyId,
+ provider: provider.id,
+ });
+
+ return { id: entity.entityId, message: "Created successfully" };
+ } catch (error) {
+ return { id: entity.entityId, message: `Failed to upsert customer: ${error.message}` };
+ }
+}
+```
+
+### Vendor Handler (Stub)
+
+```typescript
+async vendor({ client, entity, payload, provider }) {
+ // Empty - not yet implemented
+}
+```
+
+## To-Accounting-Sync Task
+
+**File**: `/Users/sidwebworks/Documents/work/carbon/packages/jobs/trigger/to-accounting-sync.ts`
+
+**Task ID**: `to-accounting-sync`
+
+**Sync Direction**: Only accepts "to-accounting" (not "from-accounting")
+
+### Customer Handler (Stub with Commented Code)
+
+```typescript
+async customer({ client, entity, payload, provider }) {
+ const customer = await getEntityWithExternalId(
+ client,
+ "customer",
+ payload.companyId,
+ provider.id,
+ { id: entity.entityId }
+ );
+
+ // Commented out - would call provider.contacts.upsert(data)
+
+ return {
+ id: entity.entityId,
+ message: "Upserted successfully",
+ };
+}
+```
+
+### Vendor Handler (Stub)
+
+```typescript
+async vendor({ client, entity, payload, provider }) {
+ // Empty - not yet implemented
+}
+```
+
+## Key Implementation Patterns
+
+### Pattern 1: External ID Lookup via externalIntegrationMapping
+```typescript
+// Lookups now use the externalIntegrationMapping table instead of a JSONB column.
+const customer = await getEntityWithExternalId(
+ client,
+ "customer", // entityType in externalIntegrationMapping
+ companyId,
+ provider.id, // integration in externalIntegrationMapping
+ { externalId: entity.entityId } // matches externalIntegrationMapping.externalId
+);
+```
+
+### Pattern 2: Provider Abstraction
+Provider instances (XeroProvider) expose standardized interfaces:
+- `provider.contacts.get(id)`: Fetch single contact from provider
+- `provider.contacts.upsert(data)`: Upsert contact to provider
+
+### Pattern 3: Atomic Transactions
+For from-accounting sync, customer creation uses Kysely transactions:
+```typescript
+await kysely.transaction().execute(async (tx) => {
+ const customerId = await upsertCustomerFromAccounting(tx, ...);
+ await upsertContactAndLinkToCustomer(tx, ...);
+});
+```
+
+### Pattern 4: Error Handling in Loops
+Handlers can return error objects instead of throwing:
+```typescript
+{
+ id: entity.entityId,
+ message: `Failed to upsert customer: ${error.message}`
+}
+```
+
+Results accumulate in success[] and failed[] arrays.
+
+## External ID Storage (externalIntegrationMapping table)
+
+External IDs are now stored in a dedicated `externalIntegrationMapping` table instead of JSONB columns on each entity table. The old `externalId` JSONB columns have been dropped from all entity tables.
+
+### Table Schema
+
+```sql
+CREATE TABLE "externalIntegrationMapping" (
+ "id" TEXT NOT NULL DEFAULT id(),
+ "entityType" TEXT NOT NULL, -- 'customer', 'supplier', 'item', 'contact', etc.
+ "entityId" TEXT NOT NULL, -- The internal Carbon ID
+ "integration" TEXT NOT NULL, -- 'xero', 'linear', 'quickbooks', etc.
+ "externalId" TEXT, -- The ID in the external system (nullable)
+ "allowDuplicateExternalId" BOOLEAN NOT NULL DEFAULT false,
+ "metadata" JSONB, -- Provider-specific extras
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "remoteUpdatedAt" TIMESTAMP WITH TIME ZONE,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT,
+ "companyId" TEXT NOT NULL,
+
+ -- One mapping per integration per entity (always enforced)
+ CONSTRAINT ... UNIQUE ("entityType", "entityId", "integration", "companyId")
+);
+```
+
+### Key Constraints
+
+- **One-to-one by default**: A unique constraint on `(entityType, entityId, integration, companyId)` ensures one mapping per integration per entity.
+- **External ID uniqueness**: A partial unique index on `(integration, externalId, entityType, companyId)` enforces uniqueness when `allowDuplicateExternalId = false`.
+- **Many-to-one support**: When `allowDuplicateExternalId = true`, multiple Carbon entities can map to the same external ID.
+
+### Query Patterns
+
+```sql
+-- Find Carbon entity by external ID
+SELECT "entityId" FROM "externalIntegrationMapping"
+WHERE "integration" = 'xero'
+ AND "externalId" = 'remote-contact-id'
+ AND "entityType" = 'customer'
+ AND "companyId" = '...';
+
+-- Find external ID for a Carbon entity
+SELECT "externalId", "metadata" FROM "externalIntegrationMapping"
+WHERE "entityType" = 'customer'
+ AND "entityId" = '...'
+ AND "integration" = 'xero';
+```
+
+### Backward-Compatible Views
+
+Database views (e.g. `suppliers`, `customers`, `parts`, `materials`, `tools`, `consumables`, `services`, `salesOrders`) reconstruct the old JSONB format using a subquery:
+
+```sql
+(
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'customer' AND eim."entityId" = c.id
+) AS "externalId"
+```
+
+This allows existing application code reading from views to continue working without changes.
+
+## Related Services & Utilities
+
+### From-Accounting Specific:
+- `upsertCustomerFromAccounting()`: Creates or updates customer from provider contact
+- `upsertContactAndLinkToCustomer()`: Creates contact and links to customer with conflict resolution
+
+### Shared:
+- `getAccountingIntegration()`: Fetches integration config by provider ID
+- `getProviderIntegration()`: Instantiates provider class (XeroProvider)
+- `getEntityWithExternalId()`: Queries entity via `externalIntegrationMapping` table by provider's external ID
+
+## Task Configuration
+
+Both tasks use Trigger.dev v4 SDK:
+
+```typescript
+task({
+ id: "from-accounting-sync" | "to-accounting-sync",
+ retry: { maxAttempts: 2, randomize: true },
+ run: async (input: Payload) => { ... }
+})
+```
+
+## Status of Implementation
+
+- **from-accounting-sync customer**: FULLY IMPLEMENTED
+- **to-accounting-sync customer**: STUBBED (commented logic for upsert)
+- **Both vendor handlers**: NOT IMPLEMENTED (empty)
+
+## Next Steps for Vendor Support
+
+To implement vendor handlers:
+
+1. Create handler functions in both UPSERT_MAP and DELETE_MAP
+2. Use similar patterns as customer handlers
+3. Determine if vendors map to accounting provider contacts or separate entity
+4. Create externalIntegrationMapping entries for vendor entity mappings
+5. Handle bi-directional sync if needed
diff --git a/llm/cache/linear-integration.md b/llm/cache/linear-integration.md
index 03ad512fd0..ebfc0f1f7b 100644
--- a/llm/cache/linear-integration.md
+++ b/llm/cache/linear-integration.md
@@ -62,14 +62,15 @@ LinearIssueSchema = {
**Functions:**
- `linkActionToLinearIssue()` - Links Carbon action task to Linear issue
- - Stores Linear issue data in `externalId.linear` JSON field
+ - Creates/updates a row in `externalIntegrationMapping` with `entityType='nonConformanceActionTask'`, `integration='linear'`
+ - Stores Linear issue data in the `metadata` JSONB field and the Linear issue ID in `externalId`
- Updates assignee if Linear assignee matches Carbon employee
- Syncs status and due date
- Returns `nonConformanceId` for creating backlink
-- `unlinkActionFromLinearIssue()` - Removes link by clearing `externalId.linear`
+- `unlinkActionFromLinearIssue()` - Removes link by deleting the `externalIntegrationMapping` row for the action task
-- `getLinearIssueFromExternalId()` - Retrieves Linear issue data from action task
+- `getLinearIssueFromExternalId()` - Retrieves Linear issue data from `externalIntegrationMapping.metadata`
- `getCompanyEmployees()` - Finds Carbon employees by email addresses
@@ -96,9 +97,9 @@ Route: `/api/integrations.linear.issue.link`
- POST: Links Carbon action task to existing Linear issue
- Fetches Linear issue by ID
- Maps Linear assignee to Carbon user (by email)
- - Stores issue data in `nonConformanceActionTask.externalId.linear`
+ - Creates `externalIntegrationMapping` row linking action task to Linear issue (stores issue data in `metadata`)
- Creates attachment link back to Carbon issue
-- DELETE: Unlinks by clearing `externalId.linear`
+- DELETE: Unlinks by deleting the `externalIntegrationMapping` row
- GET: Search Linear issues by title query
**2. Create New Issue**
@@ -116,13 +117,13 @@ Listens for Carbon events and updates Linear:
**Event: `task.status.changed`**
- Only processes action/investigation tasks
-- Gets linked Linear issue from `externalId`
+- Gets linked Linear issue from `externalIntegrationMapping` (where `entityType='nonConformanceActionTask'` and `integration='linear'`)
- Maps Carbon status to Linear workflow state
- Updates Linear issue state via API
**Event: `task.assigned`**
- Only processes `nonConformanceActionTask` table
-- Gets linked Linear issue
+- Gets linked Linear issue from `externalIntegrationMapping`
- Finds Linear user by Carbon employee email
- Updates Linear issue assignee
@@ -138,7 +139,7 @@ Listens for Carbon events and updates Linear:
`syncIssueFromLinear` task:
- Accepts event type: `Issue` with action: `update`
-- Finds linked Carbon action by `externalId->linear->>id`
+- Finds linked Carbon action via `externalIntegrationMapping` (where `integration='linear'` and `externalId` = Linear issue ID)
- Maps Linear assignee to Carbon employee (by email)
- Updates Carbon action task with:
- Latest Linear issue state (title, description, state, url)
@@ -172,7 +173,7 @@ Listens for Carbon events and updates Linear:
#### Linking Flow (Carbon → Linear)
1. User selects Linear issue or creates new one in Carbon UI
2. Carbon fetches issue details from Linear API
-3. Carbon stores issue in `nonConformanceActionTask.externalId.linear`
+3. Carbon creates an `externalIntegrationMapping` row linking the action task to the Linear issue
4. Carbon syncs assignee (if Linear assignee email matches Carbon employee)
5. Carbon creates attachment link in Linear pointing back to Carbon issue
@@ -188,36 +189,49 @@ Listens for Carbon events and updates Linear:
1. User changes task status or assignee in Carbon
2. Carbon notification pipeline detects change
3. If Linear integration is active, notification service triggers
-4. Service finds linked Linear issue from `externalId`
+4. Service finds linked Linear issue from `externalIntegrationMapping`
5. Service updates Linear issue via API
### Database Schema
-**Storage of Link:**
+**Storage of Link (externalIntegrationMapping table):**
+
+The old `externalId` JSONB column on `nonConformanceActionTask` has been replaced by a row in the `externalIntegrationMapping` table:
+
```sql
--- nonConformanceActionTask table
-externalId JSONB
- Contains: {
- linear: {
- id: string,
- title: string,
- description: string,
- url: string,
- state: { name, color, type },
- identifier: string,
- dueDate: string | null,
- assignee: { email: string } | null
- }
- }
+-- externalIntegrationMapping row for a linked Linear issue
+entityType = 'nonConformanceActionTask'
+entityId = <action task ID>
+integration = 'linear'
+externalId = <Linear issue ID>
+metadata = {
+ "id": "...",
+ "title": "...",
+ "description": "...",
+ "url": "...",
+ "state": { "name": "...", "color": "...", "type": "..." },
+ "identifier": "...",
+ "dueDate": "..." | null,
+ "assignee": { "email": "..." } | null
+}
+companyId = <company ID>
```
**Querying Linked Issues:**
-```typescript
-// Find action by Linear issue ID
-.eq("externalId->linear->>id", linearIssueId)
-
-// Check if action has Linear link
-.not("externalId->linear", "is", null)
+```sql
+-- Find action task by Linear issue ID
+SELECT "entityId" FROM "externalIntegrationMapping"
+WHERE "integration" = 'linear'
+ AND "externalId" = '<linearIssueId>'
+ AND "entityType" = 'nonConformanceActionTask';
+
+-- Check if action task has a Linear link
+SELECT EXISTS(
+ SELECT 1 FROM "externalIntegrationMapping"
+ WHERE "entityType" = 'nonConformanceActionTask'
+ AND "entityId" = '<actionTaskId>'
+ AND "integration" = 'linear'
+);
```
### UI Components
@@ -230,7 +244,7 @@ Located in `/apps/erp/app/modules/quality/ui/Issue/Linear/`:
Display in `/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx`:
- Shows Linear badge with issue identifier
- Links to Linear issue URL
-- Displays on action tasks with `externalId.linear` data
+- Displays on action tasks that have a Linear mapping in `externalIntegrationMapping`
### Notification Pipeline
@@ -265,7 +279,7 @@ Display in `/apps/erp/app/modules/quality/ui/Issue/IssueTask.tsx`:
- Only **action tasks** can be linked to Linear issues (not investigation or approval tasks)
- Assignee sync requires matching email between Linear user and Carbon employee
- Two-way sync means changes in either system update the other
-- Linear issue data is cached in Carbon's `externalId` field as JSON
+- Linear issue data is stored in `externalIntegrationMapping` table (issue ID in `externalId`, full issue data in `metadata` JSONB)
- Attachment links in Linear point back to Carbon issue details page
- Webhook processes updates asynchronously via Trigger.dev
- Integration must be active (`companyIntegration.active = true`) for notifications to flow
diff --git a/llm/cache/material-tables.md b/llm/cache/material-tables.md
index b0216b401c..ea4dd9bcbb 100644
--- a/llm/cache/material-tables.md
+++ b/llm/cache/material-tables.md
@@ -19,7 +19,6 @@ The main `material` table stores material records with the following columns:
- `approvedBy`: string | null
- `customFields`: Json | null
- `tags`: string[] | null
-- `externalId`: Json | null
- `createdAt`: string
- `createdBy`: string
- `updatedAt`: string | null
diff --git a/llm/cache/project-overview.md b/llm/cache/project-overview.md
index db22f0da38..a21f78afa8 100644
--- a/llm/cache/project-overview.md
+++ b/llm/cache/project-overview.md
@@ -28,7 +28,7 @@ Carbon is a manufacturing system built with modern web technologies. It consists
- **Monorepo**: NPM workspaces with Turbo
- **Bundler**: Vite
-- **Linting**: ESLint with custom config
+- **Linting**: Biome with custom config
- **Formatting**: Prettier
## Package Structure
diff --git a/package-lock.json b/package-lock.json
index f5dd6d415d..4916d628b1 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -34,7 +34,8 @@
"supabase": "2.54.11",
"ts-morph": "^22.0.0",
"tsx": "^4.13.2",
- "turbo": "^2.6.3"
+ "turbo": "^2.6.3",
+ "typescript": "5.8"
},
"optionalDependencies": {
"@rollup/rollup-linux-x64-gnu": "^4.0.0"
@@ -520,7 +521,9 @@
}
},
"node_modules/@ai-sdk-tools/artifacts/node_modules/zod": {
- "version": "4.3.4",
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.5.tgz",
+ "integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
@@ -595,7 +598,9 @@
}
},
"node_modules/@ai-sdk-tools/memory/node_modules/zod": {
- "version": "4.3.4",
+ "version": "4.3.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.3.5.tgz",
+ "integrity": "sha512-k7Nwx6vuWx1IJ9Bjuf4Zt1PEllcwe7cls3VNzm4CQ1/hgtFUK2bRNG3rvnpPUhFjmqJKAKtjV576KnUkHocg/g==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
@@ -615,7 +620,9 @@
}
},
"node_modules/@ai-sdk-tools/store/node_modules/@types/node": {
- "version": "24.10.4",
+ "version": "24.10.9",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.9.tgz",
+ "integrity": "sha512-ne4A0IpG3+2ETuREInjPNhUGis1SFjv1d5asp8MzEAGtOZeTeHVDOYqOgqfhvseqg/iXty2hjBf1zAOb7RNiNw==",
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
@@ -1797,137 +1804,562 @@
"version": "1.1.0",
"license": "MIT"
},
- "node_modules/@esbuild/darwin-arm64": {
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
+ "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
"version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.17.19.tgz",
+ "integrity": "sha512-rIKddzqhmav7MSmoFCmDIb6e2W57geRsM94gV2l38fzhXMwq7hZoClug9USI2pFRGL06f4IOPHHpFNOkWieR8A==",
"cpu": [
- "arm64"
+ "arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
- "darwin"
+ "android"
],
"engines": {
"node": ">=12"
}
},
- "node_modules/@floating-ui/core": {
- "version": "1.7.3",
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.17.19.tgz",
+ "integrity": "sha512-KBMWvEZooR7+kzY0BtbTQn0OAYY7CsiydT63pVEaPtVYF0hXbUaOyZog37DKxK7NF3XacBJOpYT4adIJh+avxA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@floating-ui/utils": "^0.2.10"
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@floating-ui/dom": {
- "version": "1.7.4",
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.17.19.tgz",
+ "integrity": "sha512-uUTTc4xGNDT7YSArp/zbtmbhO0uEEK9/ETW29Wk1thYUJBz3IVnvgEiEwEa9IeLyvnpKrWK64Utw2bgUmDveww==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@floating-ui/core": "^1.7.3",
- "@floating-ui/utils": "^0.2.10"
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@floating-ui/react-dom": {
- "version": "2.1.6",
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.17.19",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@floating-ui/dom": "^1.7.4"
- },
- "peerDependencies": {
- "react": ">=16.8.0",
- "react-dom": ">=16.8.0"
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@floating-ui/utils": {
- "version": "0.2.10",
- "license": "MIT"
- },
- "node_modules/@formatjs/ecma402-abstract": {
- "version": "2.3.6",
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.17.19.tgz",
+ "integrity": "sha512-IJM4JJsLhRYr9xdtLytPLSH9k/oxR3boaUIYiHkAawtwNOXKE8KoU8tMvryogdcT8AU+Bflmh81Xn6Q0vTZbQw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@formatjs/fast-memoize": "2.2.7",
- "@formatjs/intl-localematcher": "0.6.2",
- "decimal.js": "^10.4.3",
- "tslib": "^2.8.0"
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@formatjs/fast-memoize": {
- "version": "2.2.7",
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.17.19.tgz",
+ "integrity": "sha512-pBwbc7DufluUeGdjSU5Si+P3SoMF5DQ/F/UmTSb8HXO80ZEAJmrykPyzo1IfNbAoaqw48YRpv8shwd1NoI0jcQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "tslib": "^2.8.0"
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@formatjs/icu-messageformat-parser": {
- "version": "2.11.4",
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.17.19.tgz",
+ "integrity": "sha512-4lu+n8Wk0XlajEhbEffdy2xy53dpR06SlzvhGByyg36qJw6Kpfk7cp45DR/62aPH9mtJRmIyrXAS5UWBrJT6TQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@formatjs/ecma402-abstract": "2.3.6",
- "@formatjs/icu-skeleton-parser": "1.8.16",
- "tslib": "^2.8.0"
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@formatjs/icu-skeleton-parser": {
- "version": "1.8.16",
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.17.19.tgz",
+ "integrity": "sha512-cdmT3KxjlOQ/gZ2cjfrQOtmhG4HJs6hhvm3mWSRDPtZ/lP5oe8FWceS10JaSJC13GBd4eH/haHnqf7hhGNLerA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "@formatjs/ecma402-abstract": "2.3.6",
- "tslib": "^2.8.0"
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@formatjs/intl-localematcher": {
- "version": "0.6.2",
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.17.19.tgz",
+ "integrity": "sha512-ct1Tg3WGwd3P+oZYqic+YZF4snNl2bsnMKRkb3ozHmnM0dGWuxcPTTntAF6bOP0Sp4x0PjSF+4uHQ1xvxfRKqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
"license": "MIT",
- "dependencies": {
- "tslib": "^2.8.0"
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@google-cloud/precise-date": {
- "version": "4.0.0",
- "license": "Apache-2.0",
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.17.19.tgz",
+ "integrity": "sha512-w4IRhSy1VbsNxHRQpeGCHEmibqdTUx61Vc38APcsRbuVgK0OPEnQ0YD39Brymn96mOx48Y2laBQGqgZ0j9w6SQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
"engines": {
- "node": ">=14.0.0"
+ "node": ">=12"
}
},
- "node_modules/@hapi/hoek": {
- "version": "9.3.0",
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.17.19.tgz",
+ "integrity": "sha512-2iAngUbBPMq439a+z//gE+9WBldoMp1s5GWsUSgqHLzLJ9WoZLZhpwWuym0u0u/4XmZ3gpHmzV84PonE+9IIdQ==",
+ "cpu": [
+ "loong64"
+ ],
"dev": true,
- "license": "BSD-3-Clause"
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
},
- "node_modules/@hapi/topo": {
- "version": "5.1.0",
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.17.19.tgz",
+ "integrity": "sha512-LKJltc4LVdMKHsrFe4MGNPp0hqDFA1Wpt3jE1gEyM3nKUvOiO//9PheZZHfYRfYl6AwdTH4aTcXSqBerX0ml4A==",
+ "cpu": [
+ "mips64el"
+ ],
"dev": true,
- "license": "BSD-3-Clause",
- "dependencies": {
- "@hapi/hoek": "^9.0.0"
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@hookform/resolvers": {
- "version": "3.10.0",
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.17.19.tgz",
+ "integrity": "sha512-/c/DGybs95WXNS8y3Ti/ytqETiW7EU44MEKuCAcpPto3YjQbyK3IQVKfF6nbghD7EcLUGl0NbiL5Rt5DMhn5tg==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
"license": "MIT",
- "peerDependencies": {
- "react-hook-form": "^7.0.0"
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@humanwhocodes/momoa": {
- "version": "2.0.4",
- "license": "Apache-2.0",
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.17.19.tgz",
+ "integrity": "sha512-FC3nUAWhvFoutlhAkgHf8f5HwFWUL6bYdvLc/TTuxKlvLi3+pPzdZiFKSWz/PF30TB1K19SuCxDTI5KcqASJqA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
"engines": {
- "node": ">=10.10.0"
+ "node": ">=12"
}
},
- "node_modules/@internationalized/date": {
- "version": "3.10.1",
- "license": "Apache-2.0",
- "dependencies": {
- "@swc/helpers": "^0.5.0"
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.17.19.tgz",
+ "integrity": "sha512-IbFsFbxMWLuKEbH+7sTkKzL6NJmG2vRyy6K7JJo55w+8xDk7RElYn6xvXtDW8HCfoKBFK69f3pgBJSUSQPr+4Q==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
}
},
- "node_modules/@internationalized/message": {
- "version": "3.1.8",
- "license": "Apache-2.0",
- "dependencies": {
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.17.19.tgz",
+ "integrity": "sha512-68ngA9lg2H6zkZcyp22tsVt38mlhWde8l3eJLWkyLrp4HwMUr3c1s/M2t7+kHIhvMjglIBrFpncX1SzMckomGw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.17.19.tgz",
+ "integrity": "sha512-CwFq42rXCR8TYIjIfpXCbRX0rp1jo6cPIUPSaWwzbVI4aOfX96OXY8M6KNmtPcg7QjYeDmN+DD0Wp3LaBOLf4Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
+ "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.17.19.tgz",
+ "integrity": "sha512-cnq5brJYrSZ2CF6c35eCmviIN3k3RczmHz8eYaVlNasVqsNY+JKohZU5MKmaOI+KkllCdzOKKdPs762VCPC20g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.27.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
+ "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.17.19.tgz",
+ "integrity": "sha512-vCRT7yP3zX+bKWFeP/zdS6SqdWB8OIpaRq/mbXQxTGHnIxspRtigpkUcDMlSCOejlHowLqII7K2JKevwyRP2rg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.17.19.tgz",
+ "integrity": "sha512-yYx+8jwowUstVdorcMdNlzklLYhPxjniHWFKgRqH7IFlUEa0Umu3KuYplf1HUZZ422e3NU9F4LGb+4O0Kdcaag==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.17.19.tgz",
+ "integrity": "sha512-eggDKanJszUtCdlVs0RB+h35wNlb5v4TWEkq4vZcmVt5u/HiDZrTXe2bWFQUez3RgNHwx/x4sk5++4NSSicKkw==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.17.19",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.17.19.tgz",
+ "integrity": "sha512-lAhycmKnVOuRYNtRtatQR1LPQf2oYCkRGkSFnseDAKPl8lu5SOsK/e1sXe5a0Pc5kHIHe6P2I/ilntNv2xf3cA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@floating-ui/core": {
+ "version": "1.7.3",
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/utils": "^0.2.10"
+ }
+ },
+ "node_modules/@floating-ui/dom": {
+ "version": "1.7.4",
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/core": "^1.7.3",
+ "@floating-ui/utils": "^0.2.10"
+ }
+ },
+ "node_modules/@floating-ui/react-dom": {
+ "version": "2.1.6",
+ "license": "MIT",
+ "dependencies": {
+ "@floating-ui/dom": "^1.7.4"
+ },
+ "peerDependencies": {
+ "react": ">=16.8.0",
+ "react-dom": ">=16.8.0"
+ }
+ },
+ "node_modules/@floating-ui/utils": {
+ "version": "0.2.10",
+ "license": "MIT"
+ },
+ "node_modules/@formatjs/ecma402-abstract": {
+ "version": "2.3.6",
+ "license": "MIT",
+ "dependencies": {
+ "@formatjs/fast-memoize": "2.2.7",
+ "@formatjs/intl-localematcher": "0.6.2",
+ "decimal.js": "^10.4.3",
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@formatjs/fast-memoize": {
+ "version": "2.2.7",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@formatjs/icu-messageformat-parser": {
+ "version": "2.11.4",
+ "license": "MIT",
+ "dependencies": {
+ "@formatjs/ecma402-abstract": "2.3.6",
+ "@formatjs/icu-skeleton-parser": "1.8.16",
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@formatjs/icu-skeleton-parser": {
+ "version": "1.8.16",
+ "license": "MIT",
+ "dependencies": {
+ "@formatjs/ecma402-abstract": "2.3.6",
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@formatjs/intl-localematcher": {
+ "version": "0.6.2",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.8.0"
+ }
+ },
+ "node_modules/@google-cloud/precise-date": {
+ "version": "4.0.0",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/@hapi/hoek": {
+ "version": "9.3.0",
+ "dev": true,
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@hapi/topo": {
+ "version": "5.1.0",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@hapi/hoek": "^9.0.0"
+ }
+ },
+ "node_modules/@hookform/resolvers": {
+ "version": "3.10.0",
+ "license": "MIT",
+ "peerDependencies": {
+ "react-hook-form": "^7.0.0"
+ }
+ },
+ "node_modules/@humanwhocodes/momoa": {
+ "version": "2.0.4",
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=10.10.0"
+ }
+ },
+ "node_modules/@internationalized/date": {
+ "version": "3.10.1",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@swc/helpers": "^0.5.0"
+ }
+ },
+ "node_modules/@internationalized/message": {
+ "version": "3.1.8",
+ "license": "Apache-2.0",
+ "dependencies": {
"@swc/helpers": "^0.5.0",
"intl-messageformat": "^10.1.0"
}
@@ -3346,7 +3778,9 @@
}
},
"node_modules/@opentelemetry/semantic-conventions": {
- "version": "1.38.0",
+ "version": "1.39.0",
+ "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.39.0.tgz",
+ "integrity": "sha512-R5R9tb2AXs2IRLNKLBJDynhkfmx7mX0vi8NkhZb3gUkPWHn6HXk5J8iQ/dql0U3ApfWym4kXXmBDRGO+oeOfjg==",
"license": "Apache-2.0",
"engines": {
"node": ">=14"
@@ -5970,7 +6404,9 @@
}
},
"node_modules/@react-email/render/node_modules/prettier": {
- "version": "3.7.4",
+ "version": "3.8.0",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.0.tgz",
+ "integrity": "sha512-yEPsovQfpxYfgWNhCfECjG5AQaO+K3dp6XERmOepyPDVqcJm+bjyCVO3pmU+nAPe0N5dDvekfGezt/EIiRe1TA==",
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
@@ -6321,18 +6757,10 @@
}
}
},
- "node_modules/@react-router/dev/node_modules/jsesc": {
- "version": "3.0.2",
- "license": "MIT",
- "bin": {
- "jsesc": "bin/jsesc"
- },
- "engines": {
- "node": ">=6"
- }
- },
"node_modules/@react-router/dev/node_modules/prettier": {
- "version": "3.7.4",
+ "version": "3.8.0",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.0.tgz",
+ "integrity": "sha512-yEPsovQfpxYfgWNhCfECjG5AQaO+K3dp6XERmOepyPDVqcJm+bjyCVO3pmU+nAPe0N5dDvekfGezt/EIiRe1TA==",
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
@@ -7079,9 +7507,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
- "version": "1.23.0",
- "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.0.tgz",
- "integrity": "sha512-O3rHJzAQKamUz1fvE0Qaw0xSFqsA/yafi2iqeE0pvdFtCO1viYx8QL6f3Ln/aCCTLxs68SLf0KPM9eSeM8yBnA==",
+ "version": "1.23.2",
+ "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.2.tgz",
+ "integrity": "sha512-Ic6m2U/rMjTkhERIa/0ZtXJP17QUi2CbWE7cqx4J58M8aA3QTfW+2UlQ4psvTX9IO1RfNVhK3pcpdjej7L+t2w==",
"license": "MIT",
"peer": true,
"engines": {
@@ -7089,13 +7517,13 @@
}
},
"node_modules/@remix-run/server-runtime": {
- "version": "2.17.3",
- "resolved": "https://registry.npmjs.org/@remix-run/server-runtime/-/server-runtime-2.17.3.tgz",
- "integrity": "sha512-8uuV0COprImDpyDB8Rx0VLDKxsttBsMjtdv9BFViz8WfJz79jr8YRfp27hXUs9P4/NU6+wQQYcJawkBj/5uuSg==",
+ "version": "2.17.4",
+ "resolved": "https://registry.npmjs.org/@remix-run/server-runtime/-/server-runtime-2.17.4.tgz",
+ "integrity": "sha512-oCsFbPuISgh8KpPKsfBChzjcntvTz5L+ggq9VNYWX8RX3yA7OgQpKspRHOSxb05bw7m0Hx+L1KRHXjf3juKX8w==",
"license": "MIT",
"peer": true,
"dependencies": {
- "@remix-run/router": "1.23.0",
+ "@remix-run/router": "1.23.2",
"@types/cookie": "^0.6.0",
"@web3-storage/multipart-parser": "^1.0.0",
"cookie": "^0.7.2",
@@ -7120,50 +7548,351 @@
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
"license": "MIT",
- "peer": true
+ "peer": true
+ },
+ "node_modules/@remix-run/server-runtime/node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "peer": true,
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/@remix-run/server-runtime/node_modules/source-map": {
+ "version": "0.7.6",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
+ "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
+ "license": "BSD-3-Clause",
+ "peer": true,
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.55.1.tgz",
+ "integrity": "sha512-9R0DM/ykwfGIlNu6+2U09ga0WXeZ9MRC2Ter8jnz8415VbuIykVuc6bhdrbORFZANDmTDvq26mJrEVTl8TdnDg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.55.1.tgz",
+ "integrity": "sha512-eFZCb1YUqhTysgW3sj/55du5cG57S7UTNtdMjCW7LwVcj3dTTcowCsC8p7uBdzKsZYa8J7IDE8lhMI+HX1vQvg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.55.1.tgz",
+ "integrity": "sha512-p3grE2PHcQm2e8PSGZdzIhCKbMCw/xi9XvMPErPhwO17vxtvCN5FEA2mSLgmKlCjHGMQTP6phuQTYWUnKewwGg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.55.1.tgz",
+ "integrity": "sha512-rDUjG25C9qoTm+e02Esi+aqTKSBYwVTaoS1wxcN47/Luqef57Vgp96xNANwt5npq9GDxsH7kXxNkJVEsWEOEaQ==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.55.1.tgz",
+ "integrity": "sha512-+JiU7Jbp5cdxekIgdte0jfcu5oqw4GCKr6i3PJTlXTCU5H5Fvtkpbs4XJHRmWNXF+hKmn4v7ogI5OQPaupJgOg==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.55.1.tgz",
+ "integrity": "sha512-V5xC1tOVWtLLmr3YUk2f6EJK4qksksOYiz/TCsFHu/R+woubcLWdC9nZQmwjOAbmExBIVKsm1/wKmEy4z4u4Bw==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.55.1.tgz",
+ "integrity": "sha512-Rn3n+FUk2J5VWx+ywrG/HGPTD9jXNbicRtTM11e/uorplArnXZYsVifnPPqNNP5BsO3roI4n8332ukpY/zN7rQ==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.55.1.tgz",
+ "integrity": "sha512-grPNWydeKtc1aEdrJDWk4opD7nFtQbMmV7769hiAaYyUKCT1faPRm2av8CX1YJsZ4TLAZcg9gTR1KvEzoLjXkg==",
+ "cpu": [
+ "arm"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.55.1.tgz",
+ "integrity": "sha512-a59mwd1k6x8tXKcUxSyISiquLwB5pX+fJW9TkWU46lCqD/GRDe9uDN31jrMmVP3feI3mhAdvcCClhV8V5MhJFQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.55.1.tgz",
+ "integrity": "sha512-puS1MEgWX5GsHSoiAsF0TYrpomdvkaXm0CofIMG5uVkP6IBV+ZO9xhC5YEN49nsgYo1DuuMquF9+7EDBVYu4uA==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.55.1.tgz",
+ "integrity": "sha512-r3Wv40in+lTsULSb6nnoudVbARdOwb2u5fpeoOAZjFLznp6tDU8kd+GTHmJoqZ9lt6/Sys33KdIHUaQihFcu7g==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.55.1.tgz",
+ "integrity": "sha512-MR8c0+UxAlB22Fq4R+aQSPBayvYa3+9DrwG/i1TKQXFYEaoW3B5b/rkSRIypcZDdWjWnpcvxbNaAJDcSbJU3Lw==",
+ "cpu": [
+ "loong64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.55.1.tgz",
+ "integrity": "sha512-3KhoECe1BRlSYpMTeVrD4sh2Pw2xgt4jzNSZIIPLFEsnQn9gAnZagW9+VqDqAHgm1Xc77LzJOo2LdigS5qZ+gw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.55.1.tgz",
+ "integrity": "sha512-ziR1OuZx0vdYZZ30vueNZTg73alF59DicYrPViG0NEgDVN8/Jl87zkAPu4u6VjZST2llgEUjaiNl9JM6HH1Vdw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.55.1.tgz",
+ "integrity": "sha512-uW0Y12ih2XJRERZ4jAfKamTyIHVMPQnTZcQjme2HMVDAHY4amf5u414OqNYC+x+LzRdRcnIG1YodLrrtA8xsxw==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.55.1.tgz",
+ "integrity": "sha512-u9yZ0jUkOED1BFrqu3BwMQoixvGHGZ+JhJNkNKY/hyoEgOwlqKb62qu+7UjbPSHYjiVy8kKJHvXKv5coH4wDeg==",
+ "cpu": [
+ "riscv64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.55.1.tgz",
+ "integrity": "sha512-/0PenBCmqM4ZUd0190j7J0UsQ/1nsi735iPRakO8iPciE7BQ495Y6msPzaOmvx0/pn+eJVVlZrNrSh4WSYLxNg==",
+ "cpu": [
+ "s390x"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.55.1.tgz",
+ "integrity": "sha512-a8G4wiQxQG2BAvo+gU6XrReRRqj+pLS2NGXKm8io19goR+K8lw269eTrPkSdDTALwMmJp4th2Uh0D8J9bEV1vg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.55.1.tgz",
+ "integrity": "sha512-bD+zjpFrMpP/hqkfEcnjXWHMw5BIghGisOKPj+2NaNDuVT+8Ds4mPf3XcPHuat1tz89WRL+1wbcxKY3WSbiT7w==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.55.1.tgz",
+ "integrity": "sha512-eLXw0dOiqE4QmvikfQ6yjgkg/xDM+MdU9YJuP4ySTibXU0oAvnEWXt7UDJmD4UkYialMfOGFPJnIHSe/kdzPxg==",
+ "cpu": [
+ "x64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.55.1.tgz",
+ "integrity": "sha512-xzm44KgEP11te3S2HCSyYf5zIzWmx3n8HDCc7EE59+lTcswEWNpvMLfd9uJvVX8LCg9QWG67Xt75AuHn4vgsXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.55.1.tgz",
+ "integrity": "sha512-yR6Bl3tMC/gBok5cz/Qi0xYnVbIxGx5Fcf/ca0eB6/6JwOY+SRUcJfI0OpeTpPls7f194as62thCt/2BjxYN8g==",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
},
- "node_modules/@remix-run/server-runtime/node_modules/cookie": {
- "version": "0.7.2",
- "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
- "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.55.1.tgz",
+ "integrity": "sha512-3fZBidchE0eY0oFZBnekYCfg+5wAB0mbpCBuofh5mZuzIU/4jIVkbESmd2dOsFNS78b53CYv3OAtwqkZZmU5nA==",
+ "cpu": [
+ "ia32"
+ ],
"license": "MIT",
- "peer": true,
- "engines": {
- "node": ">= 0.6"
- }
- },
- "node_modules/@remix-run/server-runtime/node_modules/source-map": {
- "version": "0.7.6",
- "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz",
- "integrity": "sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==",
- "license": "BSD-3-Clause",
- "peer": true,
- "engines": {
- "node": ">= 12"
- }
+ "optional": true,
+ "os": [
+ "win32"
+ ]
},
- "node_modules/@rollup/rollup-darwin-arm64": {
- "version": "4.54.0",
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.55.1.tgz",
+ "integrity": "sha512-xGGY5pXj69IxKb4yv/POoocPy/qmEGhimy/FoTpTSVju3FYXUQQMFCaZZXJVidsmGxRioZAwpThl/4zX41gRKg==",
"cpu": [
- "arm64"
+ "x64"
],
"license": "MIT",
"optional": true,
"os": [
- "darwin"
+ "win32"
]
},
- "node_modules/@rollup/rollup-linux-x64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.54.0.tgz",
- "integrity": "sha512-WGt5J8Ij/rvyqpFexxk3ffKqqbLf9AqrTBbWDk7ApGUzaIs6V+s2s84kAxklFwmMF/vBNGrVdYgbblCOFFezMQ==",
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.55.1.tgz",
+ "integrity": "sha512-SPEpaL6DX4rmcXtnhdrQYgzQ5W2uW3SCJch88lB2zImhJRhIIK44fkUrgIV/Q8yUNfw5oyZ5vkeQsZLhCb06lw==",
"cpu": [
"x64"
],
"license": "MIT",
"optional": true,
"os": [
- "linux"
+ "win32"
]
},
"node_modules/@rvf/set-get": {
@@ -7382,6 +8111,15 @@
"@supabase/node-fetch": "^2.6.14"
}
},
+ "node_modules/@supabase/gotrue-js": {
+ "version": "2.62.2",
+ "resolved": "https://registry.npmjs.org/@supabase/gotrue-js/-/gotrue-js-2.62.2.tgz",
+ "integrity": "sha512-AP6e6W9rQXFTEJ7sTTNYQrNf0LCcnt1hUW+RIgUK+Uh3jbWvcIST7wAlYyNZiMlS9+PYyymWQ+Ykz/rOYSO0+A==",
+ "license": "MIT",
+ "dependencies": {
+ "@supabase/node-fetch": "^2.6.14"
+ }
+ },
"node_modules/@supabase/node-fetch": {
"version": "2.6.15",
"license": "MIT",
@@ -7502,7 +8240,9 @@
}
},
"node_modules/@tanstack/query-core": {
- "version": "4.41.0",
+ "version": "4.41.1",
+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-4.41.1.tgz",
+ "integrity": "sha512-XZvEw2OT+Nmi+ByQjURv3ckxRfzbYXSL6Hb60lgEn4GqUXz8HQTFdySvcSuCdxashqkBLrDvn9NwOhAbMTe9ow==",
"license": "MIT",
"funding": {
"type": "github",
@@ -8122,7 +8862,9 @@
}
},
"node_modules/@tiptap/pm": {
- "version": "2.27.1",
+ "version": "2.27.2",
+ "resolved": "https://registry.npmjs.org/@tiptap/pm/-/pm-2.27.2.tgz",
+ "integrity": "sha512-kaEg7BfiJPDQMKbjVIzEPO3wlcA+pZb2tlcK9gPrdDnEFaec2QTF1sXz2ak2IIb2curvnIrQ4yrfHgLlVA72wA==",
"license": "MIT",
"dependencies": {
"prosemirror-changeset": "^2.3.0",
@@ -8592,7 +9334,9 @@
}
},
"node_modules/@types/d3-array": {
- "version": "3.2.2",
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/d3-array/-/d3-array-3.0.3.tgz",
+ "integrity": "sha512-Reoy+pKnvsksN0lQUlcH6dOGjRZ/3WRwXR//m+/8lt1BXeI4xyaUZoqULNjyXXRuh0Mj4LNpkCvhUpQlY3X5xQ==",
"license": "MIT"
},
"node_modules/@types/d3-axis": {
@@ -8617,7 +9361,9 @@
"license": "MIT"
},
"node_modules/@types/d3-color": {
- "version": "3.1.3",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-color/-/d3-color-3.1.0.tgz",
+ "integrity": "sha512-HKuicPHJuvPgCD+np6Se9MQvS6OCbJmOjGvylzMJRlDwUXjKTTXs6Pwgk79O09Vj/ho3u1ofXnhFOaEWWPrlwA==",
"license": "MIT"
},
"node_modules/@types/d3-contour": {
@@ -8630,8 +9376,9 @@
}
},
"node_modules/@types/d3-delaunay": {
- "version": "6.0.4",
- "dev": true,
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-delaunay/-/d3-delaunay-6.0.1.tgz",
+ "integrity": "sha512-tLxQ2sfT0p6sxdG75c6f/ekqxjyYR0+LwPrsO1mbC9YDBzPJhs2HbJJRrn8Ez1DBoHRo2yx7YEATI+8V1nGMnQ==",
"license": "MIT"
},
"node_modules/@types/d3-dispatch": {
@@ -8669,8 +9416,9 @@
"license": "MIT"
},
"node_modules/@types/d3-format": {
- "version": "3.0.4",
- "dev": true,
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/@types/d3-format/-/d3-format-3.0.1.tgz",
+ "integrity": "sha512-5KY70ifCCzorkLuIkDe0Z9YTf9RR2CjBX1iaJG+rgM/cPP+sO+q9YdQ9WdhQcgPj1EQiJ2/0+yUkkziTG6Lubg==",
"license": "MIT"
},
"node_modules/@types/d3-geo": {
@@ -8693,7 +9441,9 @@
}
},
"node_modules/@types/d3-path": {
- "version": "3.1.1",
+ "version": "1.0.11",
+ "resolved": "https://registry.npmjs.org/@types/d3-path/-/d3-path-1.0.11.tgz",
+ "integrity": "sha512-4pQMp8ldf7UaB/gR8Fvvy69psNHkTpD/pVw3vmEi8iZAB9EPMBruB1JvHO4BIq9QkUUd2lV1F5YXpMNj7JPBpw==",
"license": "MIT"
},
"node_modules/@types/d3-polygon": {
@@ -8712,7 +9462,9 @@
"license": "MIT"
},
"node_modules/@types/d3-scale": {
- "version": "4.0.9",
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/d3-scale/-/d3-scale-4.0.2.tgz",
+ "integrity": "sha512-Yk4htunhPAwN0XGlIwArRomOjdoBFXC3+kCxK2Ubg7I9shQlVSJy/pG/Ht5ASN+gdMIalpk8TJ5xV74jFsetLA==",
"license": "MIT",
"dependencies": {
"@types/d3-time": "*"
@@ -8728,19 +9480,24 @@
"license": "MIT"
},
"node_modules/@types/d3-shape": {
- "version": "3.1.7",
+ "version": "3.1.8",
+ "resolved": "https://registry.npmjs.org/@types/d3-shape/-/d3-shape-3.1.8.tgz",
+ "integrity": "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w==",
"license": "MIT",
"dependencies": {
"@types/d3-path": "*"
}
},
"node_modules/@types/d3-time": {
- "version": "3.0.4",
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-time/-/d3-time-3.0.0.tgz",
+ "integrity": "sha512-sZLCdHvBUcNby1cB6Fd3ZBrABbjz3v1Vm90nysCQ6Vt7vd6e/h9Lt7SiJUoEX0l4Dzc7P5llKyhqSi1ycSf1Hg==",
"license": "MIT"
},
"node_modules/@types/d3-time-format": {
- "version": "4.0.3",
- "dev": true,
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/@types/d3-time-format/-/d3-time-format-2.1.0.tgz",
+ "integrity": "sha512-/myT3I7EwlukNOX2xVdMzb8FRgNzRMpsZddwst9Ld/VFe6LyJyRp0s32l/V9XoUzk+Gqu56F/oGk6507+8BxrA==",
"license": "MIT"
},
"node_modules/@types/d3-timer": {
@@ -8902,7 +9659,9 @@
"license": "MIT"
},
"node_modules/@types/node": {
- "version": "20.19.27",
+ "version": "20.19.30",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.30.tgz",
+ "integrity": "sha512-WJtwWJu7UdlvzEAUm484QNg5eAoq5QR08KDNx7g45Usrs2NtOPiX8ugDqmKdXkyL03rBqU5dYNYVQetEpBHq2g==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
@@ -9176,10 +9935,12 @@
}
},
"node_modules/@upstash/redis": {
- "version": "v1.36.0",
+ "version": "1.34.3",
+ "resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.34.3.tgz",
+ "integrity": "sha512-VT25TyODGy/8ljl7GADnJoMmtmJ1F8d84UXfGonRRF8fWYJz7+2J6GzW+a6ETGtk4OyuRTt7FRSvFG5GvrfSdQ==",
"license": "MIT",
"dependencies": {
- "uncrypto": "^0.1.3"
+ "crypto-js": "^4.2.0"
}
},
"node_modules/@vercel/analytics": {
@@ -9323,10 +10084,6 @@
"d3-shape": "^1.0.6"
}
},
- "node_modules/@visx/curve/node_modules/@types/d3-path": {
- "version": "1.0.11",
- "license": "MIT"
- },
"node_modules/@visx/curve/node_modules/@types/d3-shape": {
"version": "1.3.12",
"license": "MIT",
@@ -9410,10 +10167,6 @@
"@types/d3-color": "^1"
}
},
- "node_modules/@visx/shape/node_modules/@types/d3-path": {
- "version": "1.0.11",
- "license": "MIT"
- },
"node_modules/@visx/shape/node_modules/@types/d3-scale": {
"version": "3.3.5",
"license": "MIT",
@@ -9554,22 +10307,6 @@
"internmap": "2.0.3"
}
},
- "node_modules/@visx/vendor/node_modules/@types/d3-array": {
- "version": "3.0.3",
- "license": "MIT"
- },
- "node_modules/@visx/vendor/node_modules/@types/d3-color": {
- "version": "3.1.0",
- "license": "MIT"
- },
- "node_modules/@visx/vendor/node_modules/@types/d3-delaunay": {
- "version": "6.0.1",
- "license": "MIT"
- },
- "node_modules/@visx/vendor/node_modules/@types/d3-format": {
- "version": "3.0.1",
- "license": "MIT"
- },
"node_modules/@visx/vendor/node_modules/@types/d3-interpolate": {
"version": "3.0.1",
"license": "MIT",
@@ -9577,21 +10314,6 @@
"@types/d3-color": "*"
}
},
- "node_modules/@visx/vendor/node_modules/@types/d3-scale": {
- "version": "4.0.2",
- "license": "MIT",
- "dependencies": {
- "@types/d3-time": "*"
- }
- },
- "node_modules/@visx/vendor/node_modules/@types/d3-time": {
- "version": "3.0.0",
- "license": "MIT"
- },
- "node_modules/@visx/vendor/node_modules/@types/d3-time-format": {
- "version": "2.1.0",
- "license": "MIT"
- },
"node_modules/@visx/vendor/node_modules/d3-array": {
"version": "3.2.1",
"license": "ISC",
@@ -9602,26 +10324,6 @@
"node": ">=12"
}
},
- "node_modules/@visx/vendor/node_modules/d3-delaunay": {
- "version": "6.0.2",
- "license": "ISC",
- "dependencies": {
- "delaunator": "5"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/@visx/vendor/node_modules/d3-geo": {
- "version": "3.1.0",
- "license": "ISC",
- "dependencies": {
- "d3-array": "2.5.0 - 3"
- },
- "engines": {
- "node": ">=12"
- }
- },
"node_modules/@web3-storage/multipart-parser": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz",
@@ -10513,7 +11215,9 @@
}
},
"node_modules/body-parser/node_modules/iconv-lite": {
- "version": "0.7.1",
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
@@ -11740,7 +12444,9 @@
}
},
"node_modules/d3-delaunay": {
- "version": "6.0.4",
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/d3-delaunay/-/d3-delaunay-6.0.2.tgz",
+ "integrity": "sha512-IMLNldruDQScrcfT+MWnazhHbDJhcRJyOEBAJfwQnHle1RPh6WDuLvxNArUju2VSMSUuKlY5BGHRJ2cYyoFLQQ==",
"license": "ISC",
"dependencies": {
"delaunator": "5"
@@ -11834,7 +12540,9 @@
}
},
"node_modules/d3-geo": {
- "version": "3.1.1",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/d3-geo/-/d3-geo-3.1.0.tgz",
+ "integrity": "sha512-JEo5HxXDdDYXCaWdwLRt79y7giK8SbhZJbFWXqbRTolCHFI5jRqteLzCsq51NKbUoX0PjBVSohxrx+NoOUujYA==",
"license": "ISC",
"dependencies": {
"d3-array": "2.5.0 - 3"
@@ -16927,7 +17635,9 @@
}
},
"node_modules/jsesc": {
- "version": "3.1.0",
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz",
+ "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==",
"license": "MIT",
"bin": {
"jsesc": "bin/jsesc"
@@ -17109,7 +17819,9 @@
}
},
"node_modules/kysely": {
- "version": "0.28.9",
+ "version": "0.28.10",
+ "resolved": "https://registry.npmjs.org/kysely/-/kysely-0.28.10.tgz",
+ "integrity": "sha512-ksNxfzIW77OcZ+QWSAPC7yDqUSaIVwkTWnTPNiIy//vifNbwsSgQ57OkkncHxxpcBHM3LRfLAZVEh7kjq5twVA==",
"license": "MIT",
"engines": {
"node": ">=20.0.0"
@@ -20526,7 +21238,9 @@
}
},
"node_modules/raw-body/node_modules/iconv-lite": {
- "version": "0.7.1",
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
+ "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
@@ -24286,139 +25000,33 @@
"fsevents": "~2.3.3"
}
},
- "node_modules/tsx/node_modules/@esbuild/aix-ppc64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz",
- "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==",
- "cpu": [
- "ppc64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "aix"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
- "version": "0.27.2",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/tsx/node_modules/@esbuild/netbsd-arm64": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz",
- "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==",
- "cpu": [
- "arm64"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
- "os": [
- "netbsd"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/tsx/node_modules/@esbuild/openbsd-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/android-arm": {
"version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz",
- "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
+ "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
"cpu": [
- "arm64"
+ "arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
- "openbsd"
+ "android"
],
"engines": {
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/@esbuild/openharmony-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/android-arm64": {
"version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz",
- "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
+ "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
- "os": [
- "openharmony"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/tsx/node_modules/esbuild": {
- "version": "0.27.2",
- "devOptional": true,
- "hasInstallScript": true,
- "license": "MIT",
- "bin": {
- "esbuild": "bin/esbuild"
- },
- "engines": {
- "node": ">=18"
- },
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.27.2",
- "@esbuild/android-arm": "0.27.2",
- "@esbuild/android-arm64": "0.27.2",
- "@esbuild/android-x64": "0.27.2",
- "@esbuild/darwin-arm64": "0.27.2",
- "@esbuild/darwin-x64": "0.27.2",
- "@esbuild/freebsd-arm64": "0.27.2",
- "@esbuild/freebsd-x64": "0.27.2",
- "@esbuild/linux-arm": "0.27.2",
- "@esbuild/linux-arm64": "0.27.2",
- "@esbuild/linux-ia32": "0.27.2",
- "@esbuild/linux-loong64": "0.27.2",
- "@esbuild/linux-mips64el": "0.27.2",
- "@esbuild/linux-ppc64": "0.27.2",
- "@esbuild/linux-riscv64": "0.27.2",
- "@esbuild/linux-s390x": "0.27.2",
- "@esbuild/linux-x64": "0.27.2",
- "@esbuild/netbsd-arm64": "0.27.2",
- "@esbuild/netbsd-x64": "0.27.2",
- "@esbuild/openbsd-arm64": "0.27.2",
- "@esbuild/openbsd-x64": "0.27.2",
- "@esbuild/openharmony-arm64": "0.27.2",
- "@esbuild/sunos-x64": "0.27.2",
- "@esbuild/win32-arm64": "0.27.2",
- "@esbuild/win32-ia32": "0.27.2",
- "@esbuild/win32-x64": "0.27.2"
- }
- },
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/android-arm": {
- "version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz",
- "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==",
- "cpu": [
- "arm"
- ],
- "dev": true,
- "license": "MIT",
- "optional": true,
"os": [
"android"
],
@@ -24426,12 +25034,12 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/android-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/android-x64": {
"version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz",
- "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
+ "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
"cpu": [
- "arm64"
+ "x64"
],
"dev": true,
"license": "MIT",
@@ -24443,24 +25051,22 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/android-x64": {
+ "node_modules/tsx/node_modules/@esbuild/darwin-arm64": {
"version": "0.27.2",
- "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz",
- "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==",
"cpu": [
- "x64"
+ "arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
- "android"
+ "darwin"
],
"engines": {
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/darwin-x64": {
+ "node_modules/tsx/node_modules/@esbuild/darwin-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz",
"integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==",
@@ -24477,7 +25083,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/freebsd-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/freebsd-arm64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz",
"integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==",
@@ -24494,7 +25100,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/freebsd-x64": {
+ "node_modules/tsx/node_modules/@esbuild/freebsd-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz",
"integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==",
@@ -24511,7 +25117,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-arm": {
+ "node_modules/tsx/node_modules/@esbuild/linux-arm": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz",
"integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==",
@@ -24528,7 +25134,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/linux-arm64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz",
"integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==",
@@ -24545,7 +25151,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-ia32": {
+ "node_modules/tsx/node_modules/@esbuild/linux-ia32": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz",
"integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==",
@@ -24562,7 +25168,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-loong64": {
+ "node_modules/tsx/node_modules/@esbuild/linux-loong64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz",
"integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==",
@@ -24579,7 +25185,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-mips64el": {
+ "node_modules/tsx/node_modules/@esbuild/linux-mips64el": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz",
"integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==",
@@ -24596,7 +25202,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-ppc64": {
+ "node_modules/tsx/node_modules/@esbuild/linux-ppc64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz",
"integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==",
@@ -24613,7 +25219,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-riscv64": {
+ "node_modules/tsx/node_modules/@esbuild/linux-riscv64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz",
"integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==",
@@ -24630,7 +25236,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-s390x": {
+ "node_modules/tsx/node_modules/@esbuild/linux-s390x": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz",
"integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==",
@@ -24647,7 +25253,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/linux-x64": {
+ "node_modules/tsx/node_modules/@esbuild/linux-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz",
"integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==",
@@ -24664,7 +25270,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/netbsd-x64": {
+ "node_modules/tsx/node_modules/@esbuild/netbsd-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz",
"integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==",
@@ -24681,7 +25287,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/openbsd-x64": {
+ "node_modules/tsx/node_modules/@esbuild/openbsd-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz",
"integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==",
@@ -24698,7 +25304,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/sunos-x64": {
+ "node_modules/tsx/node_modules/@esbuild/sunos-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz",
"integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==",
@@ -24715,7 +25321,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/win32-arm64": {
+ "node_modules/tsx/node_modules/@esbuild/win32-arm64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz",
"integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==",
@@ -24732,7 +25338,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/win32-ia32": {
+ "node_modules/tsx/node_modules/@esbuild/win32-ia32": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz",
"integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==",
@@ -24749,7 +25355,7 @@
"node": ">=18"
}
},
- "node_modules/tsx/node_modules/esbuild/node_modules/@esbuild/win32-x64": {
+ "node_modules/tsx/node_modules/@esbuild/win32-x64": {
"version": "0.27.2",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz",
"integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==",
@@ -24766,6 +25372,46 @@
"node": ">=18"
}
},
+ "node_modules/tsx/node_modules/esbuild": {
+ "version": "0.27.2",
+ "devOptional": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.27.2",
+ "@esbuild/android-arm": "0.27.2",
+ "@esbuild/android-arm64": "0.27.2",
+ "@esbuild/android-x64": "0.27.2",
+ "@esbuild/darwin-arm64": "0.27.2",
+ "@esbuild/darwin-x64": "0.27.2",
+ "@esbuild/freebsd-arm64": "0.27.2",
+ "@esbuild/freebsd-x64": "0.27.2",
+ "@esbuild/linux-arm": "0.27.2",
+ "@esbuild/linux-arm64": "0.27.2",
+ "@esbuild/linux-ia32": "0.27.2",
+ "@esbuild/linux-loong64": "0.27.2",
+ "@esbuild/linux-mips64el": "0.27.2",
+ "@esbuild/linux-ppc64": "0.27.2",
+ "@esbuild/linux-riscv64": "0.27.2",
+ "@esbuild/linux-s390x": "0.27.2",
+ "@esbuild/linux-x64": "0.27.2",
+ "@esbuild/netbsd-arm64": "0.27.2",
+ "@esbuild/netbsd-x64": "0.27.2",
+ "@esbuild/openbsd-arm64": "0.27.2",
+ "@esbuild/openbsd-x64": "0.27.2",
+ "@esbuild/openharmony-arm64": "0.27.2",
+ "@esbuild/sunos-x64": "0.27.2",
+ "@esbuild/win32-arm64": "0.27.2",
+ "@esbuild/win32-ia32": "0.27.2",
+ "@esbuild/win32-x64": "0.27.2"
+ }
+ },
"node_modules/tunnel-rat": {
"version": "0.1.2",
"license": "MIT",
@@ -25012,7 +25658,9 @@
}
},
"node_modules/typescript": {
- "version": "5.9.3",
+ "version": "5.8.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
+ "integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -25569,395 +26217,82 @@
"yaml": {
"optional": true
}
- }
- },
- "node_modules/vite-compatible-readable-stream": {
- "version": "3.6.1",
- "license": "MIT",
- "dependencies": {
- "inherits": "^2.0.3",
- "string_decoder": "^1.1.1",
- "util-deprecate": "^1.0.1"
- },
- "engines": {
- "node": ">= 6"
- }
- },
- "node_modules/vite-node": {
- "version": "3.2.4",
- "license": "MIT",
- "dependencies": {
- "cac": "^6.7.14",
- "debug": "^4.4.1",
- "es-module-lexer": "^1.7.0",
- "pathe": "^2.0.3",
- "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
- },
- "bin": {
- "vite-node": "vite-node.mjs"
- },
- "engines": {
- "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
- },
- "funding": {
- "url": "https://opencollective.com/vitest"
- }
- },
- "node_modules/vite-node/node_modules/debug": {
- "version": "4.4.3",
- "license": "MIT",
- "dependencies": {
- "ms": "^2.1.3"
- },
- "engines": {
- "node": ">=6.0"
- },
- "peerDependenciesMeta": {
- "supports-color": {
- "optional": true
- }
- }
- },
- "node_modules/vite-node/node_modules/ms": {
- "version": "2.1.3",
- "license": "MIT"
- },
- "node_modules/vite-node/node_modules/pathe": {
- "version": "2.0.3",
- "license": "MIT"
- },
- "node_modules/vite-tsconfig-paths": {
- "version": "5.1.4",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "debug": "^4.1.1",
- "globrex": "^0.1.2",
- "tsconfck": "^3.0.3"
- },
- "peerDependencies": {
- "vite": "*"
- },
- "peerDependenciesMeta": {
- "vite": {
- "optional": true
- }
- }
- },
- "node_modules/vite/node_modules/@esbuild/darwin-arm64": {
- "version": "0.25.12",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ],
- "engines": {
- "node": ">=18"
- }
- },
- "node_modules/vite/node_modules/@rollup/rollup-android-arm-eabi": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.54.0.tgz",
- "integrity": "sha512-OywsdRHrFvCdvsewAInDKCNyR3laPA2mc9bRYJ6LBp5IyvF3fvXbbNR0bSzHlZVFtn6E0xw2oZlyjg4rKCVcng==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-android-arm64": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.54.0.tgz",
- "integrity": "sha512-Skx39Uv+u7H224Af+bDgNinitlmHyQX1K/atIA32JP3JQw6hVODX5tkbi2zof/E69M1qH2UoN3Xdxgs90mmNYw==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "android"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-darwin-x64": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.54.0.tgz",
- "integrity": "sha512-cOo7biqwkpawslEfox5Vs8/qj83M/aZCSSNIWpVzfU2CYHa2G3P1UN5WF01RdTHSgCkri7XOlTdtk17BezlV3A==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-freebsd-arm64": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.54.0.tgz",
- "integrity": "sha512-miSvuFkmvFbgJ1BevMa4CPCFt5MPGw094knM64W9I0giUIMMmRYcGW/JWZDriaw/k1kOBtsWh1z6nIFV1vPNtA==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-freebsd-x64": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.54.0.tgz",
- "integrity": "sha512-KGXIs55+b/ZfZsq9aR026tmr/+7tq6VG6MsnrvF4H8VhwflTIuYh+LFUlIsRdQSgrgmtM3fVATzEAj4hBQlaqQ==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "freebsd"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-arm-gnueabihf": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.54.0.tgz",
- "integrity": "sha512-EHMUcDwhtdRGlXZsGSIuXSYwD5kOT9NVnx9sqzYiwAc91wfYOE1g1djOEDseZJKKqtHAHGwnGPQu3kytmfaXLQ==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-arm-musleabihf": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.54.0.tgz",
- "integrity": "sha512-+pBrqEjaakN2ySv5RVrj/qLytYhPKEUwk+e3SFU5jTLHIcAtqh2rLrd/OkbNuHJpsBgxsD8ccJt5ga/SeG0JmA==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-arm64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.54.0.tgz",
- "integrity": "sha512-NSqc7rE9wuUaRBsBp5ckQ5CVz5aIRKCwsoa6WMF7G01sX3/qHUw/z4pv+D+ahL1EIKy6Enpcnz1RY8pf7bjwng==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-arm64-musl": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.54.0.tgz",
- "integrity": "sha512-gr5vDbg3Bakga5kbdpqx81m2n9IX8M6gIMlQQIXiLTNeQW6CucvuInJ91EuCJ/JYvc+rcLLsDFcfAD1K7fMofg==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-loong64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.54.0.tgz",
- "integrity": "sha512-gsrtB1NA3ZYj2vq0Rzkylo9ylCtW/PhpLEivlgWe0bpgtX5+9j9EZa0wtZiCjgu6zmSeZWyI/e2YRX1URozpIw==",
- "cpu": [
- "loong64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-ppc64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.54.0.tgz",
- "integrity": "sha512-y3qNOfTBStmFNq+t4s7Tmc9hW2ENtPg8FeUD/VShI7rKxNW7O4fFeaYbMsd3tpFlIg1Q8IapFgy7Q9i2BqeBvA==",
- "cpu": [
- "ppc64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-riscv64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.54.0.tgz",
- "integrity": "sha512-89sepv7h2lIVPsFma8iwmccN7Yjjtgz0Rj/Ou6fEqg3HDhpCa+Et+YSufy27i6b0Wav69Qv4WBNl3Rs6pwhebQ==",
- "cpu": [
- "riscv64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-riscv64-musl": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.54.0.tgz",
- "integrity": "sha512-ZcU77ieh0M2Q8Ur7D5X7KvK+UxbXeDHwiOt/CPSBTI1fBmeDMivW0dPkdqkT4rOgDjrDDBUed9x4EgraIKoR2A==",
- "cpu": [
- "riscv64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-s390x-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.54.0.tgz",
- "integrity": "sha512-2AdWy5RdDF5+4YfG/YesGDDtbyJlC9LHmL6rZw6FurBJ5n4vFGupsOBGfwMRjBYH7qRQowT8D/U4LoSvVwOhSQ==",
- "cpu": [
- "s390x"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/vite/node_modules/@rollup/rollup-linux-x64-musl": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.54.0.tgz",
- "integrity": "sha512-JzQmb38ATzHjxlPHuTH6tE7ojnMKM2kYNzt44LO/jJi8BpceEC8QuXYA908n8r3CNuG/B3BV8VR3Hi1rYtmPiw==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
+ }
},
- "node_modules/vite/node_modules/@rollup/rollup-openharmony-arm64": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.54.0.tgz",
- "integrity": "sha512-huT3fd0iC7jigGh7n3q/+lfPcXxBi+om/Rs3yiFxjvSxbSB6aohDFXbWvlspaqjeOh+hx7DDHS+5Es5qRkWkZg==",
- "cpu": [
- "arm64"
- ],
+ "node_modules/vite-compatible-readable-stream": {
+ "version": "3.6.1",
"license": "MIT",
- "optional": true,
- "os": [
- "openharmony"
- ]
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
},
- "node_modules/vite/node_modules/@rollup/rollup-win32-arm64-msvc": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.54.0.tgz",
- "integrity": "sha512-c2V0W1bsKIKfbLMBu/WGBz6Yci8nJ/ZJdheE0EwB73N3MvHYKiKGs3mVilX4Gs70eGeDaMqEob25Tw2Gb9Nqyw==",
- "cpu": [
- "arm64"
- ],
+ "node_modules/vite-node": {
+ "version": "3.2.4",
"license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
+ "dependencies": {
+ "cac": "^6.7.14",
+ "debug": "^4.4.1",
+ "es-module-lexer": "^1.7.0",
+ "pathe": "^2.0.3",
+ "vite": "^5.0.0 || ^6.0.0 || ^7.0.0-0"
+ },
+ "bin": {
+ "vite-node": "vite-node.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || ^20.0.0 || >=22.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
},
- "node_modules/vite/node_modules/@rollup/rollup-win32-ia32-msvc": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.54.0.tgz",
- "integrity": "sha512-woEHgqQqDCkAzrDhvDipnSirm5vxUXtSKDYTVpZG3nUdW/VVB5VdCYA2iReSj/u3yCZzXID4kuKG7OynPnB3WQ==",
- "cpu": [
- "ia32"
- ],
+ "node_modules/vite-node/node_modules/debug": {
+ "version": "4.4.3",
"license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
},
- "node_modules/vite/node_modules/@rollup/rollup-win32-x64-gnu": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.54.0.tgz",
- "integrity": "sha512-dzAc53LOuFvHwbCEOS0rPbXp6SIhAf2txMP5p6mGyOXXw5mWY8NGGbPMPrs4P1WItkfApDathBj/NzMLUZ9rtQ==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
+ "node_modules/vite-node/node_modules/ms": {
+ "version": "2.1.3",
+ "license": "MIT"
},
- "node_modules/vite/node_modules/@rollup/rollup-win32-x64-msvc": {
- "version": "4.54.0",
- "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.54.0.tgz",
- "integrity": "sha512-hYT5d3YNdSh3mbCU1gwQyPgQd3T2ne0A3KG8KSBdav5TiBg6eInVmV+TeR5uHufiIgSFg0XsOWGW5/RhNcSvPg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
+ "node_modules/vite-node/node_modules/pathe": {
+ "version": "2.0.3",
+ "license": "MIT"
},
- "node_modules/vite/node_modules/esbuild": {
- "version": "0.25.12",
- "hasInstallScript": true,
+ "node_modules/vite-tsconfig-paths": {
+ "version": "5.1.4",
+ "dev": true,
"license": "MIT",
- "bin": {
- "esbuild": "bin/esbuild"
+ "dependencies": {
+ "debug": "^4.1.1",
+ "globrex": "^0.1.2",
+ "tsconfck": "^3.0.3"
},
- "engines": {
- "node": ">=18"
+ "peerDependencies": {
+ "vite": "*"
},
- "optionalDependencies": {
- "@esbuild/aix-ppc64": "0.25.12",
- "@esbuild/android-arm": "0.25.12",
- "@esbuild/android-arm64": "0.25.12",
- "@esbuild/android-x64": "0.25.12",
- "@esbuild/darwin-arm64": "0.25.12",
- "@esbuild/darwin-x64": "0.25.12",
- "@esbuild/freebsd-arm64": "0.25.12",
- "@esbuild/freebsd-x64": "0.25.12",
- "@esbuild/linux-arm": "0.25.12",
- "@esbuild/linux-arm64": "0.25.12",
- "@esbuild/linux-ia32": "0.25.12",
- "@esbuild/linux-loong64": "0.25.12",
- "@esbuild/linux-mips64el": "0.25.12",
- "@esbuild/linux-ppc64": "0.25.12",
- "@esbuild/linux-riscv64": "0.25.12",
- "@esbuild/linux-s390x": "0.25.12",
- "@esbuild/linux-x64": "0.25.12",
- "@esbuild/netbsd-arm64": "0.25.12",
- "@esbuild/netbsd-x64": "0.25.12",
- "@esbuild/openbsd-arm64": "0.25.12",
- "@esbuild/openbsd-x64": "0.25.12",
- "@esbuild/openharmony-arm64": "0.25.12",
- "@esbuild/sunos-x64": "0.25.12",
- "@esbuild/win32-arm64": "0.25.12",
- "@esbuild/win32-ia32": "0.25.12",
- "@esbuild/win32-x64": "0.25.12"
+ "peerDependenciesMeta": {
+ "vite": {
+ "optional": true
+ }
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/aix-ppc64": {
+ "node_modules/vite/node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
@@ -25973,7 +26308,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/android-arm": {
+ "node_modules/vite/node_modules/@esbuild/android-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
@@ -25989,7 +26324,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/android-arm64": {
+ "node_modules/vite/node_modules/@esbuild/android-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
@@ -26005,7 +26340,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/android-x64": {
+ "node_modules/vite/node_modules/@esbuild/android-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
@@ -26021,7 +26356,21 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/darwin-x64": {
+ "node_modules/vite/node_modules/@esbuild/darwin-arm64": {
+ "version": "0.25.12",
+ "cpu": [
+ "arm64"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/vite/node_modules/@esbuild/darwin-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
@@ -26037,7 +26386,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/freebsd-arm64": {
+ "node_modules/vite/node_modules/@esbuild/freebsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
@@ -26053,7 +26402,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/freebsd-x64": {
+ "node_modules/vite/node_modules/@esbuild/freebsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
@@ -26069,7 +26418,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-arm": {
+ "node_modules/vite/node_modules/@esbuild/linux-arm": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
@@ -26085,7 +26434,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-arm64": {
+ "node_modules/vite/node_modules/@esbuild/linux-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
@@ -26101,7 +26450,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-ia32": {
+ "node_modules/vite/node_modules/@esbuild/linux-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
@@ -26117,7 +26466,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-loong64": {
+ "node_modules/vite/node_modules/@esbuild/linux-loong64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
@@ -26133,7 +26482,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-mips64el": {
+ "node_modules/vite/node_modules/@esbuild/linux-mips64el": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
@@ -26149,7 +26498,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-ppc64": {
+ "node_modules/vite/node_modules/@esbuild/linux-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
@@ -26165,7 +26514,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-riscv64": {
+ "node_modules/vite/node_modules/@esbuild/linux-riscv64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
@@ -26181,7 +26530,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-s390x": {
+ "node_modules/vite/node_modules/@esbuild/linux-s390x": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
@@ -26197,7 +26546,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/linux-x64": {
+ "node_modules/vite/node_modules/@esbuild/linux-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
@@ -26213,7 +26562,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/netbsd-arm64": {
+ "node_modules/vite/node_modules/@esbuild/netbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
@@ -26229,7 +26578,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/netbsd-x64": {
+ "node_modules/vite/node_modules/@esbuild/netbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
@@ -26245,7 +26594,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/openbsd-arm64": {
+ "node_modules/vite/node_modules/@esbuild/openbsd-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
@@ -26261,7 +26610,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/openbsd-x64": {
+ "node_modules/vite/node_modules/@esbuild/openbsd-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
@@ -26277,7 +26626,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/openharmony-arm64": {
+ "node_modules/vite/node_modules/@esbuild/openharmony-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
@@ -26293,7 +26642,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/sunos-x64": {
+ "node_modules/vite/node_modules/@esbuild/sunos-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
@@ -26309,7 +26658,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/win32-arm64": {
+ "node_modules/vite/node_modules/@esbuild/win32-arm64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
@@ -26325,7 +26674,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/win32-ia32": {
+ "node_modules/vite/node_modules/@esbuild/win32-ia32": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
@@ -26341,7 +26690,7 @@
"node": ">=18"
}
},
- "node_modules/vite/node_modules/esbuild/node_modules/@esbuild/win32-x64": {
+ "node_modules/vite/node_modules/@esbuild/win32-x64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
@@ -26357,8 +26706,49 @@
"node": ">=18"
}
},
+ "node_modules/vite/node_modules/esbuild": {
+ "version": "0.25.12",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.25.12",
+ "@esbuild/android-arm": "0.25.12",
+ "@esbuild/android-arm64": "0.25.12",
+ "@esbuild/android-x64": "0.25.12",
+ "@esbuild/darwin-arm64": "0.25.12",
+ "@esbuild/darwin-x64": "0.25.12",
+ "@esbuild/freebsd-arm64": "0.25.12",
+ "@esbuild/freebsd-x64": "0.25.12",
+ "@esbuild/linux-arm": "0.25.12",
+ "@esbuild/linux-arm64": "0.25.12",
+ "@esbuild/linux-ia32": "0.25.12",
+ "@esbuild/linux-loong64": "0.25.12",
+ "@esbuild/linux-mips64el": "0.25.12",
+ "@esbuild/linux-ppc64": "0.25.12",
+ "@esbuild/linux-riscv64": "0.25.12",
+ "@esbuild/linux-s390x": "0.25.12",
+ "@esbuild/linux-x64": "0.25.12",
+ "@esbuild/netbsd-arm64": "0.25.12",
+ "@esbuild/netbsd-x64": "0.25.12",
+ "@esbuild/openbsd-arm64": "0.25.12",
+ "@esbuild/openbsd-x64": "0.25.12",
+ "@esbuild/openharmony-arm64": "0.25.12",
+ "@esbuild/sunos-x64": "0.25.12",
+ "@esbuild/win32-arm64": "0.25.12",
+ "@esbuild/win32-ia32": "0.25.12",
+ "@esbuild/win32-x64": "0.25.12"
+ }
+ },
"node_modules/vite/node_modules/rollup": {
- "version": "4.54.0",
+ "version": "4.55.1",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.55.1.tgz",
+ "integrity": "sha512-wDv/Ht1BNHB4upNbK74s9usvl7hObDnvVzknxqY/E/O3X6rW1U1rV1aENEfJ54eFZDTNo7zv1f5N4edCluH7+A==",
"license": "MIT",
"dependencies": {
"@types/estree": "1.0.8"
@@ -26371,28 +26761,31 @@
"npm": ">=8.0.0"
},
"optionalDependencies": {
- "@rollup/rollup-android-arm-eabi": "4.54.0",
- "@rollup/rollup-android-arm64": "4.54.0",
- "@rollup/rollup-darwin-arm64": "4.54.0",
- "@rollup/rollup-darwin-x64": "4.54.0",
- "@rollup/rollup-freebsd-arm64": "4.54.0",
- "@rollup/rollup-freebsd-x64": "4.54.0",
- "@rollup/rollup-linux-arm-gnueabihf": "4.54.0",
- "@rollup/rollup-linux-arm-musleabihf": "4.54.0",
- "@rollup/rollup-linux-arm64-gnu": "4.54.0",
- "@rollup/rollup-linux-arm64-musl": "4.54.0",
- "@rollup/rollup-linux-loong64-gnu": "4.54.0",
- "@rollup/rollup-linux-ppc64-gnu": "4.54.0",
- "@rollup/rollup-linux-riscv64-gnu": "4.54.0",
- "@rollup/rollup-linux-riscv64-musl": "4.54.0",
- "@rollup/rollup-linux-s390x-gnu": "4.54.0",
- "@rollup/rollup-linux-x64-gnu": "4.54.0",
- "@rollup/rollup-linux-x64-musl": "4.54.0",
- "@rollup/rollup-openharmony-arm64": "4.54.0",
- "@rollup/rollup-win32-arm64-msvc": "4.54.0",
- "@rollup/rollup-win32-ia32-msvc": "4.54.0",
- "@rollup/rollup-win32-x64-gnu": "4.54.0",
- "@rollup/rollup-win32-x64-msvc": "4.54.0",
+ "@rollup/rollup-android-arm-eabi": "4.55.1",
+ "@rollup/rollup-android-arm64": "4.55.1",
+ "@rollup/rollup-darwin-arm64": "4.55.1",
+ "@rollup/rollup-darwin-x64": "4.55.1",
+ "@rollup/rollup-freebsd-arm64": "4.55.1",
+ "@rollup/rollup-freebsd-x64": "4.55.1",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.55.1",
+ "@rollup/rollup-linux-arm-musleabihf": "4.55.1",
+ "@rollup/rollup-linux-arm64-gnu": "4.55.1",
+ "@rollup/rollup-linux-arm64-musl": "4.55.1",
+ "@rollup/rollup-linux-loong64-gnu": "4.55.1",
+ "@rollup/rollup-linux-loong64-musl": "4.55.1",
+ "@rollup/rollup-linux-ppc64-gnu": "4.55.1",
+ "@rollup/rollup-linux-ppc64-musl": "4.55.1",
+ "@rollup/rollup-linux-riscv64-gnu": "4.55.1",
+ "@rollup/rollup-linux-riscv64-musl": "4.55.1",
+ "@rollup/rollup-linux-s390x-gnu": "4.55.1",
+ "@rollup/rollup-linux-x64-gnu": "4.55.1",
+ "@rollup/rollup-linux-x64-musl": "4.55.1",
+ "@rollup/rollup-openbsd-x64": "4.55.1",
+ "@rollup/rollup-openharmony-arm64": "4.55.1",
+ "@rollup/rollup-win32-arm64-msvc": "4.55.1",
+ "@rollup/rollup-win32-ia32-msvc": "4.55.1",
+ "@rollup/rollup-win32-x64-gnu": "4.55.1",
+ "@rollup/rollup-win32-x64-msvc": "4.55.1",
"fsevents": "~2.3.2"
}
},
@@ -26962,7 +27355,9 @@
}
},
"node_modules/zustand": {
- "version": "5.0.9",
+ "version": "5.0.10",
+ "resolved": "https://registry.npmjs.org/zustand/-/zustand-5.0.10.tgz",
+ "integrity": "sha512-U1AiltS1O9hSy3rul+Ub82ut2fqIAefiSuwECWt6jlMVUGejvf+5omLcRBSzqbRagSM3hQZbtzdeRc6QVScXTg==",
"license": "MIT",
"engines": {
"node": ">=12.20.0"
@@ -27082,41 +27477,7 @@
"typescript": "^5.2.2"
}
},
- "packages/documents/node_modules/@react-email/components": {
- "version": "1.0.3",
- "resolved": "https://registry.npmjs.org/@react-email/components/-/components-1.0.3.tgz",
- "integrity": "sha512-RbleOT35XSCWM54Rs76/BgfPA0Son55OH4awBYlkHZgLw0AdbPwobhE7izNDFqY4nHW7+omLfe3CByWbsg/hEw==",
- "license": "MIT",
- "dependencies": {
- "@react-email/body": "0.2.1",
- "@react-email/button": "0.2.1",
- "@react-email/code-block": "0.2.1",
- "@react-email/code-inline": "0.0.6",
- "@react-email/column": "0.0.14",
- "@react-email/container": "0.0.16",
- "@react-email/font": "0.0.10",
- "@react-email/head": "0.0.13",
- "@react-email/heading": "0.0.16",
- "@react-email/hr": "0.0.12",
- "@react-email/html": "0.0.12",
- "@react-email/img": "0.0.12",
- "@react-email/link": "0.0.13",
- "@react-email/markdown": "0.0.18",
- "@react-email/preview": "0.0.14",
- "@react-email/render": "2.0.1",
- "@react-email/row": "0.0.13",
- "@react-email/section": "0.0.17",
- "@react-email/tailwind": "2.0.3",
- "@react-email/text": "0.1.6"
- },
- "engines": {
- "node": ">=20.0.0"
- },
- "peerDependencies": {
- "react": "^18.0 || ^19.0 || ^19.0.0-rc"
- }
- },
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/body": {
+ "packages/documents/node_modules/@react-email/body": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@react-email/body/-/body-0.2.1.tgz",
"integrity": "sha512-ljDiQiJDu/Fq//vSIIP0z5Nuvt4+DX1RqGasstChDGJB/14ogd4VdNS9aacoede/ZjGy3o3Qb+cxyS+XgM6SwQ==",
@@ -27128,7 +27489,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/button": {
+ "packages/documents/node_modules/@react-email/button": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@react-email/button/-/button-0.2.1.tgz",
"integrity": "sha512-qXyj7RZLE7POy9BMKSoqQ00tOXThjOZSUnI2Yu9i29IHngPlmrNayIWBoVKtElES7OWwypUcpiajwi1mUWx6/A==",
@@ -27140,7 +27501,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/code-block": {
+ "packages/documents/node_modules/@react-email/code-block": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@react-email/code-block/-/code-block-0.2.1.tgz",
"integrity": "sha512-M3B7JpVH4ytgn83/ujRR1k1DQHvTeABiDM61OvAbjLRPhC/5KLHU5KkzIbbuGIrjWwxAbL1kSQzU8MhLEtSxyw==",
@@ -27155,7 +27516,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/code-inline": {
+ "packages/documents/node_modules/@react-email/code-inline": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/@react-email/code-inline/-/code-inline-0.0.6.tgz",
"integrity": "sha512-jfhebvv3dVsp3OdPgKXnk8+e2pBiDVZejDOBFzBa/IblrAJ9cQDkN6rBD5IyEg8hTOxwbw3iaI/yZFmDmIguIA==",
@@ -27167,7 +27528,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/column": {
+ "packages/documents/node_modules/@react-email/column": {
"version": "0.0.14",
"resolved": "https://registry.npmjs.org/@react-email/column/-/column-0.0.14.tgz",
"integrity": "sha512-f+W+Bk2AjNO77zynE33rHuQhyqVICx4RYtGX9NKsGUg0wWjdGP0qAuIkhx9Rnmk4/hFMo1fUrtYNqca9fwJdHg==",
@@ -27179,7 +27540,41 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/container": {
+ "packages/documents/node_modules/@react-email/components": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/@react-email/components/-/components-1.0.4.tgz",
+ "integrity": "sha512-XpSs/mN0APMD9E3TYZnj8N6kRXqb6WBl9WrE+IHyB4PdgLNqXe7uZ5+5oZkKSE8Tskzw/K2vDJUqSZ2v+sRjUA==",
+ "license": "MIT",
+ "dependencies": {
+ "@react-email/body": "0.2.1",
+ "@react-email/button": "0.2.1",
+ "@react-email/code-block": "0.2.1",
+ "@react-email/code-inline": "0.0.6",
+ "@react-email/column": "0.0.14",
+ "@react-email/container": "0.0.16",
+ "@react-email/font": "0.0.10",
+ "@react-email/head": "0.0.13",
+ "@react-email/heading": "0.0.16",
+ "@react-email/hr": "0.0.12",
+ "@react-email/html": "0.0.12",
+ "@react-email/img": "0.0.12",
+ "@react-email/link": "0.0.13",
+ "@react-email/markdown": "0.0.18",
+ "@react-email/preview": "0.0.14",
+ "@react-email/render": "2.0.2",
+ "@react-email/row": "0.0.13",
+ "@react-email/section": "0.0.17",
+ "@react-email/tailwind": "2.0.3",
+ "@react-email/text": "0.1.6"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ },
+ "peerDependencies": {
+ "react": "^18.0 || ^19.0 || ^19.0.0-rc"
+ }
+ },
+ "packages/documents/node_modules/@react-email/container": {
"version": "0.0.16",
"resolved": "https://registry.npmjs.org/@react-email/container/-/container-0.0.16.tgz",
"integrity": "sha512-QWBB56RkkU0AJ9h+qy33gfT5iuZknPC7Un/IjZv9B0QmMIK+WWacc0cH6y2SV5Cv/b99hU94fjEMOOO4enpkbQ==",
@@ -27191,7 +27586,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/font": {
+ "packages/documents/node_modules/@react-email/font": {
"version": "0.0.10",
"resolved": "https://registry.npmjs.org/@react-email/font/-/font-0.0.10.tgz",
"integrity": "sha512-0urVSgCmQIfx5r7Xc586miBnQUVnGp3OTYUm8m5pwtQRdTRO5XrTtEfNJ3JhYhSOruV0nD8fd+dXtKXobum6tA==",
@@ -27203,7 +27598,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/head": {
+ "packages/documents/node_modules/@react-email/head": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/@react-email/head/-/head-0.0.13.tgz",
"integrity": "sha512-AJg6le/08Gz4tm+6MtKXqtNNyKHzmooOCdmtqmWxD7FxoAdU1eVcizhtQ0gcnVaY6ethEyE/hnEzQxt1zu5Kog==",
@@ -27215,7 +27610,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/heading": {
+ "packages/documents/node_modules/@react-email/heading": {
"version": "0.0.16",
"resolved": "https://registry.npmjs.org/@react-email/heading/-/heading-0.0.16.tgz",
"integrity": "sha512-jmsKnQm1ykpBzw4hCYHwBkt5pW2jScXffPeEH5ZRF5tZeF5b1pvlFTO9han7C0pCkZYo1kEvWiRtx69yfCIwuw==",
@@ -27227,7 +27622,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/hr": {
+ "packages/documents/node_modules/@react-email/hr": {
"version": "0.0.12",
"resolved": "https://registry.npmjs.org/@react-email/hr/-/hr-0.0.12.tgz",
"integrity": "sha512-TwmOmBDibavUQpXBxpmZYi2Iks/yeZOzFYh+di9EltMSnEabH8dMZXrl+pxNXzCgZ2XE8HY7VmUL65Lenfu5PA==",
@@ -27239,7 +27634,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/html": {
+ "packages/documents/node_modules/@react-email/html": {
"version": "0.0.12",
"resolved": "https://registry.npmjs.org/@react-email/html/-/html-0.0.12.tgz",
"integrity": "sha512-KTShZesan+UsreU7PDUV90afrZwU5TLwYlALuCSU0OT+/U8lULNNbAUekg+tGwCnOfIKYtpDPKkAMRdYlqUznw==",
@@ -27251,7 +27646,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/img": {
+ "packages/documents/node_modules/@react-email/img": {
"version": "0.0.12",
"resolved": "https://registry.npmjs.org/@react-email/img/-/img-0.0.12.tgz",
"integrity": "sha512-sRCpEARNVTf3FQhZOC+JTvu5r6ubiYWkT0ucYXg8ctkyi4G8QG+jgYPiNUqVeTLA2STOfmPM/nrk1nb84y6CPQ==",
@@ -27263,7 +27658,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/link": {
+ "packages/documents/node_modules/@react-email/link": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/@react-email/link/-/link-0.0.13.tgz",
"integrity": "sha512-lkWc/NjOcefRZMkQoSDDbuKBEBDES9aXnFEOuPH845wD3TxPwh+QTf0fStuzjoRLUZWpHnio4z7qGGRYusn/sw==",
@@ -27275,7 +27670,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/markdown": {
+ "packages/documents/node_modules/@react-email/markdown": {
"version": "0.0.18",
"resolved": "https://registry.npmjs.org/@react-email/markdown/-/markdown-0.0.18.tgz",
"integrity": "sha512-gSuYK5fsMbGk87jDebqQ6fa2fKcWlkf2Dkva8kMONqLgGCq8/0d+ZQYMEJsdidIeBo3kmsnHZPrwdFB4HgjUXg==",
@@ -27290,7 +27685,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/preview": {
+ "packages/documents/node_modules/@react-email/preview": {
"version": "0.0.14",
"resolved": "https://registry.npmjs.org/@react-email/preview/-/preview-0.0.14.tgz",
"integrity": "sha512-aYK8q0IPkBXyMsbpMXgxazwHxYJxTrXrV95GFuu2HbEiIToMwSyUgb8HDFYwPqqfV03/jbwqlsXmFxsOd+VNaw==",
@@ -27302,10 +27697,10 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/render": {
- "version": "2.0.1",
- "resolved": "https://registry.npmjs.org/@react-email/render/-/render-2.0.1.tgz",
- "integrity": "sha512-eYNL4+SSrV1+58MIcT4znarX4YTMuYBr1uzhI6U8fBFvRMZPryxNOnD7jnZ/Ser3MtJEquQNbXjrAP+RVkfLbg==",
+ "packages/documents/node_modules/@react-email/render": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/@react-email/render/-/render-2.0.2.tgz",
+ "integrity": "sha512-AGuNo86TP9Y2JBUwFcT+z0frPDML4WLIFlnCi7laCPYJA+43kdim0y+qRNPxRxZkJiUz1JMPnE2M5HaNYhWwIg==",
"license": "MIT",
"dependencies": {
"html-to-text": "^9.0.5",
@@ -27319,7 +27714,7 @@
"react-dom": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/row": {
+ "packages/documents/node_modules/@react-email/row": {
"version": "0.0.13",
"resolved": "https://registry.npmjs.org/@react-email/row/-/row-0.0.13.tgz",
"integrity": "sha512-bYnOac40vIKCId7IkwuLAAsa3fKfSfqCvv6epJKmPE0JBuu5qI4FHFCl9o9dVpIIS08s/ub+Y/txoMt0dYziGw==",
@@ -27331,7 +27726,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/section": {
+ "packages/documents/node_modules/@react-email/section": {
"version": "0.0.17",
"resolved": "https://registry.npmjs.org/@react-email/section/-/section-0.0.17.tgz",
"integrity": "sha512-qNl65ye3W0Rd5udhdORzTV9ezjb+GFqQQSae03NDzXtmJq6sqVXNWNiVolAjvJNypim+zGXmv6J9TcV5aNtE/w==",
@@ -27343,7 +27738,7 @@
"react": "^18.0 || ^19.0 || ^19.0.0-rc"
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/tailwind": {
+ "packages/documents/node_modules/@react-email/tailwind": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@react-email/tailwind/-/tailwind-2.0.3.tgz",
"integrity": "sha512-URXb/T2WS4RlNGM5QwekYnivuiVUcU87H0y5sqLl6/Oi3bMmgL0Bmw/W9GeJylC+876Vw+E6NkE0uRiUFIQwGg==",
@@ -27401,7 +27796,7 @@
}
}
},
- "packages/documents/node_modules/@react-email/components/node_modules/@react-email/text": {
+ "packages/documents/node_modules/@react-email/text": {
"version": "0.1.6",
"resolved": "https://registry.npmjs.org/@react-email/text/-/text-0.1.6.tgz",
"integrity": "sha512-TYqkioRS45wTR5il3dYk/SbUjjEdhSwh9BtRNB99qNH1pXAwA45H7rAuxehiu8iJQJH0IyIr+6n62gBz9ezmsw==",
@@ -27426,9 +27821,9 @@
}
},
"packages/documents/node_modules/prettier": {
- "version": "3.7.4",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.7.4.tgz",
- "integrity": "sha512-v6UNi1+3hSlVvv8fSaoUbggEM5VErKmmpGA7Pl3HF8V6uKY7rvClBOJlH6yNwQtfTueNkGVpOv/mtWL9L4bgRA==",
+ "version": "3.8.0",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.8.0.tgz",
+ "integrity": "sha512-yEPsovQfpxYfgWNhCfECjG5AQaO+K3dp6XERmOepyPDVqcJm+bjyCVO3pmU+nAPe0N5dDvekfGezt/EIiRe1TA==",
"license": "MIT",
"bin": {
"prettier": "bin/prettier.cjs"
@@ -27528,6 +27923,7 @@
"@supabase/supabase-js": "2.80.0",
"@trigger.dev/sdk": "4.0.6",
"ai": "^5.0.88",
+ "kysely": "^0.28.10",
"nanoid": "5.0.4",
"resend": "^3.1.0",
"zod": "^3.25.76"
@@ -27554,13 +27950,6 @@
"typescript": "^5.2.2"
}
},
- "packages/kv/node_modules/@upstash/redis": {
- "version": "v1.34.3",
- "license": "MIT",
- "dependencies": {
- "crypto-js": "^4.2.0"
- }
- },
"packages/lib": {
"name": "@carbon/lib",
"version": "*",
@@ -27916,7 +28305,9 @@
}
},
"packages/tiptap/node_modules/@types/node": {
- "version": "22.19.3",
+ "version": "22.19.7",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.19.7.tgz",
+ "integrity": "sha512-MciR4AKGHWl7xwxkBa6xUGxQJ4VBOmPTF7sL+iGzuahOFaO0jHCsuEfS80pan1ef4gWId1oWOweIhrDEYLuaOw==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
diff --git a/package.json b/package.json
index a3cffac40c..bf0ee975df 100755
--- a/package.json
+++ b/package.json
@@ -14,7 +14,8 @@
"supabase": "2.54.11",
"ts-morph": "^22.0.0",
"tsx": "^4.13.2",
- "turbo": "^2.6.3"
+ "turbo": "^2.6.3",
+ "typescript": "5.8"
},
"lint-staged": {
"(apps|packages)/**/*.{js,ts,jsx,tsx}": [
diff --git a/packages/database/package.json b/packages/database/package.json
index 87687dee01..1aca51fb13 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -17,6 +17,7 @@
"exports": {
".": "./src/index.ts",
"./client": "./src/client.ts",
+ "./event": "./src/event.ts",
"./swagger-docs-schema": "./src/swagger-docs-schema.ts"
},
"private": true,
diff --git a/packages/database/src/event.ts b/packages/database/src/event.ts
new file mode 100644
index 0000000000..e18f3939c7
--- /dev/null
+++ b/packages/database/src/event.ts
@@ -0,0 +1,144 @@
+import type { Kysely } from "kysely";
+import { z } from "zod";
+import type { KyselyDatabase } from "./client.ts";
+
+export const OperationSchema = z.enum([
+ "INSERT",
+ "UPDATE",
+ "DELETE",
+ "TRUNCATE"
+]);
+
+const HandlerTypeSchema = z.enum(["WEBHOOK", "WORKFLOW", "SYNC"]);
+
+export const EventSchema = z.discriminatedUnion("operation", [
+ z.object({
+ table: z.string(),
+ operation: z.enum(["UPDATE"]),
+ recordId: z.string(),
+ new: z.record(z.any()),
+ old: z.record(z.any()),
+ timestamp: z.string()
+ }),
+ z.object({
+ table: z.string(),
+ operation: z.enum(["INSERT"]),
+ recordId: z.string(),
+ new: z.record(z.any()),
+ old: z.null(),
+ timestamp: z.string()
+ }),
+ z.object({
+ table: z.string(),
+ operation: z.enum(["DELETE", "TRUNCATE"]),
+ recordId: z.string(),
+ new: z.null(),
+ old: z.record(z.any()),
+ timestamp: z.string()
+ })
+]);
+
+export const QueueMessageSchema = z.object({
+ subscriptionId: z.string(),
+ triggerType: z.enum(["ROW", "STATEMENT"]),
+ handlerType: HandlerTypeSchema,
+ handlerConfig: z.record(z.any()),
+ companyId: z.string(),
+ event: EventSchema
+});
+
+export type EventSystemEvent = z.infer<typeof EventSchema>;
+export type HandlerType = z.infer<typeof HandlerTypeSchema>;
+export type QueueMessage = z.infer<typeof QueueMessageSchema>;
+
+// The Main Subscription Schema
+export const CreateSubscriptionSchema = z.object({
+ name: z.string().min(1, "Name is required"),
+ // The table name in your database
+ table: z.custom<keyof Pick<KyselyDatabase, keyof KyselyDatabase>>(
+ (val) => typeof val === "string",
+ {
+ message: "Table name must be a string"
+ }
+ ),
+ // The company this subscription belongs to
+ companyId: z.string().min(1, "Company ID is required"),
+ // Must provide at least one operation (e.g. ['INSERT'])
+ operations: z
+ .array(OperationSchema)
+ .min(1, "At least one operation is required"),
+ // The type determines how Trigger.dev processes it
+ type: HandlerTypeSchema,
+ // Configuration specific to the handler (URL for webhooks, WorkflowID for workflows)
+ // We allow any object here since it's stored as JSONB
+ config: z.record(z.any()).default({}),
+ // Database-level filtering (e.g. { status: "paid" })
+ filter: z.record(z.any()).default({}),
+ // Optimization: specific batch size for PGMQ
+ batchSize: z.number().int().positive().default(50),
+ // Defaults to true
+ active: z.boolean().default(true)
+});
+
+export type CreateSubscriptionParams = z.input<typeof CreateSubscriptionSchema>;
+
+export async function createEventSystemSubscription(
+ client: Kysely<KyselyDatabase>,
+ input: CreateSubscriptionParams
+) {
+ // 1. Runtime Validation
+ // This throws a clear ZodError if inputs are wrong (e.g. missing 'table' or invalid 'type')
+ const params = CreateSubscriptionSchema.parse(input);
+
+ // 2. Database Insert
+ // Note: We cast arrays/objects to ensure Postgres driver handles them correctly
+ const result = await client
+ .insertInto("eventSystemSubscription")
+ .values({
+ name: params.name,
+ table: params.table,
+ companyId: params.companyId,
+ operations: params.operations,
+ filter: params.filter,
+ handlerType: params.type,
+ config: params.config,
+ batchSize: params.batchSize,
+ active: params.active
+ })
+ .onConflict((oc) =>
+ oc.constraint("unique_subscription_name_per_company").doUpdateSet({
+ operations: params.operations,
+ filter: params.filter,
+ handlerType: params.type,
+ config: params.config,
+ batchSize: params.batchSize,
+ active: params.active
+ })
+ )
+ .returning(["id", "name", "handlerType", "table"])
+ .executeTakeFirst();
+
+ return result;
+}
+
+export async function deleteEventSystemSubscription(
+ client: Kysely<KyselyDatabase>,
+ subscriptionId: string
+) {
+ await client
+ .deleteFrom("eventSystemSubscription")
+ .where("id", "=", subscriptionId)
+ .execute();
+}
+
+export async function deleteEventSystemSubscriptionsByName(
+ client: Kysely<KyselyDatabase>,
+ companyId: string,
+ name: string
+) {
+ await client
+ .deleteFrom("eventSystemSubscription")
+ .where("companyId", "=", companyId)
+ .where("name", "=", name)
+ .execute();
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0447021b3d..20f5b27101 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -1461,6 +1461,9 @@ export default {
{
$ref: "#/parameters/rowFilter.consumables.itemPostingGroupId",
},
+ {
+ $ref: "#/parameters/rowFilter.consumables.externalId",
+ },
{
$ref: "#/parameters/rowFilter.consumables.createdBy",
},
@@ -2487,9 +2490,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customerLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.customerLocation.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -2567,9 +2567,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customerLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.customerLocation.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -2601,9 +2598,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customerLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.customerLocation.externalId",
- },
{
$ref: "#/parameters/body.customerLocation",
},
@@ -4110,131 +4104,23 @@ export default {
tags: ["approvalRequests"],
},
},
- "/jobOperationsWithDependencies": {
+ "/eventSystemTrigger": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.id",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobMakeMethodId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.order",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.processId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workCenterId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.description",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationOrder",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.overheadRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationType",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationMinimumCost",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationLeadTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationUnitCost",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationSupplierProcessId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workInstruction",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.companyId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdAt",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdBy",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedAt",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedBy",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.customFields",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationQuantity",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityComplete",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityScrapped",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityReworked",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.status",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.priority",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assignee",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.tableName",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.tags",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.type",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.procedureId",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.attachedFunctions",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.startDate",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.status",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dueDate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.systemTriggerName",
},
{
$ref: "#/parameters/select",
@@ -4263,7 +4149,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/jobOperationsWithDependencies",
+ $ref: "#/definitions/eventSystemTrigger",
},
type: "array",
},
@@ -4272,12 +4158,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["jobOperationsWithDependencies"],
+ tags: ["eventSystemTrigger"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.jobOperationsWithDependencies",
+ $ref: "#/parameters/body.eventSystemTrigger",
},
{
$ref: "#/parameters/select",
@@ -4291,132 +4177,55 @@ export default {
description: "Created",
},
},
- tags: ["jobOperationsWithDependencies"],
+ tags: ["eventSystemTrigger"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.id",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobMakeMethodId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.order",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.processId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workCenterId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.description",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineUnit",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationOrder",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.overheadRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineRate",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationType",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationMinimumCost",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationLeadTime",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationUnitCost",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationSupplierProcessId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workInstruction",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.companyId",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdAt",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdBy",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedAt",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedBy",
- },
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.customFields",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.tableName",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationQuantity",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.type",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityComplete",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.attachedFunctions",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityScrapped",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.status",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityReworked",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.systemTriggerName",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.status",
+ $ref: "#/parameters/preferReturn",
},
- {
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.priority",
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
},
+ },
+ tags: ["eventSystemTrigger"],
+ },
+ patch: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assignee",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.tableName",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.tags",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.type",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.procedureId",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.attachedFunctions",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.startDate",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.status",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dueDate",
+ $ref: "#/parameters/rowFilter.eventSystemTrigger.systemTriggerName",
},
{
- $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies",
+ $ref: "#/parameters/body.eventSystemTrigger",
},
{
$ref: "#/parameters/preferReturn",
@@ -4427,9 +4236,11 @@ export default {
description: "No Content",
},
},
- tags: ["jobOperationsWithDependencies"],
+ tags: ["eventSystemTrigger"],
},
- patch: {
+ },
+ "/jobOperationsWithDependencies": {
+ get: {
parameters: [
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.id",
@@ -4554,48 +4365,366 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies",
},
- {
- $ref: "#/parameters/body.jobOperationsWithDependencies",
- },
- {
- $ref: "#/parameters/preferReturn",
- },
- ],
- responses: {
- "204": {
- description: "No Content",
- },
- },
- tags: ["jobOperationsWithDependencies"],
- },
- },
- "/purchaseInvoicePriceChange": {
- get: {
- parameters: [
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.id",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.invoiceId",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.invoiceLineId",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.previousPrice",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.newPrice",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.previousQuantity",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.newQuantity",
- },
- {
- $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.updatedBy",
- },
+ {
+ $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/jobOperationsWithDependencies",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["jobOperationsWithDependencies"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobOperationsWithDependencies",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["jobOperationsWithDependencies"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobMakeMethodId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.order",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.processId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workCenterId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.overheadRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationMinimumCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationLeadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationUnitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationSupplierProcessId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workInstruction",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityComplete",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityScrapped",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityReworked",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.status",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.priority",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assignee",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.tags",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.procedureId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dueDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobOperationsWithDependencies"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.jobMakeMethodId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.order",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.processId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workCenterId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.setupUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineUnit",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationOrder",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.laborRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.overheadRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.machineRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationMinimumCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationLeadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationUnitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationSupplierProcessId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.workInstruction",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.operationQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityComplete",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityScrapped",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.quantityReworked",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.status",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.priority",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.assignee",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.tags",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.procedureId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.startDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dueDate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperationsWithDependencies.dependencies",
+ },
+ {
+ $ref: "#/parameters/body.jobOperationsWithDependencies",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobOperationsWithDependencies"],
+ },
+ },
+ "/purchaseInvoicePriceChange": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.invoiceId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.invoiceLineId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.previousPrice",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.newPrice",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.previousQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.newQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.purchaseInvoicePriceChange.updatedBy",
+ },
{
$ref: "#/parameters/select",
},
@@ -6369,9 +6498,6 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -6479,9 +6605,6 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -6543,9 +6666,6 @@ export default {
{
$ref: "#/parameters/rowFilter.nonConformanceActionTask.supplierId",
},
- {
- $ref: "#/parameters/rowFilter.nonConformanceActionTask.externalId",
- },
{
$ref: "#/parameters/body.nonConformanceActionTask",
},
@@ -11109,9 +11229,6 @@ export default {
{
$ref: "#/parameters/rowFilter.material.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.material.externalId",
- },
{
$ref: "#/parameters/rowFilter.material.tags",
},
@@ -11219,9 +11336,6 @@ export default {
{
$ref: "#/parameters/rowFilter.material.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.material.externalId",
- },
{
$ref: "#/parameters/rowFilter.material.tags",
},
@@ -11283,9 +11397,6 @@ export default {
{
$ref: "#/parameters/rowFilter.material.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.material.externalId",
- },
{
$ref: "#/parameters/rowFilter.material.tags",
},
@@ -13558,7 +13669,7 @@ export default {
$ref: "#/parameters/rowFilter.customers.invoicingContactId",
},
{
- $ref: "#/parameters/rowFilter.customers.defaultCc",
+ $ref: "#/parameters/rowFilter.customers.externalId",
},
{
$ref: "#/parameters/rowFilter.customers.type",
@@ -17112,9 +17223,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrder.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.salesOrder.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -17261,9 +17369,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrder.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.salesOrder.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -17364,9 +17469,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrder.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.salesOrder.externalId",
- },
{
$ref: "#/parameters/body.salesOrder",
},
@@ -19671,41 +19773,47 @@ export default {
tags: ["openJobMaterialLines"],
},
},
- "/sequence": {
+ "/externalIntegrationMapping": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.sequence.id",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.id",
},
{
- $ref: "#/parameters/rowFilter.sequence.table",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityType",
},
{
- $ref: "#/parameters/rowFilter.sequence.name",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityId",
},
{
- $ref: "#/parameters/rowFilter.sequence.prefix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.integration",
},
{
- $ref: "#/parameters/rowFilter.sequence.suffix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.externalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.next",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.allowDuplicateExternalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.size",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.metadata",
},
{
- $ref: "#/parameters/rowFilter.sequence.step",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.lastSyncedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.companyId",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.remoteUpdatedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedBy",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.companyId",
},
{
$ref: "#/parameters/select",
@@ -19734,7 +19842,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/sequence",
+ $ref: "#/definitions/externalIntegrationMapping",
},
type: "array",
},
@@ -19743,12 +19851,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["sequence"],
+ tags: ["externalIntegrationMapping"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.sequence",
+ $ref: "#/parameters/body.externalIntegrationMapping",
},
{
$ref: "#/parameters/select",
@@ -19762,42 +19870,48 @@ export default {
description: "Created",
},
},
- tags: ["sequence"],
+ tags: ["externalIntegrationMapping"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.sequence.id",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.id",
},
{
- $ref: "#/parameters/rowFilter.sequence.table",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityType",
},
{
- $ref: "#/parameters/rowFilter.sequence.name",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityId",
},
{
- $ref: "#/parameters/rowFilter.sequence.prefix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.integration",
},
{
- $ref: "#/parameters/rowFilter.sequence.suffix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.externalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.next",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.allowDuplicateExternalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.size",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.metadata",
},
{
- $ref: "#/parameters/rowFilter.sequence.step",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.lastSyncedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.companyId",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.remoteUpdatedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedBy",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.companyId",
},
{
$ref: "#/parameters/preferReturn",
@@ -19808,45 +19922,51 @@ export default {
description: "No Content",
},
},
- tags: ["sequence"],
+ tags: ["externalIntegrationMapping"],
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.sequence.id",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.id",
},
{
- $ref: "#/parameters/rowFilter.sequence.table",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityType",
},
{
- $ref: "#/parameters/rowFilter.sequence.name",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.entityId",
},
{
- $ref: "#/parameters/rowFilter.sequence.prefix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.integration",
},
{
- $ref: "#/parameters/rowFilter.sequence.suffix",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.externalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.next",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.allowDuplicateExternalId",
},
{
- $ref: "#/parameters/rowFilter.sequence.size",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.metadata",
},
{
- $ref: "#/parameters/rowFilter.sequence.step",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.lastSyncedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.companyId",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.remoteUpdatedAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdAt",
},
{
- $ref: "#/parameters/rowFilter.sequence.updatedBy",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.updatedAt",
},
{
- $ref: "#/parameters/body.sequence",
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.externalIntegrationMapping.companyId",
+ },
+ {
+ $ref: "#/parameters/body.externalIntegrationMapping",
},
{
$ref: "#/parameters/preferReturn",
@@ -19857,35 +19977,44 @@ export default {
description: "No Content",
},
},
- tags: ["sequence"],
+ tags: ["externalIntegrationMapping"],
},
},
- "/customerPayment": {
+ "/sequence": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.customerPayment.customerId",
+ $ref: "#/parameters/rowFilter.sequence.id",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
+ $ref: "#/parameters/rowFilter.sequence.table",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
+ $ref: "#/parameters/rowFilter.sequence.name",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
+ $ref: "#/parameters/rowFilter.sequence.prefix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
+ $ref: "#/parameters/rowFilter.sequence.suffix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.companyId",
+ $ref: "#/parameters/rowFilter.sequence.next",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
+ $ref: "#/parameters/rowFilter.sequence.size",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
+ $ref: "#/parameters/rowFilter.sequence.step",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedBy",
},
{
$ref: "#/parameters/select",
@@ -19914,7 +20043,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/customerPayment",
+ $ref: "#/definitions/sequence",
},
type: "array",
},
@@ -19923,12 +20052,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["customerPayment"],
+ tags: ["sequence"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.customerPayment",
+ $ref: "#/parameters/body.sequence",
},
{
$ref: "#/parameters/select",
@@ -19942,33 +20071,42 @@ export default {
description: "Created",
},
},
- tags: ["customerPayment"],
+ tags: ["sequence"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.customerPayment.customerId",
+ $ref: "#/parameters/rowFilter.sequence.id",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
+ $ref: "#/parameters/rowFilter.sequence.table",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
+ $ref: "#/parameters/rowFilter.sequence.name",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
+ $ref: "#/parameters/rowFilter.sequence.prefix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
+ $ref: "#/parameters/rowFilter.sequence.suffix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.companyId",
+ $ref: "#/parameters/rowFilter.sequence.next",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
+ $ref: "#/parameters/rowFilter.sequence.size",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
+ $ref: "#/parameters/rowFilter.sequence.step",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedBy",
},
{
$ref: "#/parameters/preferReturn",
@@ -19979,36 +20117,45 @@ export default {
description: "No Content",
},
},
- tags: ["customerPayment"],
+ tags: ["sequence"],
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.customerPayment.customerId",
+ $ref: "#/parameters/rowFilter.sequence.id",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
+ $ref: "#/parameters/rowFilter.sequence.table",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
+ $ref: "#/parameters/rowFilter.sequence.name",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
+ $ref: "#/parameters/rowFilter.sequence.prefix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
+ $ref: "#/parameters/rowFilter.sequence.suffix",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.companyId",
+ $ref: "#/parameters/rowFilter.sequence.next",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
+ $ref: "#/parameters/rowFilter.sequence.size",
},
{
- $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
+ $ref: "#/parameters/rowFilter.sequence.step",
},
{
- $ref: "#/parameters/body.customerPayment",
+ $ref: "#/parameters/rowFilter.sequence.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.sequence.updatedBy",
+ },
+ {
+ $ref: "#/parameters/body.sequence",
},
{
$ref: "#/parameters/preferReturn",
@@ -20019,41 +20166,35 @@ export default {
description: "No Content",
},
},
- tags: ["customerPayment"],
+ tags: ["sequence"],
},
},
- "/accountSubcategory": {
+ "/customerPayment": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.accountSubcategory.id",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.name",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
+ $ref: "#/parameters/rowFilter.customerPayment.customerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.active",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ $ref: "#/parameters/rowFilter.customerPayment.companyId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
},
{
$ref: "#/parameters/select",
@@ -20082,7 +20223,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/accountSubcategory",
+ $ref: "#/definitions/customerPayment",
},
type: "array",
},
@@ -20091,12 +20232,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["accountSubcategory"],
+ tags: ["customerPayment"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.accountSubcategory",
+ $ref: "#/parameters/body.customerPayment",
},
{
$ref: "#/parameters/select",
@@ -20110,39 +20251,33 @@ export default {
description: "Created",
},
},
- tags: ["accountSubcategory"],
+ tags: ["customerPayment"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.accountSubcategory.id",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.name",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
+ $ref: "#/parameters/rowFilter.customerPayment.customerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.active",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ $ref: "#/parameters/rowFilter.customerPayment.companyId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
},
{
$ref: "#/parameters/preferReturn",
@@ -20153,42 +20288,36 @@ export default {
description: "No Content",
},
},
- tags: ["accountSubcategory"],
+ tags: ["customerPayment"],
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.accountSubcategory.id",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.name",
- },
- {
- $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
+ $ref: "#/parameters/rowFilter.customerPayment.customerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.active",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerLocationId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ $ref: "#/parameters/rowFilter.customerPayment.invoiceCustomerContactId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ $ref: "#/parameters/rowFilter.customerPayment.paymentTermId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ $ref: "#/parameters/rowFilter.customerPayment.companyId",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ $ref: "#/parameters/rowFilter.customerPayment.updatedBy",
},
{
- $ref: "#/parameters/body.accountSubcategory",
+ $ref: "#/parameters/body.customerPayment",
},
{
$ref: "#/parameters/preferReturn",
@@ -20199,29 +20328,209 @@ export default {
description: "No Content",
},
},
- tags: ["accountSubcategory"],
+ tags: ["customerPayment"],
},
},
- "/trackedActivityInput": {
+ "/accountSubcategory": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.trackedActivityId",
+ $ref: "#/parameters/rowFilter.accountSubcategory.id",
},
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.trackedEntityId",
+ $ref: "#/parameters/rowFilter.accountSubcategory.name",
},
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.quantity",
+ $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
},
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.companyId",
+ $ref: "#/parameters/rowFilter.accountSubcategory.active",
},
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.createdAt",
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
},
{
- $ref: "#/parameters/rowFilter.trackedActivityInput.createdBy",
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ },
+ {
+ $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/accountSubcategory",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["accountSubcategory"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.accountSubcategory",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["accountSubcategory"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["accountSubcategory"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.accountCategoryId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.accountSubcategory.tags",
+ },
+ {
+ $ref: "#/parameters/body.accountSubcategory",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["accountSubcategory"],
+ },
+ },
+ "/trackedActivityInput": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.trackedActivityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.trackedEntityId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.trackedActivityInput.createdBy",
},
{
$ref: "#/parameters/select",
@@ -20376,9 +20685,6 @@ export default {
{
$ref: "#/parameters/rowFilter.consumable.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.consumable.externalId",
- },
{
$ref: "#/parameters/rowFilter.consumable.tags",
},
@@ -20468,9 +20774,6 @@ export default {
{
$ref: "#/parameters/rowFilter.consumable.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.consumable.externalId",
- },
{
$ref: "#/parameters/rowFilter.consumable.tags",
},
@@ -20514,9 +20817,6 @@ export default {
{
$ref: "#/parameters/rowFilter.consumable.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.consumable.externalId",
- },
{
$ref: "#/parameters/rowFilter.consumable.tags",
},
@@ -20976,6 +21276,126 @@ export default {
tags: ["materialType"],
},
},
+ "/services": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.services.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.assignee",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.defaultMethodType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.itemTrackingType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.replenishmentSystem",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.notes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.revision",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.readableId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.readableIdWithRevision",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.thumbnailPath",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.supplierIds",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.unitOfMeasure",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.revisions",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.tags",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.itemPostingGroupId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.externalId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.services.updatedAt",
+ },
+ {
+ $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/services",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["services"],
+ },
+ },
"/purchasePayment": {
get: {
parameters: [
@@ -22617,9 +23037,6 @@ export default {
{
$ref: "#/parameters/rowFilter.contact.companyId",
},
- {
- $ref: "#/parameters/rowFilter.contact.externalId",
- },
{
$ref: "#/parameters/rowFilter.contact.fullName",
},
@@ -22718,9 +23135,6 @@ export default {
{
$ref: "#/parameters/rowFilter.contact.companyId",
},
- {
- $ref: "#/parameters/rowFilter.contact.externalId",
- },
{
$ref: "#/parameters/rowFilter.contact.fullName",
},
@@ -22773,9 +23187,6 @@ export default {
{
$ref: "#/parameters/rowFilter.contact.companyId",
},
- {
- $ref: "#/parameters/rowFilter.contact.externalId",
- },
{
$ref: "#/parameters/rowFilter.contact.fullName",
},
@@ -23475,6 +23886,195 @@ export default {
tags: ["purchaseOrderStatusHistory"],
},
},
+ "/eventSystemSubscription": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.table",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.operations",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.filter",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.handlerType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.config",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.batchSize",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.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/eventSystemSubscription",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["eventSystemSubscription"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.eventSystemSubscription",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["eventSystemSubscription"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.table",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.operations",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.filter",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.handlerType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.config",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.batchSize",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.createdAt",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["eventSystemSubscription"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.table",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.operations",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.filter",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.handlerType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.config",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.batchSize",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.eventSystemSubscription.createdAt",
+ },
+ {
+ $ref: "#/parameters/body.eventSystemSubscription",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["eventSystemSubscription"],
+ },
+ },
"/nonConformanceWorkflow": {
get: {
parameters: [
@@ -30171,9 +30771,6 @@ export default {
{
$ref: "#/parameters/rowFilter.suppliers.embedding",
},
- {
- $ref: "#/parameters/rowFilter.suppliers.defaultCc",
- },
{
$ref: "#/parameters/rowFilter.suppliers.type",
},
@@ -34542,9 +35139,6 @@ export default {
{
$ref: "#/parameters/rowFilter.fixture.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.fixture.externalId",
- },
{
$ref: "#/parameters/rowFilter.fixture.tags",
},
@@ -34640,9 +35234,6 @@ export default {
{
$ref: "#/parameters/rowFilter.fixture.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.fixture.externalId",
- },
{
$ref: "#/parameters/rowFilter.fixture.tags",
},
@@ -34692,9 +35283,6 @@ export default {
{
$ref: "#/parameters/rowFilter.fixture.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.fixture.externalId",
- },
{
$ref: "#/parameters/rowFilter.fixture.tags",
},
@@ -38535,9 +39123,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.website",
},
- {
- $ref: "#/parameters/rowFilter.customer.externalId",
- },
{
$ref: "#/parameters/rowFilter.customer.taxPercent",
},
@@ -38669,9 +39254,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.website",
},
- {
- $ref: "#/parameters/rowFilter.customer.externalId",
- },
{
$ref: "#/parameters/rowFilter.customer.taxPercent",
},
@@ -38757,9 +39339,6 @@ export default {
{
$ref: "#/parameters/rowFilter.customer.website",
},
- {
- $ref: "#/parameters/rowFilter.customer.externalId",
- },
{
$ref: "#/parameters/rowFilter.customer.taxPercent",
},
@@ -38880,9 +39459,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId",
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrder.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -39026,9 +39602,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId",
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrder.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -39126,9 +39699,6 @@ export default {
{
$ref: "#/parameters/rowFilter.purchaseOrder.jobReadableId",
},
- {
- $ref: "#/parameters/rowFilter.purchaseOrder.externalId",
- },
{
$ref: "#/parameters/body.purchaseOrder",
},
@@ -40791,6 +41361,9 @@ export default {
{
$ref: "#/parameters/rowFilter.parts.itemPostingGroupId",
},
+ {
+ $ref: "#/parameters/rowFilter.parts.externalId",
+ },
{
$ref: "#/parameters/rowFilter.parts.createdBy",
},
@@ -41073,9 +41646,6 @@ export default {
{
$ref: "#/parameters/rowFilter.address.companyId",
},
- {
- $ref: "#/parameters/rowFilter.address.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -41165,9 +41735,6 @@ export default {
{
$ref: "#/parameters/rowFilter.address.companyId",
},
- {
- $ref: "#/parameters/rowFilter.address.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -41211,9 +41778,6 @@ export default {
{
$ref: "#/parameters/rowFilter.address.companyId",
},
- {
- $ref: "#/parameters/rowFilter.address.externalId",
- },
{
$ref: "#/parameters/body.address",
},
@@ -41331,6 +41895,9 @@ export default {
{
$ref: "#/parameters/rowFilter.materials.itemPostingGroupId",
},
+ {
+ $ref: "#/parameters/rowFilter.materials.externalId",
+ },
{
$ref: "#/parameters/rowFilter.materials.createdBy",
},
@@ -42069,9 +42636,6 @@ export default {
{
$ref: "#/parameters/rowFilter.tool.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.tool.externalId",
- },
{
$ref: "#/parameters/rowFilter.tool.tags",
},
@@ -42161,9 +42725,6 @@ export default {
{
$ref: "#/parameters/rowFilter.tool.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.tool.externalId",
- },
{
$ref: "#/parameters/rowFilter.tool.tags",
},
@@ -42207,9 +42768,6 @@ export default {
{
$ref: "#/parameters/rowFilter.tool.updatedAt",
},
- {
- $ref: "#/parameters/rowFilter.tool.externalId",
- },
{
$ref: "#/parameters/rowFilter.tool.tags",
},
@@ -42717,6 +43275,9 @@ export default {
{
$ref: "#/parameters/rowFilter.tools.itemPostingGroupId",
},
+ {
+ $ref: "#/parameters/rowFilter.tools.externalId",
+ },
{
$ref: "#/parameters/rowFilter.tools.createdBy",
},
@@ -48381,9 +48942,6 @@ export default {
{
$ref: "#/parameters/rowFilter.company.ownerId",
},
- {
- $ref: "#/parameters/rowFilter.company.externalId",
- },
{
$ref: "#/parameters/rowFilter.company.createdAt",
},
@@ -48512,9 +49070,6 @@ export default {
{
$ref: "#/parameters/rowFilter.company.ownerId",
},
- {
- $ref: "#/parameters/rowFilter.company.externalId",
- },
{
$ref: "#/parameters/rowFilter.company.createdAt",
},
@@ -48597,9 +49152,6 @@ export default {
{
$ref: "#/parameters/rowFilter.company.ownerId",
},
- {
- $ref: "#/parameters/rowFilter.company.externalId",
- },
{
$ref: "#/parameters/rowFilter.company.createdAt",
},
@@ -48822,9 +49374,6 @@ export default {
{
$ref: "#/parameters/rowFilter.user.acknowledgedITAR",
},
- {
- $ref: "#/parameters/rowFilter.user.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -48926,9 +49475,6 @@ export default {
{
$ref: "#/parameters/rowFilter.user.acknowledgedITAR",
},
- {
- $ref: "#/parameters/rowFilter.user.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -48984,9 +49530,6 @@ export default {
{
$ref: "#/parameters/rowFilter.user.acknowledgedITAR",
},
- {
- $ref: "#/parameters/rowFilter.user.externalId",
- },
{
$ref: "#/parameters/body.user",
},
@@ -49185,9 +49728,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.supplierLocation.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -49265,9 +49805,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.supplierLocation.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -49299,9 +49836,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplierLocation.tags",
},
- {
- $ref: "#/parameters/rowFilter.supplierLocation.externalId",
- },
{
$ref: "#/parameters/body.supplierLocation",
},
@@ -51165,9 +51699,6 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrders.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.salesOrders.externalId",
- },
{
$ref: "#/parameters/rowFilter.salesOrders.thumbnailPath",
},
@@ -51204,6 +51735,9 @@ export default {
{
$ref: "#/parameters/rowFilter.salesOrders.shippingCost",
},
+ {
+ $ref: "#/parameters/rowFilter.salesOrders.externalId",
+ },
{
$ref: "#/parameters/select",
},
@@ -54561,9 +55095,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.website",
},
- {
- $ref: "#/parameters/rowFilter.supplier.externalId",
- },
{
$ref: "#/parameters/rowFilter.supplier.tags",
},
@@ -54695,9 +55226,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.website",
},
- {
- $ref: "#/parameters/rowFilter.supplier.externalId",
- },
{
$ref: "#/parameters/rowFilter.supplier.tags",
},
@@ -54783,9 +55311,6 @@ export default {
{
$ref: "#/parameters/rowFilter.supplier.website",
},
- {
- $ref: "#/parameters/rowFilter.supplier.externalId",
- },
{
$ref: "#/parameters/rowFilter.supplier.tags",
},
@@ -55599,9 +56124,6 @@ export default {
{
$ref: "#/parameters/rowFilter.item.modelUploadId",
},
- {
- $ref: "#/parameters/rowFilter.item.externalId",
- },
{
$ref: "#/parameters/rowFilter.item.thumbnailPath",
},
@@ -55730,9 +56252,6 @@ export default {
{
$ref: "#/parameters/rowFilter.item.modelUploadId",
},
- {
- $ref: "#/parameters/rowFilter.item.externalId",
- },
{
$ref: "#/parameters/rowFilter.item.thumbnailPath",
},
@@ -55815,9 +56334,6 @@ export default {
{
$ref: "#/parameters/rowFilter.item.modelUploadId",
},
- {
- $ref: "#/parameters/rowFilter.item.externalId",
- },
{
$ref: "#/parameters/rowFilter.item.thumbnailPath",
},
@@ -60213,9 +60729,6 @@ export default {
{
$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.quote.externalId",
- },
{
$ref: "#/parameters/select",
},
@@ -60377,9 +60890,6 @@ export default {
{
$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.quote.externalId",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -60495,9 +61005,6 @@ export default {
{
$ref: "#/parameters/rowFilter.quote.customerEngineeringContactId",
},
- {
- $ref: "#/parameters/rowFilter.quote.externalId",
- },
{
$ref: "#/parameters/body.quote",
},
@@ -61425,9 +61932,6 @@ export default {
{
$ref: "#/parameters/rowFilter.part.customFields",
},
- {
- $ref: "#/parameters/rowFilter.part.externalId",
- },
{
$ref: "#/parameters/rowFilter.part.tags",
},
@@ -61523,9 +62027,6 @@ export default {
{
$ref: "#/parameters/rowFilter.part.customFields",
},
- {
- $ref: "#/parameters/rowFilter.part.externalId",
- },
{
$ref: "#/parameters/rowFilter.part.tags",
},
@@ -61575,9 +62076,6 @@ export default {
{
$ref: "#/parameters/rowFilter.part.customFields",
},
- {
- $ref: "#/parameters/rowFilter.part.externalId",
- },
{
$ref: "#/parameters/rowFilter.part.tags",
},
@@ -65113,6 +65611,48 @@ export default {
tags: ["(rpc) get_supplier_ids_with_supplier_permission"],
},
},
+ "/rpc/attach_event_trigger": {
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ sync_functions: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ table_name_text: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["table_name_text"],
+ 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) attach_event_trigger"],
+ },
+ },
"/rpc/get_job_operation_by_id": {
post: {
parameters: [
@@ -67422,6 +67962,9 @@ export default {
format: "text",
type: "string",
},
+ externalId: {
+ format: "jsonb",
+ },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -67874,9 +68417,6 @@ export default {
},
type: "array",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -68558,6 +69098,31 @@ export default {
},
type: "object",
},
+ eventSystemTrigger: {
+ properties: {
+ tableName: {
+ format: "text",
+ type: "string",
+ },
+ type: {
+ format: "text",
+ type: "string",
+ },
+ attachedFunctions: {
+ format: "text",
+ type: "string",
+ },
+ status: {
+ format: "text",
+ type: "string",
+ },
+ systemTriggerName: {
+ format: "name",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
jobOperationsWithDependencies: {
properties: {
id: {
@@ -69637,9 +70202,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "json",
- },
},
type: "object",
},
@@ -70507,7 +71069,7 @@ export default {
properties: {
id: {
description:
- "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -70556,7 +71118,7 @@ export default {
},
supplierLocationId: {
description:
- "Note:\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `supplierLocation.id`.<fk table='supplierLocation' column='id'/>",
format: "text",
type: "string",
},
@@ -72034,9 +72596,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -73270,12 +73829,8 @@ export default {
format: "text",
type: "string",
},
- defaultCc: {
- format: "text[]",
- items: {
- type: "string",
- },
- type: "array",
+ externalId: {
+ format: "jsonb",
},
type: {
format: "text",
@@ -75029,9 +75584,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -76201,6 +76753,81 @@ export default {
},
type: "object",
},
+ externalIntegrationMapping: {
+ required: [
+ "id",
+ "entityType",
+ "entityId",
+ "integration",
+ "allowDuplicateExternalId",
+ "createdAt",
+ "updatedAt",
+ "companyId",
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ entityType: {
+ format: "text",
+ type: "string",
+ },
+ entityId: {
+ format: "text",
+ type: "string",
+ },
+ integration: {
+ format: "text",
+ type: "string",
+ },
+ externalId: {
+ format: "text",
+ type: "string",
+ },
+ allowDuplicateExternalId: {
+ default: false,
+ format: "boolean",
+ type: "boolean",
+ },
+ metadata: {
+ format: "jsonb",
+ },
+ lastSyncedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ remoteUpdatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
sequence: {
required: ["id", "table", "name", "next", "size", "step", "companyId"],
properties: {
@@ -76471,9 +77098,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -76608,6 +77232,128 @@ export default {
},
type: "object",
},
+ services: {
+ properties: {
+ active: {
+ format: "boolean",
+ type: "boolean",
+ },
+ assignee: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ defaultMethodType: {
+ enum: ["Buy", "Make", "Pick"],
+ format: 'public."methodType"',
+ type: "string",
+ },
+ description: {
+ format: "text",
+ type: "string",
+ },
+ itemTrackingType: {
+ enum: ["Inventory", "Non-Inventory", "Serial", "Batch"],
+ format: 'public."itemTrackingType"',
+ type: "string",
+ },
+ name: {
+ format: "text",
+ type: "string",
+ },
+ replenishmentSystem: {
+ enum: ["Buy", "Make", "Buy and Make"],
+ format: 'public."itemReplenishmentSystem"',
+ type: "string",
+ },
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
+ notes: {
+ format: "jsonb",
+ },
+ revision: {
+ format: "text",
+ type: "string",
+ },
+ readableId: {
+ format: "text",
+ type: "string",
+ },
+ readableIdWithRevision: {
+ format: "text",
+ type: "string",
+ },
+ id: {
+ 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",
+ },
+ thumbnailPath: {
+ format: "text",
+ type: "string",
+ },
+ supplierIds: {
+ format: "text",
+ type: "string",
+ },
+ unitOfMeasure: {
+ format: "text",
+ type: "string",
+ },
+ revisions: {
+ format: "json",
+ },
+ customFields: {
+ format: "jsonb",
+ },
+ tags: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ itemPostingGroupId: {
+ description:
+ "Note:\nThis is a Foreign Key to `itemPostingGroup.id`.<fk table='itemPostingGroup' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ externalId: {
+ format: "jsonb",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
purchasePayment: {
required: [
"id",
@@ -77346,9 +78092,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
fullName: {
format: "text",
type: "string",
@@ -77634,6 +78377,72 @@ export default {
},
type: "object",
},
+ eventSystemSubscription: {
+ required: [
+ "id",
+ "name",
+ "companyId",
+ "table",
+ "operations",
+ "handlerType",
+ "config",
+ ],
+ properties: {
+ id: {
+ default: "public.id()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ name: {
+ format: "text",
+ type: "string",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ table: {
+ format: "text",
+ type: "string",
+ },
+ operations: {
+ format: "text[]",
+ items: {
+ type: "string",
+ },
+ type: "array",
+ },
+ filter: {
+ format: "jsonb",
+ },
+ handlerType: {
+ format: "text",
+ type: "string",
+ },
+ config: {
+ format: "jsonb",
+ },
+ batchSize: {
+ default: 50,
+ format: "integer",
+ type: "integer",
+ },
+ active: {
+ default: true,
+ format: "boolean",
+ type: "boolean",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
nonConformanceWorkflow: {
required: [
"id",
@@ -80813,13 +81622,6 @@ export default {
format: "extensions.halfvec(384)",
type: "string",
},
- defaultCc: {
- format: "text[]",
- items: {
- type: "string",
- },
- type: "array",
- },
type: {
format: "text",
type: "string",
@@ -83038,9 +83840,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -84593,9 +85392,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
taxPercent: {
default: 0,
format: "numeric",
@@ -84802,9 +85598,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -85775,6 +86568,9 @@ export default {
format: "text",
type: "string",
},
+ externalId: {
+ format: "jsonb",
+ },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -85924,9 +86720,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -86080,6 +86873,9 @@ export default {
format: "text",
type: "string",
},
+ externalId: {
+ format: "jsonb",
+ },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -86445,9 +87241,6 @@ export default {
format: "timestamp with time zone",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -86724,6 +87517,9 @@ export default {
format: "text",
type: "string",
},
+ externalId: {
+ format: "jsonb",
+ },
createdBy: {
description:
"Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
@@ -89582,9 +90378,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
createdAt: {
default: "now()",
format: "timestamp with time zone",
@@ -89796,9 +90589,6 @@ export default {
format: "boolean",
type: "boolean",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -89890,9 +90680,6 @@ export default {
},
type: "array",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -90795,9 +91582,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
thumbnailPath: {
format: "text",
type: "string",
@@ -90860,6 +91644,9 @@ export default {
format: "numeric",
type: "number",
},
+ externalId: {
+ format: "jsonb",
+ },
},
type: "object",
},
@@ -92607,9 +93394,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -93203,9 +93987,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
thumbnailPath: {
format: "text",
type: "string",
@@ -95507,9 +96288,6 @@ export default {
format: "text",
type: "string",
},
- externalId: {
- format: "jsonb",
- },
},
type: "object",
},
@@ -96008,9 +96786,6 @@ export default {
customFields: {
format: "jsonb",
},
- externalId: {
- format: "jsonb",
- },
tags: {
format: "text[]",
items: {
@@ -97265,6 +98040,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.consumables.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.consumables.createdBy": {
name: "createdBy",
required: false,
@@ -97784,12 +98565,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.customerLocation.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.oauthToken": {
name: "oauthToken",
description: "oauthToken",
@@ -98591,6 +99366,45 @@ export default {
in: "query",
type: "string",
},
+ "body.eventSystemTrigger": {
+ name: "eventSystemTrigger",
+ description: "eventSystemTrigger",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/eventSystemTrigger",
+ },
+ },
+ "rowFilter.eventSystemTrigger.tableName": {
+ name: "tableName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemTrigger.type": {
+ name: "type",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemTrigger.attachedFunctions": {
+ name: "attachedFunctions",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemTrigger.status": {
+ name: "status",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemTrigger.systemTriggerName": {
+ name: "systemTriggerName",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.jobOperationsWithDependencies": {
name: "jobOperationsWithDependencies",
description: "jobOperationsWithDependencies",
@@ -99779,12 +100593,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.nonConformanceActionTask.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.supplierInteraction": {
name: "supplierInteraction",
description: "supplierInteraction",
@@ -102506,12 +103314,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.material.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.material.tags": {
name: "tags",
required: false,
@@ -103895,8 +104697,8 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.customers.defaultCc": {
- name: "defaultCc",
+ "rowFilter.customers.externalId": {
+ name: "externalId",
required: false,
in: "query",
type: "string",
@@ -105845,12 +106647,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.salesOrder.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.jobOperationTool": {
name: "jobOperationTool",
description: "jobOperationTool",
@@ -107152,6 +107948,93 @@ export default {
in: "query",
type: "string",
},
+ "body.externalIntegrationMapping": {
+ name: "externalIntegrationMapping",
+ description: "externalIntegrationMapping",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/externalIntegrationMapping",
+ },
+ },
+ "rowFilter.externalIntegrationMapping.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.entityType": {
+ name: "entityType",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.entityId": {
+ name: "entityId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.integration": {
+ name: "integration",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.allowDuplicateExternalId": {
+ name: "allowDuplicateExternalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.metadata": {
+ name: "metadata",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.lastSyncedAt": {
+ name: "lastSyncedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.remoteUpdatedAt": {
+ name: "remoteUpdatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.externalIntegrationMapping.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.sequence": {
name: "sequence",
description: "sequence",
@@ -107461,12 +108344,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.consumable.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.consumable.tags": {
name: "tags",
required: false,
@@ -107614,6 +108491,171 @@ export default {
in: "query",
type: "string",
},
+ "body.services": {
+ name: "services",
+ description: "services",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/services",
+ },
+ },
+ "rowFilter.services.active": {
+ name: "active",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.assignee": {
+ name: "assignee",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.defaultMethodType": {
+ name: "defaultMethodType",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.description": {
+ name: "description",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.itemTrackingType": {
+ name: "itemTrackingType",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.replenishmentSystem": {
+ name: "replenishmentSystem",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.notes": {
+ name: "notes",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.revision": {
+ name: "revision",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.readableId": {
+ name: "readableId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.readableIdWithRevision": {
+ name: "readableIdWithRevision",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.thumbnailPath": {
+ name: "thumbnailPath",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.supplierIds": {
+ name: "supplierIds",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.unitOfMeasure": {
+ name: "unitOfMeasure",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.revisions": {
+ name: "revisions",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.customFields": {
+ name: "customFields",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.tags": {
+ name: "tags",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.itemPostingGroupId": {
+ name: "itemPostingGroupId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.createdBy": {
+ name: "createdBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.services.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.purchasePayment": {
name: "purchasePayment",
description: "purchasePayment",
@@ -108448,12 +109490,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.contact.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.contact.fullName": {
name: "fullName",
required: false,
@@ -108776,6 +109812,81 @@ export default {
in: "query",
type: "string",
},
+ "body.eventSystemSubscription": {
+ name: "eventSystemSubscription",
+ description: "eventSystemSubscription",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/eventSystemSubscription",
+ },
+ },
+ "rowFilter.eventSystemSubscription.id": {
+ name: "id",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.name": {
+ name: "name",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.companyId": {
+ name: "companyId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.table": {
+ name: "table",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.operations": {
+ name: "operations",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.filter": {
+ name: "filter",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.handlerType": {
+ name: "handlerType",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.config": {
+ name: "config",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.batchSize": {
+ name: "batchSize",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.active": {
+ name: "active",
+ required: false,
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.eventSystemSubscription.createdAt": {
+ name: "createdAt",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.nonConformanceWorkflow": {
name: "nonConformanceWorkflow",
description: "nonConformanceWorkflow",
@@ -112306,12 +113417,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.suppliers.defaultCc": {
- name: "defaultCc",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.suppliers.type": {
name: "type",
required: false,
@@ -114910,12 +116015,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.fixture.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.fixture.tags": {
name: "tags",
required: false,
@@ -116588,12 +117687,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.customer.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.customer.taxPercent": {
name: "taxPercent",
required: false,
@@ -116807,12 +117900,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.purchaseOrder.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.maintenanceDispatchComment": {
name: "maintenanceDispatchComment",
description: "maintenanceDispatchComment",
@@ -117998,6 +119085,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.parts.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.parts.createdBy": {
name: "createdBy",
required: false,
@@ -118172,12 +119265,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.address.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.materials": {
name: "materials",
description: "materials",
@@ -118385,6 +119472,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.materials.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.materials.createdBy": {
name: "createdBy",
required: false,
@@ -118757,12 +119850,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.tool.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.tool.tags": {
name: "tags",
required: false,
@@ -119096,6 +120183,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.tools.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"rowFilter.tools.createdBy": {
name: "createdBy",
required: false,
@@ -122269,12 +123362,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.company.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.company.createdAt": {
name: "createdAt",
required: false,
@@ -122542,12 +123629,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.user.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.externalLink": {
name: "externalLink",
description: "externalLink",
@@ -122650,12 +123731,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.supplierLocation.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.documents": {
name: "documents",
description: "documents",
@@ -123598,12 +124673,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.salesOrders.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.salesOrders.thumbnailPath": {
name: "thumbnailPath",
required: false,
@@ -123676,6 +124745,12 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.salesOrders.externalId": {
+ name: "externalId",
+ required: false,
+ in: "query",
+ type: "string",
+ },
"body.nonConformance": {
name: "nonConformance",
description: "nonConformance",
@@ -125701,12 +126776,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.supplier.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.supplier.tags": {
name: "tags",
required: false,
@@ -126322,12 +127391,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.item.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.item.thumbnailPath": {
name: "thumbnailPath",
required: false,
@@ -128926,12 +129989,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.quote.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"body.salesInvoiceLine": {
name: "salesInvoiceLine",
description: "salesInvoiceLine",
@@ -129439,12 +130496,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.part.externalId": {
- name: "externalId",
- required: false,
- in: "query",
- type: "string",
- },
"rowFilter.part.tags": {
name: "tags",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 78f8627523..c73ee27898 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -1530,7 +1530,6 @@ export type Database = {
city: string | null
companyId: string
countryCode: string | null
- externalId: Json | null
fax: string | null
id: string
phone: string | null
@@ -1543,7 +1542,6 @@ export type Database = {
city?: string | null
companyId: string
countryCode?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
phone?: string | null
@@ -1556,7 +1554,6 @@ export type Database = {
city?: string | null
companyId?: string
countryCode?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
phone?: string | null
@@ -2306,6 +2303,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "batchProperty_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "batchProperty_itemId_fkey"
columns: ["itemId"]
@@ -2422,7 +2426,6 @@ export type Database = {
countryCode: string | null
createdAt: string
email: string | null
- externalId: Json | null
fax: string | null
id: string
logoDark: string | null
@@ -2448,7 +2451,6 @@ export type Database = {
countryCode?: string | null
createdAt?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
logoDark?: string | null
@@ -2474,7 +2476,6 @@ export type Database = {
countryCode?: string | null
createdAt?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
logoDark?: string | null
@@ -3023,6 +3024,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationParameter_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationParameter_itemId_fkey"
columns: ["itemId"]
@@ -3156,6 +3164,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationParameterGroup_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationParameterGroup_itemId_fkey"
columns: ["itemId"]
@@ -3247,6 +3262,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationRule_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationRule_itemId_fkey"
columns: ["itemId"]
@@ -3299,7 +3321,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
id: string
tags: string[] | null
updatedAt: string | null
@@ -3312,7 +3333,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
id: string
tags?: string[] | null
updatedAt?: string | null
@@ -3325,7 +3345,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
tags?: string[] | null
updatedAt?: string | null
@@ -3471,7 +3490,6 @@ export type Database = {
Row: {
companyId: string
email: string | null
- externalId: Json | null
fax: string | null
firstName: string | null
fullName: string | null
@@ -3487,7 +3505,6 @@ export type Database = {
Insert: {
companyId: string
email?: string | null
- externalId?: Json | null
fax?: string | null
firstName?: string | null
fullName?: string | null
@@ -3503,7 +3520,6 @@ export type Database = {
Update: {
companyId?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
firstName?: string | null
fullName?: string | null
@@ -4059,7 +4075,6 @@ export type Database = {
customFields: Json | null
defaultCc: string[] | null
embedding: unknown
- externalId: Json | null
fax: string | null
id: string
invoicingContactId: string | null
@@ -4086,7 +4101,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -4113,7 +4127,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -4546,7 +4559,6 @@ export type Database = {
addressId: string
customerId: string
customFields: Json | null
- externalId: Json | null
id: string
name: string
tags: string[] | null
@@ -4555,7 +4567,6 @@ export type Database = {
addressId: string
customerId: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name: string
tags?: string[] | null
@@ -4564,7 +4575,6 @@ export type Database = {
addressId?: string
customerId?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name?: string
tags?: string[] | null
@@ -4703,6 +4713,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "customerPartToItem_itemId_fkey"
columns: ["itemId"]
@@ -5633,6 +5650,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandActual_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandActual_itemId_fkey"
columns: ["itemId"]
@@ -5826,6 +5850,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandForecast_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandForecast_itemId_fkey"
columns: ["itemId"]
@@ -6019,6 +6050,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandProjection_itemId_fkey"
columns: ["itemId"]
@@ -7029,6 +7067,189 @@ export type Database = {
},
]
}
+ eventSystemSubscription: {
+ Row: {
+ active: boolean | null
+ batchSize: number | null
+ companyId: string
+ config: Json
+ createdAt: string | null
+ filter: Json | null
+ handlerType: string
+ id: string
+ name: string
+ operations: string[]
+ table: string
+ }
+ Insert: {
+ active?: boolean | null
+ batchSize?: number | null
+ companyId: string
+ config?: Json
+ createdAt?: string | null
+ filter?: Json | null
+ handlerType: string
+ id?: string
+ name: string
+ operations: string[]
+ table: string
+ }
+ Update: {
+ active?: boolean | null
+ batchSize?: number | null
+ companyId?: string
+ config?: Json
+ createdAt?: string | null
+ filter?: Json | null
+ handlerType?: string
+ id?: string
+ name?: string
+ operations?: string[]
+ table?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
+ externalIntegrationMapping: {
+ Row: {
+ allowDuplicateExternalId: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string | null
+ entityId: string
+ entityType: string
+ externalId: string | null
+ id: string
+ integration: string
+ lastSyncedAt: string | null
+ metadata: Json | null
+ remoteUpdatedAt: string | null
+ updatedAt: string
+ }
+ Insert: {
+ allowDuplicateExternalId?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy?: string | null
+ entityId: string
+ entityType: string
+ externalId?: string | null
+ id?: string
+ integration: string
+ lastSyncedAt?: string | null
+ metadata?: Json | null
+ remoteUpdatedAt?: string | null
+ updatedAt?: string
+ }
+ Update: {
+ allowDuplicateExternalId?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string | null
+ entityId?: string
+ entityType?: string
+ externalId?: string | null
+ id?: string
+ integration?: string
+ lastSyncedAt?: string | null
+ metadata?: Json | null
+ remoteUpdatedAt?: string | null
+ updatedAt?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
externalLink: {
Row: {
companyId: string
@@ -7301,7 +7522,6 @@ export type Database = {
createdBy: string
customerId: string | null
customFields: Json | null
- externalId: Json | null
id: string
itemId: string | null
tags: string[] | null
@@ -7316,7 +7536,6 @@ export type Database = {
createdBy: string
customerId?: string | null
customFields?: Json | null
- externalId?: Json | null
id: string
itemId?: string | null
tags?: string[] | null
@@ -7331,7 +7550,6 @@ export type Database = {
createdBy?: string
customerId?: string | null
customFields?: Json | null
- externalId?: Json | null
id?: string
itemId?: string | null
tags?: string[] | null
@@ -7486,6 +7704,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "fixture_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "fixture_itemId_fkey"
columns: ["itemId"]
@@ -8623,7 +8848,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
embedding: unknown
- externalId: Json | null
id: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId: string | null
@@ -8649,7 +8873,6 @@ export type Database = {
defaultMethodType?: Database["public"]["Enums"]["methodType"] | null
description?: string | null
embedding?: unknown
- externalId?: Json | null
id?: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId?: string | null
@@ -8675,7 +8898,6 @@ export type Database = {
defaultMethodType?: Database["public"]["Enums"]["methodType"] | null
description?: string | null
embedding?: unknown
- externalId?: Json | null
id?: string
itemTrackingType?: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId?: string | null
@@ -8959,6 +9181,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemCost_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemCost_itemId_fkey"
columns: ["itemId"]
@@ -9170,6 +9399,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemLedger_itemId_fkey"
columns: ["itemId"]
@@ -9387,6 +9623,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemPlanning_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemPlanning_itemId_fkey"
columns: ["itemId"]
@@ -9729,6 +9972,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemReplenishment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: true
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemReplenishment_itemId_fkey"
columns: ["itemId"]
@@ -9970,6 +10220,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemUnitSalePrice_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemUnitSalePrice_itemId_fkey"
columns: ["itemId"]
@@ -10290,6 +10547,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -10637,6 +10901,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMakeMethod_itemId_fkey"
columns: ["itemId"]
@@ -10913,6 +11184,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -12295,6 +12573,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -12667,6 +12952,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "kanban_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "kanban_itemId_fkey"
columns: ["itemId"]
@@ -13740,6 +14032,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatchItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatchItem_itemId_fkey"
columns: ["itemId"]
@@ -14587,6 +14886,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
columns: ["itemId"]
@@ -14777,6 +15083,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "method_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "method_itemId_fkey"
columns: ["itemId"]
@@ -14795,7 +15108,6 @@ export type Database = {
createdBy: string
customFields: Json | null
dimensionId: string | null
- externalId: Json | null
finishId: string | null
gradeId: string | null
id: string
@@ -14814,7 +15126,6 @@ export type Database = {
createdBy: string
customFields?: Json | null
dimensionId?: string | null
- externalId?: Json | null
finishId?: string | null
gradeId?: string | null
id?: string
@@ -14833,7 +15144,6 @@ export type Database = {
createdBy?: string
customFields?: Json | null
dimensionId?: string | null
- externalId?: Json | null
finishId?: string | null
gradeId?: string | null
id?: string
@@ -15803,6 +16113,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "methodMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodMaterial_itemId_fkey"
columns: ["itemId"]
@@ -16589,6 +16906,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "methodOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -17192,7 +17516,6 @@ export type Database = {
createdAt: string
createdBy: string
dueDate: string | null
- externalId: Json | null
id: string
nonConformanceId: string
notes: Json
@@ -17211,7 +17534,6 @@ export type Database = {
createdAt?: string
createdBy: string
dueDate?: string | null
- externalId?: Json | null
id?: string
nonConformanceId: string
notes?: Json
@@ -17230,7 +17552,6 @@ export type Database = {
createdAt?: string
createdBy?: string
dueDate?: string | null
- externalId?: Json | null
id?: string
nonConformanceId?: string
notes?: Json
@@ -17937,6 +18258,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "nonConformanceItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "nonConformanceItem_itemId_fkey"
columns: ["itemId"]
@@ -20438,7 +20766,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
fromDate: string | null
id: string
tags: string[] | null
@@ -20453,7 +20780,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
fromDate?: string | null
id?: string
tags?: string[] | null
@@ -20468,7 +20794,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
fromDate?: string | null
id?: string
tags?: string[] | null
@@ -21067,6 +21392,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "pickMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "pickMethod_itemId_fkey"
columns: ["itemId"]
@@ -23674,6 +24006,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
columns: ["itemId"]
@@ -23966,7 +24305,6 @@ export type Database = {
customFields: Json | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- externalId: Json | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -23997,7 +24335,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -24028,7 +24365,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -24771,6 +25107,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -25849,6 +26192,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchasingRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchasingRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -26596,7 +26946,6 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
- externalId: Json | null
externalLinkId: string | null
externalNotes: Json | null
id: string
@@ -26633,7 +26982,6 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
- externalId?: Json | null
externalLinkId?: string | null
externalNotes?: Json | null
id?: string
@@ -26670,7 +27018,6 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
- externalId?: Json | null
externalLinkId?: string | null
externalNotes?: Json | null
id?: string
@@ -27251,6 +27598,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -27668,6 +28022,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMakeMethod_itemId_fkey"
columns: ["itemId"]
@@ -27939,6 +28300,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMaterial_itemId_fkey"
columns: ["itemId"]
@@ -28803,6 +29171,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -29544,6 +29919,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receiptLine_itemId_fkey"
columns: ["itemId"]
@@ -29791,6 +30173,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "riskRegister_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "riskRegister_itemId_fkey"
columns: ["itemId"]
@@ -30337,6 +30726,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_itemId_fkey"
columns: ["itemId"]
@@ -30645,7 +31041,6 @@ export type Database = {
customFields: Json | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- externalId: Json | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -30677,7 +31072,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -30709,7 +31103,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -31235,6 +31628,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -32388,6 +32788,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -32935,6 +33342,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "service_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "service_itemId_fkey"
columns: ["itemId"]
@@ -33796,6 +34210,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "shipmentLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "shipmentLine_itemId_fkey"
columns: ["itemId"]
@@ -34647,6 +35068,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "stockTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -34865,7 +35293,6 @@ export type Database = {
customFields: Json | null
defaultCc: string[] | null
embedding: unknown
- externalId: Json | null
fax: string | null
id: string
invoicingContactId: string | null
@@ -34892,7 +35319,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -34919,7 +35345,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -35572,7 +35997,6 @@ export type Database = {
Row: {
addressId: string
customFields: Json | null
- externalId: Json | null
id: string
name: string
supplierId: string
@@ -35581,7 +36005,6 @@ export type Database = {
Insert: {
addressId: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name: string
supplierId: string
@@ -35590,7 +36013,6 @@ export type Database = {
Update: {
addressId?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name?: string
supplierId?: string
@@ -35788,6 +36210,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "buyMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "buyMethod_itemId_fkey"
columns: ["itemId"]
@@ -36773,6 +37202,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplierQuoteLine_itemId_fkey"
columns: ["itemId"]
@@ -37609,6 +38045,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplyActual_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplyActual_itemId_fkey"
columns: ["itemId"]
@@ -37805,6 +38248,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplyForecast_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplyForecast_itemId_fkey"
columns: ["itemId"]
@@ -38200,7 +38650,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
id: string
tags: string[] | null
updatedAt: string | null
@@ -38213,7 +38662,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
id: string
tags?: string[] | null
updatedAt?: string | null
@@ -38226,7 +38674,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
tags?: string[] | null
updatedAt?: string | null
@@ -39646,7 +40093,6 @@ export type Database = {
createdAt: string
developer: boolean | null
email: string
- externalId: Json | null
firstName: string
fullName: string | null
id: string
@@ -39663,7 +40109,6 @@ export type Database = {
createdAt?: string
developer?: boolean | null
email: string
- externalId?: Json | null
firstName?: string
fullName?: string | null
id: string
@@ -39680,7 +40125,6 @@ export type Database = {
createdAt?: string
developer?: boolean | null
email?: string
- externalId?: Json | null
firstName?: string
fullName?: string | null
id?: string
@@ -40783,6 +41227,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "warehouseTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "warehouseTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -41442,6 +41893,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "workCenterReplacementPart_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "workCenterReplacementPart_itemId_fkey"
columns: ["itemId"]
@@ -42201,6 +42659,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "method_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "method_itemId_fkey"
columns: ["itemId"]
@@ -42511,6 +42976,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -42860,7 +43326,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
- defaultCc: string[] | null
+ externalId: Json | null
fax: string | null
id: string | null
invoicingContactId: string | null
@@ -43346,6 +43812,30 @@ export type Database = {
},
]
}
+ eventSystemTrigger: {
+ Row: {
+ attachedFunctions: string | null
+ status: string | null
+ systemTriggerName: unknown
+ tableName: string | null
+ type: string | null
+ }
+ Insert: {
+ attachedFunctions?: never
+ status?: never
+ systemTriggerName?: unknown
+ tableName?: never
+ type?: never
+ }
+ Update: {
+ attachedFunctions?: never
+ status?: never
+ systemTriggerName?: unknown
+ tableName?: never
+ type?: never
+ }
+ Relationships: []
+ }
gaugeCalibrationRecords: {
Row: {
approvedBy: string | null
@@ -44304,6 +44794,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -45281,6 +45778,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -45531,6 +46035,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "kanban_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "kanban_itemId_fkey"
columns: ["itemId"]
@@ -45969,6 +46480,7 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
dimensions: string | null
+ externalId: Json | null
finish: string | null
grade: string | null
id: string | null
@@ -46354,6 +46866,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -46488,6 +47007,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -46601,6 +47127,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -46682,6 +47215,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -46870,6 +47410,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -47471,6 +48012,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
columns: ["itemId"]
@@ -48018,6 +48566,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -48695,6 +49250,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchasingRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchasingRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -49441,6 +50003,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -49707,6 +50276,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -49928,6 +50504,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMaterial_itemId_fkey"
columns: ["itemId"]
@@ -50729,6 +51312,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receiptLine_itemId_fkey"
columns: ["itemId"]
@@ -50942,6 +51532,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "riskRegister_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "riskRegister_itemId_fkey"
columns: ["itemId"]
@@ -51123,6 +51720,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_itemId_fkey"
columns: ["itemId"]
@@ -51274,14 +51878,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"]
@@ -51715,6 +52319,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -52248,6 +52859,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -52599,6 +53217,189 @@ export type Database = {
},
]
}
+ services: {
+ Row: {
+ active: boolean | null
+ assignee: string | null
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ defaultMethodType: Database["public"]["Enums"]["methodType"] | null
+ description: string | null
+ externalId: Json | null
+ id: string | null
+ itemPostingGroupId: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ name: string | null
+ notes: Json | null
+ readableId: string | null
+ readableIdWithRevision: string | null
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null
+ revision: string | null
+ revisions: Json | null
+ supplierIds: string | null
+ tags: string[] | null
+ thumbnailPath: string | null
+ unitOfMeasure: string | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "item_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"
+ columns: ["itemPostingGroupId"]
+ isOneToOne: false
+ referencedRelation: "itemPostingGroup"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
shifts: {
Row: {
active: boolean | null
@@ -52826,6 +53627,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "shipmentLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "shipmentLine_itemId_fkey"
columns: ["itemId"]
@@ -53017,6 +53825,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "stockTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -53494,6 +54309,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplierQuoteLine_itemId_fkey"
columns: ["itemId"]
@@ -53807,7 +54629,6 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
- defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -54046,6 +54867,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -54625,6 +55447,10 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ attach_event_trigger: {
+ Args: { sync_functions?: string[]; table_name_text: string }
+ Returns: undefined
+ }
check_operation_dependencies: {
Args: { operation_id: string }
Returns: boolean
@@ -55033,6 +55859,7 @@ export type Database = {
Args: { jid: string }
Returns: {
description: string
+ externalId: Json
isRoot: boolean
itemId: string
itemReadableId: string
diff --git a/packages/database/src/utils.ts b/packages/database/src/utils.ts
index 16b44ac763..b8ee2160af 100644
--- a/packages/database/src/utils.ts
+++ b/packages/database/src/utils.ts
@@ -3,7 +3,7 @@ import type {
PostgrestFilterBuilder
} from "@supabase/postgrest-js";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { Database } from "./types.ts";
+import type { Database } from "./types.ts";
const BATCH_SIZE = 1000;
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index c76af8e0fe..dc93c14f08 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -34,6 +34,69 @@ const importCsvValidator = z.object({
const EXTERNAL_ID_KEY = "csv";
+/**
+ * Build a map of CSV external IDs → entity IDs from the externalIntegrationMapping table.
+ */
+async function getCsvExternalIdMap(
+ entityType: string,
+ cId: string
+): Promise<Map<string, string>> {
+ const result = await db
+ .selectFrom("externalIntegrationMapping")
+ .select(["externalId", "entityId"])
+ .where("entityType", "=", entityType)
+ .where("integration", "=", EXTERNAL_ID_KEY)
+ .where("companyId", "=", cId)
+ .execute();
+
+ return new Map(
+ result
+ .filter((r): r is typeof r & { externalId: string } => r.externalId !== null)
+ .map((r) => [r.externalId, r.entityId])
+ );
+}
+
+/**
+ * Upsert CSV external ID mappings into the externalIntegrationMapping table.
+ * Uses ON CONFLICT to handle re-imports idempotently.
+ */
+async function upsertCsvMappings(
+ trx: typeof db,
+ entityType: string,
+ mappings: Array<{ entityId: string; externalId: string }>,
+ cId: string,
+ userId: string
+): Promise<void> {
+ if (mappings.length === 0) return;
+
+ const now = new Date().toISOString();
+
+ await trx
+ .insertInto("externalIntegrationMapping")
+ .values(
+ mappings.map((m) => ({
+ entityType,
+ entityId: m.entityId,
+ integration: EXTERNAL_ID_KEY,
+ externalId: m.externalId,
+ companyId: cId,
+ allowDuplicateExternalId: false,
+ createdBy: userId,
+ createdAt: now,
+ updatedAt: now,
+ }))
+ )
+ .onConflict((oc) =>
+ oc
+ .columns(["entityType", "entityId", "integration", "companyId"])
+ .doUpdateSet((eb) => ({
+ externalId: eb.ref("excluded.externalId"),
+ updatedAt: eb.ref("excluded.updatedAt"),
+ }))
+ )
+ .execute();
+}
+
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
@@ -119,33 +182,13 @@ serve(async (req: Request) => {
switch (table) {
case "customer": {
- const currentCustomers = await db
- .selectFrom(table)
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const externalIdMap = new Map(
- currentCustomers.reduce((acc, customer) => {
- if (
- customer.externalId &&
- typeof customer.externalId === "object" &&
- EXTERNAL_ID_KEY in customer.externalId
- ) {
- acc.set(customer.externalId[EXTERNAL_ID_KEY] as string, {
- id: customer.id!,
- externalId: customer.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
-
+ const externalIdMap = await getCsvExternalIdMap("customer", companyId);
const customerIds = new Set();
await db.transaction().execute(async (trx) => {
const customerInserts: Database["public"]["Tables"]["customer"]["Insert"][] =
[];
+ const csvIdsForInserts: string[] = [];
const customerUpdates: {
id: string;
data: Database["public"]["Tables"]["customer"]["Update"];
@@ -160,18 +203,15 @@ serve(async (req: Request) => {
for (const record of mappedRecords) {
const { id, ...rest } = record;
if (externalIdMap.has(id)) {
- const existingCustomer = externalIdMap.get(id)!;
+ const existingEntityId = externalIdMap.get(id)!;
if (isCustomerValid(rest) && !customerIds.has(id)) {
customerIds.add(id);
customerUpdates.push({
- id: existingCustomer.id,
+ id: existingEntityId,
data: {
...rest,
updatedAt: new Date().toISOString(),
updatedBy: userId,
- externalId: {
- ...existingCustomer.externalId,
- },
},
});
}
@@ -182,10 +222,8 @@ serve(async (req: Request) => {
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
- externalId: {
- [EXTERNAL_ID_KEY]: id,
- },
});
+ csvIdsForInserts.push(id);
}
}
@@ -196,7 +234,21 @@ serve(async (req: Request) => {
});
if (customerInserts.length > 0) {
- await trx.insertInto(table).values(customerInserts).execute();
+ const inserted = await trx
+ .insertInto(table)
+ .values(customerInserts)
+ .returning(["id"])
+ .execute();
+ await upsertCsvMappings(
+ trx,
+ "customer",
+ inserted.map((row, i) => ({
+ entityId: row.id!,
+ externalId: csvIdsForInserts[i],
+ })),
+ companyId,
+ userId
+ );
}
if (customerUpdates.length > 0) {
for (const update of customerUpdates) {
@@ -211,33 +263,13 @@ serve(async (req: Request) => {
break;
}
case "supplier": {
- const currentSuppliers = await db
- .selectFrom(table)
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const externalIdMap = new Map(
- currentSuppliers.reduce((acc, supplier) => {
- if (
- supplier.externalId &&
- typeof supplier.externalId === "object" &&
- EXTERNAL_ID_KEY in supplier.externalId
- ) {
- acc.set(supplier.externalId[EXTERNAL_ID_KEY] as string, {
- id: supplier.id!,
- externalId: supplier.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
-
+ const externalIdMap = await getCsvExternalIdMap("supplier", companyId);
const supplierIds = new Set();
await db.transaction().execute(async (trx) => {
const supplierInserts: Database["public"]["Tables"]["supplier"]["Insert"][] =
[];
+ const csvIdsForInserts: string[] = [];
const supplierUpdates: {
id: string;
data: Database["public"]["Tables"]["supplier"]["Update"];
@@ -253,17 +285,14 @@ serve(async (req: Request) => {
const { id, ...rest } = record;
if (externalIdMap.has(id) && !supplierIds.has(id)) {
supplierIds.add(id);
- const existingSupplier = externalIdMap.get(id)!;
+ const existingEntityId = externalIdMap.get(id)!;
if (isSupplierValid(rest)) {
supplierUpdates.push({
- id: existingSupplier.id,
+ id: existingEntityId,
data: {
...rest,
updatedAt: new Date().toISOString(),
updatedBy: userId,
- externalId: {
- ...existingSupplier.externalId,
- },
},
});
}
@@ -274,10 +303,8 @@ serve(async (req: Request) => {
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
- externalId: {
- [EXTERNAL_ID_KEY]: id,
- },
});
+ csvIdsForInserts.push(id);
}
}
@@ -288,7 +315,21 @@ serve(async (req: Request) => {
});
if (supplierInserts.length > 0) {
- await trx.insertInto(table).values(supplierInserts).execute();
+ const inserted = await trx
+ .insertInto(table)
+ .values(supplierInserts)
+ .returning(["id"])
+ .execute();
+ await upsertCsvMappings(
+ trx,
+ "supplier",
+ inserted.map((row, i) => ({
+ entityId: row.id!,
+ externalId: csvIdsForInserts[i],
+ })),
+ companyId,
+ userId
+ );
}
if (supplierUpdates.length > 0) {
for (const update of supplierUpdates) {
@@ -311,33 +352,13 @@ serve(async (req: Request) => {
return `${table}:${id}`;
};
- const currentItems = await db
- .selectFrom("item")
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
+ const externalIdMap = await getCsvExternalIdMap("item", companyId);
const readableIds = new Set();
- const externalIdMap = new Map(
- currentItems.reduce((acc, item) => {
- if (
- item.externalId &&
- typeof item.externalId === "object" &&
- EXTERNAL_ID_KEY in item.externalId
- ) {
- acc.set(item.externalId[EXTERNAL_ID_KEY] as string, {
- id: item.id!,
- externalId: item.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
-
await db.transaction().execute(async (trx) => {
const itemInserts: Database["public"]["Tables"]["item"]["Insert"][] =
[];
+ const csvIdsForInserts: string[] = [];
const itemUpdates: {
id: string;
data: Database["public"]["Tables"]["item"]["Update"];
@@ -398,11 +419,11 @@ serve(async (req: Request) => {
externalIdMap.has(getExternalId(id)) &&
!readableIds.has(readableIdWithRevision)
) {
- const existingItem = externalIdMap.get(getExternalId(id))!;
+ const existingEntityId = externalIdMap.get(getExternalId(id))!;
readableIds.add(readableIdWithRevision);
itemUpdates.push({
- id: existingItem.id,
+ id: existingEntityId,
data: {
...rest,
revision: rest.revision ?? "0",
@@ -413,9 +434,6 @@ serve(async (req: Request) => {
defaultMethodType: rest.defaultMethodType || undefined,
updatedAt: new Date().toISOString(),
updatedBy: userId,
- externalId: {
- ...existingItem.externalId,
- },
},
});
@@ -458,11 +476,9 @@ serve(async (req: Request) => {
revision: rest.revision ?? "0",
createdAt: new Date().toISOString(),
createdBy: userId,
- externalId: {
- [EXTERNAL_ID_KEY]: getExternalId(id),
- },
};
itemInserts.push(newItem);
+ csvIdsForInserts.push(getExternalId(id));
if (table === "material") {
const material = materialValidator.safeParse(record);
@@ -477,9 +493,6 @@ serve(async (req: Request) => {
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
- externalId: {
- [EXTERNAL_ID_KEY]: getExternalId(id),
- },
};
}
}
@@ -501,17 +514,27 @@ serve(async (req: Request) => {
replenishmentSystem: sql`EXCLUDED."replenishmentSystem"`,
defaultMethodType: sql`EXCLUDED."defaultMethodType"`,
itemTrackingType: sql`EXCLUDED."itemTrackingType"`,
- externalId: sql`EXCLUDED."externalId"`,
})
)
- .returning(["id", "externalId", "readableId"])
+ .returning(["id", "readableId"])
.execute();
+ // Create CSV mappings for newly inserted items
+ await upsertCsvMappings(
+ trx,
+ "item",
+ insertedItems.map((item, i) => ({
+ entityId: item.id!,
+ externalId: csvIdsForInserts[i],
+ })),
+ companyId,
+ userId
+ );
+
if (["part", "fixture", "tool", "consumable"].includes(table)) {
const specificInserts = insertedItems.map((item) => ({
id: item.readableId,
approved: true,
- externalId: item.externalId,
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
@@ -540,7 +563,6 @@ serve(async (req: Request) => {
dimensionId: materialData.dimensionId || undefined,
gradeId: materialData.gradeId || undefined,
finishId: materialData.finishId || undefined,
- externalId: item.externalId,
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
@@ -565,6 +587,20 @@ serve(async (req: Request) => {
});
if (itemUpdates.length > 0) {
+ // Get current readableIds to detect changes
+ const currentItems = await trx
+ .selectFrom("item")
+ .select(["id", "readableId"])
+ .where(
+ "id",
+ "in",
+ itemUpdates.map((u) => u.id)
+ )
+ .execute();
+ const currentReadableIdMap = new Map(
+ currentItems.map((i) => [i.id, i.readableId])
+ );
+
for (const update of itemUpdates) {
await trx
.updateTable("item")
@@ -573,6 +609,24 @@ serve(async (req: Request) => {
.execute();
}
+ // Update type-specific table id when readableId changes
+ for (const update of itemUpdates) {
+ const oldReadableId = currentReadableIdMap.get(update.id);
+ const newReadableId = update.data.readableId;
+ if (
+ newReadableId &&
+ oldReadableId &&
+ oldReadableId !== newReadableId
+ ) {
+ await trx
+ .updateTable(table)
+ .set({ id: newReadableId } as never)
+ .where("id", "=", oldReadableId)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ }
+
if (materialUpdates.length > 0) {
for (const update of materialUpdates) {
await trx
@@ -588,53 +642,13 @@ serve(async (req: Request) => {
break;
}
case "customerContact": {
- const currentContacts = await db
- .selectFrom("contact")
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const currentCustomers = await db
- .selectFrom("customer")
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const externalCustomerIdMap = new Map(
- currentCustomers.reduce((acc, customer) => {
- if (
- customer.externalId &&
- typeof customer.externalId === "object" &&
- EXTERNAL_ID_KEY in customer.externalId
- ) {
- acc.set(customer.externalId[EXTERNAL_ID_KEY] as string, {
- id: customer.id!,
- externalId: customer.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
-
- const externalContactIdMap = new Map(
- currentContacts.reduce((acc, contact) => {
- if (
- contact.externalId &&
- typeof contact.externalId === "object" &&
- EXTERNAL_ID_KEY in contact.externalId
- ) {
- acc.set(contact.externalId[EXTERNAL_ID_KEY] as string, {
- id: contact.id!,
- externalId: contact.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
+ const externalContactIdMap = await getCsvExternalIdMap("contact", companyId);
+ const externalCustomerIdMap = await getCsvExternalIdMap("customer", companyId);
await db.transaction().execute(async (trx) => {
const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =
[];
+ const csvIdsForContactInserts: string[] = [];
const contactUpdates: {
id: string;
data: Database["public"]["Tables"]["contact"]["Update"];
@@ -656,15 +670,12 @@ serve(async (req: Request) => {
const { id, companyId: customerId, ...contactData } = record;
if (externalContactIdMap.has(id)) {
- const existingContact = externalContactIdMap.get(id)!;
+ const existingEntityId = externalContactIdMap.get(id)!;
if (isContactValid(contactData)) {
contactUpdates.push({
- id: existingContact.id,
+ id: existingEntityId,
data: {
...contactData,
- externalId: {
- ...existingContact.externalId,
- },
},
});
}
@@ -672,21 +683,19 @@ serve(async (req: Request) => {
isContactValid(contactData) &&
externalCustomerIdMap.has(customerId)
) {
- const existingCustomer = externalCustomerIdMap.get(customerId)!;
+ const existingCustomerId = externalCustomerIdMap.get(customerId)!;
const contactId = nanoid();
const newContact = {
id: contactId,
...contactData,
companyId,
- externalId: {
- [EXTERNAL_ID_KEY]: id,
- },
};
contactInserts.push(newContact);
+ csvIdsForContactInserts.push(id);
customerContactInserts.push({
contactId,
- customerId: existingCustomer.id,
+ customerId: existingCustomerId,
customFields: {},
});
}
@@ -700,11 +709,21 @@ serve(async (req: Request) => {
});
if (contactInserts.length > 0) {
- await trx
+ const inserted = await trx
.insertInto("contact")
.values(contactInserts)
.returning(["id"])
.execute();
+ await upsertCsvMappings(
+ trx,
+ "contact",
+ inserted.map((row, i) => ({
+ entityId: row.id!,
+ externalId: csvIdsForContactInserts[i],
+ })),
+ companyId,
+ userId
+ );
}
if (contactUpdates.length > 0) {
@@ -728,53 +747,13 @@ serve(async (req: Request) => {
break;
}
case "supplierContact": {
- const currentContacts = await db
- .selectFrom("contact")
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const currentSuppliers = await db
- .selectFrom("supplier")
- .where("companyId", "=", companyId)
- .select(["id", "externalId"])
- .execute();
-
- const externalSupplierIdMap = new Map(
- currentSuppliers.reduce((acc, supplier) => {
- if (
- supplier.externalId &&
- typeof supplier.externalId === "object" &&
- EXTERNAL_ID_KEY in supplier.externalId
- ) {
- acc.set(supplier.externalId[EXTERNAL_ID_KEY] as string, {
- id: supplier.id!,
- externalId: supplier.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
-
- const externalContactIdMap = new Map(
- currentContacts.reduce((acc, contact) => {
- if (
- contact.externalId &&
- typeof contact.externalId === "object" &&
- EXTERNAL_ID_KEY in contact.externalId
- ) {
- acc.set(contact.externalId[EXTERNAL_ID_KEY] as string, {
- id: contact.id!,
- externalId: contact.externalId as Record<string, string>,
- });
- }
- return acc;
- }, new Map<string, { id: string; externalId: Record<string, string> }>())
- );
+ const externalContactIdMap = await getCsvExternalIdMap("contact", companyId);
+ const externalSupplierIdMap = await getCsvExternalIdMap("supplier", companyId);
await db.transaction().execute(async (trx) => {
const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =
[];
+ const csvIdsForContactInserts: string[] = [];
const contactUpdates: {
id: string;
data: Database["public"]["Tables"]["contact"]["Update"];
@@ -796,15 +775,12 @@ serve(async (req: Request) => {
const { id, companyId: supplierId, ...contactData } = record;
if (externalContactIdMap.has(id)) {
- const existingContact = externalContactIdMap.get(id)!;
+ const existingEntityId = externalContactIdMap.get(id)!;
if (isContactValid(contactData)) {
contactUpdates.push({
- id: existingContact.id,
+ id: existingEntityId,
data: {
...contactData,
- externalId: {
- ...existingContact.externalId,
- },
},
});
}
@@ -812,20 +788,18 @@ serve(async (req: Request) => {
isContactValid(contactData) &&
externalSupplierIdMap.has(supplierId)
) {
- const existingSupplier = externalSupplierIdMap.get(supplierId)!;
+ const existingSupplierId = externalSupplierIdMap.get(supplierId)!;
const contactId = nanoid();
const newContact = {
id: contactId,
...contactData,
companyId,
- externalId: {
- [EXTERNAL_ID_KEY]: id,
- },
};
contactInserts.push(newContact);
+ csvIdsForContactInserts.push(id);
supplierContactInserts.push({
contactId,
- supplierId: existingSupplier.id,
+ supplierId: existingSupplierId,
customFields: {},
});
}
@@ -839,11 +813,21 @@ serve(async (req: Request) => {
});
if (contactInserts.length > 0) {
- await trx
+ const inserted = await trx
.insertInto("contact")
.values(contactInserts)
.returning(["id"])
.execute();
+ await upsertCsvMappings(
+ trx,
+ "contact",
+ inserted.map((row, i) => ({
+ entityId: row.id!,
+ externalId: csvIdsForContactInserts[i],
+ })),
+ companyId,
+ userId
+ );
}
if (contactUpdates.length > 0) {
diff --git a/packages/database/supabase/functions/lib/postgres/index.ts b/packages/database/supabase/functions/lib/postgres/index.ts
index 3744f82313..b85c88feee 100644
--- a/packages/database/supabase/functions/lib/postgres/index.ts
+++ b/packages/database/supabase/functions/lib/postgres/index.ts
@@ -5,15 +5,18 @@ import {
PostgresDialectConfig,
PostgresIntrospector,
PostgresQueryCompiler,
- Transaction
+ Transaction,
} from "kysely";
import type { KyselifyDatabase } from "kysely-supabase";
// Aliased it as pg so can be imported as-is in Node environment
import { Pool } from "pg";
-import type { Database as SupabaseDatabase } from "../types.ts";
+import type { Database as SupabaseDatabase } from "../../../../src/types.ts";
export type KyselyDatabase = KyselifyDatabase<SupabaseDatabase>;
export type KyselyTx = Transaction<KyselyDatabase>;
+export type KyselyDbTx = KyselyDatabase | KyselyTx;
+
+export type { Kysely } from "kysely";
export function getRuntime() {
if (typeof globalThis.Deno !== "undefined") {
@@ -27,7 +30,7 @@ export function getRuntime() {
return "node";
}
-export function getPostgresConnectionPool(connections: number) {
+export function getPostgresConnectionPool(connections: number): Pool {
const runtime = getRuntime();
switch (runtime) {
@@ -40,14 +43,15 @@ export function getPostgresConnectionPool(connections: number) {
}
case "node": {
// @ts-expect-error process.env is not available in Deno with ESM
- const url = process.env.SUPABASE_DB_URL! ?? import.meta.env.SUPABASE_DB_URL;
+ const url =
+ process.env.SUPABASE_DB_URL! ?? import.meta.env.SUPABASE_DB_URL;
const connectionPoolerUrl = url.includes("supabase.co")
? url.replace("5432", "6543")
: url;
// @ts-expect-error -- Kysely uses a subset of the pg Pool type
return new Pool({
connectionString: connectionPoolerUrl,
- max: connections
+ max: connections,
});
}
@@ -62,13 +66,16 @@ interface PgDriverConstructor {
new (config: PostgresDialectConfig): Driver;
}
-export function getPostgresClient(pool: Pool, driver: PgDriverConstructor) {
+export function getPostgresClient<D = KyselyDatabase>(
+ pool: Pool,
+ driver: PgDriverConstructor
+): Kysely<D> {
const runtime = getRuntime();
switch (runtime) {
case "node":
case "deno": {
- return new Kysely<KyselyDatabase>({
+ return new Kysely<D>({
dialect: {
createAdapter() {
return new PostgresAdapter();
@@ -82,8 +89,8 @@ export function getPostgresClient(pool: Pool, driver: PgDriverConstructor) {
},
createQueryCompiler() {
return new PostgresQueryCompiler();
- }
- }
+ },
+ },
});
}
@@ -92,4 +99,4 @@ export function getPostgresClient(pool: Pool, driver: PgDriverConstructor) {
"getPostgresClient is not supported in non-server environments"
);
}
-}
\ No newline at end of file
+}
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 78f8627523..c73ee27898 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -1530,7 +1530,6 @@ export type Database = {
city: string | null
companyId: string
countryCode: string | null
- externalId: Json | null
fax: string | null
id: string
phone: string | null
@@ -1543,7 +1542,6 @@ export type Database = {
city?: string | null
companyId: string
countryCode?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
phone?: string | null
@@ -1556,7 +1554,6 @@ export type Database = {
city?: string | null
companyId?: string
countryCode?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
phone?: string | null
@@ -2306,6 +2303,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "batchProperty_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "batchProperty_itemId_fkey"
columns: ["itemId"]
@@ -2422,7 +2426,6 @@ export type Database = {
countryCode: string | null
createdAt: string
email: string | null
- externalId: Json | null
fax: string | null
id: string
logoDark: string | null
@@ -2448,7 +2451,6 @@ export type Database = {
countryCode?: string | null
createdAt?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
logoDark?: string | null
@@ -2474,7 +2476,6 @@ export type Database = {
countryCode?: string | null
createdAt?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
id?: string
logoDark?: string | null
@@ -3023,6 +3024,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationParameter_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationParameter_itemId_fkey"
columns: ["itemId"]
@@ -3156,6 +3164,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationParameterGroup_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationParameterGroup_itemId_fkey"
columns: ["itemId"]
@@ -3247,6 +3262,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "configurationRule_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "configurationRule_itemId_fkey"
columns: ["itemId"]
@@ -3299,7 +3321,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
id: string
tags: string[] | null
updatedAt: string | null
@@ -3312,7 +3333,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
id: string
tags?: string[] | null
updatedAt?: string | null
@@ -3325,7 +3345,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
tags?: string[] | null
updatedAt?: string | null
@@ -3471,7 +3490,6 @@ export type Database = {
Row: {
companyId: string
email: string | null
- externalId: Json | null
fax: string | null
firstName: string | null
fullName: string | null
@@ -3487,7 +3505,6 @@ export type Database = {
Insert: {
companyId: string
email?: string | null
- externalId?: Json | null
fax?: string | null
firstName?: string | null
fullName?: string | null
@@ -3503,7 +3520,6 @@ export type Database = {
Update: {
companyId?: string
email?: string | null
- externalId?: Json | null
fax?: string | null
firstName?: string | null
fullName?: string | null
@@ -4059,7 +4075,6 @@ export type Database = {
customFields: Json | null
defaultCc: string[] | null
embedding: unknown
- externalId: Json | null
fax: string | null
id: string
invoicingContactId: string | null
@@ -4086,7 +4101,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -4113,7 +4127,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -4546,7 +4559,6 @@ export type Database = {
addressId: string
customerId: string
customFields: Json | null
- externalId: Json | null
id: string
name: string
tags: string[] | null
@@ -4555,7 +4567,6 @@ export type Database = {
addressId: string
customerId: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name: string
tags?: string[] | null
@@ -4564,7 +4575,6 @@ export type Database = {
addressId?: string
customerId?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name?: string
tags?: string[] | null
@@ -4703,6 +4713,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "customerPartToItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "customerPartToItem_itemId_fkey"
columns: ["itemId"]
@@ -5633,6 +5650,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandActual_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandActual_itemId_fkey"
columns: ["itemId"]
@@ -5826,6 +5850,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandForecast_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandForecast_itemId_fkey"
columns: ["itemId"]
@@ -6019,6 +6050,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "demandProjection_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "demandProjection_itemId_fkey"
columns: ["itemId"]
@@ -7029,6 +7067,189 @@ export type Database = {
},
]
}
+ eventSystemSubscription: {
+ Row: {
+ active: boolean | null
+ batchSize: number | null
+ companyId: string
+ config: Json
+ createdAt: string | null
+ filter: Json | null
+ handlerType: string
+ id: string
+ name: string
+ operations: string[]
+ table: string
+ }
+ Insert: {
+ active?: boolean | null
+ batchSize?: number | null
+ companyId: string
+ config?: Json
+ createdAt?: string | null
+ filter?: Json | null
+ handlerType: string
+ id?: string
+ name: string
+ operations: string[]
+ table: string
+ }
+ Update: {
+ active?: boolean | null
+ batchSize?: number | null
+ companyId?: string
+ config?: Json
+ createdAt?: string | null
+ filter?: Json | null
+ handlerType?: string
+ id?: string
+ name?: string
+ operations?: string[]
+ table?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "eventSystemSubscription_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ ]
+ }
+ externalIntegrationMapping: {
+ Row: {
+ allowDuplicateExternalId: boolean
+ companyId: string
+ createdAt: string
+ createdBy: string | null
+ entityId: string
+ entityType: string
+ externalId: string | null
+ id: string
+ integration: string
+ lastSyncedAt: string | null
+ metadata: Json | null
+ remoteUpdatedAt: string | null
+ updatedAt: string
+ }
+ Insert: {
+ allowDuplicateExternalId?: boolean
+ companyId: string
+ createdAt?: string
+ createdBy?: string | null
+ entityId: string
+ entityType: string
+ externalId?: string | null
+ id?: string
+ integration: string
+ lastSyncedAt?: string | null
+ metadata?: Json | null
+ remoteUpdatedAt?: string | null
+ updatedAt?: string
+ }
+ Update: {
+ allowDuplicateExternalId?: boolean
+ companyId?: string
+ createdAt?: string
+ createdBy?: string | null
+ entityId?: string
+ entityType?: string
+ externalId?: string | null
+ id?: string
+ integration?: string
+ lastSyncedAt?: string | null
+ metadata?: Json | null
+ remoteUpdatedAt?: string | null
+ updatedAt?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "externalIntegrationMapping_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
externalLink: {
Row: {
companyId: string
@@ -7301,7 +7522,6 @@ export type Database = {
createdBy: string
customerId: string | null
customFields: Json | null
- externalId: Json | null
id: string
itemId: string | null
tags: string[] | null
@@ -7316,7 +7536,6 @@ export type Database = {
createdBy: string
customerId?: string | null
customFields?: Json | null
- externalId?: Json | null
id: string
itemId?: string | null
tags?: string[] | null
@@ -7331,7 +7550,6 @@ export type Database = {
createdBy?: string
customerId?: string | null
customFields?: Json | null
- externalId?: Json | null
id?: string
itemId?: string | null
tags?: string[] | null
@@ -7486,6 +7704,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "fixture_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "fixture_itemId_fkey"
columns: ["itemId"]
@@ -8623,7 +8848,6 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
embedding: unknown
- externalId: Json | null
id: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId: string | null
@@ -8649,7 +8873,6 @@ export type Database = {
defaultMethodType?: Database["public"]["Enums"]["methodType"] | null
description?: string | null
embedding?: unknown
- externalId?: Json | null
id?: string
itemTrackingType: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId?: string | null
@@ -8675,7 +8898,6 @@ export type Database = {
defaultMethodType?: Database["public"]["Enums"]["methodType"] | null
description?: string | null
embedding?: unknown
- externalId?: Json | null
id?: string
itemTrackingType?: Database["public"]["Enums"]["itemTrackingType"]
modelUploadId?: string | null
@@ -8959,6 +9181,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemCost_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemCost_itemId_fkey"
columns: ["itemId"]
@@ -9170,6 +9399,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemLedger_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemLedger_itemId_fkey"
columns: ["itemId"]
@@ -9387,6 +9623,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemPlanning_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemPlanning_itemId_fkey"
columns: ["itemId"]
@@ -9729,6 +9972,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemReplenishment_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: true
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemReplenishment_itemId_fkey"
columns: ["itemId"]
@@ -9970,6 +10220,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "itemUnitSalePrice_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "itemUnitSalePrice_itemId_fkey"
columns: ["itemId"]
@@ -10290,6 +10547,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -10637,6 +10901,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMakeMethod_itemId_fkey"
columns: ["itemId"]
@@ -10913,6 +11184,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -12295,6 +12573,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -12667,6 +12952,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "kanban_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "kanban_itemId_fkey"
columns: ["itemId"]
@@ -13740,6 +14032,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceDispatchItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceDispatchItem_itemId_fkey"
columns: ["itemId"]
@@ -14587,6 +14886,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "maintenanceScheduleItem_itemId_fkey"
columns: ["itemId"]
@@ -14777,6 +15083,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "method_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "method_itemId_fkey"
columns: ["itemId"]
@@ -14795,7 +15108,6 @@ export type Database = {
createdBy: string
customFields: Json | null
dimensionId: string | null
- externalId: Json | null
finishId: string | null
gradeId: string | null
id: string
@@ -14814,7 +15126,6 @@ export type Database = {
createdBy: string
customFields?: Json | null
dimensionId?: string | null
- externalId?: Json | null
finishId?: string | null
gradeId?: string | null
id?: string
@@ -14833,7 +15144,6 @@ export type Database = {
createdBy?: string
customFields?: Json | null
dimensionId?: string | null
- externalId?: Json | null
finishId?: string | null
gradeId?: string | null
id?: string
@@ -15803,6 +16113,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "methodMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodMaterial_itemId_fkey"
columns: ["itemId"]
@@ -16589,6 +16906,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "methodOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "methodOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -17192,7 +17516,6 @@ export type Database = {
createdAt: string
createdBy: string
dueDate: string | null
- externalId: Json | null
id: string
nonConformanceId: string
notes: Json
@@ -17211,7 +17534,6 @@ export type Database = {
createdAt?: string
createdBy: string
dueDate?: string | null
- externalId?: Json | null
id?: string
nonConformanceId: string
notes?: Json
@@ -17230,7 +17552,6 @@ export type Database = {
createdAt?: string
createdBy?: string
dueDate?: string | null
- externalId?: Json | null
id?: string
nonConformanceId?: string
notes?: Json
@@ -17937,6 +18258,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "nonConformanceItem_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "nonConformanceItem_itemId_fkey"
columns: ["itemId"]
@@ -20438,7 +20766,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
fromDate: string | null
id: string
tags: string[] | null
@@ -20453,7 +20780,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
fromDate?: string | null
id?: string
tags?: string[] | null
@@ -20468,7 +20794,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
fromDate?: string | null
id?: string
tags?: string[] | null
@@ -21067,6 +21392,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "pickMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "pickMethod_itemId_fkey"
columns: ["itemId"]
@@ -23674,6 +24006,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
columns: ["itemId"]
@@ -23966,7 +24305,6 @@ export type Database = {
customFields: Json | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- externalId: Json | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -23997,7 +24335,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -24028,7 +24365,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -24771,6 +25107,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -25849,6 +26192,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchasingRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchasingRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -26596,7 +26946,6 @@ export type Database = {
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
expirationDate: string | null
- externalId: Json | null
externalLinkId: string | null
externalNotes: Json | null
id: string
@@ -26633,7 +26982,6 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
- externalId?: Json | null
externalLinkId?: string | null
externalNotes?: Json | null
id?: string
@@ -26670,7 +27018,6 @@ export type Database = {
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
expirationDate?: string | null
- externalId?: Json | null
externalLinkId?: string | null
externalNotes?: Json | null
id?: string
@@ -27251,6 +27598,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -27668,6 +28022,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMakeMethod_itemId_fkey"
columns: ["itemId"]
@@ -27939,6 +28300,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMaterial_itemId_fkey"
columns: ["itemId"]
@@ -28803,6 +29171,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperationTool_toolId_fkey"
+ columns: ["toolId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperationTool_toolId_fkey"
columns: ["toolId"]
@@ -29544,6 +29919,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receiptLine_itemId_fkey"
columns: ["itemId"]
@@ -29791,6 +30173,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "riskRegister_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "riskRegister_itemId_fkey"
columns: ["itemId"]
@@ -30337,6 +30726,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_itemId_fkey"
columns: ["itemId"]
@@ -30645,7 +31041,6 @@ export type Database = {
customFields: Json | null
exchangeRate: number | null
exchangeRateUpdatedAt: string | null
- externalId: Json | null
externalNotes: Json | null
id: string
internalNotes: Json | null
@@ -30677,7 +31072,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -30709,7 +31103,6 @@ export type Database = {
customFields?: Json | null
exchangeRate?: number | null
exchangeRateUpdatedAt?: string | null
- externalId?: Json | null
externalNotes?: Json | null
id?: string
internalNotes?: Json | null
@@ -31235,6 +31628,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -32388,6 +32788,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -32935,6 +33342,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "service_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "service_itemId_fkey"
columns: ["itemId"]
@@ -33796,6 +34210,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "shipmentLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "shipmentLine_itemId_fkey"
columns: ["itemId"]
@@ -34647,6 +35068,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "stockTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -34865,7 +35293,6 @@ export type Database = {
customFields: Json | null
defaultCc: string[] | null
embedding: unknown
- externalId: Json | null
fax: string | null
id: string
invoicingContactId: string | null
@@ -34892,7 +35319,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -34919,7 +35345,6 @@ export type Database = {
customFields?: Json | null
defaultCc?: string[] | null
embedding?: unknown
- externalId?: Json | null
fax?: string | null
id?: string
invoicingContactId?: string | null
@@ -35572,7 +35997,6 @@ export type Database = {
Row: {
addressId: string
customFields: Json | null
- externalId: Json | null
id: string
name: string
supplierId: string
@@ -35581,7 +36005,6 @@ export type Database = {
Insert: {
addressId: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name: string
supplierId: string
@@ -35590,7 +36013,6 @@ export type Database = {
Update: {
addressId?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
name?: string
supplierId?: string
@@ -35788,6 +36210,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "buyMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "buyMethod_itemId_fkey"
columns: ["itemId"]
@@ -36773,6 +37202,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplierQuoteLine_itemId_fkey"
columns: ["itemId"]
@@ -37609,6 +38045,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplyActual_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplyActual_itemId_fkey"
columns: ["itemId"]
@@ -37805,6 +38248,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplyForecast_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplyForecast_itemId_fkey"
columns: ["itemId"]
@@ -38200,7 +38650,6 @@ export type Database = {
createdAt: string
createdBy: string
customFields: Json | null
- externalId: Json | null
id: string
tags: string[] | null
updatedAt: string | null
@@ -38213,7 +38662,6 @@ export type Database = {
createdAt?: string
createdBy: string
customFields?: Json | null
- externalId?: Json | null
id: string
tags?: string[] | null
updatedAt?: string | null
@@ -38226,7 +38674,6 @@ export type Database = {
createdAt?: string
createdBy?: string
customFields?: Json | null
- externalId?: Json | null
id?: string
tags?: string[] | null
updatedAt?: string | null
@@ -39646,7 +40093,6 @@ export type Database = {
createdAt: string
developer: boolean | null
email: string
- externalId: Json | null
firstName: string
fullName: string | null
id: string
@@ -39663,7 +40109,6 @@ export type Database = {
createdAt?: string
developer?: boolean | null
email: string
- externalId?: Json | null
firstName?: string
fullName?: string | null
id: string
@@ -39680,7 +40125,6 @@ export type Database = {
createdAt?: string
developer?: boolean | null
email?: string
- externalId?: Json | null
firstName?: string
fullName?: string | null
id?: string
@@ -40783,6 +41227,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "warehouseTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "warehouseTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -41442,6 +41893,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "workCenterReplacementPart_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "workCenterReplacementPart_itemId_fkey"
columns: ["itemId"]
@@ -42201,6 +42659,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "method_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "method_itemId_fkey"
columns: ["itemId"]
@@ -42511,6 +42976,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -42860,7 +43326,7 @@ export type Database = {
customerStatusId: string | null
customerTypeId: string | null
customFields: Json | null
- defaultCc: string[] | null
+ externalId: Json | null
fax: string | null
id: string | null
invoicingContactId: string | null
@@ -43346,6 +43812,30 @@ export type Database = {
},
]
}
+ eventSystemTrigger: {
+ Row: {
+ attachedFunctions: string | null
+ status: string | null
+ systemTriggerName: unknown
+ tableName: string | null
+ type: string | null
+ }
+ Insert: {
+ attachedFunctions?: never
+ status?: never
+ systemTriggerName?: unknown
+ tableName?: never
+ type?: never
+ }
+ Update: {
+ attachedFunctions?: never
+ status?: never
+ systemTriggerName?: unknown
+ tableName?: never
+ type?: never
+ }
+ Relationships: []
+ }
gaugeCalibrationRecords: {
Row: {
approvedBy: string | null
@@ -44304,6 +44794,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -45281,6 +45778,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -45531,6 +46035,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "kanban_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "kanban_itemId_fkey"
columns: ["itemId"]
@@ -45969,6 +46480,7 @@ export type Database = {
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
dimensions: string | null
+ externalId: Json | null
finish: string | null
grade: string | null
id: string | null
@@ -46354,6 +46866,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "jobMaterial_itemId_fkey"
columns: ["itemId"]
@@ -46488,6 +47007,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "job_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "job_itemId_fkey"
columns: ["itemId"]
@@ -46601,6 +47127,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -46682,6 +47215,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -46870,6 +47410,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -47471,6 +48012,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseInvoiceLines_itemId_fkey"
columns: ["itemId"]
@@ -48018,6 +48566,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchaseOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchaseOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -48695,6 +49250,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "purchasingRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "purchasingRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -49441,6 +50003,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -49707,6 +50276,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteLine_itemId_fkey"
columns: ["itemId"]
@@ -49928,6 +50504,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteMaterial_itemId_fkey"
columns: ["itemId"]
@@ -50729,6 +51312,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "receiptLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "receiptLine_itemId_fkey"
columns: ["itemId"]
@@ -50942,6 +51532,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "riskRegister_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "riskRegister_itemId_fkey"
columns: ["itemId"]
@@ -51123,6 +51720,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesInvoiceLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesInvoiceLine_itemId_fkey"
columns: ["itemId"]
@@ -51274,14 +51878,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"]
@@ -51715,6 +52319,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesOrderLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesOrderLine_itemId_fkey"
columns: ["itemId"]
@@ -52248,6 +52859,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "salesRfqLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "salesRfqLine_itemId_fkey"
columns: ["itemId"]
@@ -52599,6 +53217,189 @@ export type Database = {
},
]
}
+ services: {
+ Row: {
+ active: boolean | null
+ assignee: string | null
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ defaultMethodType: Database["public"]["Enums"]["methodType"] | null
+ description: string | null
+ externalId: Json | null
+ id: string | null
+ itemPostingGroupId: string | null
+ itemTrackingType:
+ | Database["public"]["Enums"]["itemTrackingType"]
+ | null
+ name: string | null
+ notes: Json | null
+ readableId: string | null
+ readableIdWithRevision: string | null
+ replenishmentSystem:
+ | Database["public"]["Enums"]["itemReplenishmentSystem"]
+ | null
+ revision: string | null
+ revisions: Json | null
+ supplierIds: string | null
+ tags: string[] | null
+ thumbnailPath: string | null
+ unitOfMeasure: string | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_assignee_fkey"
+ columns: ["assignee"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "item_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "item_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "item_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "itemCost_itemPostingGroupId_fkey"
+ columns: ["itemPostingGroupId"]
+ isOneToOne: false
+ referencedRelation: "itemPostingGroup"
+ referencedColumns: ["id"]
+ },
+ ]
+ }
shifts: {
Row: {
active: boolean | null
@@ -52826,6 +53627,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "shipmentLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "shipmentLine_itemId_fkey"
columns: ["itemId"]
@@ -53017,6 +53825,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "stockTransferLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "stockTransferLine_itemId_fkey"
columns: ["itemId"]
@@ -53494,6 +54309,13 @@ export type Database = {
referencedRelation: "parts"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "supplierQuoteLine_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "services"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "supplierQuoteLine_itemId_fkey"
columns: ["itemId"]
@@ -53807,7 +54629,6 @@ export type Database = {
createdBy: string | null
currencyCode: string | null
customFields: Json | null
- defaultCc: string[] | null
embedding: unknown
externalId: Json | null
fax: string | null
@@ -54046,6 +54867,7 @@ export type Database = {
customFields: Json | null
defaultMethodType: Database["public"]["Enums"]["methodType"] | null
description: string | null
+ externalId: Json | null
id: string | null
itemPostingGroupId: string | null
itemTrackingType:
@@ -54625,6 +55447,10 @@ export type Database = {
}
Functions: {
_xid_machine_id: { Args: never; Returns: number }
+ attach_event_trigger: {
+ Args: { sync_functions?: string[]; table_name_text: string }
+ Returns: undefined
+ }
check_operation_dependencies: {
Args: { operation_id: string }
Returns: boolean
@@ -55033,6 +55859,7 @@ export type Database = {
Args: { jid: string }
Returns: {
description: string
+ externalId: Json
isRoot: boolean
itemId: string
itemReadableId: string
diff --git a/packages/database/supabase/functions/sync/index.ts b/packages/database/supabase/functions/sync/index.ts
index 9bd4f14d0f..d6c313daee 100644
--- a/packages/database/supabase/functions/sync/index.ts
+++ b/packages/database/supabase/functions/sync/index.ts
@@ -404,18 +404,36 @@ serve(async (req: Request) => {
let itemId = id;
if (itemId) {
- // Update existing item with Onshape data
+ // Update existing item
await trx
.updateTable("item")
.set({
- externalId: {
- onshapeData: data.data,
- },
updatedBy: userId,
updatedAt: new Date().toISOString(),
})
.where("id", "=", itemId)
.execute();
+
+ // Upsert OnShape mapping
+ await trx
+ .deleteFrom("externalIntegrationMapping")
+ .where("entityType", "=", "item")
+ .where("entityId", "=", itemId)
+ .where("integration", "=", "onshapeData")
+ .execute();
+
+ await trx
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: "item",
+ entityId: itemId,
+ integration: "onshapeData",
+ externalId: partId,
+ metadata: data.data,
+ companyId,
+ allowDuplicateExternalId: false,
+ })
+ .execute();
} else {
// Check if we've already created this part in this transaction
itemId = newlyCreatedItemsByPartId.get(partId);
@@ -434,9 +452,6 @@ serve(async (req: Request) => {
replenishmentSystem,
defaultMethodType,
companyId,
- externalId: {
- onshapeData: data.data,
- },
createdBy: userId,
})
.returning(["id"])
@@ -444,6 +459,22 @@ serve(async (req: Request) => {
itemId = item?.id;
+ // Create OnShape mapping for the new item
+ if (itemId) {
+ await trx
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType: "item",
+ entityId: itemId,
+ integration: "onshapeData",
+ externalId: partId,
+ metadata: data.data,
+ companyId,
+ allowDuplicateExternalId: false,
+ })
+ .execute();
+ }
+
await trx
.insertInto("part")
.values({
diff --git a/packages/database/supabase/migrations/20260112120041_contact_drop_email_unique.sql b/packages/database/supabase/migrations/20260112120041_contact_drop_email_unique.sql
new file mode 100644
index 0000000000..cabd3eb8f5
--- /dev/null
+++ b/packages/database/supabase/migrations/20260112120041_contact_drop_email_unique.sql
@@ -0,0 +1,2 @@
+-- Remove unique index on contact email and companyId
+DROP INDEX IF EXISTS contact_email_companyId_unique_idx;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20260116215036_event_system_impl.sql b/packages/database/supabase/migrations/20260116215036_event_system_impl.sql
new file mode 100644
index 0000000000..ab8e83c374
--- /dev/null
+++ b/packages/database/supabase/migrations/20260116215036_event_system_impl.sql
@@ -0,0 +1,333 @@
+-- Event System Engine
+
+-- 1. PGMQ Create Queue
+-- ------------------------------------------------------------------
+DO $$
+BEGIN
+ IF NOT EXISTS (SELECT 1 FROM pgmq.list_queues() WHERE queue_name = 'event_system') THEN
+ PERFORM pgmq.create('event_system');
+ END IF;
+END $$;
+
+
+-- 2. Create the Subscription Registry (Strict Multi-Tenant)
+-- ------------------------------------------------------------------
+DROP TABLE IF EXISTS "eventSystemSubscription";
+
+CREATE TABLE "eventSystemSubscription" (
+ "id" TEXT PRIMARY KEY DEFAULT id(),
+ "name" TEXT NOT NULL,
+
+ -- Tenant Isolation
+ "companyId" TEXT NOT NULL REFERENCES "company"("id") ON DELETE CASCADE,
+
+ -- Matching Rules
+ "table" TEXT NOT NULL,
+ "operations" TEXT [] NOT NULL CHECK ("operations" <@ ARRAY['INSERT', 'UPDATE', 'DELETE', 'TRUNCATE']::text[]),
+ "filter" JSONB DEFAULT '{}'::jsonb,
+
+ -- Handler Logic
+ "handlerType" TEXT NOT NULL CHECK ("handlerType" IN ('WEBHOOK', 'WORKFLOW', 'SYNC')),
+ "config" JSONB NOT NULL DEFAULT '{}'::jsonb,
+ "batchSize" INTEGER DEFAULT 50,
+
+ -- Metadata
+ "active" BOOLEAN DEFAULT TRUE,
+ "createdAt" TIMESTAMPTZ DEFAULT NOW(),
+
+ -- Constraints: Unique name per company
+ CONSTRAINT "unique_subscription_name_per_company" UNIQUE ("companyId", "name", "table")
+);
+
+-- OPTIMIZATION: Partial Index for High-Performance Dispatch
+-- Filters by Table AND Company, but only for active subscriptions.
+CREATE INDEX "idx_eventSystemSubscription_dispatch"
+ON "eventSystemSubscription" ("table", "companyId")
+WHERE "active" = TRUE;
+
+
+-- 3. Row Level Security
+-- ------------------------------------------------------------------
+ALTER TABLE "eventSystemSubscription" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "manage_subscriptions" ON "eventSystemSubscription"
+FOR ALL USING ( auth.role() = 'authenticated' );
+
+
+-- 4. Sync Triggers
+-- ------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.dispatch_event_interceptors()
+RETURNS TRIGGER
+LANGUAGE plpgsql
+AS $$
+DECLARE
+ func_name TEXT;
+ payload_data JSONB;
+ old_payload_data JSONB;
+ i INTEGER;
+BEGIN
+ -- A. Normalize Data
+ IF TG_OP = 'DELETE' THEN
+ payload_data := row_to_json(OLD)::jsonb;
+ old_payload_data := payload_data;
+ ELSIF TG_OP = 'INSERT' THEN
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := NULL;
+ ELSE -- UPDATE
+ payload_data := row_to_json(NEW)::jsonb;
+ old_payload_data := row_to_json(OLD)::jsonb;
+ END IF;
+
+ -- B. Execute Interceptor Functions
+ -- Loop through arguments passed in CREATE TRIGGER ... EXECUTE FUNCTION func(arg1, arg2)
+ FOR i IN 0 .. (TG_NARGS - 1) LOOP
+ func_name := TG_ARGV[i];
+ EXECUTE format('SELECT %I($1, $2, $3, $4)', func_name)
+ USING TG_TABLE_NAME, TG_OP, payload_data, old_payload_data;
+ END LOOP;
+
+ IF TG_OP = 'DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
+END;
+$$;
+
+
+-- 5. Async Triggers
+-- ------------------------------------------------------------------
+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;
+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;
+
+ -- 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,
+ '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,
+ '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,
+ '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;
+$$;
+
+
+-- 6. Trigger Attachment Helper
+-- ------------------------------------------------------------------
+CREATE OR REPLACE FUNCTION public.attach_event_trigger(
+ table_name_text TEXT,
+ sync_functions TEXT[] DEFAULT ARRAY[]::TEXT[]
+)
+RETURNS VOID AS $$
+DECLARE
+ sync_args TEXT;
+BEGIN
+ -- A. Attach SYNC Trigger (Row Level)
+ IF array_length(sync_functions, 1) > 0 THEN
+ SELECT string_agg(quote_literal(x), ', ') INTO sync_args FROM unnest(sync_functions) x;
+
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_sync_%1$s"
+ BEFORE INSERT OR UPDATE OR DELETE ON %1$I
+ FOR EACH ROW
+ EXECUTE FUNCTION public.dispatch_event_interceptors(%2$s);
+ ', table_name_text, sync_args);
+ ELSE
+ EXECUTE format('DROP TRIGGER IF EXISTS "trg_event_sync_%1$s" ON %1$I;', table_name_text);
+ END IF;
+
+ -- B. Attach ASYNC Triggers (Statement Level)
+ -- 1. INSERT
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_ins_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_ins_%1$s"
+ AFTER INSERT ON %1$I
+ REFERENCING NEW TABLE AS batched_new
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 2. DELETE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_del_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_del_%1$s"
+ AFTER DELETE ON %1$I
+ REFERENCING OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+ -- 3. UPDATE
+ EXECUTE format('
+ DROP TRIGGER IF EXISTS "trg_event_async_upd_%1$s" ON %1$I;
+ CREATE TRIGGER "trg_event_async_upd_%1$s"
+ AFTER UPDATE ON %1$I
+ REFERENCING NEW TABLE AS batched_new OLD TABLE AS batched_old
+ FOR EACH STATEMENT
+ EXECUTE FUNCTION public.dispatch_event_batch();
+ ', table_name_text);
+
+END;
+$$ LANGUAGE plpgsql;
+
+
+-- 7. Status View
+-- ------------------------------------------------------------------
+DROP VIEW IF EXISTS "eventSystemTrigger";
+
+CREATE VIEW "eventSystemTrigger" AS
+SELECT
+ t.tgrelid::regclass::text AS "tableName",
+
+ -- Friendly Type Name
+ CASE
+ WHEN t.tgname LIKE 'trg_event_sync_%' THEN 'SYNC (ROW)'
+ WHEN t.tgname LIKE 'trg_event_async_%' THEN 'ASYNC (STATEMENT)'
+ ELSE 'UNKNOWN'
+ END AS "type",
+
+ -- Cleaned Function List
+ CASE
+ WHEN t.tgname LIKE 'trg_event_sync_%' THEN
+ -- Regex to extract args from "dispatch_event_interceptors('func1', 'func2')"
+ REPLACE(
+ REPLACE(
+ substring(pg_get_triggerdef(t.oid) FROM 'dispatch_event_interceptors\((.*)\)'),
+ '''', ''
+ ),
+ ', ', ' → '
+ )
+ ELSE 'PGMQ Batch'
+ END AS "attachedFunctions",
+
+ -- Status Badge
+ CASE
+ WHEN t.tgenabled = 'O' THEN 'Active'
+ WHEN t.tgenabled = 'D' THEN 'Disabled'
+ ELSE 'Replica Only'
+ END AS "status",
+
+ t.tgname AS "systemTriggerName"
+FROM pg_trigger t
+WHERE t.tgname LIKE 'trg_event_%'
+ORDER BY "tableName", "type" DESC;
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20260119084845_event_system_register_triggers.sql b/packages/database/supabase/migrations/20260119084845_event_system_register_triggers.sql
new file mode 100644
index 0000000000..243734f1f0
--- /dev/null
+++ b/packages/database/supabase/migrations/20260119084845_event_system_register_triggers.sql
@@ -0,0 +1,12 @@
+-- Register event system triggers for relevant tables
+SELECT attach_event_trigger('contact');
+SELECT attach_event_trigger('supplier');
+SELECT attach_event_trigger('customer');
+SELECT attach_event_trigger('salesOrder');
+SELECT attach_event_trigger('salesOrderLine');
+SELECT attach_event_trigger('purchaseOrder');
+SELECT attach_event_trigger('purchaseOrderLine');
+SELECT attach_event_trigger('item');
+SELECT attach_event_trigger('job');
+SELECT attach_event_trigger('salesInvoice');
+SELECT attach_event_trigger('purchaseInvoice');
\ No newline at end of file
diff --git a/packages/database/supabase/migrations/20260122182044_add-sales-invoice-external-id.sql b/packages/database/supabase/migrations/20260122182044_add-sales-invoice-external-id.sql
new file mode 100644
index 0000000000..2bc8c63160
--- /dev/null
+++ b/packages/database/supabase/migrations/20260122182044_add-sales-invoice-external-id.sql
@@ -0,0 +1,7 @@
+-- Add externalId column to salesInvoice for accounting provider sync
+ALTER TABLE "salesInvoice"
+ADD COLUMN IF NOT EXISTS "externalId" JSONB;
+
+-- Create index for efficient lookups by provider
+CREATE INDEX IF NOT EXISTS "salesInvoice_externalId_idx"
+ON "salesInvoice" USING GIN ("externalId");
diff --git a/packages/database/supabase/migrations/20260128140000_external-integration-mapping.sql b/packages/database/supabase/migrations/20260128140000_external-integration-mapping.sql
new file mode 100644
index 0000000000..cf7c068a32
--- /dev/null
+++ b/packages/database/supabase/migrations/20260128140000_external-integration-mapping.sql
@@ -0,0 +1,57 @@
+-- External Integration Mapping Table
+-- A generic mapping table for linking Carbon entities to external system entities (Xero, QuickBooks, etc.)
+-- This replaces the externalId JSONB column pattern with a proper relational approach.
+
+CREATE TABLE "externalIntegrationMapping" (
+ "id" TEXT NOT NULL DEFAULT id(),
+
+ -- Generic entity reference (Carbon side)
+ "entityType" TEXT NOT NULL, -- 'customer', 'supplier', 'item', 'contact', 'purchaseOrder', etc.
+ "entityId" TEXT NOT NULL, -- The internal Carbon ID
+
+ -- External system reference
+ "integration" TEXT NOT NULL, -- 'xero', 'linear', 'quickbooks', etc.
+ "externalId" TEXT NOT NULL, -- The ID in the external system
+
+ -- Mapping configuration
+ "allowDuplicateExternalId" BOOLEAN NOT NULL DEFAULT false, -- When true, allows many Carbon entities to map to one external ID
+
+ -- Sync metadata
+ "metadata" JSONB, -- Provider-specific extras
+ "lastSyncedAt" TIMESTAMP WITH TIME ZONE,
+ "remoteUpdatedAt" TIMESTAMP WITH TIME ZONE, -- For fast bailout on pull
+
+ -- Audit
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT,
+
+ -- Multi-tenancy
+ "companyId" TEXT NOT NULL,
+
+ CONSTRAINT "externalIntegrationMapping_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "externalIntegrationMapping_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "externalIntegrationMapping_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON DELETE SET NULL ON UPDATE CASCADE,
+
+
+ -- One mapping per integration per entity (always enforced)
+ CONSTRAINT "externalIntegrationMapping_entityType_entityId_integration_companyId_key" UNIQUE ("entityType", "entityId", "integration", "companyId")
+);
+
+-- Partial unique index: Only enforce external ID uniqueness when allowDuplicateExternalId is false
+-- This allows many-to-one (Carbon to External) mappings when explicitly configured
+CREATE UNIQUE INDEX "externalIntegrationMapping_unique_externalId_idx"
+ON "externalIntegrationMapping" ("integration", "externalId", "entityType", "companyId")
+WHERE "allowDuplicateExternalId" = false;
+
+-- Indexes for common query patterns
+CREATE INDEX "externalIntegrationMapping_entity_idx" ON "externalIntegrationMapping"("entityType", "entityId");
+CREATE INDEX "externalIntegrationMapping_lookup_idx" ON "externalIntegrationMapping"("integration", "externalId", "companyId");
+CREATE INDEX "externalIntegrationMapping_companyId_idx" ON "externalIntegrationMapping"("companyId");
+
+-- Enable RLS
+ALTER TABLE "externalIntegrationMapping" ENABLE ROW LEVEL SECURITY;
+
+-- RLS Policies
+CREATE POLICY "manage_externalIntegrationMapping" ON "externalIntegrationMapping"
+FOR ALL USING ( auth.role() = 'authenticated' );
diff --git a/packages/database/supabase/migrations/20260130005853_external-id-migration.sql b/packages/database/supabase/migrations/20260130005853_external-id-migration.sql
new file mode 100644
index 0000000000..ee1a7c792e
--- /dev/null
+++ b/packages/database/supabase/migrations/20260130005853_external-id-migration.sql
@@ -0,0 +1,1755 @@
+-- Make externalId nullable in externalIntegrationMapping table
+ALTER TABLE "externalIntegrationMapping" ALTER COLUMN "externalId" DROP NOT NULL;
+
+DROP VIEW IF EXISTS "suppliers";
+DROP VIEW IF EXISTS "customers";
+DROP VIEW IF EXISTS "parts";
+DROP VIEW IF EXISTS "materials";
+DROP VIEW IF EXISTS "tools";
+DROP VIEW IF EXISTS "consumables";
+DROP VIEW IF EXISTS "services";
+DROP VIEW IF EXISTS "salesOrders";
+
+-- Migration: Convert all externalId JSONB columns to the externalIntegrationMapping table
+-- Then drop the old columns and indexes.
+--
+-- Three data patterns exist:
+-- 1. Object with "id" field (Xero, Linear): { "xero": { "id": "...", "provider": "xero", ... } }
+-- 2. Object with "Part number" field (OnShape): { "onshapeData": { "Part number": "PRT-000587", ... } }
+-- 3. Plain string value (Paperless Parts): { "paperlessPartsId": "123" }
+--
+-- externalId extraction:
+-- - string value → use the string itself
+-- - onshapeData → use "Part number" field (only for items, parts, materials, tools, consumables, services)
+-- - other objects → use "id" field
+--
+-- metadata: store full object for objects, NULL for strings
+
+-- ============================================================================
+-- STEP 1: Migrate tables with direct companyId
+-- ============================================================================
+
+-- customer
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'customer',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "customer" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- supplier
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'supplier',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "supplier" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- contact
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'contact',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "contact" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- item
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'item',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "item" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- part
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'part',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "part" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- material
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'material',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "material" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- tool
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'tool',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "tool" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- fixture
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'fixture',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "fixture" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- consumable
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'consumable',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "consumable" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- address
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'address',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "address" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- salesOrder
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'salesOrder',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "salesOrder" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- purchaseOrder
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'purchaseOrder',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "purchaseOrder" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- quote
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'quote',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "quote" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- salesInvoice
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'salesInvoice',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "salesInvoice" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- nonConformanceActionTask (JSON type, cast to JSONB)
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'nonConformanceActionTask',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."companyId"
+FROM "nonConformanceActionTask" t,
+LATERAL jsonb_each(t."externalId"::jsonb) AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId"::jsonb != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- ============================================================================
+-- STEP 2: Migrate tables requiring JOINs for companyId
+-- ============================================================================
+
+-- customerLocation (join customer for companyId)
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'customerLocation',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ c."companyId"
+FROM "customerLocation" t
+JOIN "customer" c ON t."customerId" = c."id",
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- supplierLocation (join supplier for companyId)
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'supplierLocation',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ s."companyId"
+FROM "supplierLocation" t
+JOIN "supplier" s ON t."supplierId" = s."id",
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- ============================================================================
+-- STEP 3: Migrate special tables
+-- ============================================================================
+
+-- company (id IS the companyId)
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'company',
+ t."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ t."id"
+FROM "company" t,
+LATERAL jsonb_each(t."externalId") AS kv(key, value)
+WHERE t."externalId" IS NOT NULL
+ AND t."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- user (many-to-many via userToCompany, one mapping per company membership)
+INSERT INTO "externalIntegrationMapping" (
+ "entityType", "entityId", "integration", "externalId",
+ "metadata", "lastSyncedAt", "companyId"
+)
+SELECT
+ 'user',
+ u."id",
+ kv.key,
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN kv.value ELSE NULL END,
+ CASE WHEN jsonb_typeof(kv.value) = 'object' THEN (kv.value->>'lastSyncedAt')::timestamptz ELSE NULL END,
+ uc."companyId"
+FROM "user" u
+JOIN "userToCompany" uc ON u."id" = uc."userId",
+LATERAL jsonb_each(u."externalId") AS kv(key, value)
+WHERE u."externalId" IS NOT NULL
+ AND u."externalId" != '{}'::jsonb
+ AND (
+ CASE
+ WHEN jsonb_typeof(kv.value) = 'string' THEN kv.value #>> '{}'
+ ELSE kv.value->>'id'
+ END
+ ) IS NOT NULL;
+
+-- ============================================================================
+-- STEP 4: Drop old indexes and columns
+-- ============================================================================
+
+-- Drop GIN indexes
+DROP INDEX IF EXISTS "idx_customer_external_id";
+DROP INDEX IF EXISTS "idx_supplier_external_id";
+DROP INDEX IF EXISTS "idx_contact_external_id";
+DROP INDEX IF EXISTS "idx_item_external_id";
+DROP INDEX IF EXISTS "idx_part_external_id";
+DROP INDEX IF EXISTS "idx_material_external_id";
+DROP INDEX IF EXISTS "idx_tool_external_id";
+DROP INDEX IF EXISTS "idx_fixture_external_id";
+DROP INDEX IF EXISTS "idx_consumable_external_id";
+DROP INDEX IF EXISTS "idx_address_external_id";
+DROP INDEX IF EXISTS "idx_customerLocation_external_id";
+DROP INDEX IF EXISTS "idx_supplierLocation_external_id";
+DROP INDEX IF EXISTS "idx_salesOrder_external_id";
+DROP INDEX IF EXISTS "idx_purchaseOrder_external_id";
+DROP INDEX IF EXISTS "idx_quote_external_id";
+DROP INDEX IF EXISTS "salesInvoice_externalId_idx";
+DROP INDEX IF EXISTS "idx_user_external_id";
+DROP INDEX IF EXISTS "idx_company_external_id";
+
+-- Drop externalId columns
+ALTER TABLE "customer" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "supplier" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "contact" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "item" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "part" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "material" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "tool" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "fixture" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "consumable" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "address" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "customerLocation" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "supplierLocation" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "salesOrder" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "purchaseOrder" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "quote" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "salesInvoice" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "user" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "company" DROP COLUMN IF EXISTS "externalId";
+ALTER TABLE "nonConformanceActionTask" DROP COLUMN IF EXISTS "externalId";
+
+-- ============================================================================
+-- STEP 4: Recreate RPC functions that referenced item.externalId
+-- ============================================================================
+DROP FUNCTION get_method_tree;
+CREATE OR REPLACE FUNCTION get_method_tree(uid TEXT)
+RETURNS TABLE (
+ "methodMaterialId" TEXT,
+ "makeMethodId" TEXT,
+ "materialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "itemType" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "unitCost" NUMERIC,
+ "quantity" NUMERIC,
+ "methodType" "methodType",
+ "itemTrackingType" TEXT,
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "operationId" TEXT,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2),
+ "shelfIds" JSONB
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "id",
+ "makeMethodId",
+ "methodType",
+ "materialMakeMethodId",
+ "itemId",
+ "itemType",
+ "quantity",
+ "makeMethodId" AS "parentMaterialId",
+ NULL AS "operationId",
+ COALESCE("order", 1) AS "order",
+ "kit",
+ "shelfIds"
+ FROM
+ "methodMaterial"
+ WHERE
+ "makeMethodId" = uid
+ UNION
+ SELECT
+ child."id",
+ child."makeMethodId",
+ child."methodType",
+ child."materialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ parent."id" AS "parentMaterialId",
+ child."methodOperationId" AS "operationId",
+ child."order",
+ child."kit",
+ child."shelfIds"
+ FROM
+ "methodMaterial" child
+ INNER JOIN material parent ON parent."materialMakeMethodId" = child."makeMethodId"
+)
+SELECT
+ material.id as "methodMaterialId",
+ material."makeMethodId",
+ material."materialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ material."itemType",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ material."quantity",
+ material."methodType",
+ item."itemTrackingType",
+ material."parentMaterialId",
+ material."order",
+ material."operationId",
+ false AS "isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm2."version",
+ material."shelfIds"
+FROM material
+INNER JOIN item
+ ON material."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+INNER JOIN "makeMethod" mm
+ ON material."makeMethodId" = mm.id
+LEFT JOIN "makeMethod" mm2
+ ON material."materialMakeMethodId" = mm2.id
+UNION
+SELECT
+ mm."id" AS "methodMaterialId",
+ NULL AS "makeMethodId",
+ mm.id AS "materialMakeMethodId",
+ mm."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."type"::text,
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ cost."unitCost",
+ 1 AS "quantity",
+ 'Make' AS "methodType",
+ item."itemTrackingType",
+ NULL AS "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ NULL AS "operationId",
+ true AS "isRoot",
+ false AS "kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ mm."version",
+ '{}'::JSONB AS "shelfIds"
+FROM "makeMethod" mm
+INNER JOIN item
+ ON mm."itemId" = item.id
+INNER JOIN "itemCost" cost
+ ON item.id = cost."itemId"
+WHERE mm.id = uid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+
+
+
+DROP FUNCTION IF EXISTS get_quote_methods_by_method_id;
+CREATE OR REPLACE FUNCTION get_quote_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "itemTrackingType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2),
+ "shelfId" TEXT
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "version",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ NULL::TEXT AS "shelfId"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "id" = mid
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."version",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."shelfId"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ item."itemTrackingType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ material."version",
+ material."shelfId"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+DROP FUNCTION IF EXISTS get_quote_methods;
+CREATE OR REPLACE FUNCTION get_quote_methods(qid TEXT)
+RETURNS TABLE (
+ "quoteId" TEXT,
+ "quoteLineId" TEXT,
+ "methodMaterialId" TEXT,
+ "quoteMakeMethodId" TEXT,
+ "quoteMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2),
+ "shelfId" TEXT
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "quoteId",
+ "quoteLineId",
+ "id",
+ "id" AS "quoteMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "quoteMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version",
+ NULL::TEXT AS "shelfId"
+ FROM
+ "quoteMakeMethod"
+ WHERE
+ "quoteId" = qid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."quoteId",
+ child."quoteLineId",
+ child."id",
+ child."quoteMakeMethodId",
+ child."methodType",
+ child."quoteMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version",
+ child."shelfId"
+ FROM
+ "quoteMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."quoteMaterialMakeMethodId" = child."quoteMakeMethodId"
+)
+SELECT
+ material."quoteId",
+ material."quoteLineId",
+ material.id as "methodMaterialId",
+ material."quoteMakeMethodId",
+ material."quoteMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ material."version",
+ material."shelfId"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."quoteId" = qid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+DROP FUNCTION IF EXISTS get_job_method;
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN,
+ "kit" BOOLEAN,
+ "revision" TEXT,
+ "externalId" JSONB,
+ "version" NUMERIC(10,2),
+ "shelfId" TEXT
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC AS "quantity",
+ 0::NUMERIC AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot",
+ FALSE AS "kit",
+ "version",
+ NULL::TEXT AS "shelfId"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot",
+ child."kit",
+ child."version",
+ child."shelfId"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+ WHERE parent."methodType" = 'Make'
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableIdWithRevision" AS "itemReadableId",
+ item."name" AS "description",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot",
+ material."kit",
+ item."revision",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = item.id
+ ) AS "externalId",
+ material."version",
+ material."shelfId"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+
+DROP VIEW IF EXISTS "suppliers";
+CREATE OR REPLACE VIEW "suppliers" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.id,
+ s.name,
+ s."supplierTypeId",
+ s."supplierStatusId",
+ s."taxId",
+ s."accountManagerId",
+ s.logo,
+ s.assignee,
+ s."companyId",
+ s."createdAt",
+ s."createdBy",
+ s."updatedAt",
+ s."updatedBy",
+ s."customFields",
+ s."currencyCode",
+ s.website,
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'supplier' AND eim."entityId" = s.id
+ ) AS "externalId",
+ s.tags,
+ s."taxPercent",
+ s."purchasingContactId",
+ s."invoicingContactId",
+ s.embedding,
+ st.name AS "type",
+ ss.name AS "status",
+ po.count AS "orderCount",
+ p.count AS "partCount",
+ pc."workPhone" AS "phone",
+ pc.fax AS "fax"
+ FROM "supplier" s
+ LEFT JOIN "supplierType" st ON st.id = s."supplierTypeId"
+ LEFT JOIN "supplierStatus" ss ON ss.id = s."supplierStatusId"
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "purchaseOrder"
+ GROUP BY "supplierId"
+ ) po ON po."supplierId" = s.id
+ LEFT JOIN (
+ SELECT
+ "supplierId",
+ COUNT(*) AS "count"
+ FROM "supplierPart"
+ GROUP BY "supplierId"
+ ) p ON p."supplierId" = s.id
+ LEFT JOIN (
+ SELECT DISTINCT ON (sc."supplierId")
+ sc."supplierId" AS id,
+ co."workPhone",
+ co."fax"
+ FROM "supplierContact" sc
+ JOIN "contact" co
+ ON co.id = sc."contactId"
+ ORDER BY sc."supplierId", sc.id
+ ) pc
+ ON pc.id = s.id;
+
+
+
+DROP VIEW IF EXISTS "customers";
+CREATE OR REPLACE VIEW "customers" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ c.id,
+ c.name,
+ c."customerTypeId",
+ c."customerStatusId",
+ c."taxId",
+ c."accountManagerId",
+ c.logo,
+ c.assignee,
+ c."taxPercent",
+ c.website,
+ c."companyId",
+ c."createdAt",
+ c."createdBy",
+ c."updatedAt",
+ c."updatedBy",
+ c."customFields",
+ c."currencyCode",
+ c."salesContactId",
+ c."invoicingContactId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'customer' AND eim."entityId" = c.id
+ ) AS "externalId",
+ ct.name AS "type",
+ cs.name AS "status",
+ so.count AS "orderCount",
+ pc."workPhone" AS "phone",
+ pc."fax" AS "fax"
+ FROM "customer" c
+ LEFT JOIN "customerType" ct ON ct.id = c."customerTypeId"
+ LEFT JOIN "customerStatus" cs ON cs.id = c."customerStatusId"
+ LEFT JOIN (
+ SELECT
+ "customerId",
+ COUNT(*) AS "count"
+ FROM "salesOrder"
+ GROUP BY "customerId"
+ ) so ON so."customerId" = c.id
+ LEFT JOIN (
+ SELECT DISTINCT ON (cc."customerId")
+ cc."customerId",
+ co."workPhone",
+ co."fax"
+ FROM "customerContact" cc
+ INNER JOIN "contact" co ON co.id = cc."contactId"
+ ORDER BY cc."customerId"
+ ) pc ON pc."customerId" = c.id;
+
+DROP VIEW IF EXISTS "parts";
+CREATE OR REPLACE VIEW "parts" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ mu.id as "modelUploadId",
+
+ mu."modelPath",
+ mu."thumbnailPath" as "modelThumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize"
+ FROM "item" i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ ORDER BY i."readableId", i."companyId", i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'name', i."name",
+ 'description', i."description",
+ 'active', i."active",
+ 'createdAt', i."createdAt"
+ ) ORDER BY i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ li."active",
+ li."assignee",
+ li."defaultMethodType",
+ li."description",
+ li."itemTrackingType",
+ li."name",
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li."notes",
+ li."revision",
+ li."readableId",
+ li."readableIdWithRevision",
+ li."id",
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END as "thumbnailPath",
+
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ p."customFields",
+ p."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "part" p
+INNER JOIN latest_items li ON li."readableId" = p."id" AND li."companyId" = p."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = p."id" AND ir."companyId" = p."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "companyId"
+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"
+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;
+
+DROP VIEW IF EXISTS "materials";
+CREATE OR REPLACE VIEW "materials" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+
+ mu."modelPath",
+ mu."thumbnailPath" as "modelThumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize"
+ FROM "item" i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ ORDER BY i."readableId", i."companyId", i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ i."active",
+ i."assignee",
+ i."defaultMethodType",
+ i."description",
+ i."itemTrackingType",
+ i."name",
+ i."replenishmentSystem",
+ i."unitOfMeasureCode",
+ i."notes",
+ i."revision",
+ i."readableId",
+ i."readableIdWithRevision",
+ i."id",
+ i."companyId",
+ CASE
+ WHEN i."thumbnailPath" IS NULL AND i."modelThumbnailPath" IS NOT NULL THEN i."modelThumbnailPath"
+ ELSE i."thumbnailPath"
+ END as "thumbnailPath",
+ i."modelUploadId",
+ i."modelPath",
+ i."modelName",
+ i."modelSize",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ mf."name" AS "materialForm",
+ ms."name" AS "materialSubstance",
+ md."name" AS "dimensions",
+ mfin."name" AS "finish",
+ mg."name" AS "grade",
+ mt."name" AS "materialType",
+ m."materialSubstanceId",
+ m."materialFormId",
+ m."customFields",
+ m."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = i.id
+ ) AS "externalId",
+ i."createdBy",
+ i."createdAt",
+ i."updatedBy",
+ i."updatedAt"
+FROM "material" m
+ INNER JOIN latest_items i ON i."readableId" = m."id" AND i."companyId" = m."companyId"
+ LEFT JOIN item_revisions ir ON ir."readableId" = m."id" AND ir."companyId" = i."companyId"
+ LEFT JOIN (
+ SELECT
+ ps."itemId",
+ ps."companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY ps."itemId", ps."companyId"
+ ) ps ON ps."itemId" = i."id" AND ps."companyId" = i."companyId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "unitOfMeasure" uom ON uom.code = i."unitOfMeasureCode" AND uom."companyId" = i."companyId"
+ LEFT JOIN "materialForm" mf ON mf."id" = m."materialFormId"
+ LEFT JOIN "materialSubstance" ms ON ms."id" = m."materialSubstanceId"
+ LEFT JOIN "materialDimension" md ON m."dimensionId" = md."id"
+ LEFT JOIN "materialFinish" mfin ON m."finishId" = mfin."id"
+ LEFT JOIN "materialGrade" mg ON m."gradeId" = mg."id"
+ LEFT JOIN "materialType" mt ON m."materialTypeId" = mt."id"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = i.id;
+
+
+DROP VIEW IF EXISTS "tools";
+CREATE OR REPLACE VIEW "tools" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ mu.id as "modelUploadId",
+
+ mu."modelPath",
+ mu."thumbnailPath" as "modelThumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize"
+ FROM "item" i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ ORDER BY i."readableId", i."companyId", i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ li."active",
+ li."assignee",
+ li."defaultMethodType",
+ li."description",
+ li."itemTrackingType",
+ li."name",
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li."notes",
+ li."revision",
+ li."readableId",
+ li."readableIdWithRevision",
+ li."id",
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END as "thumbnailPath",
+
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ t."customFields",
+ t."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "tool" t
+ INNER JOIN latest_items li ON li."readableId" = t."id" AND li."companyId" = t."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = t."id" AND ir."companyId" = li."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "companyId"
+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"
+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;
+
+DROP VIEW IF EXISTS "consumables";
+CREATE OR REPLACE VIEW "consumables" WITH (SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*,
+ mu."modelPath",
+ mu."thumbnailPath" as "modelThumbnailPath",
+ mu."name" as "modelName",
+ mu."size" as "modelSize"
+ FROM "item" i
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ ORDER BY i."readableId", i."companyId", i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ li."active",
+ li."assignee",
+ li."defaultMethodType",
+ li."description",
+ li."itemTrackingType",
+ li."name",
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li."notes",
+ li."revision",
+ li."readableId",
+ li."readableIdWithRevision",
+ li."id",
+ li."companyId",
+ CASE
+ WHEN li."thumbnailPath" IS NULL AND li."modelThumbnailPath" IS NOT NULL THEN li."modelThumbnailPath"
+ ELSE li."thumbnailPath"
+ END as "thumbnailPath",
+ li."modelUploadId",
+ li."modelPath",
+ li."modelName",
+ li."modelSize",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ c."customFields",
+ c."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "consumable" c
+ INNER JOIN latest_items li ON li."readableId" = c."id" AND li."companyId" = c."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = c."id" AND ir."companyId" = li."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "companyId"
+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"
+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;
+
+CREATE OR REPLACE VIEW "services" WITH(SECURITY_INVOKER=true) AS
+WITH latest_items AS (
+ SELECT DISTINCT ON (i."readableId", i."companyId")
+ i.*
+ FROM "item" i
+ ORDER BY i."readableId", i."companyId", i."createdAt" DESC NULLS LAST
+),
+item_revisions AS (
+ SELECT
+ i."readableId",
+ i."companyId",
+ json_agg(
+ json_build_object(
+ 'id', i.id,
+ 'revision', i."revision",
+ 'methodType', i."defaultMethodType",
+ 'type', i."type"
+ ) ORDER BY i."createdAt"
+ ) as "revisions"
+ FROM "item" i
+ GROUP BY i."readableId", i."companyId"
+)
+SELECT
+ li."active",
+ li."assignee",
+ li."defaultMethodType",
+ li."description",
+ li."itemTrackingType",
+ li."name",
+ li."replenishmentSystem",
+ li."unitOfMeasureCode",
+ li."notes",
+ li."revision",
+ li."readableId",
+ li."readableIdWithRevision",
+ li."id",
+ li."companyId",
+ li."thumbnailPath",
+ ps."supplierIds",
+ uom.name as "unitOfMeasure",
+ ir."revisions",
+ s."customFields",
+ s."tags",
+ ic."itemPostingGroupId",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'item' AND eim."entityId" = li.id
+ ) AS "externalId",
+ li."createdBy",
+ li."createdAt",
+ li."updatedBy",
+ li."updatedAt"
+FROM "service" s
+ INNER JOIN latest_items li ON li."readableId" = s."id" AND li."companyId" = s."companyId"
+LEFT JOIN item_revisions ir ON ir."readableId" = s."id" AND ir."companyId" = li."companyId"
+LEFT JOIN (
+ SELECT
+ "itemId",
+ "companyId",
+ string_agg(ps."supplierPartId", ',') AS "supplierIds"
+ FROM "supplierPart" ps
+ GROUP BY "itemId", "companyId"
+) ps ON ps."itemId" = li."id" AND ps."companyId" = li."companyId"
+LEFT JOIN "unitOfMeasure" uom ON uom.code = li."unitOfMeasureCode" AND uom."companyId" = li."companyId"
+LEFT JOIN "itemCost" ic ON ic."itemId" = li.id;
+
+DROP VIEW IF EXISTS "salesOrders";
+CREATE OR REPLACE VIEW "salesOrders" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ s.*,
+ sl."thumbnailPath",
+ sl."itemType",
+ sl."orderTotal" + COALESCE(ss."shippingCost", 0) AS "orderTotal",
+ sl."jobs",
+ sl."lines",
+ st."name" AS "shippingTermName",
+ sp."paymentTermId",
+ ss."shippingMethodId",
+ ss."receiptRequestedDate",
+ ss."receiptPromisedDate",
+ ss."dropShipment",
+ ss."shippingCost",
+ (
+ SELECT COALESCE(
+ jsonb_object_agg(
+ eim."integration",
+ CASE
+ WHEN eim."metadata" IS NOT NULL THEN eim."metadata"
+ ELSE to_jsonb(eim."externalId")
+ END
+ ) FILTER (WHERE eim."externalId" IS NOT NULL),
+ '{}'::jsonb
+ )
+ FROM "externalIntegrationMapping" eim
+ WHERE eim."entityType" = 'salesOrder' AND eim."entityId" = s.id
+ ) AS "externalId"
+ FROM "salesOrder" s
+ LEFT JOIN (
+ SELECT
+ sol."salesOrderId",
+ MIN(CASE
+ WHEN i."thumbnailPath" IS NULL AND mu."thumbnailPath" IS NOT NULL THEN mu."thumbnailPath"
+ ELSE i."thumbnailPath"
+ END) AS "thumbnailPath",
+ SUM(
+ DISTINCT (1+COALESCE(sol."taxPercent", 0))*(COALESCE(sol."saleQuantity", 0)*(COALESCE(sol."unitPrice", 0)) + COALESCE(sol."shippingCost", 0) + COALESCE(sol."addOnCost", 0))
+ ) AS "orderTotal",
+ MIN(i."type") AS "itemType",
+ ARRAY_AGG(
+ CASE
+ WHEN j.id IS NOT NULL THEN json_build_object(
+ 'id', j.id,
+ 'jobId', j."jobId",
+ 'status', j."status",
+ 'dueDate', j."dueDate",
+ 'productionQuantity', j."productionQuantity",
+ 'quantityComplete', j."quantityComplete",
+ 'quantityShipped', j."quantityShipped",
+ 'quantity', j."quantity",
+ 'scrapQuantity', j."scrapQuantity",
+ 'salesOrderLineId', sol.id,
+ 'assignee', j."assignee"
+ )
+ ELSE NULL
+ END
+ ) FILTER (WHERE j.id IS NOT NULL) AS "jobs",
+ ARRAY_AGG(
+ json_build_object(
+ 'id', sol.id,
+ 'methodType', sol."methodType",
+ 'saleQuantity', sol."saleQuantity"
+ )
+ ) AS "lines"
+ FROM "salesOrderLine" sol
+ LEFT JOIN "item" i
+ ON i."id" = sol."itemId"
+ LEFT JOIN "modelUpload" mu ON mu.id = i."modelUploadId"
+ LEFT JOIN "job" j ON j."salesOrderId" = sol."salesOrderId" AND j."salesOrderLineId" = sol."id"
+ GROUP BY sol."salesOrderId"
+ ) sl ON sl."salesOrderId" = s."id"
+ LEFT JOIN "salesOrderShipment" ss ON ss."id" = s."id"
+ LEFT JOIN "shippingTerm" st ON st."id" = ss."shippingTermId"
+ LEFT JOIN "salesOrderPayment" sp ON sp."id" = s."id";
diff --git a/packages/database/tsconfig.json b/packages/database/tsconfig.json
index fc3043b055..f37cd0a928 100644
--- a/packages/database/tsconfig.json
+++ b/packages/database/tsconfig.json
@@ -6,5 +6,5 @@
},
"exclude": ["node_modules"],
"extends": "@carbon/tsconfig/base.json",
- "include": ["src"]
+ "include": ["src", "supabase/functions/lib/postgres/**/*.ts"]
}
diff --git a/packages/documents/src/email/components/Button.tsx b/packages/documents/src/email/components/Button.tsx
index a645aa7b77..b368c3d199 100644
--- a/packages/documents/src/email/components/Button.tsx
+++ b/packages/documents/src/email/components/Button.tsx
@@ -1,5 +1,5 @@
import { Button as ReactEmailButton } from "@react-email/components";
-import React from "react";
+import type React from "react";
import { getEmailInlineStyles, getEmailThemeClasses } from "./Theme";
interface ButtonProps {
diff --git a/packages/documents/src/email/components/Theme.tsx b/packages/documents/src/email/components/Theme.tsx
index cd9514ad7e..79d531e2c5 100644
--- a/packages/documents/src/email/components/Theme.tsx
+++ b/packages/documents/src/email/components/Theme.tsx
@@ -1,6 +1,6 @@
// credit: [email protected]
import { Font, Head, Html, Tailwind } from "@react-email/components";
-import React from "react";
+import type React from "react";
// Re-export Button component for convenience
export { Button } from "./Button";
diff --git a/packages/documents/src/zpl/ProductLabelZPL.tsx b/packages/documents/src/zpl/ProductLabelZPL.tsx
index d243a73308..eba5dcb39d 100644
--- a/packages/documents/src/zpl/ProductLabelZPL.tsx
+++ b/packages/documents/src/zpl/ProductLabelZPL.tsx
@@ -1,4 +1,4 @@
-import { LabelSize, ProductLabelItem } from "@carbon/utils";
+import type { LabelSize, ProductLabelItem } from "@carbon/utils";
export function generateProductLabelZPL(
item: ProductLabelItem,
diff --git a/packages/ee/package.json b/packages/ee/package.json
index 9838833ce9..34094be367 100644
--- a/packages/ee/package.json
+++ b/packages/ee/package.json
@@ -10,7 +10,6 @@
"./onshape": "./src/onshape/lib/index.ts",
"./linear": "./src/linear/lib/index.ts",
"./paperless-parts": "./src/paperless-parts/lib/index.ts",
- "./quickbooks": "./src/accounting/providers/quickbooks.ts",
"./slack.server": "./src/slack.server.ts",
"./slack/messages": "./src/slack/lib/messages.ts",
"./xero": "./src/accounting/providers/xero.ts"
diff --git a/packages/ee/src/accounting/core/external-mapping.ts b/packages/ee/src/accounting/core/external-mapping.ts
new file mode 100644
index 0000000000..3ed7a84204
--- /dev/null
+++ b/packages/ee/src/accounting/core/external-mapping.ts
@@ -0,0 +1,366 @@
+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+
+export interface ExternalIntegrationMapping {
+ id: string;
+ entityType: string;
+ entityId: string;
+ integration: string;
+ externalId: string;
+ allowDuplicateExternalId: boolean;
+ companyId: string;
+ metadata: Record<string, unknown> | null;
+ lastSyncedAt: string | null;
+ remoteUpdatedAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+ createdBy: string | null;
+}
+
+export interface LinkOptions {
+ metadata?: Record<string, unknown>;
+ remoteUpdatedAt?: Date | string;
+ createdBy?: string;
+ /**
+ * When true, allows multiple Carbon entities to map to the same external ID.
+ * Use this for many-to-one (Carbon to External) relationships.
+ * Default: false (enforces unique external IDs per integration per company)
+ */
+ allowDuplicateExternalId?: boolean;
+}
+
+/**
+ * Service for managing external integration mappings.
+ * Provides a clean interface for linking Carbon entities to external system entities.
+ */
+export class ExternalIntegrationMappingService {
+ constructor(
+ private db: Kysely<KyselyDatabase> | KyselyTx,
+ private companyId: string
+ ) {}
+
+ /**
+ * Link a Carbon entity to an external system entity.
+ * Uses upsert to handle both create and update cases.
+ * If remoteUpdatedAt is not provided, it defaults to the current timestamp.
+ */
+ async link(
+ entityType: string,
+ entityId: string,
+ integration: string,
+ externalId: string,
+ options?: LinkOptions
+ ): Promise<void> {
+ const now = new Date().toISOString();
+ // Default to current timestamp if remoteUpdatedAt is not provided
+ const remoteUpdatedAt =
+ options?.remoteUpdatedAt instanceof Date
+ ? options.remoteUpdatedAt.toISOString()
+ : (options?.remoteUpdatedAt ?? now);
+ const allowDuplicateExternalId = options?.allowDuplicateExternalId ?? false;
+
+ await this.db
+ .insertInto("externalIntegrationMapping")
+ .values({
+ entityType,
+ entityId,
+ integration,
+ externalId,
+ allowDuplicateExternalId,
+ companyId: this.companyId,
+ metadata: options?.metadata ?? null,
+ lastSyncedAt: now,
+ remoteUpdatedAt,
+ createdBy: options?.createdBy ?? null,
+ createdAt: now,
+ updatedAt: now
+ })
+ .onConflict((oc) =>
+ oc
+ .columns(["entityType", "entityId", "integration", "companyId"])
+ .doUpdateSet({
+ externalId,
+ allowDuplicateExternalId,
+ metadata: options?.metadata ?? null,
+ lastSyncedAt: now,
+ remoteUpdatedAt,
+ updatedAt: now
+ })
+ )
+ .execute();
+ }
+
+ /**
+ * Unlink a Carbon entity from an external system.
+ */
+ async unlink(
+ entityType: string,
+ entityId: string,
+ integration: string
+ ): Promise<void> {
+ await this.db
+ .deleteFrom("externalIntegrationMapping")
+ .where("entityType", "=", entityType)
+ .where("entityId", "=", entityId)
+ .where("integration", "=", integration)
+ .where("companyId", "=", this.companyId)
+ .execute();
+ }
+
+ /**
+ * Get the external ID for a Carbon entity.
+ */
+ async getExternalId(
+ entityType: string,
+ entityId: string,
+ integration: string
+ ): Promise<string | null> {
+ const mapping = await this.db
+ .selectFrom("externalIntegrationMapping")
+ .select("externalId")
+ .where("entityType", "=", entityType)
+ .where("entityId", "=", entityId)
+ .where("integration", "=", integration)
+ .where("companyId", "=", this.companyId)
+ .executeTakeFirst();
+
+ return mapping?.externalId ?? null;
+ }
+
+ /**
+ * Get the Carbon entity ID for an external ID.
+ */
+ async getEntityId(
+ integration: string,
+ externalId: string,
+ entityType?: string
+ ): Promise<string | null> {
+ let query = this.db
+ .selectFrom("externalIntegrationMapping")
+ .select("entityId")
+ .where("integration", "=", integration)
+ .where("externalId", "=", externalId)
+ .where("companyId", "=", this.companyId);
+
+ if (entityType) {
+ query = query.where("entityType", "=", entityType);
+ }
+
+ const mapping = await query.executeTakeFirst();
+ return mapping?.entityId ?? null;
+ }
+
+ /**
+ * Get the full mapping for a Carbon entity.
+ */
+ async getByEntity(
+ entityType: string,
+ entityId: string,
+ integration: string
+ ): Promise<ExternalIntegrationMapping | null> {
+ const mapping = await this.db
+ .selectFrom("externalIntegrationMapping")
+ .selectAll()
+ .where("entityType", "=", entityType)
+ .where("entityId", "=", entityId)
+ .where("integration", "=", integration)
+ .where("companyId", "=", this.companyId)
+ .executeTakeFirst();
+
+ return (mapping as ExternalIntegrationMapping) ?? null;
+ }
+
+ /**
+ * Get the full mapping for an external ID.
+ */
+ async getByExternalId(
+ integration: string,
+ externalId: string,
+ entityType?: string
+ ): Promise<ExternalIntegrationMapping | null> {
+ let query = this.db
+ .selectFrom("externalIntegrationMapping")
+ .selectAll()
+ .where("integration", "=", integration)
+ .where("externalId", "=", externalId)
+ .where("companyId", "=", this.companyId);
+
+ if (entityType) {
+ query = query.where("entityType", "=", entityType);
+ }
+
+ const mapping = await query.executeTakeFirst();
+ return (mapping as ExternalIntegrationMapping) ?? null;
+ }
+
+ /**
+ * Get all mappings for a Carbon entity (across all integrations).
+ */
+ async getAllByEntity(
+ entityType: string,
+ entityId: string
+ ): Promise<ExternalIntegrationMapping[]> {
+ const mappings = await this.db
+ .selectFrom("externalIntegrationMapping")
+ .selectAll()
+ .where("entityType", "=", entityType)
+ .where("entityId", "=", entityId)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ return mappings as ExternalIntegrationMapping[];
+ }
+
+ /**
+ * Get all mappings for an integration.
+ */
+ async getAllByIntegration(
+ integration: string,
+ entityType?: string
+ ): Promise<ExternalIntegrationMapping[]> {
+ let query = this.db
+ .selectFrom("externalIntegrationMapping")
+ .selectAll()
+ .where("integration", "=", integration)
+ .where("companyId", "=", this.companyId);
+
+ if (entityType) {
+ query = query.where("entityType", "=", entityType);
+ }
+
+ const mappings = await query.execute();
+ return mappings as ExternalIntegrationMapping[];
+ }
+
+ /**
+ * Check if a mapping already exists and is up to date.
+ * Returns true if the mapping exists and remoteUpdatedAt >= the provided timestamp.
+ */
+ async isUpToDate(
+ integration: string,
+ externalId: string,
+ remoteUpdatedAt: Date
+ ): Promise<boolean> {
+ const mapping = await this.getByExternalId(integration, externalId);
+
+ if (!mapping?.remoteUpdatedAt) {
+ return false;
+ }
+
+ return new Date(mapping.remoteUpdatedAt) >= remoteUpdatedAt;
+ }
+
+ /**
+ * Get entity IDs that don't have a mapping for a specific integration.
+ * Useful for finding entities that need to be synced.
+ */
+ async getUnsyncedEntityIds(
+ entityType: string,
+ tableName: string,
+ integration: string,
+ limit: number
+ ): Promise<string[]> {
+ const result = await this.db
+ .selectFrom(tableName as keyof KyselyDatabase)
+ .leftJoin("externalIntegrationMapping as m", (join) =>
+ join
+ .onRef("m.entityId", "=", `${tableName}.id` as any)
+ .on("m.entityType", "=", entityType)
+ .on("m.integration", "=", integration)
+ .on("m.companyId", "=", this.companyId)
+ )
+ .select([`${tableName}.id` as any])
+ .where(`${tableName}.companyId` as any, "=", this.companyId)
+ .where("m.id", "is", null)
+ .limit(limit)
+ .execute();
+
+ return result.map((r: { id: string }) => r.id);
+ }
+
+ /**
+ * Update only the lastSyncedAt timestamp for a mapping.
+ */
+ async touchLastSyncedAt(
+ entityType: string,
+ entityId: string,
+ integration: string
+ ): Promise<void> {
+ await this.db
+ .updateTable("externalIntegrationMapping")
+ .set({
+ lastSyncedAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ })
+ .where("entityType", "=", entityType)
+ .where("entityId", "=", entityId)
+ .where("integration", "=", integration)
+ .where("companyId", "=", this.companyId)
+ .execute();
+ }
+
+ /**
+ * Batch link multiple entities to external IDs.
+ * If remoteUpdatedAt is not provided for a mapping, it defaults to the current timestamp.
+ */
+ async linkBatch(
+ mappings: Array<{
+ entityType: string;
+ entityId: string;
+ integration: string;
+ externalId: string;
+ options?: LinkOptions;
+ }>
+ ): Promise<void> {
+ if (mappings.length === 0) return;
+
+ const now = new Date().toISOString();
+
+ const values = mappings.map((m) => ({
+ entityType: m.entityType,
+ entityId: m.entityId,
+ integration: m.integration,
+ externalId: m.externalId,
+ allowDuplicateExternalId: m.options?.allowDuplicateExternalId ?? false,
+ companyId: this.companyId,
+ metadata: m.options?.metadata ?? null,
+ lastSyncedAt: now,
+ // Default to current timestamp if remoteUpdatedAt is not provided
+ remoteUpdatedAt:
+ m.options?.remoteUpdatedAt instanceof Date
+ ? m.options.remoteUpdatedAt.toISOString()
+ : (m.options?.remoteUpdatedAt ?? now),
+ createdBy: m.options?.createdBy ?? null,
+ createdAt: now,
+ updatedAt: now
+ }));
+
+ await this.db
+ .insertInto("externalIntegrationMapping")
+ .values(values)
+ .onConflict((oc) =>
+ oc
+ .columns(["entityType", "entityId", "integration", "companyId"])
+ .doUpdateSet((eb) => ({
+ externalId: eb.ref("excluded.externalId"),
+ allowDuplicateExternalId: eb.ref(
+ "excluded.allowDuplicateExternalId"
+ ),
+ metadata: eb.ref("excluded.metadata"),
+ lastSyncedAt: eb.ref("excluded.lastSyncedAt"),
+ remoteUpdatedAt: eb.ref("excluded.remoteUpdatedAt"),
+ updatedAt: eb.ref("excluded.updatedAt")
+ }))
+ )
+ .execute();
+ }
+}
+
+/**
+ * Create a new ExternalIntegrationMappingService instance.
+ */
+export function createMappingService(
+ db: Kysely<KyselyDatabase> | KyselyTx,
+ companyId: string
+): ExternalIntegrationMappingService {
+ return new ExternalIntegrationMappingService(db, companyId);
+}
diff --git a/packages/ee/src/accounting/core/index.ts b/packages/ee/src/accounting/core/index.ts
deleted file mode 100644
index ded7277f9c..0000000000
--- a/packages/ee/src/accounting/core/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-export * from "./models";
-export * from "./provider";
-export * from "./service";
-export * from "./sync";
-export * from "./utils";
diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.ts
index 97f83985dd..3f36083eb1 100644
--- a/packages/ee/src/accounting/core/models.ts
+++ b/packages/ee/src/accounting/core/models.ts
@@ -1,13 +1,14 @@
import z from "zod";
+import type {
+ AccountingEntity,
+ AccountingEntityType,
+ EntityDefinition,
+ GlobalSyncConfig
+} from "./types";
-/**
- * Provider core interfaces and base classes.
- */
-export type ProviderConfig<T = unknown> = {
- id: ProviderID;
- companyId: string;
- onTokenRefresh?: (creds: ProviderCredentials) => void;
-} & T;
+function withNullable<T extends z.ZodTypeAny>(schema: T) {
+ return z.preprocess((v) => (v === undefined ? null : v), schema.nullish());
+}
export enum ProviderID {
XERO = "xero"
@@ -18,6 +19,7 @@ export enum ProviderID {
/**
* Schemas for shared provider entities and credentials.
*/
+
export const ProviderCredentialsSchema = z.discriminatedUnion("type", [
z.object({
type: z.literal("oauth2"),
@@ -25,21 +27,479 @@ export const ProviderCredentialsSchema = z.discriminatedUnion("type", [
refreshToken: z.string().optional(),
expiresAt: z.string().datetime().optional(),
scope: z.array(z.string()).optional(),
- tenantId: z.string().optional()
+ tenantId: z.string().optional(),
+ tenantName: z.string().optional()
})
]);
-export type ProviderCredentials = z.output<typeof ProviderCredentialsSchema>;
+/**
+ * Direction of data flow.
+ */
+export const SyncDirectionSchema = z.enum([
+ "two-way",
+ "push-to-accounting",
+ "pull-from-accounting"
+]);
+
+export const AccountingSyncSchema = z.object({
+ companyId: z.string(),
+ provider: z.nativeEnum(ProviderID),
+ syncType: z.enum(["webhook", "scheduled", "trigger"]),
+ syncDirection: SyncDirectionSchema,
+ entities: z.array(z.custom<AccountingEntity>()),
+ metadata: z.record(z.any()).optional()
+});
+
+export const ENTITY_DEFINITIONS: Record<
+ AccountingEntityType,
+ EntityDefinition
+> = {
+ customer: {
+ label: "Customers",
+ type: "master",
+ supportedDirections: [
+ "two-way",
+ "push-to-accounting",
+ "pull-from-accounting"
+ ]
+ },
+ vendor: {
+ label: "Vendors",
+ type: "master",
+ supportedDirections: [
+ "two-way",
+ "push-to-accounting",
+ "pull-from-accounting"
+ ]
+ },
+ item: {
+ label: "Items / Products",
+ type: "master",
+ supportedDirections: ["two-way", "push-to-accounting"]
+ },
+ employee: {
+ label: "Employees",
+ type: "master",
+ supportedDirections: ["two-way", "push-to-accounting"]
+ },
+ purchaseOrder: {
+ label: "Purchase Orders",
+ type: "transaction",
+ dependsOn: ["vendor", "item"],
+ supportedDirections: ["push-to-accounting"]
+ },
+ bill: {
+ label: "Bills (Purchase Invoices)",
+ type: "transaction",
+ dependsOn: ["vendor", "item"],
+ supportedDirections: ["two-way", "push-to-accounting"]
+ },
+ salesOrder: {
+ label: "Sales Orders",
+ type: "transaction",
+ dependsOn: ["customer", "item"],
+ supportedDirections: ["push-to-accounting"]
+ },
+ invoice: {
+ label: "Sales Invoices",
+ type: "transaction",
+ dependsOn: ["customer", "item"],
+ supportedDirections: ["two-way", "push-to-accounting"]
+ },
+ payment: {
+ label: "Payments",
+ type: "transaction",
+ dependsOn: ["invoice", "bill"],
+ supportedDirections: ["pull-from-accounting"]
+ },
+ inventoryAdjustment: {
+ label: "Inventory Adjustments",
+ type: "transaction",
+ dependsOn: ["item"],
+ supportedDirections: ["push-to-accounting"]
+ }
+};
+
+/**
+ * Default Safe Configuration
+ */
+export const DEFAULT_SYNC_CONFIG: GlobalSyncConfig = {
+ entities: {
+ customer: {
+ enabled: true,
+ direction: "two-way",
+ owner: "accounting"
+ },
+ vendor: { enabled: true, direction: "two-way", owner: "accounting" },
+ item: { enabled: true, direction: "push-to-accounting", owner: "carbon" },
+ employee: {
+ enabled: false, // https://developer.xero.com/documentation/api/accounting/employees
+ direction: "two-way",
+ owner: "carbon"
+ },
+ purchaseOrder: {
+ enabled: false,
+ direction: "two-way",
+ owner: "accounting"
+ },
+ bill: { enabled: true, direction: "two-way", owner: "accounting" },
+ salesOrder: {
+ enabled: false,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ },
+ invoice: { enabled: true, direction: "two-way", owner: "accounting" },
+ payment: {
+ enabled: false,
+ direction: "pull-from-accounting",
+ owner: "accounting"
+ },
+ inventoryAdjustment: {
+ enabled: false,
+ direction: "push-to-accounting",
+ owner: "carbon"
+ }
+ }
+};
-export const ExternalIdSchema = z.object({
- [`${ProviderID.XERO}`]: z.object({
- id: z.string(),
- provider: z.literal(ProviderID.XERO),
- metadata: z.record(z.any()).optional()
+// ============================================================================
+// 4. VALIDATION LOGIC
+// ============================================================================
+
+export function validateSyncConfig(config: GlobalSyncConfig): string[] {
+ const errors: string[] = [];
+
+ // 1. Validate Dependencies (Always Enforced)
+ (Object.keys(config.entities) as AccountingEntityType[]).forEach((entity) => {
+ const entityConfig = config.entities[entity];
+ const definition = ENTITY_DEFINITIONS[entity];
+
+ if (entityConfig.enabled && definition.dependsOn) {
+ definition.dependsOn.forEach((dependency) => {
+ if (!config.entities[dependency].enabled) {
+ errors.push(
+ `Cannot enable '${definition.label}': Missing dependency '${ENTITY_DEFINITIONS[dependency].label}'.`
+ );
+ }
+ });
+ }
+ });
+
+ // 2. Validate Directions
+ (Object.keys(config.entities) as AccountingEntityType[]).forEach((entity) => {
+ const entityConfig = config.entities[entity];
+ const definition = ENTITY_DEFINITIONS[entity];
+
+ if (
+ entityConfig.enabled &&
+ !definition.supportedDirections.includes(entityConfig.direction)
+ ) {
+ errors.push(
+ `Entity '${definition.label}' does not support direction '${
+ entityConfig.direction
+ }'. Supported: ${definition.supportedDirections.join(", ")}`
+ );
+ }
+ });
+
+ return errors;
+}
+
+const createEntityConfigSchema = () =>
+ z.object({
+ enabled: z.boolean(),
+ direction: SyncDirectionSchema,
+ owner: z.enum(["carbon", "accounting"]),
+ syncFromDate: z.string().datetime().optional()
+ });
+
+export const SyncConfigSchema = z.object({
+ entities: z.object({
+ customer: createEntityConfigSchema(),
+ vendor: createEntityConfigSchema(),
+ item: createEntityConfigSchema(),
+ employee: createEntityConfigSchema(),
+ purchaseOrder: createEntityConfigSchema(),
+ bill: createEntityConfigSchema(),
+ salesOrder: createEntityConfigSchema(),
+ invoice: createEntityConfigSchema(),
+ payment: createEntityConfigSchema(),
+ inventoryAdjustment: createEntityConfigSchema()
})
- // [`${ProviderID.QUICKBOOKS}`]: z.object({
- // id: z.string(),
- // provider: z.literal(ProviderID.QUICKBOOKS),
- // metadata: z.record(z.any()).optional()
- // })
+});
+
+export const ProviderIntegrationMetadataSchema = z.object({
+ syncConfig: SyncConfigSchema,
+ credentials: ProviderCredentialsSchema.optional()
+});
+
+// /********************************************************\
+// * Accounting Entity Schemas *
+// \********************************************************/
+
+export const ContactSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ firstName: z.string(),
+ lastName: z.string(),
+ companyId: z.string(),
+ email: z.string().optional(),
+ website: withNullable(z.string().url()),
+ taxId: withNullable(z.string()),
+ currencyCode: z.string().default("USD"),
+ balance: z.number().nullish(),
+ creditLimit: z.number().nullish(),
+ paymentTerms: z.string().nullish(),
+ updatedAt: z.string().datetime(),
+ workPhone: withNullable(z.string()),
+ mobilePhone: withNullable(z.string()),
+ fax: withNullable(z.string()),
+ homePhone: withNullable(z.string()),
+ isVendor: z.boolean(),
+ isCustomer: z.boolean(),
+ addresses: z.array(
+ z.object({
+ label: z.string().nullish(),
+ type: z.string().nullish(),
+ line1: z.string().nullish(),
+ line2: z.string().nullish(),
+ city: z.string().nullish(),
+ country: z.string().nullish(),
+ region: z.string().nullish(),
+ postalCode: z.string().nullish()
+ })
+ ),
+ raw: z.record(z.any())
+});
+
+export const EmployeeSchema = z.object({
+ id: z.string(),
+ companyId: z.string(),
+ firstName: z.string(),
+ lastName: z.string(),
+ fullName: withNullable(z.string()),
+ email: withNullable(z.string().email()),
+ active: z.boolean().default(true),
+ // Job-related fields from employeeJob
+ title: withNullable(z.string()),
+ departmentId: withNullable(z.string()),
+ locationId: withNullable(z.string()),
+ managerId: withNullable(z.string()),
+ startDate: withNullable(z.string()),
+ // External link (used by Xero)
+ externalLink: z
+ .object({
+ url: withNullable(z.string().url()),
+ description: withNullable(z.string())
+ })
+ .optional(),
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
+});
+
+// ============================================================================
+// SALES ORDER (push-only to accounting as Xero Quotes)
+// ============================================================================
+
+export const SalesOrderLineSchema = z.object({
+ id: z.string(),
+ salesOrderLineType: z.string(),
+ itemId: withNullable(z.string()),
+ itemCode: withNullable(z.string()), // item.readableIdWithRevision
+ description: withNullable(z.string()),
+ quantity: z.number(),
+ unitPrice: z.number(),
+ setupPrice: z.number(),
+ accountNumber: withNullable(z.string()),
+ lineAmount: z.number()
+});
+
+export const SalesOrderSchema = z.object({
+ id: z.string(),
+ salesOrderId: z.string(), // Human-readable SO number
+ companyId: z.string(),
+ customerId: z.string(),
+ customerExternalId: withNullable(z.string()), // Xero ContactID for the customer
+ status: z.enum([
+ "Draft",
+ "Needs Approval",
+ "Confirmed",
+ "In Progress",
+ "To Ship and Invoice",
+ "To Ship",
+ "To Invoice",
+ "Completed",
+ "Invoiced",
+ "Cancelled",
+ "Closed"
+ ]),
+ orderDate: withNullable(z.string()),
+ currencyCode: z.string(),
+ exchangeRate: z.number(),
+ customerReference: withNullable(z.string()),
+ lines: z.array(SalesOrderLineSchema),
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
+});
+
+// Sales Invoice schemas
+export const SalesInvoiceLineSchema = z.object({
+ id: z.string(),
+ invoiceLineType: z.string(),
+ itemId: withNullable(z.string()),
+ itemCode: withNullable(z.string()), // readableIdWithRevision
+ description: withNullable(z.string()),
+ quantity: z.number(),
+ unitPrice: z.number(),
+ taxPercent: z.number(),
+ lineAmount: z.number()
+});
+
+export const SalesInvoiceSchema = z.object({
+ id: z.string(),
+ invoiceId: z.string(), // readable ID like "INV-0001"
+ companyId: z.string(),
+ customerId: z.string(),
+ customerExternalId: withNullable(z.string()), // Xero ContactID for the customer
+ status: z.enum([
+ "Draft",
+ "Pending",
+ "Submitted",
+ "Partially Paid",
+ "Paid",
+ "Overdue",
+ "Voided",
+ "Credit Note Issued",
+ "Return"
+ ]),
+ currencyCode: z.string(),
+ exchangeRate: z.number(),
+ dateIssued: withNullable(z.string()),
+ dateDue: withNullable(z.string()),
+ datePaid: withNullable(z.string()),
+ customerReference: withNullable(z.string()),
+ subtotal: z.number(),
+ totalTax: z.number(),
+ totalDiscount: z.number(),
+ totalAmount: z.number(),
+ balance: z.number(),
+ lines: z.array(SalesInvoiceLineSchema),
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
+});
+
+// Bill (Purchase Invoice) schemas
+export const BillLineSchema = z.object({
+ id: z.string(),
+ description: withNullable(z.string()),
+ quantity: z.number(),
+ unitPrice: z.number(),
+ itemId: withNullable(z.string()),
+ itemCode: withNullable(z.string()),
+ accountNumber: withNullable(z.string()),
+ taxPercent: withNullable(z.number()),
+ taxAmount: withNullable(z.number()),
+ totalAmount: z.number(),
+ purchaseOrderLineId: withNullable(z.string())
+});
+
+export const BillSchema = z.object({
+ id: z.string(),
+ companyId: z.string(),
+ invoiceId: z.string(), // Human-readable invoice number
+ supplierId: withNullable(z.string()),
+ supplierExternalId: withNullable(z.string()), // Xero ContactID for the supplier
+ status: z.enum([
+ "Draft",
+ "Pending",
+ "Submitted",
+ "Return",
+ "Debit Note Issued",
+ "Paid",
+ "Partially Paid",
+ "Overdue",
+ "Voided"
+ ]),
+ dateIssued: withNullable(z.string()),
+ dateDue: withNullable(z.string()),
+ datePaid: withNullable(z.string()),
+ currencyCode: z.string(),
+ exchangeRate: z.number(),
+ subtotal: z.number(),
+ totalTax: z.number(),
+ totalDiscount: z.number(),
+ totalAmount: z.number(),
+ balance: z.number(),
+ supplierReference: withNullable(z.string()),
+ lines: z.array(BillLineSchema),
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
+});
+
+// Purchase Order schemas
+export const PurchaseOrderLineSchema = z.object({
+ id: z.string(),
+ description: withNullable(z.string()),
+ quantity: z.number(),
+ unitPrice: z.number(),
+ itemId: withNullable(z.string()),
+ itemCode: withNullable(z.string()),
+ accountNumber: withNullable(z.string()),
+ taxPercent: withNullable(z.number()),
+ taxAmount: withNullable(z.number()),
+ totalAmount: z.number(),
+ quantityReceived: withNullable(z.number()),
+ quantityInvoiced: withNullable(z.number())
+});
+
+export const PurchaseOrderSchema = z.object({
+ id: z.string(),
+ companyId: z.string(),
+ purchaseOrderId: z.string(), // Human-readable PO number
+ supplierId: z.string(),
+ supplierExternalId: withNullable(z.string()), // Xero ContactID for the supplier
+ status: z.enum([
+ "Draft",
+ "To Review",
+ "Rejected",
+ "To Receive",
+ "To Receive and Invoice",
+ "To Invoice",
+ "Completed",
+ "Closed",
+ "Planned"
+ ]),
+ orderDate: withNullable(z.string()),
+ deliveryDate: withNullable(z.string()),
+ deliveryAddress: withNullable(z.string()),
+ deliveryInstructions: withNullable(z.string()),
+ currencyCode: withNullable(z.string()),
+ exchangeRate: withNullable(z.number()),
+ subtotal: z.number(),
+ totalTax: z.number(),
+ totalAmount: z.number(),
+ supplierReference: withNullable(z.string()),
+ lines: z.array(PurchaseOrderLineSchema),
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
+});
+
+// ============================================================================
+// INVENTORY ADJUSTMENT (itemLedger-based, push-only to accounting)
+// ============================================================================
+
+export const InventoryAdjustmentSchema = z.object({
+ id: z.string(),
+ entryNumber: z.number(),
+ postingDate: z.string(),
+ entryType: z.enum(["Positive Adjmt.", "Negative Adjmt."]),
+ itemId: z.string(),
+ locationId: withNullable(z.string()),
+ quantity: z.number(), // positive for positive adj, negative for negative adj
+ companyId: z.string(),
+ unitCost: z.number(), // from itemCost table
+ inventoryAccount: z.string(), // GL account code from postingGroupInventory
+ adjustmentVarianceAccount: z.string(), // GL account code from postingGroupInventory
+ updatedAt: z.string().datetime(),
+ raw: z.record(z.any()).optional()
});
diff --git a/packages/ee/src/accounting/core/provider.ts b/packages/ee/src/accounting/core/provider.ts
deleted file mode 100644
index 5b64de59bf..0000000000
--- a/packages/ee/src/accounting/core/provider.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-import { ProviderCredentials, ProviderID } from "./models";
-
-export interface AuthProvider {
- getCredentials(): ProviderCredentials;
- getAuthUrl(scopes: string[], redirectUri: string): string;
- exchangeCode(code: string, redirectUri: string): Promise<ProviderCredentials>;
- refresh(): Promise<ProviderCredentials>;
-}
-
-export interface RequestContext {
- auth?: ProviderCredentials;
- signal?: AbortSignal;
-}
-
-export interface SyncOptions {
- modifiedSince?: Date;
- cursor?: string;
- limit?: number;
- includeDeleted?: boolean;
-}
-
-export interface ReadableResource<T> {
- list(options?: SyncOptions): Promise<T[]>;
- get(id: string): Promise<T>;
-}
-
-export type WritableResource<T, Create, Update> = {
- create(data: Create): Promise<T>;
- update(id: string, data: Update): Promise<T>;
- upsert(data: Update & { id: string }): Promise<T>;
- delete(id: string): Promise<void>;
-};
-
-export type Resource<T, Create, Update = Create> = ReadableResource<T> &
- WritableResource<T, Create, Update>;
-
-export abstract class BaseProvider {
- static id: ProviderID;
-
- protected creds?: ProviderCredentials;
- public auth!: AuthProvider;
-
- abstract validate(auth: ProviderCredentials): Promise<boolean>;
-
- abstract authenticate(...args: any[]): Promise<ProviderCredentials>;
-}
diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.ts
index cd43f91f1d..9be841afd9 100644
--- a/packages/ee/src/accounting/core/service.ts
+++ b/packages/ee/src/accounting/core/service.ts
@@ -1,44 +1,54 @@
import type { Database } from "@carbon/database";
-import type { KyselyTx } from "@carbon/database/client";
import type { SupabaseClient } from "@supabase/supabase-js";
-import { Accounting, TablesWithExternalId } from "../entities";
-import { XeroProvider } from "../providers";
+import { XeroProvider } from "../providers/xero";
+import type { ProviderID } from "./models";
import {
- ExternalIdSchema,
- ProviderCredentials,
- ProviderCredentialsSchema,
- ProviderID
+ DEFAULT_SYNC_CONFIG,
+ ProviderIntegrationMetadataSchema
} from "./models";
-import { AccountingSyncPayload } from "./sync";
+import type { ProviderCredentials, ProviderIntegrationMetadata } from "./types";
export const getAccountingIntegration = async <T extends ProviderID>(
client: SupabaseClient<Database>,
- companyId: string,
+ companyOrTenantId: string,
provider: T
) => {
const integration = await client
.from("companyIntegration")
.select("*")
- .eq("companyId", companyId)
.eq("id", provider)
+ .or(
+ `companyId.eq.${companyOrTenantId},metadata->credentials->>tenantId.eq.${companyOrTenantId}`
+ )
.single();
+ console.log(
+ "Fetched integration for",
+ provider,
+ "and ID",
+ companyOrTenantId,
+ integration
+ );
+
if (integration.error || !integration.data) {
throw new Error(
- `No ${provider} integration found for company ${companyId}`
+ `No ${provider} integration found for company or tenant ${companyOrTenantId}`
);
}
- const config = ProviderCredentialsSchema.safeParse(integration.data.metadata);
+ const config = ProviderIntegrationMetadataSchema.safeParse(
+ integration.data.metadata
+ );
if (!config.success) {
- console.error(integration.error);
+ console.dir(config.error, { depth: null });
throw new Error("Invalid provider config");
}
return {
+ ...integration.data,
id: provider as T,
- config: config.data
+ metadata: config.data
} as const;
};
@@ -46,9 +56,11 @@ export const getProviderIntegration = (
client: SupabaseClient<Database>,
companyId: string,
provider: ProviderID,
- config?: ProviderCredentials
+ config?: ProviderIntegrationMetadata
) => {
- const { accessToken, refreshToken, tenantId } = config ?? {};
+ const { accessToken, refreshToken, tenantId } = config?.credentials || {};
+
+ const syncConfig = DEFAULT_SYNC_CONFIG; // TODO use config?.syncConfig to make it configurable
// Create a callback function to update the integration metadata when tokens are refreshed
const onTokenRefresh = async (auth: ProviderCredentials) => {
@@ -63,14 +75,9 @@ export const getProviderIntegration = (
await client
.from("companyIntegration")
- .update({ metadata: update })
+ .update({ metadata: { ...config, credentials: update } })
.eq("companyId", companyId)
.eq("id", provider);
-
- console.log(
- `Updated ${provider} integration metadata for company ${companyId}`,
- config
- );
} catch (error) {
console.error(
`Failed to update ${provider} integration metadata:`,
@@ -103,6 +110,7 @@ export const getProviderIntegration = (
clientId: process.env.XERO_CLIENT_ID!,
clientSecret: process.env.XERO_CLIENT_SECRET!,
redirectUri: process.env.XERO_REDIRECT_URI,
+ syncConfig,
onTokenRefresh
});
// Add other providers as needed
@@ -112,93 +120,3 @@ export const getProviderIntegration = (
throw new Error(`Unsupported provider: ${provider}`);
}
};
-
-export const getContactFromExternalId = async (
- client: SupabaseClient<Database>,
- companyId: string,
- provider: ProviderID,
- id: string
-) => {
- const contact = await client
- .from("contact")
- .select("*")
- .eq("companyId", companyId)
- .eq("externalId->>provider", provider)
- .eq("externalId->>id", id)
- .single();
-
- if (contact.error || !contact.data) {
- return null;
- }
-
- const externalId = await ExternalIdSchema.safeParseAsync(
- contact.data.externalId
- );
-
- if (!externalId.success) {
- throw new Error("Invalid external ID format");
- }
-
- return {
- ...contact.data,
- externalId
- };
-};
-
-export const getEntityWithExternalId = async <T extends TablesWithExternalId>(
- client: SupabaseClient<Database>,
- table: T,
- companyId: string,
- provider: ProviderID,
- select: { externalId: string } | { id: string }
-) => {
- let query = client
- .from(table as any) // Supabase typing issue
- .select("*")
- .eq("companyId", companyId)
- .eq(`externalId->${provider}->>provider`, provider);
-
- if ("id" in select) {
- query = query.eq("id", select.id);
- }
-
- if ("externalId" in select) {
- query = query.eq(`externalId->${provider}->>id`, select.externalId);
- }
-
- const entry = await query.maybeSingle();
-
- if (!entry.data) {
- return null;
- }
-
- const externalId = await ExternalIdSchema.safeParseAsync(
- // @ts-expect-error Supabase typing issue
- entry.data.externalId
- );
-
- if (!externalId.success) {
- throw new Error("Invalid external ID format");
- }
-
- return {
- ...(entry.data as unknown as Omit<
- Database["public"]["Tables"][T]["Row"],
- "externalId"
- >),
- externalId: externalId.data
- };
-};
-
-export const upsertAccountingCustomer = async (
- client: SupabaseClient<Database>,
- remote: Accounting.Contact,
- payload: AccountingSyncPayload
-) => {};
-
-export const upsertAccountingContact = async (
- tx: KyselyTx,
- remote: Accounting.Contact,
- customerId: string,
- payload: AccountingSyncPayload
-) => {};
diff --git a/packages/ee/src/accounting/core/sync.ts b/packages/ee/src/accounting/core/sync.ts
index 689291734b..c786e716bc 100644
--- a/packages/ee/src/accounting/core/sync.ts
+++ b/packages/ee/src/accounting/core/sync.ts
@@ -1,49 +1,50 @@
-import { Database } from "@carbon/database";
-import { SupabaseClient } from "@supabase/supabase-js";
-import z from "zod";
-import { AccountingEntityType } from "../entities";
-import { AccountingProvider } from "../providers";
-import { ProviderID } from "./models";
+import { BillSyncer } from "../providers/xero/entities/bill";
+import { ContactSyncer } from "../providers/xero/entities/contact";
+import { InventoryAdjustmentSyncer } from "../providers/xero/entities/inventory-adjustment";
+import { SalesInvoiceSyncer } from "../providers/xero/entities/invoice";
+import { ItemSyncer } from "../providers/xero/entities/item";
+import { PurchaseOrderSyncer } from "../providers/xero/entities/purchase-order";
+import { SalesOrderSyncer } from "../providers/xero/entities/sales-order";
+import type { IEntitySyncer, SyncContext } from "./types";
-export const AccountingSyncSchema = z.object({
- companyId: z.string(),
- provider: z.nativeEnum(ProviderID),
- syncType: z.enum(["webhook", "scheduled", "trigger"]),
- syncDirection: z.enum(["from-accounting", "to-accounting", "bi-directional"]),
- entities: z.array(z.custom<AccountingEntity>()),
- metadata: z.record(z.any()).optional()
-});
+export const SyncFactory = {
+ /**
+ * Instantiates the correct Syncer class based on the Entity Type from context.
+ * @param context - The execution context (DB connection, Provider, Config, entityType)
+ */
+ getSyncer(context: SyncContext): IEntitySyncer {
+ switch (context.entityType) {
+ // Master Data
+ case "vendor":
+ case "customer":
+ return new ContactSyncer(context);
+ case "item":
+ return new ItemSyncer(context);
-export type AccountingSyncPayload = z.infer<typeof AccountingSyncSchema>;
+ // Transaction Data
+ case "bill":
+ return new BillSyncer(context);
+ case "invoice":
+ return new SalesInvoiceSyncer(context);
+ case "purchaseOrder":
+ return new PurchaseOrderSyncer(context);
-export type SyncFn = (input: {
- client: SupabaseClient<Database>;
- entity: AccountingEntity;
- provider: AccountingProvider;
- payload: AccountingSyncPayload;
-}) => Promise<any> | any;
+ case "inventoryAdjustment":
+ return new InventoryAdjustmentSyncer(context);
-/**
- * {
- companyId: string;
- provider: AccountingProvider;
- syncType: "webhook" | "scheduled" | "trigger";
- syncDirection: "from-accounting" | "to-accounting" | "bi-directional";
- entities: AccountingEntity[];
- metadata?: {
- tenantId?: string;
- webhookId?: string;
- userId?: string;
- [key: string]: any;
- };
+ case "salesOrder":
+ return new SalesOrderSyncer(context);
- */
+ // Not yet implemented
+ // case "employee":
+ // Xero no longer supports the Employees API
+ // case "payment":
+ // return new PaymentSyncer(context);
-export interface AccountingEntity<
- T extends AccountingEntityType = AccountingEntityType
-> {
- entityType: T;
- entityId: string;
- operation: "create" | "update" | "delete" | "sync";
- lastSyncedAt?: string;
-}
+ default:
+ throw new Error(
+ `No Syncer implementation found for entity type: ${context.entityType}`
+ );
+ }
+ }
+};
diff --git a/packages/ee/src/accounting/core/types.ts b/packages/ee/src/accounting/core/types.ts
new file mode 100644
index 0000000000..2cba9eb1f6
--- /dev/null
+++ b/packages/ee/src/accounting/core/types.ts
@@ -0,0 +1,1002 @@
+import type { Database } from "@carbon/database";
+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import type { SupabaseClient } from "@supabase/supabase-js";
+import type z from "zod";
+import type { AccountingProvider } from "../providers";
+import {
+ createMappingService,
+ type ExternalIntegrationMappingService
+} from "./external-mapping";
+import type {
+ AccountingSyncSchema,
+ BillLineSchema,
+ BillSchema,
+ ContactSchema,
+ EmployeeSchema,
+ InventoryAdjustmentSchema,
+ ItemSchema,
+ ProviderCredentialsSchema,
+ ProviderID,
+ ProviderIntegrationMetadataSchema,
+ PurchaseOrderLineSchema,
+ PurchaseOrderSchema,
+ SalesInvoiceLineSchema,
+ SalesInvoiceSchema,
+ SalesOrderLineSchema,
+ SalesOrderSchema,
+ SyncDirectionSchema
+} from "./models";
+import { AccountingApiError, withTriggersDisabled } from "./utils";
+
+// /********************************************************\
+// * Provider Types Start *
+// \********************************************************/
+export type ProviderCredentials = z.output<typeof ProviderCredentialsSchema>;
+export type ProviderIntegrationMetadata = z.infer<
+ typeof ProviderIntegrationMetadataSchema
+>;
+
+export interface OAuthClientOptions {
+ clientId: string;
+ clientSecret: string;
+ tokenUrl: string;
+ accessToken?: string;
+ refreshToken?: string;
+ redirectUri?: string;
+ getAuthUrl: (scopes: string[], redirectUri: string) => string;
+ onTokenRefresh?: (creds: ProviderCredentials) => Promise<void>;
+}
+
+export interface AuthProvider {
+ getCredentials(): ProviderCredentials;
+ getAuthUrl(scopes: string[], redirectUri: string): string;
+ exchangeCode(code: string, redirectUri: string): Promise<ProviderCredentials>;
+ refresh(): Promise<ProviderCredentials>;
+}
+
+export type ProviderConfig<T = unknown> = {
+ id: ProviderID;
+ companyId: string;
+ syncConfig: GlobalSyncConfig;
+ onTokenRefresh?: OAuthClientOptions["onTokenRefresh"];
+} & T;
+
+export abstract class BaseProvider {
+ static id: ProviderID;
+
+ protected creds?: ProviderCredentials;
+ public auth!: AuthProvider;
+
+ abstract getSyncConfig<T extends AccountingEntityType>(
+ entity: T
+ ): GlobalSyncConfig["entities"][T];
+
+ abstract validate(auth: ProviderCredentials): Promise<boolean>;
+
+ abstract authenticate(...args: any[]): Promise<ProviderCredentials>;
+}
+
+// /********************************************************\
+// * Provider Types End *
+// \********************************************************/
+
+// /********************************************************\
+// * Sync Types Start *
+// \********************************************************/
+
+export type SyncDirection = z.infer<typeof SyncDirectionSchema>;
+
+/**
+ * Defines which system owns the data integrity.
+ * - 'carbon': Carbon data overwrites Accounting data.
+ * - 'accounting': Accounting data overwrites Carbon data.
+ */
+export type SystemOfRecord = "carbon" | "accounting";
+
+// ============================================================================
+// 2. CONFIGURATION INTERFACES
+// ============================================================================
+
+// Core domain types
+export type AccountingEntityType =
+ | "customer"
+ | "vendor"
+ | "item"
+ | "employee"
+ | "purchaseOrder"
+ | "bill"
+ | "salesOrder"
+ | "invoice"
+ | "payment"
+ | "inventoryAdjustment";
+
+export interface EntityConfig {
+ /** Is this entity sync active? */
+ enabled: boolean;
+
+ /** Direction of sync. */
+ direction: SyncDirection;
+
+ /** In case of a data conflict, who wins? */
+ owner: SystemOfRecord;
+
+ /**
+ * ISO Date string. Only sync records modified after this date.
+ * Critical for initial setup to prevent syncing ancient history.
+ */
+ syncFromDate?: string;
+}
+
+export interface GlobalSyncConfig {
+ /**
+ * The configuration for each specific entity
+ */
+ entities: Record<AccountingEntityType, EntityConfig>;
+}
+
+export interface EntityDefinition {
+ label: string;
+ type: "master" | "transaction";
+ dependsOn?: AccountingEntityType[];
+ supportedDirections: SyncDirection[];
+}
+
+export type AccountingSyncPayload = z.infer<typeof AccountingSyncSchema>;
+
+export type SyncFn = (input: {
+ client: SupabaseClient<Database>;
+ kysely: Kysely<KyselyDatabase>;
+ entity: AccountingEntity;
+ provider: AccountingProvider;
+ payload: AccountingSyncPayload;
+}) => Promise<any> | any;
+
+export interface AccountingEntity<
+ T extends AccountingEntityType = AccountingEntityType
+> {
+ entityType: T;
+ entityId: string;
+ operation: "create" | "update" | "delete" | "sync";
+ lastSyncedAt?: string;
+}
+
+export interface SyncContext {
+ database: Kysely<KyselyDatabase>;
+ companyId: string;
+ provider: AccountingProvider;
+ config: EntityConfig;
+ entityType: AccountingEntityType;
+}
+
+export interface SyncResult {
+ status: "success" | "skipped" | "error";
+ action: "created" | "updated" | "deleted" | "none";
+ localId?: string;
+ remoteId?: string;
+ error?: unknown;
+}
+
+export interface BatchSyncResult {
+ results: SyncResult[];
+ successCount: number;
+ errorCount: number;
+ skippedCount: number;
+}
+
+/**
+ * Context passed to the optional shouldSync method to determine
+ * if an entity should be synced.
+ */
+export interface ShouldSyncContext<TLocal, TRemote> {
+ /** Direction of the sync operation */
+ direction: "push" | "pull";
+
+ /** The local entity (available for push, and after mapping for pull) */
+ localEntity?: TLocal;
+
+ /** The remote entity (available for pull, before mapping) */
+ remoteEntity?: TRemote;
+
+ /** Whether this is a first-time sync (no existing mapping) */
+ isFirstSync: boolean;
+
+ /** The entity ID (local for push, remote for pull) */
+ entityId: string;
+}
+
+export interface IEntitySyncer {
+ // Single-item methods
+ pushToAccounting(entityId: string): Promise<SyncResult>;
+ pullFromAccounting(remoteId: string): Promise<SyncResult>;
+
+ // Batch methods
+ pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult>;
+ pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult>;
+}
+
+export abstract class BaseEntitySyncer<
+ TLocal, // Carbon DB Entity Type (e.g. Invoice)
+ TRemote, // Accounting API Entity Type (e.g. Xero.Invoice)
+ TOmit extends string | symbol | number // Fields to omit from mapping
+> implements IEntitySyncer
+{
+ protected database: Kysely<KyselyDatabase>;
+ protected companyId: string;
+ protected provider: AccountingProvider;
+ protected config: EntityConfig;
+ protected entityType: AccountingEntityType;
+ protected mappingService: ExternalIntegrationMappingService;
+
+ constructor(protected context: SyncContext) {
+ this.database = context.database;
+ this.companyId = context.companyId;
+ this.provider = context.provider;
+ this.config = context.config;
+ this.entityType = context.entityType;
+ this.mappingService = createMappingService(
+ context.database,
+ context.companyId
+ );
+ }
+
+ // =================================================================
+ // 1. ID MAPPING (Default implementations using mapping service)
+ // =================================================================
+
+ /**
+ * Look up the Remote ID (e.g. Xero ID) for a given Local ID (Carbon ID).
+ * Default implementation uses the external integration mapping table.
+ * Can be overridden by subclasses for custom behavior.
+ */
+ public async getRemoteId(localId: string): Promise<string | null> {
+ return this.mappingService.getExternalId(
+ this.entityType,
+ localId,
+ this.provider.id
+ );
+ }
+
+ /**
+ * Look up the Local ID (Carbon ID) for a given Remote ID (e.g. Xero ID).
+ * Default implementation uses the external integration mapping table.
+ * Can be overridden by subclasses for custom behavior.
+ */
+ public async getLocalId(remoteId: string): Promise<string | null> {
+ return this.mappingService.getEntityId(
+ this.provider.id,
+ remoteId,
+ this.entityType
+ );
+ }
+
+ /**
+ * Save the link between a Carbon ID and a Remote ID.
+ * Default implementation uses the external integration mapping table.
+ * Can be overridden by subclasses for custom behavior.
+ */
+ protected async linkEntities(
+ tx: KyselyTx,
+ localId: string,
+ remoteId: string,
+ remoteUpdatedAt?: Date
+ ): Promise<void> {
+ // Create a mapping service with the transaction
+ const txMappingService = createMappingService(tx, this.companyId);
+ await txMappingService.link(
+ this.entityType,
+ localId,
+ this.provider.id,
+ remoteId,
+ { remoteUpdatedAt }
+ );
+ }
+
+ protected abstract fetchLocal(id: string): Promise<TLocal | null>;
+
+ protected abstract fetchRemote(id: string): Promise<TRemote | null>;
+
+ protected abstract mapToRemote(local: TLocal): Promise<Omit<TRemote, TOmit>>;
+
+ protected abstract mapToLocal(remote: TRemote): Promise<Partial<TLocal>>;
+
+ /**
+ * Extract the last updated timestamp from a remote entity.
+ * Used to compare with local entity to avoid unnecessary updates.
+ */
+ protected abstract getRemoteUpdatedAt(remote: TRemote): Date | null;
+
+ protected abstract upsertLocal(
+ tx: KyselyTx,
+ data: Partial<TLocal>,
+ remoteId: string
+ ): Promise<string>;
+
+ protected abstract upsertRemote(
+ data: Omit<TRemote, TOmit>,
+ localId: string
+ ): Promise<string>;
+
+ // =================================================================
+ // 2. ABSTRACT BATCH METHODS (Implemented by Subclasses)
+ // =================================================================
+
+ /**
+ * Fetch multiple local entities by their IDs.
+ * Returns a Map of localId -> entity.
+ */
+ protected abstract fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, TLocal>>;
+
+ /**
+ * Fetch multiple remote entities by their IDs.
+ * Returns a Map of remoteId -> entity.
+ */
+ protected abstract fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, TRemote>>;
+
+ /**
+ * Upsert multiple remote entities in a single API call.
+ * Returns a Map of localId -> remoteId.
+ */
+ protected abstract upsertRemoteBatch(
+ data: Array<{ localId: string; payload: Omit<TRemote, TOmit> }>
+ ): Promise<Map<string, string>>;
+
+ /**
+ * Optional method to determine if an entity should be synced.
+ * Override this in subclasses to implement business logic like
+ * "only sync posted invoices" or "don't sync archived items".
+ *
+ * @param context - Context about the sync operation including direction,
+ * the entity being synced, and whether it's a first sync
+ * @returns true to proceed with sync, false to skip silently,
+ * or a string with a reason to skip
+ */
+ protected shouldSync?(
+ context: ShouldSyncContext<TLocal, TRemote>
+ ): boolean | string | Promise<boolean | string>;
+
+ // =================================================================
+ // 3. PUSH WORKFLOW (Carbon -> Accounting)
+ // =================================================================
+
+ async pushToAccounting(entityId: string): Promise<SyncResult> {
+ if (!this.config.enabled) {
+ return {
+ status: "skipped",
+ action: "none",
+ error: "Sync disabled in config"
+ };
+ }
+
+ try {
+ // 1. Check if already linked
+ const existingMapping = await this.mappingService.getByEntity(
+ this.entityType,
+ entityId,
+ this.provider.id
+ );
+
+ // 2. Fetch local entity
+ const localEntity = await this.fetchLocal(entityId);
+ if (!localEntity) {
+ return {
+ status: "error",
+ action: "none",
+ error: `Entity ${entityId} not found in Carbon`
+ };
+ }
+
+ // 3. Check if entity should be synced (optional business logic)
+ if (this.shouldSync) {
+ const shouldSyncResult = await this.shouldSync({
+ direction: "push",
+ localEntity,
+ isFirstSync: !existingMapping,
+ entityId
+ });
+
+ if (shouldSyncResult !== true) {
+ return {
+ status: "skipped",
+ action: "none",
+ localId: entityId,
+ error:
+ typeof shouldSyncResult === "string"
+ ? shouldSyncResult
+ : "Entity not eligible for sync"
+ };
+ }
+ }
+
+ const localUpdatedAt = new Date((localEntity as any).updatedAt);
+
+ // 4. FAST BAILOUT: If already synced and local hasn't changed
+ if (existingMapping?.lastSyncedAt) {
+ if (localUpdatedAt <= new Date(existingMapping.lastSyncedAt)) {
+ return {
+ status: "skipped",
+ action: "none",
+ localId: entityId,
+ remoteId: existingMapping.externalId,
+ error: "Already synced - local unchanged"
+ };
+ }
+ }
+
+ // 5. Map and push
+ const remotePayload = await this.mapToRemote(localEntity);
+ const id = await this.upsertRemote(remotePayload, entityId);
+
+ // 6. Update mapping
+ const remoteId = await withTriggersDisabled(this.database, async (tx) => {
+ await this.linkEntities(tx, entityId, id);
+ return id;
+ });
+
+ await this.logSyncOperation("push", entityId, remoteId, "success");
+
+ return {
+ status: "success",
+ action: existingMapping ? "updated" : "created",
+ localId: entityId,
+ remoteId
+ };
+ } catch (err: any) {
+ await this.logSyncOperation("push", entityId, undefined, "error", err);
+ return {
+ status: "error",
+ action: "none",
+ localId: entityId,
+ error: err instanceof Error ? err.message : String(err)
+ };
+ }
+ }
+
+ // =================================================================
+ // 4. PULL WORKFLOW (Accounting -> Carbon)
+ // =================================================================
+
+ async pullFromAccounting(remoteId: string): Promise<SyncResult> {
+ if (!this.config.enabled) {
+ return {
+ status: "skipped",
+ action: "none",
+ error: "Sync disabled in config"
+ };
+ }
+
+ try {
+ // 1. Check mapping table FIRST (fast, indexed lookup)
+ const existingMapping = await this.mappingService.getByExternalId(
+ this.provider.id,
+ remoteId,
+ this.entityType
+ );
+
+ // 2. Fetch remote entity
+ const remoteEntity = await this.fetchRemote(remoteId);
+ if (!remoteEntity) {
+ return {
+ status: "error",
+ action: "none",
+ error: `Entity ${remoteId} not found in Remote`
+ };
+ }
+
+ // 3. Check if entity should be synced (optional business logic)
+ if (this.shouldSync) {
+ const shouldSyncResult = await this.shouldSync({
+ direction: "pull",
+ remoteEntity,
+ isFirstSync: !existingMapping,
+ entityId: remoteId
+ });
+
+ if (shouldSyncResult !== true) {
+ return {
+ status: "skipped",
+ action: "none",
+ remoteId,
+ error:
+ typeof shouldSyncResult === "string"
+ ? shouldSyncResult
+ : "Entity not eligible for sync"
+ };
+ }
+ }
+
+ const remoteUpdatedAt = this.getRemoteUpdatedAt(remoteEntity);
+
+ // 4. FAST BAILOUT: Compare timestamps without fetching local entity
+ if (existingMapping?.remoteUpdatedAt && remoteUpdatedAt) {
+ if (new Date(existingMapping.remoteUpdatedAt) >= remoteUpdatedAt) {
+ return {
+ status: "skipped",
+ action: "none",
+ localId: existingMapping.entityId,
+ remoteId,
+ error: "Already synced - remote unchanged"
+ };
+ }
+ }
+
+ // 5. Map and upsert (only if needed)
+ const localPayload = await this.mapToLocal(remoteEntity);
+
+ // Wrap DB writes in withTriggersDisabled to prevent circular triggers
+ // (external sync -> DB write -> trigger -> sync back to external)
+ const newLocalId = await withTriggersDisabled(
+ this.database,
+ async (tx) => {
+ const id = await this.upsertLocal(tx, localPayload, remoteId);
+ await this.linkEntities(
+ tx,
+ id,
+ remoteId,
+ remoteUpdatedAt ?? undefined
+ );
+
+ return id;
+ }
+ );
+
+ await this.logSyncOperation("pull", newLocalId, remoteId, "success");
+
+ return {
+ status: "success",
+ action: existingMapping ? "updated" : "created",
+ localId: newLocalId,
+ remoteId
+ };
+ } catch (err: any) {
+ await this.logSyncOperation("pull", undefined, remoteId, "error", err);
+ return {
+ status: "error",
+ action: "none",
+ remoteId,
+ error: err instanceof Error ? err.message : String(err)
+ };
+ }
+ }
+
+ // =================================================================
+ // 5. BATCH PUSH WORKFLOW (Carbon -> Accounting)
+ // =================================================================
+
+ async pushBatchToAccounting(entityIds: string[]): Promise<BatchSyncResult> {
+ const results: SyncResult[] = [];
+
+ if (!this.config.enabled) {
+ for (const id of entityIds) {
+ results.push({
+ status: "skipped",
+ action: "none",
+ localId: id,
+ error: "Sync disabled in config"
+ });
+ }
+ return this.summarizeBatchResults(results);
+ }
+
+ try {
+ // 1. Fetch all local entities in batch
+ const localEntities = await this.fetchLocalBatch(entityIds);
+
+ // Track entities not found locally
+ const notFoundIds = entityIds.filter((id) => !localEntities.has(id));
+ for (const id of notFoundIds) {
+ results.push({
+ status: "error",
+ action: "none",
+ localId: id,
+ error: `Entity ${id} not found in Carbon`
+ });
+ }
+
+ // 2. Check shouldSync and map all found entities to remote payloads
+ const batchPayloads: Array<{
+ localId: string;
+ payload: Omit<TRemote, TOmit>;
+ }> = [];
+
+ for (const [localId, entity] of localEntities) {
+ try {
+ // Check if entity should be synced (optional business logic)
+ if (this.shouldSync) {
+ const shouldSyncResult = await this.shouldSync({
+ direction: "push",
+ localEntity: entity,
+ isFirstSync: true, // Batch doesn't check existing mappings for perf
+ entityId: localId
+ });
+
+ if (shouldSyncResult !== true) {
+ results.push({
+ status: "skipped",
+ action: "none",
+ localId,
+ error:
+ typeof shouldSyncResult === "string"
+ ? shouldSyncResult
+ : "Entity not eligible for sync"
+ });
+ continue;
+ }
+ }
+
+ const payload = await this.mapToRemote(entity);
+ batchPayloads.push({ localId, payload });
+ } catch (err) {
+ results.push({
+ status: "error",
+ action: "none",
+ localId,
+ error: err instanceof Error ? err.message : String(err)
+ });
+ }
+ }
+
+ if (batchPayloads.length === 0) {
+ return this.summarizeBatchResults(results);
+ }
+
+ // 3. Upsert all in a single batch call
+ const remoteIdMap = await this.upsertRemoteBatch(batchPayloads);
+
+ // 4. Link entities using batch operation
+ const mappingsToLink: Array<{
+ entityType: string;
+ entityId: string;
+ integration: string;
+ externalId: string;
+ }> = [];
+
+ for (const { localId } of batchPayloads) {
+ const remoteId = remoteIdMap.get(localId);
+ if (remoteId) {
+ mappingsToLink.push({
+ entityType: this.entityType,
+ entityId: localId,
+ integration: this.provider.id,
+ externalId: remoteId
+ });
+ results.push({
+ status: "success",
+ action: "updated",
+ localId,
+ remoteId
+ });
+ } else {
+ results.push({
+ status: "error",
+ action: "none",
+ localId,
+ error: "Remote upsert did not return ID"
+ });
+ }
+ }
+
+ if (mappingsToLink.length > 0) {
+ await withTriggersDisabled(this.database, async (tx) => {
+ const txMappingService = createMappingService(tx, this.companyId);
+ await txMappingService.linkBatch(mappingsToLink);
+ });
+ }
+ } catch (err: any) {
+ // If the whole batch fails, mark all as errors
+ for (const id of entityIds) {
+ if (!results.find((r) => r.localId === id)) {
+ results.push({
+ status: "error",
+ action: "none",
+ localId: id,
+ error: err instanceof Error ? err.message : String(err)
+ });
+ }
+ }
+ }
+
+ return this.summarizeBatchResults(results);
+ }
+
+ // =================================================================
+ // 6. BATCH PULL WORKFLOW (Accounting -> Carbon)
+ // =================================================================
+
+ async pullBatchFromAccounting(remoteIds: string[]): Promise<BatchSyncResult> {
+ const results: SyncResult[] = [];
+
+ if (!this.config.enabled) {
+ for (const id of remoteIds) {
+ results.push({
+ status: "skipped",
+ action: "none",
+ remoteId: id,
+ error: "Sync disabled in config"
+ });
+ }
+ return this.summarizeBatchResults(results);
+ }
+
+ try {
+ // 1. Fetch all remote entities in batch
+ const remoteEntities = await this.fetchRemoteBatch(remoteIds);
+
+ // Track entities not found remotely
+ const notFoundIds = remoteIds.filter((id) => !remoteEntities.has(id));
+ for (const id of notFoundIds) {
+ results.push({
+ status: "error",
+ action: "none",
+ remoteId: id,
+ error: `Entity ${id} not found in Remote`
+ });
+ }
+
+ // 2. Process each found entity
+ for (const [remoteId, entity] of remoteEntities) {
+ try {
+ // Check system of record
+ const existingLocalId = await this.getLocalId(remoteId);
+ if (existingLocalId && this.config.owner === "carbon") {
+ results.push({
+ status: "skipped",
+ action: "none",
+ remoteId,
+ localId: existingLocalId,
+ error: "Carbon is System of Record"
+ });
+ continue;
+ }
+
+ // Check if entity should be synced (optional business logic)
+ if (this.shouldSync) {
+ const shouldSyncResult = await this.shouldSync({
+ direction: "pull",
+ remoteEntity: entity,
+ isFirstSync: !existingLocalId,
+ entityId: remoteId
+ });
+
+ if (shouldSyncResult !== true) {
+ results.push({
+ status: "skipped",
+ action: "none",
+ remoteId,
+ error:
+ typeof shouldSyncResult === "string"
+ ? shouldSyncResult
+ : "Entity not eligible for sync"
+ });
+ continue;
+ }
+ }
+
+ // Map and upsert locally
+ const localPayload = await this.mapToLocal(entity);
+
+ const localId = await withTriggersDisabled(
+ this.database,
+ async (tx) => {
+ const id = await this.upsertLocal(tx, localPayload, remoteId);
+
+ await this.linkEntities(tx, id, remoteId);
+
+ return id;
+ }
+ );
+
+ results.push({
+ status: "success",
+ action: "updated",
+ localId,
+ remoteId
+ });
+ } catch (err) {
+ results.push({
+ status: "error",
+ action: "none",
+ remoteId,
+ error: err instanceof Error ? err.message : String(err)
+ });
+ }
+ }
+ } catch (err: any) {
+ // If the whole batch fails, mark all as errors
+ for (const id of remoteIds) {
+ if (!results.find((r) => r.remoteId === id)) {
+ results.push({
+ status: "error",
+ action: "none",
+ remoteId: id,
+ error: err instanceof Error ? err.message : String(err)
+ });
+ }
+ }
+ }
+
+ return this.summarizeBatchResults(results);
+ }
+
+ private summarizeBatchResults(results: SyncResult[]): BatchSyncResult {
+ return {
+ results,
+ successCount: results.filter((r) => r.status === "success").length,
+ errorCount: results.filter((r) => r.status === "error").length,
+ skippedCount: results.filter((r) => r.status === "skipped").length
+ };
+ }
+
+ // =================================================================
+ // 7. DEPENDENCY HELPER
+ // =================================================================
+
+ /**
+ * JIT (Just-In-Time) Dependency Sync.
+ * Finds the Remote ID for a related entity. If not synced, it syncs it.
+ */
+ protected async ensureDependencySynced(
+ type: AccountingEntityType,
+ localId: string
+ ): Promise<string> {
+ console.log(`[BaseSyncer] Resolving dependency: ${type} ${localId}`);
+
+ // 1. Instantiate the dependency's Syncer
+ // Dynamic import to avoid circular dependency
+ const { SyncFactory } = await import("./sync");
+
+ // Get sync config for the dependency, with a fallback to enabled by default
+ const dependencyConfig = this.context.provider.getSyncConfig(type) ?? {
+ enabled: true,
+ direction: "two-way" as const,
+ owner: "carbon" as const
+ };
+
+ const syncer = SyncFactory.getSyncer({
+ ...this.context,
+ config: dependencyConfig,
+ entityType: type
+ });
+
+ // 2. Check if it's already synced (using the dependency's own logic)
+ // Note: This requires getRemoteId to be exposed on the syncer instance
+ const existingRemoteId = await (syncer as any).getRemoteId(localId);
+ if (existingRemoteId) {
+ console.log(
+ `[BaseSyncer] Dependency ${type} ${localId} already synced: ${existingRemoteId}`
+ );
+ return existingRemoteId;
+ }
+
+ console.log(
+ `[BaseSyncer] Dependency not found. Triggering sync for ${type} ${localId}`
+ );
+
+ // 3. Force a Push
+ const result = await syncer.pushToAccounting(localId);
+
+ if (result.status === "skipped") {
+ throw new Error(
+ `Dependency sync skipped for ${type} ${localId}: ${
+ result.error ?? "Sync disabled in config"
+ }`
+ );
+ }
+
+ if (result.status === "error" || !result.remoteId) {
+ throw new Error(
+ `Dependency failed: Could not sync ${type} ${localId}. Error: ${
+ result.error ?? "No remote ID returned"
+ }`
+ );
+ }
+
+ console.log(
+ `[BaseSyncer] Dependency ${type} ${localId} synced successfully: ${result.remoteId}`
+ );
+ return result.remoteId;
+ }
+
+ // =================================================================
+ // 6. LOGGING
+ // =================================================================
+
+ private async logSyncOperation(
+ direction: "push" | "pull",
+ localId: string | undefined,
+ remoteId: string | undefined,
+ status: "success" | "error",
+ error?: unknown
+ ) {
+ const logEntry = {
+ direction: direction.toUpperCase(),
+ entity: this.getEntityTypeName(),
+ localId,
+ remoteId,
+ status
+ };
+
+ if (status === "success") {
+ console.log("[SyncLog]", logEntry);
+ } else {
+ // Enhanced error logging with structured details
+ const errorDetails: Record<string, unknown> = { ...logEntry };
+
+ if (error instanceof AccountingApiError) {
+ errorDetails.errorType = error.name;
+ errorDetails.provider = error.provider;
+ errorDetails.operation = error.operation;
+ errorDetails.apiDetails = {
+ statusCode: error.details.statusCode,
+ statusText: error.details.statusText,
+ providerErrorType: error.details.providerErrorType,
+ providerErrorCode: error.details.providerErrorCode,
+ providerMessage: error.details.providerMessage,
+ validationErrors: error.details.validationErrors
+ };
+ errorDetails.userMessage = error.getUserMessage();
+ } else if (error instanceof Error) {
+ errorDetails.errorType = error.name;
+ errorDetails.errorMessage = error.message;
+ errorDetails.stack = error.stack;
+ } else {
+ errorDetails.error = error;
+ }
+
+ console.error("[SyncLog] ERROR", errorDetails);
+ }
+ }
+
+ private getEntityTypeName(): string {
+ return (this.context as any).entityType || "unknown";
+ }
+}
+
+// /********************************************************\
+// * Sync Types End *
+// \********************************************************/
+
+export namespace Accounting {
+ export type Contact = z.infer<typeof ContactSchema>;
+ export type Employee = z.infer<typeof EmployeeSchema>;
+ export type Item = z.infer<typeof ItemSchema>;
+ export type Bill = z.infer<typeof BillSchema>;
+ export type BillLine = z.infer<typeof BillLineSchema>;
+ export type SalesInvoice = z.infer<typeof SalesInvoiceSchema>;
+ export type SalesInvoiceLine = z.infer<typeof SalesInvoiceLineSchema>;
+ export type PurchaseOrder = z.infer<typeof PurchaseOrderSchema>;
+ export type PurchaseOrderLine = z.infer<typeof PurchaseOrderLineSchema>;
+ export type InventoryAdjustment = z.infer<typeof InventoryAdjustmentSchema>;
+ export type SalesOrder = z.infer<typeof SalesOrderSchema>;
+ export type SalesOrderLine = z.infer<typeof SalesOrderLineSchema>;
+}
+
+export interface RequestContext {
+ auth?: ProviderCredentials;
+ signal?: AbortSignal;
+}
+
+export interface SyncOptions {
+ modifiedSince?: Date;
+ cursor?: string;
+ limit?: number;
+ includeDeleted?: boolean;
+}
+
+export interface ReadableResource<T> {
+ list(options?: SyncOptions): Promise<T[]>;
+ get(id: string): Promise<T>;
+}
+
+export type WritableResource<T, Create, Update> = {
+ create(data: Create): Promise<T>;
+ update(id: string, data: Update): Promise<T>;
+ upsert(...data: Array<Update & { id: string }>): Promise<T>;
+ delete(id: string): Promise<void>;
+};
+
+export type Resource<T, Create, Update = Create> = ReadableResource<T> &
+ WritableResource<T, Create, Update>;
diff --git a/packages/ee/src/accounting/core/utils.ts b/packages/ee/src/accounting/core/utils.ts
index b991eebf3b..502072a9b9 100644
--- a/packages/ee/src/accounting/core/utils.ts
+++ b/packages/ee/src/accounting/core/utils.ts
@@ -1,36 +1,49 @@
-import { ProviderCredentials } from "./models";
-import { AuthProvider } from "./provider";
+import type { Kysely, KyselyDatabase, KyselyTx } from "@carbon/database/client";
+import { sql } from "kysely";
+import type {
+ AuthProvider,
+ OAuthClientOptions,
+ ProviderCredentials
+} from "./types";
+
+/**
+ * Execute a database operation with sync triggers disabled.
+ * This prevents circular trigger loops when syncing from external systems.
+ *
+ * Uses PostgreSQL session variable `app.sync_in_progress` which is checked
+ * by the `dispatch_event_batch` trigger function.
+ *
+ * @param db - The Kysely database instance
+ * @param operation - A callback that receives the transaction and performs DB operations
+ */
+export async function withTriggersDisabled<T>(
+ db: Kysely<KyselyDatabase>,
+ operation: (tx: KyselyTx) => Promise<T>
+): Promise<T> {
+ return db.transaction().execute(async (tx) => {
+ // Set the session variable to disable event triggers for this transaction
+ await sql`SET LOCAL "app.sync_in_progress" = 'true'`.execute(tx);
+ return await operation(tx);
+ });
+}
export class HTTPClient {
- constructor(
- private baseUrl?: string,
- private maxRetries: number = 3
- ) {}
+ constructor(private baseUrl?: string) {}
async request<T>(method: string, path: string, opts: RequestInit = {}) {
- const response = await this.fetch(method, path, opts);
- return this.parseResponse<T>(response);
- }
+ let response!: Response;
- async requestWithRetry<T>(
- method: string,
- path: string,
- opts: RequestInit = {}
- ) {
- let attempt = 0;
-
- while (true) {
- const response = await this.fetch(method, path, opts);
+ try {
+ response = await this.fetch(method, path, opts);
- if (this.shouldRetry(response, attempt)) {
- attempt++;
-
- const retryAfterMs = this.getRetryAfterMs(response);
- if (retryAfterMs !== undefined) {
- await this.sleep(retryAfterMs);
- }
+ if (response.status === 429) {
+ throw new RatelimitError("Rate limit exceeded", response);
+ }
- continue;
+ return this.parseResponse<T>(response);
+ } catch (error) {
+ if (error instanceof RatelimitError) {
+ throw error;
}
return this.parseResponse<T>(response);
@@ -51,26 +64,55 @@ export class HTTPClient {
}
private async parseResponse<T>(response: Response) {
- const hasBody =
- response.headers.get("content-length") !== "0" &&
- response.headers.get("content-type")?.includes("application/json");
+ const contentType = response.headers.get("content-type");
+ const isJson = contentType?.includes("application/json");
if (!response.ok) {
+ const text = await response.text();
+ let parsedData: unknown = text;
+
+ // Try to parse JSON error responses for better error details
+ if (isJson && text) {
+ try {
+ parsedData = JSON.parse(text);
+ } catch {
+ // Keep as raw string if parsing fails
+ }
+ }
+
return {
error: true,
message: response.statusText,
code: response.status,
- data: await response.text()
+ data: parsedData
} as const;
}
- if (hasBody) {
- return {
- error: false,
- message: response.statusText,
- code: response.status,
- data: (await response.json()) as T
- } as const;
+ if (isJson) {
+ try {
+ const text = await response.text();
+ if (!text || text.trim() === "") {
+ return {
+ error: false,
+ message: response.statusText,
+ code: response.status,
+ data: null
+ } as const;
+ }
+ return {
+ error: false,
+ message: response.statusText,
+ code: response.status,
+ data: JSON.parse(text) as T
+ } as const;
+ } catch {
+ return {
+ error: true,
+ message: "Invalid JSON response",
+ code: response.status,
+ data: null
+ } as const;
+ }
}
return {
@@ -80,51 +122,240 @@ export class HTTPClient {
data: null
} as const;
}
+}
+
+// /********************************************************\
+// * Custom Errors Start *
+// \********************************************************/
+export class NotImplementedError extends Error {
+ constructor(name: string) {
+ super(`Method ${name} is not implemented.`);
+ this.name = "NotImplementedError";
+ }
+}
- private shouldRetry(response: Response, attempt: number): boolean {
- return response.status === 429 && attempt < this.maxRetries;
+export class RatelimitError extends Error {
+ constructor(
+ message: string,
+ public response: Response
+ ) {
+ super(message);
+ this.name = "RatelimitError";
+ this.response = response;
}
+}
- private getRetryAfterMs(response: Response): number | undefined {
- const retryAfter = response.headers.get("Retry-After");
- if (!retryAfter) return undefined;
+/** Structured details from an accounting provider API error */
+export interface ApiErrorDetails {
+ /** HTTP status code (e.g., 400, 401, 500) */
+ statusCode: number;
+ /** HTTP status text (e.g., "Bad Request") */
+ statusText: string;
+ /** Provider-specific error code if available */
+ providerErrorCode?: string | number;
+ /** Provider-specific error type (e.g., "ValidationException") */
+ providerErrorType?: string;
+ /** Human-readable error message from the provider */
+ providerMessage?: string;
+ /** Validation errors for specific fields/elements */
+ validationErrors?: Array<{
+ field?: string;
+ message: string;
+ }>;
+ /** Raw response body for debugging (only logged in development) */
+ rawResponse?: unknown;
+}
- const seconds = Number(retryAfter);
- if (!Number.isNaN(seconds)) {
- return seconds * 1000;
+/**
+ * Structured error class for accounting provider API errors.
+ * Captures detailed error information for debugging and user display.
+ */
+export class AccountingApiError extends Error {
+ public readonly details: ApiErrorDetails;
+ public readonly provider: string;
+ public readonly operation: string;
+
+ constructor(provider: string, operation: string, details: ApiErrorDetails) {
+ // Build a human-readable message
+ const messages: string[] = [`${details.statusCode} ${details.statusText}`];
+
+ if (details.providerMessage) {
+ messages.push(details.providerMessage);
}
- const date = Date.parse(retryAfter);
- if (!Number.isNaN(date)) {
- return Math.max(0, date - Date.now());
+ if (details.validationErrors?.length) {
+ messages.push(details.validationErrors.map((e) => e.message).join("; "));
}
- return undefined;
+ super(`[${provider}] ${operation} failed: ${messages.join(" - ")}`);
+
+ this.name = "AccountingApiError";
+ this.provider = provider;
+ this.operation = operation;
+ this.details = details;
}
- private sleep(ms: number) {
- return new Promise((resolve) => setTimeout(resolve, ms));
+ /** Get a concise error message suitable for user display */
+ getUserMessage(): string {
+ if (this.details.validationErrors?.length) {
+ return this.details.validationErrors.map((e) => e.message).join("; ");
+ }
+ return this.details.providerMessage || this.details.statusText;
}
}
+// /********************************************************\
+// * Custom Errors End *
+// \********************************************************/
+
+// /********************************************************\
+// * Xero Error Parsing Start *
+// \********************************************************/
+
+/**
+ * Parses Xero API error responses into structured ApiErrorDetails.
+ *
+ * Xero returns errors in several formats:
+ *
+ * 1. ValidationException with Elements:
+ * {
+ * "ErrorNumber": 10,
+ * "Type": "ValidationException",
+ * "Message": "A validation exception occurred",
+ * "Elements": [{
+ * "ValidationErrors": [{ "Message": "Code must be unique" }]
+ * }]
+ * }
+ *
+ * 2. Simple error:
+ * { "Message": "Something went wrong" }
+ *
+ * 3. OAuth error:
+ * { "error": "invalid_grant", "error_description": "Token expired" }
+ *
+ * 4. RFC 7807 problem+json:
+ * { "type": "...", "title": "...", "detail": "..." }
+ */
+export function extractXeroErrorDetails(
+ statusCode: number,
+ statusText: string,
+ responseData: unknown
+): ApiErrorDetails {
+ const details: ApiErrorDetails = {
+ statusCode,
+ statusText,
+ rawResponse: responseData
+ };
-export class NotImplementedError extends Error {
- constructor(name: string) {
- super(`Method ${name} is not implemented.`);
- this.name = "NotImplementedError";
+ // Try to parse if it's a string
+ let data: unknown = responseData;
+ if (typeof responseData === "string") {
+ try {
+ data = JSON.parse(responseData);
+ } catch {
+ // Not JSON, use raw string as message if short enough
+ if (responseData.length < 500) {
+ details.providerMessage = responseData;
+ }
+ return details;
+ }
}
+
+ if (typeof data !== "object" || data === null) {
+ return details;
+ }
+
+ const obj = data as Record<string, unknown>;
+
+ // Extract error type and code
+ if (typeof obj.Type === "string") {
+ details.providerErrorType = obj.Type;
+ }
+ if (obj.ErrorNumber !== undefined) {
+ details.providerErrorCode = obj.ErrorNumber as number;
+ }
+
+ // Extract main message (try multiple common formats)
+ if (typeof obj.Message === "string") {
+ details.providerMessage = obj.Message;
+ } else if (typeof obj.message === "string") {
+ details.providerMessage = obj.message;
+ } else if (typeof obj.detail === "string") {
+ // RFC 7807 format
+ details.providerMessage = obj.detail;
+ } else if (typeof obj.error_description === "string") {
+ // OAuth format
+ details.providerMessage = obj.error_description;
+ details.providerErrorType = obj.error as string;
+ }
+
+ // Extract validation errors from Elements array
+ if (Array.isArray(obj.Elements)) {
+ const validationErrors: Array<{ field?: string; message: string }> = [];
+
+ for (const element of obj.Elements) {
+ if (element && Array.isArray(element.ValidationErrors)) {
+ for (const err of element.ValidationErrors) {
+ if (err && typeof err.Message === "string") {
+ validationErrors.push({ message: err.Message });
+ }
+ }
+ }
+ }
+
+ if (validationErrors.length > 0) {
+ details.validationErrors = validationErrors;
+ }
+ }
+
+ return details;
}
-interface OAuthClientOptions {
- clientId: string;
- clientSecret: string;
- tokenUrl: string;
- accessToken?: string;
- refreshToken?: string;
- redirectUri?: string;
- getAuthUrl: (scopes: string[], redirectUri: string) => string;
- onTokenRefresh?: (creds: ProviderCredentials) => void;
+const isDevelopment = process.env.NODE_ENV !== "production";
+
+/**
+ * Creates and logs an AccountingApiError from an HTTP response, then throws it.
+ * Logs full error details to console for debugging.
+ *
+ * @param operation - Description of the operation that failed (e.g., "create item", "batch upsert contacts")
+ * @param response - The HTTP response object from HTTPClient
+ * @throws AccountingApiError
+ */
+export function throwXeroApiError(
+ operation: string,
+ response: { error: boolean; message: string; code: number; data: unknown }
+): never {
+ const details = extractXeroErrorDetails(
+ response.code,
+ response.message,
+ response.data
+ );
+
+ const error = new AccountingApiError("xero", operation, details);
+
+ // Log full error details for debugging
+ const logDetails: Record<string, unknown> = {
+ statusCode: details.statusCode,
+ statusText: details.statusText,
+ providerErrorType: details.providerErrorType,
+ providerErrorCode: details.providerErrorCode,
+ providerMessage: details.providerMessage,
+ validationErrors: details.validationErrors
+ };
+
+ // Only include raw response in development to avoid log bloat
+ if (isDevelopment) {
+ logDetails.rawResponse = details.rawResponse;
+ }
+
+ console.error(`[Xero API Error] ${operation}`, logDetails);
+
+ throw error;
}
+// /********************************************************\
+// * Xero Error Parsing End *
+// \********************************************************/
+
export function createOAuthClient({
clientId,
clientSecret,
@@ -171,11 +402,17 @@ export function createOAuthClient({
).toISOString()
} satisfies ProviderCredentials;
- options.onTokenRefresh?.(newCreds);
+ creds = {
+ ...creds,
+ ...newCreds
+ };
+
+ options.onTokenRefresh && (await options.onTokenRefresh(newCreds));
return newCreds;
},
async refresh() {
+ console.log("Refreshing OAuth tokens", creds);
if (!creds?.refreshToken) {
throw new Error("No refresh token available");
}
@@ -210,7 +447,12 @@ export function createOAuthClient({
tenantId: creds?.tenantId
} satisfies ProviderCredentials;
- options.onTokenRefresh?.(newCreds);
+ creds = {
+ ...creds,
+ ...newCreds
+ };
+
+ options.onTokenRefresh && (await options.onTokenRefresh(newCreds));
return newCreds;
},
diff --git a/packages/ee/src/accounting/entities/index.ts b/packages/ee/src/accounting/entities/index.ts
deleted file mode 100644
index b2c49a74cf..0000000000
--- a/packages/ee/src/accounting/entities/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-export * from "./provider";
-export * from "./schema";
-export * from "./types";
diff --git a/packages/ee/src/accounting/entities/provider.ts b/packages/ee/src/accounting/entities/provider.ts
deleted file mode 100644
index 35c6856346..0000000000
--- a/packages/ee/src/accounting/entities/provider.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-import { z } from "zod";
-
-export namespace Xero {
- export const AddressSchema = z.object({
- AddressType: z.enum(["POBOX", "STREET", "DELIVERY"]),
- AddressLine1: z.string().optional(),
- AddressLine2: z.string().optional(),
- AddressLine3: z.string().optional(),
- AddressLine4: z.string().optional(),
- City: z.string().optional(),
- Region: z.string().optional(),
- PostalCode: z.string().optional(),
- Country: z.string().optional(),
- AttentionTo: z.string().optional()
- });
-
- export const PhoneSchema = z.object({
- PhoneType: z.enum(["DDI", "DEFAULT", "FAX", "MOBILE"]),
- PhoneNumber: z.string().optional(),
- PhoneAreaCode: z.string().optional(),
- PhoneCountryCode: z.string().optional()
- });
-
- export const BalancesSchema = z.object({
- AccountsReceivable: z.object({
- Outstanding: z.number(),
- Overdue: z.number()
- }),
- AccountsPayable: z.object({
- Outstanding: z.number(),
- Overdue: z.number()
- })
- });
-
- export const BrandingThemeSchema = z.object({
- BrandingThemeID: z.string().uuid(),
- Name: z.string()
- });
-
- export const BatchPaymentsSchema = z.object({
- BankAccountNumber: z.string(),
- BankAccountName: z.string(),
- Details: z.string(),
- Code: z.string().optional(),
- Reference: z.string().optional()
- });
-
- export const ContactSchema = z.object({
- ContactID: z.string().uuid(),
- ContactStatus: z.literal("ACTIVE"),
-
- Name: z.string(),
- Website: z.string().optional(),
-
- FirstName: z.string().optional(),
- LastName: z.string().optional(),
-
- EmailAddress: z.string().email().optional(),
- ContactNumber: z.string().optional(),
-
- BankAccountDetails: z.string().optional(),
- TaxNumber: z.string().optional(),
-
- AccountsReceivableTaxType: z.string().optional(),
- AccountsPayableTaxType: z.string().optional(),
-
- Addresses: z.array(AddressSchema),
- Phones: z.array(PhoneSchema),
-
- UpdatedDateUTC: z.string(), // serialized /Date(...)/
-
- ContactGroups: z.array(z.unknown()),
-
- IsSupplier: z.boolean(),
- IsCustomer: z.boolean(),
-
- DefaultCurrency: z.string().optional(),
-
- BrandingTheme: BrandingThemeSchema.optional(),
- BatchPayments: BatchPaymentsSchema.optional(),
-
- Balances: BalancesSchema.optional(),
-
- ContactPersons: z.array(z.unknown()),
-
- HasAttachments: z.boolean(),
- HasValidationErrors: z.boolean()
- });
-
- export type Contact = z.infer<typeof ContactSchema>;
-}
-
-export namespace QuickBooks {
- export const BillAddrSchema = z.object({
- City: z.string(),
- Line1: z.string(),
- PostalCode: z.string(),
- Lat: z.string(),
- Long: z.string(),
- CountrySubDivisionCode: z.string(),
- Id: z.string()
- });
-
- export const MetaDataSchema = z.object({
- CreateTime: z.coerce.date(),
- LastUpdatedTime: z.coerce.date()
- });
-
- export const PrimaryEmailAddrSchema = z.object({
- Address: z.string()
- });
-
- export const PrimaryPhoneSchema = z.object({
- FreeFormNumber: z.string()
- });
-
- export const CustomerSchema = z.object({
- PrimaryEmailAddr: PrimaryEmailAddrSchema,
- SyncToken: z.string(),
- domain: z.string(),
- GivenName: z.string(),
- DisplayName: z.string(),
- BillWithParent: z.boolean(),
- FullyQualifiedName: z.string(),
- CompanyName: z.string(),
- FamilyName: z.string(),
- sparse: z.boolean(),
- PrimaryPhone: PrimaryPhoneSchema,
- Active: z.boolean(),
- Job: z.boolean(),
- BalanceWithJobs: z.number(),
- BillAddr: BillAddrSchema,
- PreferredDeliveryMethod: z.string(),
- Taxable: z.boolean(),
- PrintOnCheckName: z.string(),
- Balance: z.number(),
- Id: z.string(),
- MetaData: MetaDataSchema
- });
-
- export type Customer = z.infer<typeof CustomerSchema>;
-}
diff --git a/packages/ee/src/accounting/entities/schema.ts b/packages/ee/src/accounting/entities/schema.ts
deleted file mode 100644
index 18c7c7494b..0000000000
--- a/packages/ee/src/accounting/entities/schema.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import z from "zod";
-
-function withNullable<T extends z.ZodTypeAny>(schema: T) {
- return z.preprocess((v) => (v === undefined ? null : v), schema.nullish());
-}
-
-// export const BaseEntitySchema = z.object({
-// id: z.string(),
-// externalId: z.string().optional(), // Provider-specific ID
-// createdAt: z.string().datetime(),
-// updatedAt: z.string().datetime(),
-// lastSyncedAt: z.string().datetime().optional(),
-// });
-
-export const ContactSchema = z.object({
- id: z.string(),
- name: z.string(),
- firstName: z.string(),
- lastName: z.string(),
- companyId: z.string(),
- email: z.string().optional(),
- website: withNullable(z.string().url()),
- taxId: withNullable(z.string()),
- currencyCode: z.string().default("USD"),
- balance: z.number().nullish(),
- creditLimit: z.number().nullish(),
- paymentTerms: z.string().nullish(),
- updatedAt: z.string().datetime(),
- phones: z.array(
- z.object({
- type: z.string().optional(),
- phone: z.string().optional()
- })
- ),
- addresses: z.array(
- z.object({
- label: z.string().nullish(),
- type: z.string().nullish(),
- line1: z.string().nullish(),
- line2: z.string().nullish(),
- city: z.string().nullish(),
- country: z.string().nullish(),
- region: z.string().nullish(),
- postalCode: z.string().nullish()
- })
- ),
- isVendor: z.boolean(),
- isCustomer: z.boolean()
-});
diff --git a/packages/ee/src/accounting/entities/types.ts b/packages/ee/src/accounting/entities/types.ts
deleted file mode 100644
index 9f251f24e9..0000000000
--- a/packages/ee/src/accounting/entities/types.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { Database, Json } from "@carbon/database";
-import z from "zod";
-import { ContactSchema } from "./schema";
-
-export type AccountingEntityType = "customer" | "vendor";
-// Uncomment and expand as needed
-// | "bill" // Purchase Invoice
-// | "employee"
-// | "invoice"
-// | "item"
-// | "purchase_order"
-// | "sales_order"
-// | "inventory_adjustment";
-
-export interface EntityMap {
- customer: Accounting.Contact;
- vendor: Accounting.Contact;
-}
-
-export namespace Accounting {
- export type Contact = z.infer<typeof ContactSchema>;
-}
-
-export type TablesWithExternalId = {
- [K in keyof Database["public"]["Tables"]]: Database["public"]["Tables"][K]["Row"] extends {
- externalId: Json;
- companyId: string;
- }
- ? K
- : never;
-}[keyof Database["public"]["Tables"]];
diff --git a/packages/ee/src/accounting/index.ts b/packages/ee/src/accounting/index.ts
index db875efa28..bf9759ce32 100644
--- a/packages/ee/src/accounting/index.ts
+++ b/packages/ee/src/accounting/index.ts
@@ -1,3 +1,6 @@
-export * from "./core";
-export * from "./entities";
+export * from "./core/external-mapping";
+export * from "./core/models";
+export * from "./core/service";
+export * from "./core/sync";
+export * from "./core/types";
export * from "./providers";
diff --git a/packages/ee/src/accounting/models.ts b/packages/ee/src/accounting/models.ts
index 40fca66eed..b1488481a9 100644
--- a/packages/ee/src/accounting/models.ts
+++ b/packages/ee/src/accounting/models.ts
@@ -9,7 +9,6 @@ import { z } from "zod";
// Base schemas
export const BaseEntitySchema = z.object({
id: z.string(),
- externalId: z.string().optional(), // Provider-specific ID
createdAt: z.string().datetime(),
updatedAt: z.string().datetime(),
lastSyncedAt: z.string().datetime().optional(),
diff --git a/packages/ee/src/accounting/providers/index.ts b/packages/ee/src/accounting/providers/index.ts
index 50046bd1f0..a38b816a63 100644
--- a/packages/ee/src/accounting/providers/index.ts
+++ b/packages/ee/src/accounting/providers/index.ts
@@ -1,6 +1,5 @@
-import { XeroProvider } from "./xero";
-
-export * from "./quickbooks";
-export * from "./xero";
+import type { XeroProvider } from "./xero";
export type AccountingProvider = XeroProvider;
+
+export * from "./xero";
diff --git a/packages/ee/src/accounting/providers/quickbooks.ts b/packages/ee/src/accounting/providers/quickbooks.ts
deleted file mode 100644
index b19ed4fd2c..0000000000
--- a/packages/ee/src/accounting/providers/quickbooks.ts
+++ /dev/null
@@ -1,163 +0,0 @@
-import {
- AuthProvider,
- BaseProvider,
- createOAuthClient,
- HTTPClient,
- ProviderConfig,
- ProviderCredentials,
- ProviderID,
- Resource
-} from "../core";
-import { Accounting, QuickBooks } from "../entities";
-
-export interface IQuickBooksProvider extends BaseProvider {
- // Add resource interfaces as needed, e.g.: customers, invoices, etc.
- contacts: Pick<
- Resource<Accounting.Contact, unknown, unknown>,
- "get" | "list"
- >;
-}
-
-type QuickBooksProviderConfig = ProviderConfig<{
- clientId: string;
- clientSecret: string;
- redirectUri?: string;
- tenantId?: string;
- environment?: "sandbox" | "production";
-}> & {
- id: ProviderID.QUICKBOOKS;
-};
-
-export class QuickBooksProvider implements IQuickBooksProvider {
- http: HTTPClient;
- auth: AuthProvider;
-
- static id = ProviderID.QUICKBOOKS;
-
- constructor(public config: Omit<QuickBooksProviderConfig, "id">) {
- const host =
- config.environment === "production"
- ? "https://quickbooks.api.intuit.com"
- : "https://sandbox-quickbooks.api.intuit.com";
- const baseURL = `${host}/v3/company/${this.config.tenantId}`;
-
- this.http = new HTTPClient(baseURL, 3);
- this.auth = createOAuthClient({
- clientId: config.clientId,
- clientSecret: config.clientSecret,
- redirectUri: config.redirectUri,
- tokenUrl: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer",
- onTokenRefresh: config.onTokenRefresh,
- getAuthUrl(scopes, redirect_uri = "") {
- const params = new URLSearchParams({
- client_id: config.clientId,
- scope: scopes.join(" ") || "com.intuit.quickbooks.accounting",
- redirect_uri,
- response_type: "code",
- access_type: "offline",
- state: crypto.randomUUID()
- });
- return `https://appcenter.intuit.com/connect/oauth2?${params.toString()}`;
- }
- });
- }
-
- get id(): ProviderID.QUICKBOOKS {
- // @ts-expect-error
- return this.constructor.id;
- }
-
- contacts: IQuickBooksProvider["contacts"] = {
- list: async () => {
- const res = await this.http.requestWithRetry<{
- QueryResponse: {
- Customer: QuickBooks.Customer[];
- };
- }>(
- "GET",
- `/query?query=${encodeURIComponent("select * from Customer")}'`
- );
-
- if (res.error) {
- throw new Error(`Failed to fetch contacts: ${res.message}`);
- }
-
- return res.data?.QueryResponse.Customer || [];
- },
- get: async (id) => {
- const res = await this.http.requestWithRetry<{
- Contacts: Xero.Contact[];
- }>("GET", `/Contacts/${id}`);
-
- if (res.error || !res.data?.Contacts?.length) {
- throw new Error(`Failed to fetch contact ${id}: ${res.message}`);
- }
-
- const contact = res.data.Contacts[0]!;
-
- return contact;
- }
- };
-
- authenticate(
- code: string,
- redirectUri: string
- ): Promise<ProviderCredentials> {
- return this.auth.exchangeCode(code, redirectUri);
- }
-
- async request<T>(method: string, url: string, options?: RequestInit) {
- const { accessToken, ...creds } = this.auth.getCredentials();
-
- const tenantId = creds.tenantId || this.config.tenantId;
-
- const baseHeaders: Record<string, string> = {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json",
- "Content-Type": "application/json",
- ...((options?.headers ?? {}) as Record<string, string>)
- };
-
- const endpoint = `/v3/company/${tenantId}${url}`;
-
- const response = await this.http.requestWithRetry(method, endpoint, {
- ...options,
- headers: baseHeaders
- });
-
- if (response.code === 401) {
- await this.auth.refresh();
-
- const c = this.auth.getCredentials();
-
- if (typeof this.config.onTokenRefresh === "function") {
- this.config.onTokenRefresh(c);
- }
-
- const retryHeaders: Record<string, string> = {
- ...baseHeaders,
- Authorization: `Bearer ${c.accessToken}`
- };
-
- return this.http.request<T>(method, url, {
- ...options,
- headers: retryHeaders
- });
- }
-
- return response;
- }
-
- async validate(auth: ProviderCredentials): Promise<boolean> {
- if (!auth?.accessToken || !auth?.tenantId) {
- return false;
- }
-
- try {
- const response = await this.request("GET", "/companyinfo");
- return !response.error;
- } catch {
- return false;
- }
- }
-}
diff --git a/packages/ee/src/accounting/providers/xero.ts b/packages/ee/src/accounting/providers/xero.ts
deleted file mode 100644
index a73b6ba329..0000000000
--- a/packages/ee/src/accounting/providers/xero.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-import {
- AuthProvider,
- BaseProvider,
- createOAuthClient,
- HTTPClient,
- ProviderConfig,
- ProviderCredentials,
- ProviderID,
- Resource
-} from "../core";
-import { Xero } from "../entities";
-import { Accounting } from "../entities/types";
-
-export interface IXeroProvider extends BaseProvider {
- contacts: Resource<Accounting.Contact, Accounting.Contact>;
-}
-
-type XeroProviderConfig = ProviderConfig<{
- clientId: string;
- clientSecret: string;
- redirectUri?: string;
- tenantId?: string;
-}> & {
- id: ProviderID.XERO;
- accessToken?: string;
- refreshToken?: string;
-};
-
-const fromDotnetDate = (date: Date | string) => {
- if (typeof date === "string") {
- const value = date.replace(/\/Date\((\d+)([-+]\d+)?\)\//, "$1");
- return new Date(parseInt(value));
- }
-
- return date;
-};
-
-export class XeroProvider implements IXeroProvider {
- static id = ProviderID.XERO;
-
- http: HTTPClient;
- auth: AuthProvider;
-
- constructor(public config: Omit<XeroProviderConfig, "id">) {
- this.http = new HTTPClient("https://api.xero.com/api.xro/2.0", 3);
- this.auth = createOAuthClient({
- clientId: config.clientId,
- clientSecret: config.clientSecret,
- accessToken: config.accessToken,
- refreshToken: config.refreshToken,
- redirectUri: config.redirectUri,
- tokenUrl: "https://identity.xero.com/connect/token",
- onTokenRefresh: config.onTokenRefresh,
- getAuthUrl(scopes: string[], redirectURL): string {
- const params = new URLSearchParams({
- response_type: "code",
- client_id: config.clientId,
- redirect_uri: redirectURL,
- scope: scopes.join(" "),
- state: crypto.randomUUID()
- });
-
- return `https://login.xero.com/identity/connect/authorize?${params.toString()}`;
- }
- });
- }
-
- get id(): ProviderID.XERO {
- // @ts-expect-error
- return this.constructor.id;
- }
-
- contacts: IXeroProvider["contacts"] = {
- list: async () => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("GET", `/Contacts`);
-
- if (res.error) {
- throw new Error(`Failed to fetch contacts: ${res.message}`);
- }
-
- return (res.data?.Contacts || []).map((c) =>
- transformContact(c, this.config.companyId)
- );
- },
- get: async (id) => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("GET", `/Contacts/${id}`);
-
- if (res.error || !res.data?.Contacts?.length) {
- throw new Error(`Failed to fetch contact ${id}: ${res.message}`);
- }
-
- const contact = res.data.Contacts[0]!;
-
- return transformContact(contact, this.config.companyId);
- },
- create: async (data) => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("PUT", `/Contacts`, {
- body: JSON.stringify({
- Contacts: [
- {
- Name: data.name,
- FirstName: data.firstName,
- LastName: data.lastName,
- EmailAddress: data.email,
- Website: data.website,
- TaxNumber: data.taxId,
- IsCustomer: data.isCustomer,
- IsSupplier: data.isVendor,
- Phones: data.phones?.map((p) => ({
- PhoneType: p.type,
- PhoneNumber: p.phone
- })),
- Addresses: data.addresses?.map((a) => ({
- AddressLine1: a.line1,
- AddressLine2: a.line2,
- City: a.city,
- Region: a.region,
- Country: a.country,
- PostalCode: a.postalCode
- }))
- }
- ]
- })
- });
-
- if (res.error || !res.data?.Contacts?.length) {
- throw new Error(`Failed to create contact: ${res.message}`);
- }
-
- const contact = res.data.Contacts[0]!;
-
- return transformContact(contact, this.config.companyId);
- },
- update: async (id, data) => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("POST", `/Contacts/${id}`, {
- body: JSON.stringify({
- Contacts: [
- {
- Name: data.name,
- FirstName: data.firstName,
- LastName: data.lastName,
- EmailAddress: data.email,
- Website: data.website,
- TaxNumber: data.taxId,
- IsCustomer: data.isCustomer,
- IsSupplier: data.isVendor,
- Phones: data.phones?.map((p) => ({
- PhoneType: p.type,
- PhoneNumber: p.phone
- })),
- Addresses: data.addresses?.map((a) => ({
- AddressLine1: a.line1,
- AddressLine2: a.line2,
- City: a.city,
- Region: a.region,
- Country: a.country,
- PostalCode: a.postalCode
- }))
- }
- ]
- })
- });
-
- if (res.error || !res.data?.Contacts?.length) {
- throw new Error(`Failed to update contact: ${res.message}`);
- }
-
- const contact = res.data.Contacts[0]!;
-
- return transformContact(contact, this.config.companyId);
- },
- delete: async (id) => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("POST", `/Contacts/${id}`, {
- body: JSON.stringify({
- ContactID: id,
- ContactStatus: "ARCHIVED"
- })
- });
-
- if (res.error) {
- throw new Error(`Failed to delete contact ${id}: ${res.message}`);
- }
- },
- upsert: async ({ id, ...data }) => {
- const res = await this.request<{
- Contacts: Xero.Contact[];
- }>("POST", `/Contacts`, {
- body: JSON.stringify({
- Contacts: [
- {
- ContactID: id,
- Name: data.name,
- FirstName: data.firstName,
- LastName: data.lastName,
- EmailAddress: data.email,
- Website: data.website,
- TaxNumber: data.taxId,
- IsCustomer: data.isCustomer,
- IsSupplier: data.isVendor,
- Phones: data.phones?.map((p) => ({
- PhoneType: p.type,
- PhoneNumber: p.phone
- })),
- Addresses: data.addresses?.map((a) => ({
- AddressLine1: a.line1,
- AddressLine2: a.line2,
- City: a.city,
- Region: a.region,
- Country: a.country,
- PostalCode: a.postalCode
- }))
- }
- ]
- })
- });
-
- if (res.error || !res.data?.Contacts?.length) {
- throw new Error(`Failed to upsert contact: ${res.message}`);
- }
-
- const contact = res.data.Contacts[0]!;
-
- return transformContact(contact, this.config.companyId);
- }
- };
-
- authenticate(
- code: string,
- redirectUri: string
- ): Promise<ProviderCredentials> {
- return this.auth.exchangeCode(code, redirectUri);
- }
-
- async request<T>(method: string, url: string, options?: RequestInit) {
- const { accessToken, ...creds } = this.auth.getCredentials();
-
- const tenantId = creds.tenantId || this.config.tenantId;
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${accessToken}`,
- Accept: "application/json",
- "Content-Type": "application/json",
- ...((options?.headers ?? {}) as Record<string, string>)
- };
-
- if (tenantId) {
- headers["xero-tenant-id"] = tenantId;
- }
-
- const response = await this.http.requestWithRetry<T>(method, url, {
- ...options,
- headers: headers
- });
-
- if (response.code === 401) {
- await this.auth.refresh();
-
- const c = this.auth.getCredentials();
-
- const retryHeaders: Record<string, string> = {
- ...headers,
- Authorization: `Bearer ${c.accessToken}`
- };
-
- if (tenantId) {
- retryHeaders["xero-tenant-id"] = tenantId;
- }
-
- return this.http.request<T>(method, url, {
- ...options,
- headers: retryHeaders
- });
- }
-
- return response;
- }
-
- async validate(auth: ProviderCredentials): Promise<boolean> {
- if (!auth?.accessToken || !auth.tenantId) return false;
- try {
- const response = await this.request("GET", `/Organisation`);
- return !response.error;
- } catch {
- return false;
- }
- }
-}
-
-/** Helpers */
-const transformContact = (
- contact: Xero.Contact,
- companyId: string
-): Accounting.Contact => {
- const firstName = contact.FirstName || "";
- const lastName = contact.LastName || "";
-
- const phones = contact.Phones ?? [];
- const addresses = contact.Addresses ?? [];
-
- return {
- id: contact.ContactID,
- name: `${firstName} ${lastName}`.trim(),
- firstName,
- lastName,
- companyId,
- website: contact.Website,
- currencyCode: contact.DefaultCurrency ?? "USD",
- taxId: contact.TaxNumber,
- email: contact.EmailAddress,
- isCustomer: contact.IsCustomer,
- isVendor: contact.IsSupplier,
- addresses: addresses.map((a) => ({
- label: a.AttentionTo,
- line1: a.AddressLine1,
- line2: a.AddressLine2,
- city: a.City,
- region: a.Region,
- country: a.Country,
- postalCode: a.PostalCode
- })),
- phones: phones.map((p) => ({
- type: p.PhoneType,
- phone: p.PhoneNumber
- })),
- updatedAt: fromDotnetDate(contact.UpdatedDateUTC).toISOString()
- };
-};
diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.ts
new file mode 100644
index 0000000000..421917ea2b
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts
@@ -0,0 +1,669 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { createMappingService } from "../../../core/external-mapping";
+import { type Accounting, BaseEntitySyncer } from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Note: This syncer uses the default ID mapping from BaseEntitySyncer
+// which uses the externalIntegrationMapping table with entityType "bill"
+
+// Type for rows returned from purchaseInvoice queries
+type BillRow = {
+ id: string;
+ companyId: string;
+ invoiceId: string;
+ supplierId: string | null;
+ status:
+ | "Draft"
+ | "Pending"
+ | "Submitted"
+ | "Return"
+ | "Debit Note Issued"
+ | "Paid"
+ | "Partially Paid"
+ | "Overdue"
+ | "Voided";
+ dateIssued: string | null;
+ dateDue: string | null;
+ datePaid: string | null;
+ currencyCode: string;
+ exchangeRate: number;
+ subtotal: number;
+ totalTax: number;
+ totalDiscount: number;
+ totalAmount: number;
+ balance: number;
+ supplierReference: string | null;
+ updatedAt: string | null;
+ customFields: Record<string, unknown> | null;
+};
+
+// Type for rows returned from purchaseInvoiceLine queries
+type BillLineRow = {
+ id: string;
+ invoiceId: string;
+ description: string | null;
+ quantity: number;
+ unitPrice: number | null;
+ itemId: string | null;
+ accountNumber: string | null;
+ taxPercent: number | null;
+ taxAmount: number | null;
+ totalAmount: number | null;
+ itemCode: string | null;
+ purchaseOrderLineId: string | null;
+};
+
+// Status mapping between Carbon and Xero
+const CARBON_TO_XERO_STATUS: Record<BillRow["status"], Xero.Invoice["Status"]> =
+ {
+ Draft: "DRAFT",
+ Pending: "SUBMITTED",
+ Submitted: "AUTHORISED",
+ Return: "DRAFT", // No direct equivalent, map to DRAFT
+ "Debit Note Issued": "AUTHORISED",
+ Paid: "PAID",
+ "Partially Paid": "AUTHORISED", // Xero tracks partial payment via AmountDue
+ Overdue: "AUTHORISED", // Xero doesn't have overdue status
+ Voided: "VOIDED"
+ };
+
+const XERO_TO_CARBON_STATUS: Record<
+ Xero.Invoice["Status"],
+ Accounting.Bill["status"]
+> = {
+ DRAFT: "Draft",
+ SUBMITTED: "Pending",
+ AUTHORISED: "Submitted",
+ PAID: "Paid",
+ VOIDED: "Voided",
+ DELETED: "Voided"
+};
+
+export class BillSyncer extends BaseEntitySyncer<
+ Accounting.Bill,
+ Xero.Invoice,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // The entityType "bill" maps to the purchaseInvoice table
+ // =================================================================
+
+ protected async linkEntities(
+ tx: KyselyTx,
+ localId: string,
+ remoteId: string,
+ remoteUpdatedAt?: Date
+ ): Promise<void> {
+ // Use the mapping service to link bill -> purchaseInvoice
+ const txMappingService = createMappingService(tx, this.companyId);
+ await txMappingService.link("bill", localId, this.provider.id, remoteId, {
+ remoteUpdatedAt
+ });
+ }
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.Invoice): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.Bill | null> {
+ const bills = await this.fetchBillsByIds([id]);
+ return bills.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Bill>> {
+ if (ids.length === 0) return new Map();
+ return this.fetchBillsByIds(ids);
+ }
+
+ private async fetchBillsByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Bill>> {
+ if (ids.length === 0) return new Map();
+
+ // Fetch bills
+ const billRows = await this.database
+ .selectFrom("purchaseInvoice")
+ .select([
+ "id",
+ "companyId",
+ "invoiceId",
+ "supplierId",
+ "status",
+ "dateIssued",
+ "dateDue",
+ "datePaid",
+ "currencyCode",
+ "exchangeRate",
+ "subtotal",
+ "totalTax",
+ "totalDiscount",
+ "totalAmount",
+ "balance",
+ "supplierReference",
+ "updatedAt",
+ "customFields"
+ ])
+ .where("id", "in", ids)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ if (billRows.length === 0) return new Map();
+
+ // Fetch lines for all bills
+ const billIds = billRows.map((b) => b.id);
+ const lineRows = await this.database
+ .selectFrom("purchaseInvoiceLine")
+ .leftJoin("item", "item.id", "purchaseInvoiceLine.itemId")
+ .select([
+ "purchaseInvoiceLine.id",
+ "purchaseInvoiceLine.invoiceId",
+ "purchaseInvoiceLine.description",
+ "purchaseInvoiceLine.quantity",
+ "purchaseInvoiceLine.unitPrice",
+ "purchaseInvoiceLine.itemId",
+ "purchaseInvoiceLine.accountNumber",
+ "purchaseInvoiceLine.taxPercent",
+ "purchaseInvoiceLine.taxAmount",
+ "purchaseInvoiceLine.totalAmount",
+ "purchaseInvoiceLine.purchaseOrderLineId",
+ "item.readableId as itemCode"
+ ])
+ .where("purchaseInvoiceLine.invoiceId", "in", billIds)
+ .execute();
+
+ // Fetch supplier external IDs for mapping via the mapping service
+ const supplierIds = billRows
+ .map((b) => b.supplierId)
+ .filter((id): id is string => id !== null);
+
+ const supplierExternalIds = new Map<string, string | null>();
+ if (supplierIds.length > 0) {
+ const mappingService = createMappingService(this.database, this.companyId);
+ for (const supplierId of supplierIds) {
+ const externalId = await mappingService.getExternalId(
+ "supplier",
+ supplierId,
+ this.provider.id
+ );
+ supplierExternalIds.set(supplierId, externalId);
+ }
+ }
+
+ // Group lines by invoice
+ const linesByInvoice = new Map<string, BillLineRow[]>();
+ for (const line of lineRows) {
+ const existing = linesByInvoice.get(line.invoiceId) ?? [];
+ existing.push(line as BillLineRow);
+ linesByInvoice.set(line.invoiceId, existing);
+ }
+
+ // Transform to Accounting.Bill
+ const result = new Map<string, Accounting.Bill>();
+ for (const row of billRows) {
+ const lines = linesByInvoice.get(row.id) ?? [];
+ result.set(row.id, {
+ id: row.id,
+ companyId: row.companyId,
+ invoiceId: row.invoiceId,
+ supplierId: row.supplierId,
+ supplierExternalId: row.supplierId
+ ? (supplierExternalIds.get(row.supplierId) ?? null)
+ : null,
+ status: row.status,
+ dateIssued: row.dateIssued,
+ dateDue: row.dateDue,
+ datePaid: row.datePaid,
+ currencyCode: row.currencyCode,
+ exchangeRate: row.exchangeRate,
+ subtotal: row.subtotal,
+ totalTax: row.totalTax,
+ totalDiscount: row.totalDiscount,
+ totalAmount: row.totalAmount,
+ balance: row.balance,
+ supplierReference: row.supplierReference,
+ lines: lines.map((line) => ({
+ id: line.id,
+ description: line.description,
+ quantity: line.quantity,
+ unitPrice: line.unitPrice ?? 0,
+ itemId: line.itemId,
+ itemCode: line.itemCode,
+ accountNumber: line.accountNumber,
+ taxPercent: line.taxPercent,
+ taxAmount: line.taxAmount,
+ totalAmount: line.totalAmount ?? 0,
+ purchaseOrderLineId: line.purchaseOrderLineId
+ })),
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.Invoice | null> {
+ const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "GET",
+ `/Invoices/${id}`
+ );
+
+ if (result.error) return null;
+
+ const data = result.data as { Invoices: Xero.Invoice[] } | undefined;
+ const invoice = data?.Invoices?.[0];
+
+ // Only return if it's a Bill (ACCPAY)
+ if (!invoice || invoice.Type !== "ACCPAY") {
+ return null;
+ }
+
+ return invoice;
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.Invoice>> {
+ const result = new Map<string, Xero.Invoice>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "GET",
+ `/Invoices?IDs=${ids.join(",")}`
+ );
+
+ if (response.error) {
+ throwXeroApiError("fetch bills batch", response);
+ }
+
+ const data = response.data as { Invoices: Xero.Invoice[] } | undefined;
+ for (const invoice of data?.Invoices ?? []) {
+ // Only include Bills (ACCPAY)
+ if (invoice.Type === "ACCPAY") {
+ result.set(invoice.InvoiceID, invoice);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.Bill
+ ): Promise<Omit<Xero.Invoice, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ // Get supplier's Xero ContactID - ensure supplier is synced first
+ let contactId = local.supplierExternalId;
+ if (!contactId && local.supplierId) {
+ contactId = await this.ensureDependencySynced("vendor", local.supplierId);
+ }
+
+ if (!contactId) {
+ throw new Error(
+ `Cannot sync bill ${local.id}: No supplier linked or supplier not synced to Xero`
+ );
+ }
+
+ // Map line items
+ const lineItems: Xero.InvoiceLineItem[] = await Promise.all(
+ local.lines.map(async (line) => {
+ let itemCode = line.itemCode;
+
+ // If we have an itemId but no itemCode, try to get it from the item table
+ if (!itemCode && line.itemId) {
+ const item = await this.database
+ .selectFrom("item")
+ .select("readableId")
+ .where("id", "=", line.itemId)
+ .executeTakeFirst();
+ itemCode = item?.readableId ?? null;
+ }
+
+ // Embed PO line reference in description for later extraction
+ let description = line.description ?? undefined;
+ if (line.purchaseOrderLineId) {
+ const ref = `[ref:${line.purchaseOrderLineId}]`;
+ description = description ? `${description} ${ref}` : ref;
+ }
+
+ return {
+ Description: description,
+ Quantity: line.quantity,
+ UnitAmount: line.unitPrice,
+ ItemCode: itemCode?.slice(0, 30) ?? undefined,
+ AccountCode: line.accountNumber ?? undefined,
+ TaxAmount: line.taxAmount ?? undefined,
+ LineAmount: line.totalAmount
+ };
+ })
+ );
+
+ return {
+ InvoiceID: existingRemoteId!,
+ Type: "ACCPAY",
+ InvoiceNumber: local.invoiceId,
+ Reference: local.supplierReference ?? undefined,
+ Contact: { ContactID: contactId },
+ Date: local.dateIssued ?? undefined,
+ DueDate: local.dateDue ?? undefined,
+ Status: CARBON_TO_XERO_STATUS[local.status],
+ CurrencyCode: local.currencyCode,
+ CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,
+ LineItems: lineItems,
+ SubTotal: local.subtotal,
+ TotalTax: local.totalTax,
+ Total: local.totalAmount
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon)
+ // =================================================================
+
+ protected async mapToLocal(
+ remote: Xero.Invoice
+ ): Promise<Partial<Accounting.Bill>> {
+ // Determine Carbon status based on Xero status and amounts
+ let status = XERO_TO_CARBON_STATUS[remote.Status];
+
+ // Check for partial payment
+ if (
+ remote.Status === "AUTHORISED" &&
+ remote.AmountPaid &&
+ remote.AmountPaid > 0 &&
+ remote.AmountDue &&
+ remote.AmountDue > 0
+ ) {
+ status = "Partially Paid";
+ }
+
+ // Check for overdue (would need to compare DueDate with current date)
+ if (
+ remote.Status === "AUTHORISED" &&
+ remote.DueDate &&
+ new Date(remote.DueDate) < new Date()
+ ) {
+ status = "Overdue";
+ }
+
+ // Map line items
+ const lines: Accounting.BillLine[] = (remote.LineItems ?? []).map(
+ (line, index) => {
+ // Extract [ref:<id>] from description if present
+ const refMatch = line.Description?.match(/\s*\[ref:([^\]]+)\]$/);
+ const purchaseOrderLineId = refMatch?.[1] ?? null;
+ const description =
+ line.Description?.replace(/\s*\[ref:[^\]]+\]$/, "") ?? null;
+
+ return {
+ id: line.LineItemID ?? `temp-${index}`,
+ description,
+ quantity: line.Quantity ?? 1,
+ unitPrice: line.UnitAmount ?? 0,
+ itemId: null, // Will be resolved during upsertLocal if ItemCode matches
+ itemCode: line.ItemCode ?? null,
+ accountNumber: line.AccountCode ?? null,
+ taxPercent: null,
+ taxAmount: line.TaxAmount ?? null,
+ totalAmount: line.LineAmount ?? 0,
+ purchaseOrderLineId
+ };
+ }
+ );
+
+ return {
+ invoiceId: remote.InvoiceNumber ?? remote.InvoiceID,
+ supplierExternalId: remote.Contact.ContactID,
+ status,
+ dateIssued: remote.Date ?? null,
+ dateDue: remote.DueDate ?? null,
+ datePaid: remote.Status === "PAID" ? new Date().toISOString() : null,
+ currencyCode: remote.CurrencyCode ?? "USD",
+ exchangeRate: remote.CurrencyRate ?? 1,
+ subtotal: remote.SubTotal ?? 0,
+ totalTax: remote.TotalTax ?? 0,
+ totalDiscount: 0,
+ totalAmount: remote.Total ?? 0,
+ balance: remote.AmountDue ?? 0,
+ supplierReference: remote.Reference ?? null,
+ lines,
+ updatedAt: remote.UpdatedDateUTC
+ ? parseDotnetDate(remote.UpdatedDateUTC).toISOString()
+ : new Date().toISOString()
+ };
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL
+ // =================================================================
+
+ protected async upsertLocal(
+ tx: KyselyTx,
+ data: Partial<Accounting.Bill>,
+ remoteId: string
+ ): Promise<string> {
+ const existingLocalId = await this.getLocalId(remoteId);
+
+ // Resolve supplier from Xero ContactID using mapping service
+ let supplierId: string | null = null;
+ if (data.supplierExternalId) {
+ const txMappingService = createMappingService(tx, this.companyId);
+ supplierId = await txMappingService.getEntityId(
+ this.provider.id,
+ data.supplierExternalId,
+ "supplier"
+ );
+ }
+
+ if (existingLocalId) {
+ // Update existing purchase invoice (mapping is handled by linkEntities in base class)
+ await tx
+ .updateTable("purchaseInvoice")
+ .set({
+ supplierId,
+ status: data.status,
+ dateIssued: data.dateIssued,
+ dateDue: data.dateDue,
+ datePaid: data.datePaid,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
+ subtotal: data.subtotal,
+ totalTax: data.totalTax,
+ totalDiscount: data.totalDiscount,
+ totalAmount: data.totalAmount,
+ balance: data.balance,
+ supplierReference: data.supplierReference,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", existingLocalId)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ // Update lines - delete existing and recreate
+ await this.upsertLines(tx, existingLocalId, data.lines ?? []);
+
+ return existingLocalId;
+ }
+
+ // For new bills from Xero, we need to create them
+ // This requires more context (supplierInteractionId, createdBy, etc.)
+ throw new Error(
+ `Cannot create new purchase invoice from Xero. Invoice with ID ${remoteId} must be created in Carbon first and then synced.`
+ );
+ }
+
+ private async upsertLines(
+ tx: KyselyTx,
+ invoiceId: string,
+ lines: Accounting.BillLine[]
+ ): Promise<void> {
+ // Delete existing lines
+ await tx
+ .deleteFrom("purchaseInvoiceLine")
+ .where("invoiceId", "=", invoiceId)
+ .execute();
+
+ if (lines.length === 0) return;
+
+ // Resolve item IDs from item codes
+ const itemCodes = lines
+ .map((l) => l.itemCode)
+ .filter((code): code is string => code !== null);
+
+ const itemMap = new Map<string, string>();
+ if (itemCodes.length > 0) {
+ const items = await tx
+ .selectFrom("item")
+ .select(["id", "readableId"])
+ .where("readableId", "in", itemCodes)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ for (const item of items) {
+ itemMap.set(item.readableId, item.id);
+ }
+ }
+
+ // Get the invoice to get companyId and createdBy
+ const invoice = await tx
+ .selectFrom("purchaseInvoice")
+ .select(["companyId", "createdBy", "exchangeRate"])
+ .where("id", "=", invoiceId)
+ .executeTakeFirstOrThrow();
+
+ // Insert new lines
+ for (const line of lines) {
+ const itemId = line.itemCode
+ ? (itemMap.get(line.itemCode) ?? null)
+ : null;
+
+ await tx
+ .insertInto("purchaseInvoiceLine")
+ .values({
+ invoiceId,
+ companyId: invoice.companyId,
+ createdBy: invoice.createdBy,
+ description: line.description,
+ quantity: line.quantity,
+ unitPrice: line.unitPrice,
+ supplierUnitPrice: line.unitPrice,
+ itemId,
+ accountNumber: line.accountNumber,
+ taxPercent: line.taxPercent,
+ taxAmount: line.taxAmount,
+ supplierTaxAmount: line.taxAmount ?? 0,
+ totalAmount: line.totalAmount,
+ supplierExtendedPrice: line.totalAmount,
+ exchangeRate: invoice.exchangeRate,
+ invoiceLineType: itemId ? "Part" : "G/L Account",
+ supplierShippingCost: 0
+ })
+ .execute();
+ }
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch)
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.Invoice, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ const existingRemoteId = await this.getRemoteId(localId);
+ const invoices = existingRemoteId
+ ? [{ ...data, InvoiceID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "POST",
+ "/Invoices",
+ { body: JSON.stringify({ Invoices: invoices }) }
+ );
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId ? "update bill" : "create bill",
+ result
+ );
+ }
+
+ if (!result.data?.Invoices?.[0]?.InvoiceID) {
+ throw new Error(
+ "Xero API returned success but no InvoiceID was returned for bill"
+ );
+ }
+
+ return result.data.Invoices[0].InvoiceID;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.Invoice, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const invoices: Xero.Invoice[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ invoices.push(
+ existingRemoteId
+ ? ({ ...payload, InvoiceID: existingRemoteId } as Xero.Invoice)
+ : (payload as Xero.Invoice)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "POST",
+ "/Invoices",
+ { body: JSON.stringify({ Invoices: invoices }) }
+ );
+
+ if (response.error) {
+ throwXeroApiError("batch upsert bills", response);
+ }
+
+ if (!response.data?.Invoices) {
+ throw new Error(
+ "Xero API returned success but no Invoices array was returned for bills"
+ );
+ }
+
+ for (let i = 0; i < response.data.Invoices.length; i++) {
+ const returnedInvoice = response.data.Invoices[i];
+ const localId = localIdOrder[i];
+ if (returnedInvoice?.InvoiceID && localId) {
+ result.set(localId, returnedInvoice.InvoiceID);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/contact.ts b/packages/ee/src/accounting/providers/xero/entities/contact.ts
new file mode 100644
index 0000000000..5075da1e37
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/contact.ts
@@ -0,0 +1,675 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { createMappingService } from "../../../core/external-mapping";
+import { type Accounting, BaseEntitySyncer } from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Type for rows returned from customer/supplier queries with address joins
+type EntityRow = {
+ id: string;
+ name: string;
+ companyId: string;
+ taxId: string | null;
+ phone: string | null;
+ fax: string | null;
+ website: string | null;
+ currencyCode: string | null;
+ updatedAt: string | null;
+ locationName: string | null;
+ addressLine1: string | null;
+ addressLine2: string | null;
+ city: string | null;
+ postalCode: string | null;
+};
+
+export class ContactSyncer extends BaseEntitySyncer<
+ Accounting.Contact,
+ Xero.Contact,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING (Override to check both customer and supplier)
+ // =================================================================
+
+ async getRemoteId(localId: string): Promise<string | null> {
+ // Try customer first
+ const customerMapping = await this.mappingService.getExternalId(
+ "customer",
+ localId,
+ this.provider.id
+ );
+
+ if (customerMapping) {
+ return customerMapping;
+ }
+
+ // Try vendor (supplier)
+ const vendorMapping = await this.mappingService.getExternalId(
+ "vendor",
+ localId,
+ this.provider.id
+ );
+
+ return vendorMapping;
+ }
+
+ async getLocalId(remoteId: string): Promise<string | null> {
+ // Check customer
+ const customerMapping = await this.mappingService.getEntityId(
+ this.provider.id,
+ remoteId,
+ "customer"
+ );
+ if (customerMapping) return customerMapping;
+
+ // Check vendor (supplier)
+ const vendorMapping = await this.mappingService.getEntityId(
+ this.provider.id,
+ remoteId,
+ "vendor"
+ );
+ return vendorMapping;
+ }
+
+ protected async linkEntities(
+ tx: KyselyTx,
+ localId: string,
+ remoteId: string,
+ remoteUpdatedAt?: Date
+ ): Promise<void> {
+ // Use the syncer's configured entityType so the mapping is consistent
+ // with what the base class queries for. The syncer is configured with
+ // "customer" or "vendor" — we store that exact value.
+ // The unique index includes entityType, so a Xero contact that is both
+ // customer and supplier naturally gets two distinct mapping rows.
+ const txMappingService = createMappingService(tx, this.companyId);
+ await txMappingService.link(
+ this.entityType,
+ localId,
+ this.provider.id,
+ remoteId,
+ { remoteUpdatedAt }
+ );
+ }
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.Contact): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.Contact | null> {
+ const customer = await this.fetchCustomersByIds([id]);
+ if (customer.has(id)) return customer.get(id)!;
+
+ const supplier = await this.fetchSuppliersByIds([id]);
+ return supplier.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Contact>> {
+ if (ids.length === 0) return new Map();
+
+ const customers = await this.fetchCustomersByIds(ids);
+ const remainingIds = ids.filter((id) => !customers.has(id));
+ const suppliers = await this.fetchSuppliersByIds(remainingIds);
+
+ return new Map([...customers, ...suppliers]);
+ }
+
+ private async fetchCustomersByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Contact>> {
+ if (ids.length === 0) return new Map();
+
+ const rows = await this.database
+ .selectFrom("customer")
+ .leftJoin(
+ "customerLocation",
+ "customerLocation.customerId",
+ "customer.id"
+ )
+ .leftJoin("address", "address.id", "customerLocation.addressId")
+ .select([
+ "customer.id",
+ "customer.name",
+ "customer.companyId",
+ "customer.taxId",
+ "customer.phone",
+ "customer.fax",
+ "customer.website",
+ "customer.currencyCode",
+ "customer.updatedAt",
+ "customerLocation.name as locationName",
+ "address.addressLine1",
+ "address.addressLine2",
+ "address.city",
+ "address.postalCode"
+ ])
+ .where("customer.id", "in", ids)
+ .where("customer.companyId", "=", this.companyId)
+ .execute();
+
+ return this.groupAndTransformRows(rows, true);
+ }
+
+ private async fetchSuppliersByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Contact>> {
+ if (ids.length === 0) return new Map();
+
+ const rows = await this.database
+ .selectFrom("supplier")
+ .leftJoin(
+ "supplierLocation",
+ "supplierLocation.supplierId",
+ "supplier.id"
+ )
+ .leftJoin("address", "address.id", "supplierLocation.addressId")
+ .select([
+ "supplier.id",
+ "supplier.name",
+ "supplier.companyId",
+ "supplier.taxId",
+ "supplier.phone",
+ "supplier.fax",
+ "supplier.website",
+ "supplier.currencyCode",
+ "supplier.updatedAt",
+ "supplierLocation.name as locationName",
+ "address.addressLine1",
+ "address.addressLine2",
+ "address.city",
+ "address.postalCode"
+ ])
+ .where("supplier.id", "in", ids)
+ .where("supplier.companyId", "=", this.companyId)
+ .execute();
+
+ return this.groupAndTransformRows(rows, false);
+ }
+
+ private groupAndTransformRows(
+ rows: EntityRow[],
+ isCustomer: boolean
+ ): Map<string, Accounting.Contact> {
+ const result = new Map<string, Accounting.Contact>();
+
+ // Group rows by ID
+ const groups = new Map<string, EntityRow[]>();
+ for (const row of rows) {
+ const existing = groups.get(row.id) ?? [];
+ existing.push(row);
+ groups.set(row.id, existing);
+ }
+
+ for (const [id, groupRows] of groups) {
+ const addresses = this.transformAddressRows(groupRows);
+ result.set(id, this.buildContact(groupRows[0]!, addresses, isCustomer));
+ }
+
+ return result;
+ }
+
+ private transformAddressRows(
+ rows: EntityRow[]
+ ): Accounting.Contact["addresses"] {
+ return rows
+ .filter((r) => r.addressLine1 || r.city)
+ .map((r) => ({
+ label: r.locationName ?? null,
+ type: null,
+ line1: r.addressLine1 ?? null,
+ line2: r.addressLine2 ?? null,
+ city: r.city ?? null,
+ country: null,
+ region: null,
+ postalCode: r.postalCode ?? null
+ }));
+ }
+
+ private buildContact(
+ row: EntityRow,
+ addresses: Accounting.Contact["addresses"],
+ isCustomer: boolean
+ ): Accounting.Contact {
+ return {
+ id: row.id,
+ name: row.name,
+ firstName: "",
+ lastName: "",
+ companyId: row.companyId,
+ email: undefined,
+ website: row.website ?? null,
+ taxId: row.taxId ?? null,
+ currencyCode: row.currencyCode ?? "USD",
+ balance: null,
+ creditLimit: null,
+ paymentTerms: null,
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ workPhone: row.phone ?? null,
+ mobilePhone: null,
+ fax: row.fax ?? null,
+ homePhone: null,
+ isVendor: !isCustomer,
+ isCustomer,
+ addresses,
+ raw: row
+ };
+ }
+
+ // =================================================================
+ // 3. REMOTE FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.Contact | null> {
+ const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(
+ "GET",
+ `/Contacts/${id}`
+ );
+
+ return result.error ? null : (result.data?.Contacts?.[0] ?? null);
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.Contact>> {
+ const result = new Map<string, Xero.Contact>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{ Contacts: Xero.Contact[] }>(
+ "GET",
+ `/Contacts?IDs=${ids.join(",")}`
+ );
+
+ if (response.error) {
+ throwXeroApiError("fetch contacts batch", response);
+ }
+
+ if (response.data?.Contacts) {
+ for (const contact of response.data.Contacts) {
+ result.set(contact.ContactID, contact);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.Contact
+ ): Promise<Omit<Xero.Contact, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ const phones: Xero.Contact["Phones"] = [];
+ if (local.workPhone)
+ phones.push({ PhoneType: "DEFAULT", PhoneNumber: local.workPhone });
+ if (local.mobilePhone)
+ phones.push({ PhoneType: "MOBILE", PhoneNumber: local.mobilePhone });
+ if (local.fax) phones.push({ PhoneType: "FAX", PhoneNumber: local.fax });
+ if (local.homePhone)
+ phones.push({ PhoneType: "DDI", PhoneNumber: local.homePhone });
+
+ const addresses: Xero.Contact["Addresses"] = local.addresses.map((a) => ({
+ AddressType: "STREET" as const,
+ AddressLine1: a.line1 ?? undefined,
+ AddressLine2: a.line2 ?? undefined,
+ City: a.city ?? undefined,
+ Region: a.region ?? undefined,
+ PostalCode: a.postalCode ?? undefined,
+ Country: a.country ?? undefined,
+ AttentionTo: a.label ?? undefined
+ }));
+
+ return {
+ ContactID: existingRemoteId!,
+ ContactStatus: "ACTIVE",
+ Name: local.name,
+ FirstName: local.firstName || undefined,
+ LastName: local.lastName || undefined,
+ EmailAddress: local.email ?? undefined,
+ Website: local.website ?? undefined,
+ TaxNumber: local.taxId ?? undefined,
+ DefaultCurrency: local.currencyCode,
+ IsCustomer: local.isCustomer,
+ IsSupplier: local.isVendor,
+ Phones: phones,
+ Addresses: addresses,
+ ContactGroups: [],
+ ContactPersons: [],
+ HasAttachments: false,
+ HasValidationErrors: false
+ };
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Xero -> Carbon)
+ // =================================================================
+
+ protected async mapToLocal(
+ remote: Xero.Contact
+ ): Promise<Partial<Accounting.Contact>> {
+ const phones = remote.Phones ?? [];
+ const findPhone = (type: string) =>
+ phones.find((p) => p.PhoneType === type)?.PhoneNumber ?? null;
+
+ const addresses = (remote.Addresses ?? []).map((a) => ({
+ label: a.AttentionTo ?? null,
+ type: a.AddressType ?? null,
+ line1: a.AddressLine1 ?? null,
+ line2: a.AddressLine2 ?? null,
+ city: a.City ?? null,
+ region: a.Region ?? null,
+ country: a.Country ?? null,
+ postalCode: a.PostalCode ?? null
+ }));
+
+ return {
+ name: remote.Name,
+ firstName: remote.FirstName ?? "",
+ lastName: remote.LastName ?? "",
+ email: remote.EmailAddress ?? undefined,
+ website: remote.Website ?? null,
+ taxId: remote.TaxNumber ?? null,
+ currencyCode: remote.DefaultCurrency ?? "USD",
+ isCustomer: remote.IsCustomer,
+ isVendor: remote.IsSupplier,
+ workPhone: findPhone("DEFAULT"),
+ mobilePhone: findPhone("MOBILE"),
+ fax: findPhone("FAX"),
+ homePhone: findPhone("DDI"),
+ addresses
+ };
+ }
+
+ // =================================================================
+ // 6. UPSERT LOCAL
+ // =================================================================
+
+ protected async upsertLocal(
+ tx: KyselyTx,
+ data: Partial<Accounting.Contact>,
+ remoteId: string
+ ): Promise<string> {
+ let existingLocalId = await this.getLocalId(remoteId);
+ const isVendor = data.isVendor && !data.isCustomer ? true : false;
+
+ // Smart match: if no mapping exists, try to find by name (Xero enforces
+ // unique contact names, and Carbon enforces unique customer/supplier names
+ // per company). This prevents duplicates during backfill.
+ if (!existingLocalId && data.name) {
+ existingLocalId = await this.findLocalEntityByName(
+ tx,
+ data.name,
+ isVendor
+ );
+ }
+
+ // 1. Upsert customer/supplier
+ const entityId = await this.upsertEntity(
+ tx,
+ data,
+ existingLocalId,
+ isVendor
+ );
+
+ // 2. Upsert contact and link to customer/supplier
+ await this.upsertContactAndLink(tx, data, remoteId, entityId, isVendor);
+
+ return entityId;
+ }
+
+ /**
+ * Try to find an existing customer/supplier by name within the same company.
+ * Used for smart matching during backfill when no ID mapping exists yet.
+ */
+ private async findLocalEntityByName(
+ tx: KyselyTx,
+ name: string,
+ isVendor: boolean
+ ): Promise<string | null> {
+ const table = isVendor ? "supplier" : "customer";
+ const match = await tx
+ .selectFrom(table)
+ .select("id")
+ .where("name", "=", name)
+ .where("companyId", "=", this.companyId)
+ .executeTakeFirst();
+
+ return match?.id ?? null;
+ }
+
+ private async upsertEntity(
+ tx: KyselyTx,
+ data: Partial<Accounting.Contact>,
+ existingId: string | null,
+ isVendor: boolean
+ ): Promise<string> {
+ const table = isVendor ? "supplier" : "customer";
+
+ if (existingId) {
+ await tx
+ .updateTable(table)
+ .set({
+ name: data.name,
+ taxId: data.taxId,
+ website: data.website,
+ phone: data.workPhone,
+ fax: data.fax,
+ currencyCode: data.currencyCode,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", existingId)
+ .execute();
+ return existingId;
+ }
+
+ const result = await tx
+ .insertInto(table)
+ .values({
+ companyId: this.companyId,
+ name: data.name!,
+ taxId: data.taxId,
+ website: data.website,
+ phone: data.workPhone,
+ fax: data.fax,
+ currencyCode: data.currencyCode,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString()
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+
+ return result.id;
+ }
+
+ private async upsertContactAndLink(
+ tx: KyselyTx,
+ data: Partial<Accounting.Contact>,
+ _remoteId: string,
+ entityId: string,
+ isVendor: boolean
+ ): Promise<void> {
+ const junctionTable = isVendor ? "supplierContact" : "customerContact";
+ const fkColumn = isVendor ? "supplierId" : "customerId";
+
+ // Find existing contact person via the junction table (not the mapping
+ // table). The contact person is a child of the customer/supplier and
+ // doesn't need its own external integration mapping.
+ const existingJunction = await tx
+ .selectFrom(junctionTable)
+ .select("contactId")
+ .where(fkColumn as any, "=", entityId)
+ .executeTakeFirst();
+
+ // Xero contacts often only have a company Name with no FirstName/LastName.
+ // Fall back to the entity name so the contact person isn't blank.
+ const firstName = data.firstName || data.name || "";
+ const lastName = data.lastName ?? "";
+
+ let contactId: string;
+
+ if (existingJunction) {
+ // Update existing contact person
+ await tx
+ .updateTable("contact")
+ .set({
+ email: data.email ?? null,
+ firstName,
+ lastName,
+ workPhone: data.workPhone ?? null,
+ mobilePhone: data.mobilePhone ?? null,
+ homePhone: data.homePhone ?? null,
+ fax: data.fax ?? null
+ })
+ .where("id", "=", existingJunction.contactId)
+ .execute();
+ contactId = existingJunction.contactId;
+ } else {
+ // Insert new contact person
+ const result = await tx
+ .insertInto("contact")
+ .values({
+ companyId: this.companyId,
+ email: data.email ?? null,
+ firstName,
+ lastName,
+ workPhone: data.workPhone ?? null,
+ mobilePhone: data.mobilePhone ?? null,
+ homePhone: data.homePhone ?? null,
+ fax: data.fax ?? null,
+ isCustomer: !isVendor
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ contactId = result.id;
+
+ // Create the junction link
+ await tx
+ .insertInto(junctionTable)
+ .values({ [fkColumn]: entityId, contactId } as any)
+ .execute();
+ }
+ }
+
+ // =================================================================
+ // 7. UPSERT REMOTE (Single + Batch)
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Xero.Contact,
+ localId: string
+ ): Promise<string> {
+ let existingRemoteId = await this.getRemoteId(localId);
+
+ // Smart match: if no mapping exists, search Xero by name before creating.
+ // Xero enforces unique contact names across all active contacts.
+ if (!existingRemoteId && data.Name) {
+ existingRemoteId = await this.findRemoteContactByName(data.Name);
+ }
+
+ const contacts = existingRemoteId
+ ? [{ ...data, ContactID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(
+ "POST",
+ "/Contacts",
+ { body: JSON.stringify({ Contacts: contacts }) }
+ );
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId ? "update contact" : "create contact",
+ result
+ );
+ }
+
+ if (!result.data?.Contacts?.[0]?.ContactID) {
+ throw new Error(
+ "Xero API returned success but no ContactID was returned"
+ );
+ }
+
+ return result.data.Contacts[0].ContactID;
+ }
+
+ /**
+ * Search Xero for an existing contact by exact name match.
+ * Used for smart matching during backfill when no ID mapping exists yet.
+ */
+ private async findRemoteContactByName(name: string): Promise<string | null> {
+ // Xero where filter requires double-quoting string values and escaping quotes
+ const escapedName = name.replace(/"/g, '\\"');
+ const result = await this.provider.request<{ Contacts: Xero.Contact[] }>(
+ "GET",
+ `/Contacts?where=Name=="${escapedName}"`
+ );
+
+ if (!result.error && result.data?.Contacts?.[0]?.ContactID) {
+ return result.data.Contacts[0].ContactID;
+ }
+
+ return null;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.Contact, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const contacts: Xero.Contact[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ contacts.push(
+ existingRemoteId
+ ? ({ ...payload, ContactID: existingRemoteId } as Xero.Contact)
+ : (payload as Xero.Contact)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{ Contacts: Xero.Contact[] }>(
+ "POST",
+ "/Contacts",
+ { body: JSON.stringify({ Contacts: contacts }) }
+ );
+
+ if (response.error) {
+ throwXeroApiError("batch upsert contacts", response);
+ }
+
+ if (!response.data?.Contacts) {
+ throw new Error(
+ "Xero API returned success but no Contacts array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.Contacts.length; i++) {
+ const returnedContact = response.data.Contacts[i];
+ const localId = localIdOrder[i];
+ if (returnedContact?.ContactID && localId) {
+ result.set(localId, returnedContact.ContactID);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
new file mode 100644
index 0000000000..98f848fe75
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts
@@ -0,0 +1,332 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { type Accounting, BaseEntitySyncer } from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Note: This is a push-only syncer (Carbon -> Xero).
+// Inventory adjustments are pushed as Manual Journals to Xero since
+// Xero has no dedicated inventory adjustment endpoint.
+
+// Type for rows returned from itemLedger queries with cost/account joins
+type InventoryAdjustmentRow = {
+ id: string;
+ entryNumber: number;
+ postingDate: string;
+ entryType: "Positive Adjmt." | "Negative Adjmt.";
+ itemId: string;
+ locationId: string | null;
+ quantity: number;
+ companyId: string;
+ createdAt: string;
+ unitCost: number | null;
+ inventoryAccount: string | null;
+ adjustmentVarianceAccount: string | null;
+ itemReadableId: string | null;
+};
+
+export class InventoryAdjustmentSyncer extends BaseEntitySyncer<
+ Accounting.InventoryAdjustment,
+ Xero.ManualJournal,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // =================================================================
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.ManualJournal): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.InventoryAdjustment | null> {
+ const items = await this.fetchAdjustmentsByIds([id]);
+ return items.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.InventoryAdjustment>> {
+ return this.fetchAdjustmentsByIds(ids);
+ }
+
+ private async fetchAdjustmentsByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.InventoryAdjustment>> {
+ if (ids.length === 0) return new Map();
+
+ const rows = await this.database
+ .selectFrom("itemLedger")
+ .innerJoin("item", "item.id", "itemLedger.itemId")
+ .leftJoin("itemCost", "itemCost.itemId", "itemLedger.itemId")
+ .leftJoin("postingGroupInventory", (join) =>
+ join
+ .onRef(
+ "postingGroupInventory.itemPostingGroupId",
+ "=",
+ "itemCost.itemPostingGroupId" as any
+ )
+ .onRef(
+ "postingGroupInventory.locationId",
+ "=",
+ "itemLedger.locationId" as any
+ )
+ )
+ .select([
+ "itemLedger.id",
+ "itemLedger.entryNumber",
+ "itemLedger.postingDate",
+ "itemLedger.entryType",
+ "itemLedger.itemId",
+ "itemLedger.locationId",
+ "itemLedger.quantity",
+ "itemLedger.companyId",
+ "itemLedger.createdAt",
+ "itemCost.unitCost",
+ "postingGroupInventory.inventoryAccount",
+ "postingGroupInventory.inventoryAdjustmentVarianceAccount as adjustmentVarianceAccount",
+ "item.readableId as itemReadableId"
+ ])
+ .where("itemLedger.id", "in", ids)
+ .where("itemLedger.companyId", "=", this.companyId)
+ .where("itemLedger.entryType", "in", [
+ "Positive Adjmt.",
+ "Negative Adjmt."
+ ])
+ .execute();
+
+ return this.transformRows(rows as unknown as InventoryAdjustmentRow[]);
+ }
+
+ private transformRows(
+ rows: InventoryAdjustmentRow[]
+ ): Map<string, Accounting.InventoryAdjustment> {
+ const result = new Map<string, Accounting.InventoryAdjustment>();
+
+ for (const row of rows) {
+ // Skip rows without required GL accounts
+ if (!row.inventoryAccount || !row.adjustmentVarianceAccount) {
+ continue;
+ }
+
+ result.set(row.id, {
+ id: row.id,
+ entryNumber: row.entryNumber,
+ postingDate: row.postingDate,
+ entryType: row.entryType,
+ itemId: row.itemId,
+ locationId: row.locationId,
+ quantity: row.quantity,
+ companyId: row.companyId,
+ unitCost: row.unitCost ?? 0,
+ inventoryAccount: row.inventoryAccount,
+ adjustmentVarianceAccount: row.adjustmentVarianceAccount,
+ updatedAt: row.createdAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH - Stubs (push-only syncer)
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.ManualJournal | null> {
+ const result = await this.provider.request<{
+ ManualJournals: Xero.ManualJournal[];
+ }>("GET", `/ManualJournals/${id}`);
+ return result.error ? null : (result.data?.ManualJournals?.[0] ?? null);
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.ManualJournal>> {
+ const result = new Map<string, Xero.ManualJournal>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{
+ ManualJournals: Xero.ManualJournal[];
+ }>("GET", `/ManualJournals?IDs=${ids.join(",")}`);
+
+ if (response.error) {
+ throwXeroApiError("fetch manual journals batch", response);
+ }
+
+ if (response.data?.ManualJournals) {
+ for (const journal of response.data.ManualJournals) {
+ result.set(journal.ManualJournalID, journal);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.InventoryAdjustment
+ ): Promise<Omit<Xero.ManualJournal, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+ const amount = Math.abs(local.quantity) * local.unitCost;
+ const isPositive = local.entryType === "Positive Adjmt.";
+
+ // Ensure item dependency is synced
+ await this.ensureDependencySynced("item", local.itemId);
+
+ // For a positive adjustment:
+ // Debit Inventory Account (increase inventory asset)
+ // Credit Adjustment Variance Account (offset)
+ // For a negative adjustment:
+ // Credit Inventory Account (decrease inventory asset)
+ // Debit Adjustment Variance Account (offset)
+ const journalLines: Xero.ManualJournalLine[] = [
+ {
+ LineAmount: isPositive ? amount : -amount,
+ AccountCode: local.inventoryAccount,
+ Description: `Inventory ${isPositive ? "increase" : "decrease"}: ${
+ local.quantity
+ } units`
+ },
+ {
+ LineAmount: isPositive ? -amount : amount,
+ AccountCode: local.adjustmentVarianceAccount,
+ Description: `Adjustment variance: ${local.quantity} units`
+ }
+ ];
+
+ return {
+ ManualJournalID: existingRemoteId!,
+ Narration: `Inventory Adjustment #${local.entryNumber}: ${local.entryType} (${local.quantity} units @ ${local.unitCost}/unit)`,
+ Date: local.postingDate,
+ Status: "POSTED",
+ LineAmountTypes: "NoTax",
+ JournalLines: journalLines
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon) - Not supported (push-only)
+ // =================================================================
+
+ protected async mapToLocal(
+ _remote: Xero.ManualJournal
+ ): Promise<Partial<Accounting.InventoryAdjustment>> {
+ throw new Error(
+ "Inventory adjustments are push-only. Cannot map from Xero to Carbon."
+ );
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL - Not supported (push-only)
+ // =================================================================
+
+ protected async upsertLocal(
+ _tx: KyselyTx,
+ _data: Partial<Accounting.InventoryAdjustment>,
+ _remoteId: string
+ ): Promise<string> {
+ throw new Error(
+ "Inventory adjustments are push-only. Cannot upsert locally from Xero."
+ );
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch)
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.ManualJournal, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ const existingRemoteId = await this.getRemoteId(localId);
+ const journals = existingRemoteId
+ ? [{ ...data, ManualJournalID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{
+ ManualJournals: Xero.ManualJournal[];
+ }>("POST", "/ManualJournals", {
+ body: JSON.stringify({ ManualJournals: journals })
+ });
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId
+ ? "update inventory adjustment journal"
+ : "create inventory adjustment journal",
+ result
+ );
+ }
+
+ if (!result.data?.ManualJournals?.[0]?.ManualJournalID) {
+ throw new Error(
+ "Xero API returned success but no ManualJournalID was returned"
+ );
+ }
+
+ return result.data.ManualJournals[0].ManualJournalID;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.ManualJournal, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const journals: Xero.ManualJournal[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ journals.push(
+ existingRemoteId
+ ? ({
+ ...payload,
+ ManualJournalID: existingRemoteId
+ } as Xero.ManualJournal)
+ : (payload as Xero.ManualJournal)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{
+ ManualJournals: Xero.ManualJournal[];
+ }>("POST", "/ManualJournals", {
+ body: JSON.stringify({ ManualJournals: journals })
+ });
+
+ if (response.error) {
+ throwXeroApiError("batch upsert inventory adjustment journals", response);
+ }
+
+ if (!response.data?.ManualJournals) {
+ throw new Error(
+ "Xero API returned success but no ManualJournals array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.ManualJournals.length; i++) {
+ const returnedJournal = response.data.ManualJournals[i];
+ const localId = localIdOrder[i];
+ if (returnedJournal?.ManualJournalID && localId) {
+ result.set(localId, returnedJournal.ManualJournalID);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
new file mode 100644
index 0000000000..3aa7df03af
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts
@@ -0,0 +1,545 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { createMappingService } from "../../../core/external-mapping";
+import {
+ type Accounting,
+ BaseEntitySyncer,
+ type ShouldSyncContext
+} from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Note: This syncer uses the default ID mapping from BaseEntitySyncer
+// which uses the externalIntegrationMapping table with entityType "invoice"
+
+// Type for rows returned from sales invoice queries with line joins
+type InvoiceRow = {
+ id: string;
+ invoiceId: string;
+ companyId: string;
+ customerId: string;
+ status:
+ | "Draft"
+ | "Pending"
+ | "Submitted"
+ | "Partially Paid"
+ | "Paid"
+ | "Overdue"
+ | "Voided"
+ | "Credit Note Issued"
+ | "Return";
+ currencyCode: string;
+ exchangeRate: number;
+ dateIssued: string | null;
+ dateDue: string | null;
+ datePaid: string | null;
+ customerReference: string | null;
+ subtotal: number;
+ totalTax: number;
+ totalDiscount: number;
+ totalAmount: number;
+ balance: number;
+ updatedAt: string | null;
+};
+
+type InvoiceLineRow = {
+ id: string;
+ invoiceId: string;
+ invoiceLineType: string;
+ itemId: string | null;
+ description: string | null;
+ quantity: number;
+ unitPrice: number;
+ taxPercent: number;
+ // For item code lookup
+ itemReadableIdWithRevision: string | null;
+};
+
+// Status mapping: Carbon -> Xero
+const CARBON_TO_XERO_STATUS: Record<
+ Accounting.SalesInvoice["status"],
+ Xero.Invoice["Status"]
+> = {
+ Draft: "DRAFT",
+ Pending: "SUBMITTED",
+ Submitted: "AUTHORISED",
+ "Partially Paid": "AUTHORISED",
+ Paid: "PAID",
+ Overdue: "AUTHORISED",
+ Voided: "VOIDED",
+ "Credit Note Issued": "AUTHORISED",
+ Return: "AUTHORISED"
+};
+
+// Status mapping: Xero -> Carbon
+const XERO_TO_CARBON_STATUS: Record<
+ Xero.Invoice["Status"],
+ Accounting.SalesInvoice["status"]
+> = {
+ DRAFT: "Draft",
+ SUBMITTED: "Pending",
+ AUTHORISED: "Submitted",
+ PAID: "Paid",
+ VOIDED: "Voided",
+ DELETED: "Voided"
+};
+
+// Syncable statuses (we only push posted invoices to Xero, not drafts)
+const SYNCABLE_STATUSES: Accounting.SalesInvoice["status"][] = [
+ "Pending",
+ "Submitted",
+ "Partially Paid",
+ "Paid",
+ "Overdue"
+];
+
+export class SalesInvoiceSyncer extends BaseEntitySyncer<
+ Accounting.SalesInvoice,
+ Xero.Invoice,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // The entityType "invoice" maps to the salesInvoice table
+ // =================================================================
+
+ protected async linkEntities(
+ tx: KyselyTx,
+ localId: string,
+ remoteId: string,
+ remoteUpdatedAt?: Date
+ ): Promise<void> {
+ // Use the mapping service to link invoice -> salesInvoice
+ const txMappingService = createMappingService(tx, this.companyId);
+ await txMappingService.link(
+ "invoice",
+ localId,
+ this.provider.id,
+ remoteId,
+ {
+ remoteUpdatedAt
+ }
+ );
+
+ // Also update updatedAt on salesInvoice
+ await tx
+ .updateTable("salesInvoice")
+ .set({
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", localId)
+ .execute();
+ }
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.Invoice): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.SalesInvoice | null> {
+ const invoices = await this.fetchInvoicesByIds([id]);
+ return invoices.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.SalesInvoice>> {
+ return this.fetchInvoicesByIds(ids);
+ }
+
+ private async fetchInvoicesByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.SalesInvoice>> {
+ if (ids.length === 0) return new Map();
+
+ // Fetch invoice headers
+ const invoiceRows = await this.database
+ .selectFrom("salesInvoice")
+ .select([
+ "salesInvoice.id",
+ "salesInvoice.invoiceId",
+ "salesInvoice.companyId",
+ "salesInvoice.customerId",
+ "salesInvoice.status",
+ "salesInvoice.currencyCode",
+ "salesInvoice.exchangeRate",
+ "salesInvoice.dateIssued",
+ "salesInvoice.dateDue",
+ "salesInvoice.datePaid",
+ "salesInvoice.customerReference",
+ "salesInvoice.subtotal",
+ "salesInvoice.totalTax",
+ "salesInvoice.totalDiscount",
+ "salesInvoice.totalAmount",
+ "salesInvoice.balance",
+ "salesInvoice.updatedAt"
+ ])
+ .where("salesInvoice.id", "in", ids)
+ .where("salesInvoice.companyId", "=", this.companyId)
+ .execute();
+
+ if (invoiceRows.length === 0) return new Map();
+
+ // Fetch invoice lines with item codes
+ const lineRows = await this.database
+ .selectFrom("salesInvoiceLine")
+ .leftJoin("item", "item.id", "salesInvoiceLine.itemId")
+ .select([
+ "salesInvoiceLine.id",
+ "salesInvoiceLine.invoiceId",
+ "salesInvoiceLine.invoiceLineType",
+ "salesInvoiceLine.itemId",
+ "salesInvoiceLine.description",
+ "salesInvoiceLine.quantity",
+ "salesInvoiceLine.unitPrice",
+ "salesInvoiceLine.taxPercent",
+ "item.readableIdWithRevision as itemReadableIdWithRevision"
+ ])
+ .where(
+ "salesInvoiceLine.invoiceId",
+ "in",
+ invoiceRows.map((r) => r.id)
+ )
+ .execute();
+
+ // Group lines by invoice ID
+ const linesByInvoiceId = new Map<string, InvoiceLineRow[]>();
+ for (const line of lineRows as InvoiceLineRow[]) {
+ const existing = linesByInvoiceId.get(line.invoiceId) ?? [];
+ existing.push(line);
+ linesByInvoiceId.set(line.invoiceId, existing);
+ }
+
+ // Transform to Accounting.SalesInvoice
+ const result = new Map<string, Accounting.SalesInvoice>();
+ for (const row of invoiceRows as InvoiceRow[]) {
+ const lines = linesByInvoiceId.get(row.id) ?? [];
+
+ result.set(row.id, {
+ id: row.id,
+ invoiceId: row.invoiceId,
+ companyId: row.companyId,
+ customerId: row.customerId,
+ customerExternalId: null, // Will be resolved during mapToRemote
+ status: row.status,
+ currencyCode: row.currencyCode,
+ exchangeRate: row.exchangeRate,
+ dateIssued: row.dateIssued,
+ dateDue: row.dateDue,
+ datePaid: row.datePaid,
+ customerReference: row.customerReference,
+ subtotal: row.subtotal,
+ totalTax: row.totalTax,
+ totalDiscount: row.totalDiscount,
+ totalAmount: row.totalAmount,
+ balance: row.balance,
+ lines: lines.map((line) => ({
+ id: line.id,
+ invoiceLineType: line.invoiceLineType,
+ itemId: line.itemId,
+ itemCode: line.itemReadableIdWithRevision,
+ description: line.description,
+ quantity: line.quantity,
+ unitPrice: line.unitPrice,
+ taxPercent: line.taxPercent,
+ lineAmount: line.quantity * line.unitPrice
+ })),
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH (Single + Batch) - API calls within syncer
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.Invoice | null> {
+ const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "GET",
+ `/Invoices/${id}`
+ );
+ return result.error ? null : (result.data?.Invoices?.[0] ?? null);
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.Invoice>> {
+ const result = new Map<string, Xero.Invoice>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "GET",
+ `/Invoices?IDs=${ids.join(",")}`
+ );
+
+ if (response.error) {
+ throwXeroApiError("fetch invoices batch", response);
+ }
+
+ if (response.data?.Invoices) {
+ for (const invoice of response.data.Invoices) {
+ result.set(invoice.InvoiceID, invoice);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.SalesInvoice
+ ): Promise<Omit<Xero.Invoice, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ // Resolve customer dependency - ensure customer is synced to Xero
+ const customerRemoteId = await this.ensureDependencySynced(
+ "customer",
+ local.customerId
+ );
+
+ // Build line items, resolving item dependencies
+ const lineItems: Xero.InvoiceLineItem[] = [];
+ for (const line of local.lines) {
+ const lineItem: Xero.InvoiceLineItem = {
+ Description: line.description ?? undefined,
+ Quantity: line.quantity,
+ UnitAmount: line.unitPrice,
+ TaxAmount: (line.quantity * line.unitPrice * line.taxPercent) / 100,
+ LineAmount: line.quantity * line.unitPrice
+ };
+
+ // If line has an item, ensure it's synced and get the ItemCode
+ if (line.itemId) {
+ // Ensure item is synced
+ await this.ensureDependencySynced("item", line.itemId);
+ // Use the item code from Carbon (readableIdWithRevision)
+ if (line.itemCode) {
+ lineItem.ItemCode = line.itemCode.slice(0, 30);
+ }
+ }
+
+ lineItems.push(lineItem);
+ }
+
+ return {
+ InvoiceID: existingRemoteId!,
+ Type: "ACCREC", // Accounts Receivable = Sales Invoice
+ InvoiceNumber: local.invoiceId,
+ Reference: local.customerReference ?? undefined,
+ Contact: {
+ ContactID: customerRemoteId
+ },
+ Date: local.dateIssued ?? undefined,
+ DueDate: local.dateDue ?? undefined,
+ Status: CARBON_TO_XERO_STATUS[local.status],
+ LineAmountTypes: "Exclusive", // Tax is calculated separately
+ LineItems: lineItems,
+ SubTotal: local.subtotal,
+ TotalTax: local.totalTax,
+ Total: local.totalAmount,
+ AmountDue: local.balance,
+ AmountPaid: local.totalAmount - local.balance,
+ CurrencyCode: local.currencyCode,
+ CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon) - Update only
+ // =================================================================
+
+ protected async mapToLocal(
+ remote: Xero.Invoice
+ ): Promise<Partial<Accounting.SalesInvoice>> {
+ // Map Xero line items to Carbon line format
+ const lines: Accounting.SalesInvoiceLine[] = (remote.LineItems ?? []).map(
+ (line, index) => ({
+ id: line.LineItemID ?? `line-${index}`,
+ invoiceLineType: "Part", // Default, will be matched with existing lines
+ itemId: null, // Will be resolved by looking up ItemCode
+ itemCode: line.ItemCode ?? null,
+ description: line.Description ?? null,
+ quantity: line.Quantity ?? 0,
+ unitPrice: line.UnitAmount ?? 0,
+ taxPercent: line.TaxAmount
+ ? (line.TaxAmount / (line.LineAmount ?? 1)) * 100 || 0
+ : 0,
+ lineAmount: line.LineAmount ?? 0
+ })
+ );
+
+ return {
+ status: XERO_TO_CARBON_STATUS[remote.Status],
+ dateIssued: remote.Date ?? null,
+ dateDue: remote.DueDate ?? null,
+ customerReference: remote.Reference ?? null,
+ subtotal: remote.SubTotal ?? 0,
+ totalTax: remote.TotalTax ?? 0,
+ totalAmount: remote.Total ?? 0,
+ balance: remote.AmountDue ?? 0,
+ currencyCode: remote.CurrencyCode ?? "USD",
+ exchangeRate: remote.CurrencyRate ?? 1,
+ lines
+ };
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL (Update existing only - Carbon is source of truth)
+ // =================================================================
+
+ protected async upsertLocal(
+ tx: KyselyTx,
+ data: Partial<Accounting.SalesInvoice>,
+ remoteId: string
+ ): Promise<string> {
+ const existingLocalId = await this.getLocalId(remoteId);
+
+ if (!existingLocalId) {
+ throw new Error(
+ `Cannot create new invoices from Xero. Invoice with remote ID ${remoteId} not found locally.`
+ );
+ }
+
+ // Update invoice header (mapping is handled by linkEntities in base class)
+ await tx
+ .updateTable("salesInvoice")
+ .set({
+ status: data.status,
+ dateIssued: data.dateIssued,
+ dateDue: data.dateDue,
+ customerReference: data.customerReference,
+ subtotal: data.subtotal,
+ totalTax: data.totalTax,
+ totalAmount: data.totalAmount,
+ balance: data.balance,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", existingLocalId)
+ .execute();
+
+ // Note: We don't update line items from Xero to preserve Carbon's line structure
+ // Lines are only updated from Carbon -> Xero direction
+
+ return existingLocalId;
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch) - API calls within syncer
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.Invoice, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ const existingRemoteId = await this.getRemoteId(localId);
+ const invoices = existingRemoteId
+ ? [{ ...data, InvoiceID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "POST",
+ "/Invoices",
+ { body: JSON.stringify({ Invoices: invoices }) }
+ );
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId ? "update invoice" : "create invoice",
+ result
+ );
+ }
+
+ if (!result.data?.Invoices?.[0]?.InvoiceID) {
+ throw new Error(
+ "Xero API returned success but no InvoiceID was returned"
+ );
+ }
+
+ return result.data.Invoices[0].InvoiceID;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.Invoice, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const invoices: Xero.Invoice[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ invoices.push(
+ existingRemoteId
+ ? ({ ...payload, InvoiceID: existingRemoteId } as Xero.Invoice)
+ : (payload as Xero.Invoice)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{ Invoices: Xero.Invoice[] }>(
+ "POST",
+ "/Invoices",
+ { body: JSON.stringify({ Invoices: invoices }) }
+ );
+
+ if (response.error) {
+ throwXeroApiError("batch upsert invoices", response);
+ }
+
+ if (!response.data?.Invoices) {
+ throw new Error(
+ "Xero API returned success but no Invoices array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.Invoices.length; i++) {
+ const returnedInvoice = response.data.Invoices[i];
+ const localId = localIdOrder[i];
+ if (returnedInvoice?.InvoiceID && localId) {
+ result.set(localId, returnedInvoice.InvoiceID);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 9. SHOULD SYNC: Business logic for sync eligibility
+ // =================================================================
+
+ /**
+ * Determine if an invoice should be synced based on its status.
+ * Only invoices with syncable statuses (not Draft or Cancelled) are synced.
+ */
+ protected shouldSync(
+ context: ShouldSyncContext<Accounting.SalesInvoice, Xero.Invoice>
+ ): boolean | string {
+ // For push operations, check the local entity status
+ if (context.direction === "push" && context.localEntity) {
+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {
+ return `Invoice must be posted before syncing (current status: ${context.localEntity.status})`;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/item.ts b/packages/ee/src/accounting/providers/xero/entities/item.ts
new file mode 100644
index 0000000000..264c65a7bf
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/item.ts
@@ -0,0 +1,387 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { type Accounting, BaseEntitySyncer } from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Type for rows returned from item queries with cost/price joins
+type ItemRow = {
+ id: string;
+ readableId: string;
+ readableIdWithRevision: string | null;
+ name: string;
+ description: string | null;
+ companyId: string | null;
+ type: "Part" | "Material" | "Tool" | "Consumable" | "Fixture";
+ unitOfMeasureCode: string | null;
+ replenishmentSystem: "Buy" | "Make" | "Buy and Make";
+ itemTrackingType: string;
+ updatedAt: string | null;
+ unitCost: number | null;
+ unitSalePrice: number | null;
+};
+
+export class ItemSyncer extends BaseEntitySyncer<
+ Accounting.Item,
+ Xero.Item,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // =================================================================
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.Item): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.Item | null> {
+ const items = await this.fetchItemsByIds([id]);
+ return items.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Item>> {
+ return this.fetchItemsByIds(ids);
+ }
+
+ private async fetchItemsByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.Item>> {
+ if (ids.length === 0) return new Map();
+
+ const rows = await this.database
+ .selectFrom("item")
+ .leftJoin("itemCost", "itemCost.itemId", "item.id")
+ .leftJoin("itemUnitSalePrice", "itemUnitSalePrice.itemId", "item.id")
+ .select([
+ "item.id",
+ "item.readableId",
+ "item.readableIdWithRevision",
+ "item.name",
+ "item.description",
+ "item.companyId",
+ "item.type",
+ "item.unitOfMeasureCode",
+ "item.replenishmentSystem",
+ "item.itemTrackingType",
+ "item.updatedAt",
+ "itemCost.unitCost",
+ "itemUnitSalePrice.unitSalePrice"
+ ])
+ .where("item.id", "in", ids)
+ .where("item.companyId", "=", this.companyId)
+ .execute();
+
+ return this.transformRows(rows as ItemRow[]);
+ }
+
+ private transformRows(rows: ItemRow[]): Map<string, Accounting.Item> {
+ const result = new Map<string, Accounting.Item>();
+
+ for (const row of rows) {
+ const isPurchased =
+ row.replenishmentSystem === "Buy" ||
+ row.replenishmentSystem === "Buy and Make";
+ const isSold = true; // Assume all items can be sold
+ const isTrackedAsInventory = row.itemTrackingType !== "None";
+
+ result.set(row.id, {
+ id: row.id,
+ code: row.readableIdWithRevision ?? row.readableId,
+ name: row.name,
+ description: row.description,
+ companyId: row.companyId!,
+ type: row.type,
+ unitOfMeasureCode: row.unitOfMeasureCode,
+ unitCost: row.unitCost ?? 0,
+ unitSalePrice: row.unitSalePrice ?? 0,
+ isPurchased,
+ isSold,
+ isTrackedAsInventory,
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH (Single + Batch) - API calls within syncer
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.Item | null> {
+ const result = await this.provider.request<{ Items: Xero.Item[] }>(
+ "GET",
+ `/Items/${id}`
+ );
+ return result.error ? null : (result.data?.Items?.[0] ?? null);
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.Item>> {
+ const result = new Map<string, Xero.Item>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{ Items: Xero.Item[] }>(
+ "GET",
+ `/Items?IDs=${ids.join(",")}`
+ );
+
+ if (response.error) {
+ throwXeroApiError("fetch items batch", response);
+ }
+
+ if (response.data?.Items) {
+ for (const item of response.data.Items) {
+ result.set(item.ItemID, item);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.Item
+ ): Promise<Omit<Xero.Item, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ return {
+ ItemID: existingRemoteId!,
+ Code: local.code.slice(0, 30),
+ Name: local.name.slice(0, 50),
+ Description: local.description?.slice(0, 4000) ?? undefined,
+ IsPurchased: local.isPurchased,
+ IsSold: local.isSold,
+ IsTrackedAsInventory: local.isTrackedAsInventory,
+ PurchaseDetails: local.isPurchased
+ ? { UnitPrice: local.unitCost }
+ : undefined,
+ SalesDetails: local.isSold
+ ? { UnitPrice: local.unitSalePrice }
+ : undefined
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon) - Update only
+ // =================================================================
+
+ protected async mapToLocal(
+ remote: Xero.Item
+ ): Promise<Partial<Accounting.Item>> {
+ return {
+ code: remote.Code,
+ name: remote.Name ?? "",
+ description: remote.Description ?? null,
+ unitCost: remote.PurchaseDetails?.UnitPrice ?? 0,
+ unitSalePrice: remote.SalesDetails?.UnitPrice ?? 0,
+ isPurchased: remote.IsPurchased ?? false,
+ isSold: remote.IsSold ?? false,
+ isTrackedAsInventory: remote.IsTrackedAsInventory ?? false
+ };
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL (Update existing only - Carbon is source of truth)
+ // =================================================================
+
+ protected async upsertLocal(
+ tx: KyselyTx,
+ data: Partial<Accounting.Item>,
+ remoteId: string
+ ): Promise<string> {
+ let existingLocalId = await this.getLocalId(remoteId);
+
+ // Smart match: if no mapping exists, try to find by item code.
+ // Xero Item.Code maps to Carbon item.readableIdWithRevision (or readableId).
+ // This prevents errors during backfill when items exist in both systems.
+ if (!existingLocalId && data.code) {
+ existingLocalId = await this.findLocalItemByCode(tx, data.code);
+ }
+
+ if (!existingLocalId) {
+ throw new Error(
+ `Cannot create new items from Xero. Item with remote ID ${remoteId} (code: ${
+ data.code ?? "unknown"
+ }) not found locally.`
+ );
+ }
+
+ // Update item table (mapping is handled by linkEntities in base class)
+ await tx
+ .updateTable("item")
+ .set({
+ name: data.name,
+ description: data.description,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", existingLocalId)
+ .execute();
+
+ // Update itemCost if unitCost changed
+ if (data.unitCost !== undefined) {
+ await tx
+ .updateTable("itemCost")
+ .set({ unitCost: data.unitCost })
+ .where("itemId", "=", existingLocalId)
+ .execute();
+ }
+
+ // Update itemUnitSalePrice if unitSalePrice changed
+ if (data.unitSalePrice !== undefined) {
+ await tx
+ .updateTable("itemUnitSalePrice")
+ .set({ unitSalePrice: data.unitSalePrice })
+ .where("itemId", "=", existingLocalId)
+ .execute();
+ }
+
+ return existingLocalId;
+ }
+
+ /**
+ * Try to find an existing Carbon item by its code (readableIdWithRevision or readableId).
+ * Used for smart matching during backfill when no ID mapping exists yet.
+ */
+ private async findLocalItemByCode(
+ tx: KyselyTx,
+ code: string
+ ): Promise<string | null> {
+ // Try readableIdWithRevision first (exact match for the Code sent to Xero)
+ const match = await tx
+ .selectFrom("item")
+ .select("id")
+ .where("companyId", "=", this.companyId)
+ .where((eb) =>
+ eb.or([
+ eb("readableIdWithRevision" as any, "=", code),
+ eb("readableId", "=", code)
+ ])
+ )
+ .executeTakeFirst();
+
+ return match?.id ?? null;
+ }
+
+ /**
+ * Search Xero for an existing item by exact Code match.
+ * Used for smart matching during push when no ID mapping exists yet.
+ */
+ private async findRemoteItemByCode(code: string): Promise<string | null> {
+ const escapedCode = code.replace(/"/g, '\\"');
+ const result = await this.provider.request<{ Items: Xero.Item[] }>(
+ "GET",
+ `/Items?where=Code=="${escapedCode}"`
+ );
+
+ if (!result.error && result.data?.Items?.[0]?.ItemID) {
+ return result.data.Items[0].ItemID;
+ }
+
+ return null;
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch) - API calls within syncer
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.Item, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ let existingRemoteId = await this.getRemoteId(localId);
+
+ // Smart match: if no mapping exists, search Xero by Code before creating.
+ // Xero enforces unique item codes.
+ if (!existingRemoteId && data.Code) {
+ existingRemoteId = await this.findRemoteItemByCode(data.Code);
+ }
+
+ const items = existingRemoteId
+ ? [{ ...data, ItemID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{ Items: Xero.Item[] }>(
+ "POST",
+ "/Items",
+ { body: JSON.stringify({ Items: items }) }
+ );
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId ? "update item" : "create item",
+ result
+ );
+ }
+
+ if (!result.data?.Items?.[0]?.ItemID) {
+ throw new Error("Xero API returned success but no ItemID was returned");
+ }
+
+ return result.data.Items[0].ItemID;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.Item, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const items: Xero.Item[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ items.push(
+ existingRemoteId
+ ? ({ ...payload, ItemID: existingRemoteId } as Xero.Item)
+ : (payload as Xero.Item)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{ Items: Xero.Item[] }>(
+ "POST",
+ "/Items",
+ { body: JSON.stringify({ Items: items }) }
+ );
+
+ if (response.error) {
+ throwXeroApiError("batch upsert items", response);
+ }
+
+ if (!response.data?.Items) {
+ throw new Error(
+ "Xero API returned success but no Items array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.Items.length; i++) {
+ const returnedItem = response.data.Items[i];
+ const localId = localIdOrder[i];
+ if (returnedItem?.ItemID && localId) {
+ result.set(localId, returnedItem.ItemID);
+ }
+ }
+
+ return result;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
new file mode 100644
index 0000000000..34164b8daa
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts
@@ -0,0 +1,635 @@
+import type { KyselyTx } from "@carbon/database/client";
+import { createMappingService } from "../../../core/external-mapping";
+import {
+ type Accounting,
+ BaseEntitySyncer,
+ type ShouldSyncContext
+} from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Note: This syncer uses the default ID mapping from BaseEntitySyncer
+// which uses the externalIntegrationMapping table with entityType "purchaseOrder"
+
+// Type for rows returned from purchaseOrder queries
+type PurchaseOrderRow = {
+ id: string;
+ companyId: string;
+ purchaseOrderId: string;
+ supplierId: string;
+ status:
+ | "Draft"
+ | "To Review"
+ | "Rejected"
+ | "To Receive"
+ | "To Receive and Invoice"
+ | "To Invoice"
+ | "Completed"
+ | "Closed"
+ | "Planned";
+ orderDate: string | null;
+ currencyCode: string | null;
+ exchangeRate: number | null;
+ supplierReference: string | null;
+ updatedAt: string | null;
+};
+
+// Type for rows returned from purchaseOrderLine queries
+type PurchaseOrderLineRow = {
+ id: string;
+ purchaseOrderId: string;
+ description: string | null;
+ purchaseQuantity: number | null;
+ unitPrice: number | null;
+ itemId: string | null;
+ accountNumber: string | null;
+ taxPercent: number | null;
+ taxAmount: number | null;
+ extendedPrice: number | null;
+ quantityReceived: number | null;
+ quantityInvoiced: number | null;
+ itemCode: string | null;
+};
+
+// Status mapping between Carbon and Xero
+const CARBON_TO_XERO_STATUS: Record<
+ PurchaseOrderRow["status"],
+ Xero.PurchaseOrder["Status"]
+> = {
+ Draft: "DRAFT",
+ "To Review": "SUBMITTED",
+ Rejected: "DRAFT",
+ Planned: "DRAFT",
+ "To Receive": "AUTHORISED",
+ "To Receive and Invoice": "AUTHORISED",
+ "To Invoice": "BILLED",
+ Completed: "BILLED",
+ Closed: "BILLED"
+};
+
+const XERO_TO_CARBON_STATUS: Record<
+ Xero.PurchaseOrder["Status"],
+ Accounting.PurchaseOrder["status"]
+> = {
+ DRAFT: "Draft",
+ SUBMITTED: "To Review",
+ AUTHORISED: "To Receive",
+ BILLED: "To Invoice",
+ DELETED: "Closed"
+};
+
+export class PurchaseOrderSyncer extends BaseEntitySyncer<
+ Accounting.PurchaseOrder,
+ Xero.PurchaseOrder,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // The entityType "purchaseOrder" maps to the purchaseOrder table
+ // =================================================================
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.PurchaseOrder): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.PurchaseOrder | null> {
+ const orders = await this.fetchOrdersByIds([id]);
+ return orders.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.PurchaseOrder>> {
+ if (ids.length === 0) return new Map();
+ return this.fetchOrdersByIds(ids);
+ }
+
+ private async fetchOrdersByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.PurchaseOrder>> {
+ if (ids.length === 0) return new Map();
+
+ // Fetch purchase orders
+ const orderRows = await this.database
+ .selectFrom("purchaseOrder")
+ .select([
+ "id",
+ "companyId",
+ "purchaseOrderId",
+ "supplierId",
+ "status",
+ "orderDate",
+ "currencyCode",
+ "exchangeRate",
+ "supplierReference",
+ "updatedAt"
+ ])
+ .where("id", "in", ids)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ if (orderRows.length === 0) return new Map();
+
+ // Fetch lines for all orders
+ const orderIds = orderRows.map((o) => o.id);
+ const lineRows = await this.database
+ .selectFrom("purchaseOrderLine")
+ .leftJoin("item", "item.id", "purchaseOrderLine.itemId")
+ .select([
+ "purchaseOrderLine.id",
+ "purchaseOrderLine.purchaseOrderId",
+ "purchaseOrderLine.description",
+ "purchaseOrderLine.purchaseQuantity",
+ "purchaseOrderLine.unitPrice",
+ "purchaseOrderLine.itemId",
+ "purchaseOrderLine.accountNumber",
+ "purchaseOrderLine.taxPercent",
+ "purchaseOrderLine.taxAmount",
+ "purchaseOrderLine.extendedPrice",
+ "purchaseOrderLine.quantityReceived",
+ "purchaseOrderLine.quantityInvoiced",
+ "item.readableId as itemCode"
+ ])
+ .where("purchaseOrderLine.purchaseOrderId", "in", orderIds)
+ .execute();
+
+ // Fetch supplier external IDs for mapping via the mapping service
+ const supplierIds = orderRows.map((o) => o.supplierId);
+ const supplierExternalIds = new Map<string, string | null>();
+ if (supplierIds.length > 0) {
+ const mappingService = createMappingService(this.database, this.companyId);
+ for (const supplierId of supplierIds) {
+ const externalId = await mappingService.getExternalId(
+ "supplier",
+ supplierId,
+ this.provider.id
+ );
+ supplierExternalIds.set(supplierId, externalId);
+ }
+ }
+
+ // Group lines by order
+ const linesByOrder = new Map<string, PurchaseOrderLineRow[]>();
+ for (const line of lineRows) {
+ const existing = linesByOrder.get(line.purchaseOrderId) ?? [];
+ existing.push(line as PurchaseOrderLineRow);
+ linesByOrder.set(line.purchaseOrderId, existing);
+ }
+
+ // Calculate totals and transform to Accounting.PurchaseOrder
+ const result = new Map<string, Accounting.PurchaseOrder>();
+ for (const row of orderRows) {
+ const lines = linesByOrder.get(row.id) ?? [];
+
+ // Calculate totals from lines
+ let subtotal = 0;
+ let totalTax = 0;
+ for (const line of lines) {
+ subtotal += line.extendedPrice ?? 0;
+ totalTax += line.taxAmount ?? 0;
+ }
+
+ result.set(row.id, {
+ id: row.id,
+ companyId: row.companyId,
+ purchaseOrderId: row.purchaseOrderId,
+ supplierId: row.supplierId,
+ supplierExternalId: supplierExternalIds.get(row.supplierId) ?? null,
+ status: row.status,
+ orderDate: row.orderDate,
+ deliveryDate: null, // Would need to join purchaseOrderDelivery
+ deliveryAddress: null,
+ deliveryInstructions: null,
+ currencyCode: row.currencyCode,
+ exchangeRate: row.exchangeRate,
+ subtotal,
+ totalTax,
+ totalAmount: subtotal + totalTax,
+ supplierReference: row.supplierReference,
+ lines: lines.map((line) => ({
+ id: line.id,
+ description: line.description,
+ quantity: line.purchaseQuantity ?? 0,
+ unitPrice: line.unitPrice ?? 0,
+ itemId: line.itemId,
+ itemCode: line.itemCode,
+ accountNumber: line.accountNumber,
+ taxPercent: line.taxPercent,
+ taxAmount: line.taxAmount,
+ totalAmount: line.extendedPrice ?? 0,
+ quantityReceived: line.quantityReceived,
+ quantityInvoiced: line.quantityInvoiced
+ })),
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.PurchaseOrder | null> {
+ const result = await this.provider.request<{
+ PurchaseOrders: Xero.PurchaseOrder[];
+ }>("GET", `/PurchaseOrders/${id}`);
+
+ if (result.error) return null;
+
+ const data = result.data as
+ | { PurchaseOrders: Xero.PurchaseOrder[] }
+ | undefined;
+ return data?.PurchaseOrders?.[0] ?? null;
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.PurchaseOrder>> {
+ const result = new Map<string, Xero.PurchaseOrder>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{
+ PurchaseOrders: Xero.PurchaseOrder[];
+ }>("GET", `/PurchaseOrders?IDs=${ids.join(",")}`);
+
+ if (response.error) {
+ throwXeroApiError("fetch purchase orders batch", response);
+ }
+
+ const data = response.data as
+ | { PurchaseOrders: Xero.PurchaseOrder[] }
+ | undefined;
+ for (const po of data?.PurchaseOrders ?? []) {
+ result.set(po.PurchaseOrderID, po);
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.PurchaseOrder
+ ): Promise<Omit<Xero.PurchaseOrder, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ // Get supplier's Xero ContactID - ensure supplier is synced first
+ let contactId = local.supplierExternalId;
+ if (!contactId && local.supplierId) {
+ contactId = await this.ensureDependencySynced("vendor", local.supplierId);
+ }
+
+ if (!contactId) {
+ throw new Error(
+ `Cannot sync PO ${local.id}: No supplier linked or supplier not synced to Xero`
+ );
+ }
+
+ // Map line items
+ const lineItems: Xero.PurchaseOrderLineItem[] = await Promise.all(
+ local.lines.map(async (line) => {
+ let itemCode = line.itemCode;
+
+ // If we have an itemId but no itemCode, try to get it from the item table
+ if (!itemCode && line.itemId) {
+ const item = await this.database
+ .selectFrom("item")
+ .select("readableId")
+ .where("id", "=", line.itemId)
+ .executeTakeFirst();
+ itemCode = item?.readableId ?? null;
+ }
+
+ return {
+ Description: line.description ?? undefined,
+ Quantity: line.quantity,
+ UnitAmount: line.unitPrice,
+ ItemCode: itemCode?.slice(0, 30) ?? undefined,
+ AccountCode: line.accountNumber ?? undefined,
+ TaxAmount: line.taxAmount ?? undefined,
+ LineAmount: line.totalAmount
+ };
+ })
+ );
+
+ return {
+ PurchaseOrderID: existingRemoteId!,
+ PurchaseOrderNumber: local.purchaseOrderId,
+ Reference: local.supplierReference ?? undefined,
+ Contact: { ContactID: contactId },
+ Date: local.orderDate ?? undefined,
+ DeliveryDate: local.deliveryDate ?? undefined,
+ DeliveryAddress: local.deliveryAddress ?? undefined,
+ DeliveryInstructions: local.deliveryInstructions ?? undefined,
+ Status: CARBON_TO_XERO_STATUS[local.status],
+ CurrencyCode: local.currencyCode ?? undefined,
+ CurrencyRate:
+ local.exchangeRate && local.exchangeRate !== 1
+ ? local.exchangeRate
+ : undefined,
+ LineItems: lineItems,
+ SubTotal: local.subtotal,
+ TotalTax: local.totalTax,
+ Total: local.totalAmount
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon)
+ // =================================================================
+
+ protected async mapToLocal(
+ remote: Xero.PurchaseOrder
+ ): Promise<Partial<Accounting.PurchaseOrder>> {
+ const status = XERO_TO_CARBON_STATUS[remote.Status];
+
+ // Map line items
+ const lines: Accounting.PurchaseOrderLine[] = (remote.LineItems ?? []).map(
+ (line, index) => ({
+ id: line.LineItemID ?? `temp-${index}`,
+ description: line.Description ?? null,
+ quantity: line.Quantity ?? 1,
+ unitPrice: line.UnitAmount ?? 0,
+ itemId: null, // Will be resolved during upsertLocal if ItemCode matches
+ itemCode: line.ItemCode ?? null,
+ accountNumber: line.AccountCode ?? null,
+ taxPercent: null,
+ taxAmount: line.TaxAmount ?? null,
+ totalAmount: line.LineAmount ?? 0,
+ quantityReceived: null,
+ quantityInvoiced: null
+ })
+ );
+
+ return {
+ purchaseOrderId: remote.PurchaseOrderNumber ?? remote.PurchaseOrderID,
+ supplierExternalId: remote.Contact.ContactID,
+ status,
+ orderDate: remote.Date ?? null,
+ deliveryDate: remote.DeliveryDate ?? null,
+ deliveryAddress: remote.DeliveryAddress ?? null,
+ deliveryInstructions: remote.DeliveryInstructions ?? null,
+ currencyCode: remote.CurrencyCode ?? "USD",
+ exchangeRate: remote.CurrencyRate ?? 1,
+ subtotal: remote.SubTotal ?? 0,
+ totalTax: remote.TotalTax ?? 0,
+ totalAmount: remote.Total ?? 0,
+ supplierReference: remote.Reference ?? null,
+ lines,
+ updatedAt: remote.UpdatedDateUTC
+ ? parseDotnetDate(remote.UpdatedDateUTC).toISOString()
+ : new Date().toISOString()
+ };
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL
+ // =================================================================
+
+ protected async upsertLocal(
+ tx: KyselyTx,
+ data: Partial<Accounting.PurchaseOrder>,
+ remoteId: string
+ ): Promise<string> {
+ const existingLocalId = await this.getLocalId(remoteId);
+
+ // Resolve supplier from Xero ContactID using mapping service
+ let supplierId: string | null = null;
+ if (data.supplierExternalId) {
+ const txMappingService = createMappingService(tx, this.companyId);
+ supplierId = await txMappingService.getEntityId(
+ this.provider.id,
+ data.supplierExternalId,
+ "supplier"
+ );
+ }
+
+ if (existingLocalId) {
+ // Update existing purchase order (mapping is handled by linkEntities in base class)
+ await tx
+ .updateTable("purchaseOrder")
+ .set({
+ supplierId: supplierId ?? undefined,
+ status: data.status,
+ orderDate: data.orderDate,
+ currencyCode: data.currencyCode,
+ exchangeRate: data.exchangeRate,
+ supplierReference: data.supplierReference,
+ updatedAt: new Date().toISOString()
+ })
+ .where("id", "=", existingLocalId)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ // Update lines
+ await this.upsertLines(tx, existingLocalId, data.lines ?? []);
+
+ return existingLocalId;
+ }
+
+ // For new POs from Xero, we need to create them
+ // This requires more context (supplierInteractionId, createdBy, etc.)
+ throw new Error(
+ `Cannot create new purchase order from Xero. PO with ID ${remoteId} must be created in Carbon first and then synced.`
+ );
+ }
+
+ private async upsertLines(
+ tx: KyselyTx,
+ purchaseOrderId: string,
+ lines: Accounting.PurchaseOrderLine[]
+ ): Promise<void> {
+ // Delete existing lines
+ await tx
+ .deleteFrom("purchaseOrderLine")
+ .where("purchaseOrderId", "=", purchaseOrderId)
+ .execute();
+
+ if (lines.length === 0) return;
+
+ // Resolve item IDs from item codes
+ const itemCodes = lines
+ .map((l) => l.itemCode)
+ .filter((code): code is string => code !== null);
+
+ const itemMap = new Map<string, string>();
+ if (itemCodes.length > 0) {
+ const items = await tx
+ .selectFrom("item")
+ .select(["id", "readableId"])
+ .where("readableId", "in", itemCodes)
+ .where("companyId", "=", this.companyId)
+ .execute();
+
+ for (const item of items) {
+ itemMap.set(item.readableId, item.id);
+ }
+ }
+
+ // Get the PO to get companyId and createdBy
+ const po = await tx
+ .selectFrom("purchaseOrder")
+ .select(["companyId", "createdBy", "exchangeRate"])
+ .where("id", "=", purchaseOrderId)
+ .executeTakeFirstOrThrow();
+
+ // Insert new lines
+ for (const line of lines) {
+ const itemId = line.itemCode
+ ? (itemMap.get(line.itemCode) ?? null)
+ : null;
+
+ await tx
+ .insertInto("purchaseOrderLine")
+ .values({
+ purchaseOrderId,
+ companyId: po.companyId,
+ createdBy: po.createdBy,
+ description: line.description,
+ purchaseQuantity: line.quantity,
+ unitPrice: line.unitPrice,
+ supplierUnitPrice: line.unitPrice,
+ itemId,
+ accountNumber: line.accountNumber,
+ taxPercent: line.taxPercent,
+ taxAmount: line.taxAmount,
+ supplierTaxAmount: line.taxAmount ?? 0,
+ extendedPrice: line.totalAmount,
+ supplierExtendedPrice: line.totalAmount,
+ exchangeRate: po.exchangeRate ?? 1,
+ purchaseOrderLineType: itemId ? "Part" : "G/L Account",
+ supplierShippingCost: 0,
+ invoicedComplete: false,
+ receivedComplete: false,
+ requiresInspection: false
+ })
+ .execute();
+ }
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch)
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.PurchaseOrder, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ const existingRemoteId = await this.getRemoteId(localId);
+ const purchaseOrders = existingRemoteId
+ ? [{ ...data, PurchaseOrderID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{
+ PurchaseOrders: Xero.PurchaseOrder[];
+ }>("POST", "/PurchaseOrders", {
+ body: JSON.stringify({ PurchaseOrders: purchaseOrders })
+ });
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId ? "update purchase order" : "create purchase order",
+ result
+ );
+ }
+
+ const resData = result.data as
+ | { PurchaseOrders: Xero.PurchaseOrder[] }
+ | undefined;
+ const poId = resData?.PurchaseOrders?.[0]?.PurchaseOrderID;
+
+ if (!poId) {
+ throw new Error(
+ "Xero API returned success but no PurchaseOrderID was returned"
+ );
+ }
+
+ return poId;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.PurchaseOrder, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const purchaseOrders: Xero.PurchaseOrder[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ purchaseOrders.push(
+ existingRemoteId
+ ? ({
+ ...payload,
+ PurchaseOrderID: existingRemoteId
+ } as Xero.PurchaseOrder)
+ : (payload as Xero.PurchaseOrder)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{
+ PurchaseOrders: Xero.PurchaseOrder[];
+ }>("POST", "/PurchaseOrders", {
+ body: JSON.stringify({ PurchaseOrders: purchaseOrders })
+ });
+
+ if (response.error) {
+ throwXeroApiError("batch upsert purchase orders", response);
+ }
+
+ if (!response.data?.PurchaseOrders) {
+ throw new Error(
+ "Xero API returned success but no PurchaseOrders array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.PurchaseOrders.length; i++) {
+ const returnedPO = response.data.PurchaseOrders[i];
+ const localId = localIdOrder[i];
+ if (returnedPO?.PurchaseOrderID && localId) {
+ result.set(localId, returnedPO.PurchaseOrderID);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 9. SHOULD SYNC: Only sync POs that are past Draft/Planned status
+ // =================================================================
+
+ protected shouldSync(
+ context: ShouldSyncContext<Accounting.PurchaseOrder, Xero.PurchaseOrder>
+ ): boolean | string {
+ if (context.direction === "push" && context.localEntity) {
+ const nonSyncableStatuses: Accounting.PurchaseOrder["status"][] = [
+ "Draft",
+ "Planned"
+ ];
+ if (nonSyncableStatuses.includes(context.localEntity.status)) {
+ return `Purchase order must be past Draft/Planned before syncing (current status: ${context.localEntity.status})`;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts
new file mode 100644
index 0000000000..fb9905196a
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts
@@ -0,0 +1,436 @@
+import type { KyselyTx } from "@carbon/database/client";
+import {
+ type Accounting,
+ BaseEntitySyncer,
+ type ShouldSyncContext
+} from "../../../core/types";
+import { throwXeroApiError } from "../../../core/utils";
+import { parseDotnetDate, type Xero } from "../models";
+
+// Note: This is a push-only syncer (Carbon -> Xero).
+// Carbon sales orders are pushed as Xero Quotes since Xero
+// has no dedicated sales order endpoint.
+
+// Type for rows returned from salesOrder queries
+type SalesOrderRow = {
+ id: string;
+ salesOrderId: string;
+ companyId: string;
+ customerId: string;
+ status:
+ | "Draft"
+ | "Needs Approval"
+ | "Confirmed"
+ | "In Progress"
+ | "To Ship and Invoice"
+ | "To Ship"
+ | "To Invoice"
+ | "Completed"
+ | "Invoiced"
+ | "Cancelled"
+ | "Closed";
+ orderDate: string | null;
+ currencyCode: string;
+ exchangeRate: number;
+ customerReference: string | null;
+ updatedAt: string | null;
+};
+
+// Type for rows returned from salesOrderLine queries
+type SalesOrderLineRow = {
+ id: string;
+ salesOrderId: string;
+ salesOrderLineType: string;
+ itemId: string | null;
+ description: string | null;
+ saleQuantity: number;
+ unitPrice: number | null;
+ setupPrice: number | null;
+ accountNumber: string | null;
+ itemReadableIdWithRevision: string | null;
+};
+
+// Status mapping: Carbon -> Xero Quote
+const CARBON_TO_XERO_STATUS: Record<
+ SalesOrderRow["status"],
+ Xero.Quote["Status"]
+> = {
+ Draft: "DRAFT",
+ "Needs Approval": "DRAFT",
+ Confirmed: "ACCEPTED",
+ "In Progress": "ACCEPTED",
+ "To Ship and Invoice": "ACCEPTED",
+ "To Ship": "ACCEPTED",
+ "To Invoice": "ACCEPTED",
+ Completed: "ACCEPTED",
+ Invoiced: "INVOICED",
+ Cancelled: "DELETED",
+ Closed: "ACCEPTED"
+};
+
+// Syncable statuses — only sync orders past Draft/Needs Approval/Cancelled
+const SYNCABLE_STATUSES: SalesOrderRow["status"][] = [
+ "Confirmed",
+ "In Progress",
+ "To Ship and Invoice",
+ "To Ship",
+ "To Invoice",
+ "Completed",
+ "Invoiced"
+];
+
+export class SalesOrderSyncer extends BaseEntitySyncer<
+ Accounting.SalesOrder,
+ Xero.Quote,
+ "UpdatedDateUTC"
+> {
+ // =================================================================
+ // 1. ID MAPPING - Uses default implementation from BaseEntitySyncer
+ // =================================================================
+
+ // =================================================================
+ // 2. TIMESTAMP EXTRACTION
+ // =================================================================
+
+ protected getRemoteUpdatedAt(remote: Xero.Quote): Date | null {
+ if (!remote.UpdatedDateUTC) return null;
+ return parseDotnetDate(remote.UpdatedDateUTC);
+ }
+
+ // =================================================================
+ // 3. LOCAL FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchLocal(id: string): Promise<Accounting.SalesOrder | null> {
+ const orders = await this.fetchOrdersByIds([id]);
+ return orders.get(id) ?? null;
+ }
+
+ protected async fetchLocalBatch(
+ ids: string[]
+ ): Promise<Map<string, Accounting.SalesOrder>> {
+ return this.fetchOrdersByIds(ids);
+ }
+
+ private async fetchOrdersByIds(
+ ids: string[]
+ ): Promise<Map<string, Accounting.SalesOrder>> {
+ if (ids.length === 0) return new Map();
+
+ // Fetch order headers
+ const orderRows = await this.database
+ .selectFrom("salesOrder")
+ .select([
+ "salesOrder.id",
+ "salesOrder.salesOrderId",
+ "salesOrder.companyId",
+ "salesOrder.customerId",
+ "salesOrder.status",
+ "salesOrder.orderDate",
+ "salesOrder.currencyCode",
+ "salesOrder.exchangeRate",
+ "salesOrder.customerReference",
+ "salesOrder.updatedAt"
+ ])
+ .where("salesOrder.id", "in", ids)
+ .where("salesOrder.companyId", "=", this.companyId)
+ .execute();
+
+ if (orderRows.length === 0) return new Map();
+
+ // Fetch order lines with item codes
+ const lineRows = await this.database
+ .selectFrom("salesOrderLine")
+ .leftJoin("item", "item.id", "salesOrderLine.itemId")
+ .select([
+ "salesOrderLine.id",
+ "salesOrderLine.salesOrderId",
+ "salesOrderLine.salesOrderLineType",
+ "salesOrderLine.itemId",
+ "salesOrderLine.description",
+ "salesOrderLine.saleQuantity",
+ "salesOrderLine.unitPrice",
+ "salesOrderLine.setupPrice",
+ "salesOrderLine.accountNumber",
+ "item.readableIdWithRevision as itemReadableIdWithRevision"
+ ])
+ .where(
+ "salesOrderLine.salesOrderId",
+ "in",
+ orderRows.map((r) => r.id)
+ )
+ .execute();
+
+ // Group lines by order ID
+ const linesByOrderId = new Map<string, SalesOrderLineRow[]>();
+ for (const line of lineRows as unknown as SalesOrderLineRow[]) {
+ const existing = linesByOrderId.get(line.salesOrderId) ?? [];
+ existing.push(line);
+ linesByOrderId.set(line.salesOrderId, existing);
+ }
+
+ // Transform to Accounting.SalesOrder
+ const result = new Map<string, Accounting.SalesOrder>();
+ for (const row of orderRows as unknown as SalesOrderRow[]) {
+ const lines = linesByOrderId.get(row.id) ?? [];
+
+ result.set(row.id, {
+ id: row.id,
+ salesOrderId: row.salesOrderId,
+ companyId: row.companyId,
+ customerId: row.customerId,
+ customerExternalId: null, // Will be resolved during mapToRemote
+ status: row.status,
+ orderDate: row.orderDate,
+ currencyCode: row.currencyCode,
+ exchangeRate: row.exchangeRate,
+ customerReference: row.customerReference,
+ lines: lines.map((line) => {
+ const unitPrice = line.unitPrice ?? 0;
+ const setupPrice = line.setupPrice ?? 0;
+ const quantity = line.saleQuantity;
+ return {
+ id: line.id,
+ salesOrderLineType: line.salesOrderLineType,
+ itemId: line.itemId,
+ itemCode: line.itemReadableIdWithRevision,
+ description: line.description,
+ quantity,
+ unitPrice,
+ setupPrice,
+ accountNumber: line.accountNumber,
+ lineAmount: quantity * unitPrice + setupPrice
+ };
+ }),
+ updatedAt: row.updatedAt ?? new Date().toISOString(),
+ raw: row
+ });
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 4. REMOTE FETCH (Single + Batch)
+ // =================================================================
+
+ async fetchRemote(id: string): Promise<Xero.Quote | null> {
+ const result = await this.provider.request<{ Quotes: Xero.Quote[] }>(
+ "GET",
+ `/Quotes/${id}`
+ );
+ return result.error ? null : (result.data?.Quotes?.[0] ?? null);
+ }
+
+ protected async fetchRemoteBatch(
+ ids: string[]
+ ): Promise<Map<string, Xero.Quote>> {
+ const result = new Map<string, Xero.Quote>();
+ if (ids.length === 0) return result;
+
+ const response = await this.provider.request<{ Quotes: Xero.Quote[] }>(
+ "GET",
+ `/Quotes?IDs=${ids.join(",")}`
+ );
+
+ if (response.error) {
+ throwXeroApiError("fetch quotes batch", response);
+ }
+
+ if (response.data?.Quotes) {
+ for (const quote of response.data.Quotes) {
+ result.set(quote.QuoteID, quote);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 5. TRANSFORMATION (Carbon -> Xero)
+ // =================================================================
+
+ protected async mapToRemote(
+ local: Accounting.SalesOrder
+ ): Promise<Omit<Xero.Quote, "UpdatedDateUTC">> {
+ const existingRemoteId = await this.getRemoteId(local.id);
+
+ // Resolve customer dependency — ensure customer is synced to Xero
+ const customerRemoteId = await this.ensureDependencySynced(
+ "customer",
+ local.customerId
+ );
+
+ // Build line items, resolving item dependencies
+ const lineItems: Xero.QuoteLineItem[] = [];
+ for (const line of local.lines) {
+ // Skip comment lines — they have no financial data
+ if (line.salesOrderLineType === "Comment") {
+ continue;
+ }
+
+ const lineItem: Xero.QuoteLineItem = {
+ Description: line.description ?? undefined,
+ Quantity: line.quantity,
+ UnitAmount: line.unitPrice,
+ AccountCode: line.accountNumber ?? undefined,
+ LineAmount: line.lineAmount
+ };
+
+ // If line has an item, ensure it's synced and set ItemCode
+ if (line.itemId) {
+ await this.ensureDependencySynced("item", line.itemId);
+ if (line.itemCode) {
+ lineItem.ItemCode = line.itemCode.slice(0, 30);
+ }
+ }
+
+ lineItems.push(lineItem);
+ }
+
+ return {
+ QuoteID: existingRemoteId!,
+ QuoteNumber: local.salesOrderId,
+ Reference: local.customerReference ?? undefined,
+ Contact: {
+ ContactID: customerRemoteId
+ },
+ Date: local.orderDate ?? undefined,
+ Status: CARBON_TO_XERO_STATUS[local.status],
+ LineAmountTypes: "Exclusive",
+ LineItems: lineItems,
+ CurrencyCode: local.currencyCode,
+ CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,
+ Title: `Sales Order ${local.salesOrderId}`
+ };
+ }
+
+ // =================================================================
+ // 6. TRANSFORMATION (Xero -> Carbon) - Not supported (push-only)
+ // =================================================================
+
+ protected async mapToLocal(
+ _remote: Xero.Quote
+ ): Promise<Partial<Accounting.SalesOrder>> {
+ throw new Error(
+ "Sales orders are push-only. Cannot map from Xero to Carbon."
+ );
+ }
+
+ // =================================================================
+ // 7. UPSERT LOCAL - Not supported (push-only)
+ // =================================================================
+
+ protected async upsertLocal(
+ _tx: KyselyTx,
+ _data: Partial<Accounting.SalesOrder>,
+ _remoteId: string
+ ): Promise<string> {
+ throw new Error(
+ "Sales orders are push-only. Cannot upsert locally from Xero."
+ );
+ }
+
+ // =================================================================
+ // 8. UPSERT REMOTE (Single + Batch)
+ // =================================================================
+
+ protected async upsertRemote(
+ data: Omit<Xero.Quote, "UpdatedDateUTC">,
+ localId: string
+ ): Promise<string> {
+ const existingRemoteId = await this.getRemoteId(localId);
+
+ // Xero uses PUT for create, POST for update-or-create
+ const method = existingRemoteId ? "POST" : "PUT";
+ const quotes = existingRemoteId
+ ? [{ ...data, QuoteID: existingRemoteId }]
+ : [data];
+
+ const result = await this.provider.request<{ Quotes: Xero.Quote[] }>(
+ method,
+ "/Quotes",
+ { body: JSON.stringify({ Quotes: quotes }) }
+ );
+
+ if (result.error) {
+ throwXeroApiError(
+ existingRemoteId
+ ? "update sales order quote"
+ : "create sales order quote",
+ result
+ );
+ }
+
+ if (!result.data?.Quotes?.[0]?.QuoteID) {
+ throw new Error("Xero API returned success but no QuoteID was returned");
+ }
+
+ return result.data.Quotes[0].QuoteID;
+ }
+
+ protected async upsertRemoteBatch(
+ data: Array<{
+ localId: string;
+ payload: Omit<Xero.Quote, "UpdatedDateUTC">;
+ }>
+ ): Promise<Map<string, string>> {
+ const result = new Map<string, string>();
+ if (data.length === 0) return result;
+
+ const quotes: Xero.Quote[] = [];
+ const localIdOrder: string[] = [];
+
+ for (const { localId, payload } of data) {
+ const existingRemoteId = await this.getRemoteId(localId);
+ quotes.push(
+ existingRemoteId
+ ? ({ ...payload, QuoteID: existingRemoteId } as Xero.Quote)
+ : (payload as Xero.Quote)
+ );
+ localIdOrder.push(localId);
+ }
+
+ const response = await this.provider.request<{ Quotes: Xero.Quote[] }>(
+ "POST",
+ "/Quotes",
+ { body: JSON.stringify({ Quotes: quotes }) }
+ );
+
+ if (response.error) {
+ throwXeroApiError("batch upsert sales order quotes", response);
+ }
+
+ if (!response.data?.Quotes) {
+ throw new Error(
+ "Xero API returned success but no Quotes array was returned"
+ );
+ }
+
+ for (let i = 0; i < response.data.Quotes.length; i++) {
+ const returnedQuote = response.data.Quotes[i];
+ const localId = localIdOrder[i];
+ if (returnedQuote?.QuoteID && localId) {
+ result.set(localId, returnedQuote.QuoteID);
+ }
+ }
+
+ return result;
+ }
+
+ // =================================================================
+ // 9. SHOULD SYNC: Only sync orders past Draft/Needs Approval
+ // =================================================================
+
+ protected shouldSync(
+ context: ShouldSyncContext<Accounting.SalesOrder, Xero.Quote>
+ ): boolean | string {
+ if (context.direction === "push" && context.localEntity) {
+ if (!SYNCABLE_STATUSES.includes(context.localEntity.status)) {
+ return `Sales order must be confirmed before syncing (current status: ${context.localEntity.status})`;
+ }
+ }
+
+ return true;
+ }
+}
diff --git a/packages/ee/src/accounting/providers/xero/index.ts b/packages/ee/src/accounting/providers/xero/index.ts
new file mode 100644
index 0000000000..2c61194c8a
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/index.ts
@@ -0,0 +1,7 @@
+export * from "./entities/bill";
+export * from "./entities/contact";
+export * from "./entities/invoice";
+export * from "./entities/item";
+export * from "./entities/purchase-order";
+export * from "./models";
+export * from "./provider";
diff --git a/packages/ee/src/accounting/providers/xero/models.ts b/packages/ee/src/accounting/providers/xero/models.ts
new file mode 100644
index 0000000000..04d76ffe63
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/models.ts
@@ -0,0 +1,400 @@
+import { z } from "zod";
+import type { Accounting } from "../../core/types";
+
+export namespace Xero {
+ // Shared address schema for contacts and employees
+ export const AddressSchema = z.object({
+ AddressType: z.enum(["POBOX", "STREET", "DELIVERY"]),
+ AddressLine1: z.string().optional(),
+ AddressLine2: z.string().optional(),
+ AddressLine3: z.string().optional(),
+ AddressLine4: z.string().optional(),
+ City: z.string().optional(),
+ Region: z.string().optional(),
+ PostalCode: z.string().optional(),
+ Country: z.string().optional(),
+ AttentionTo: z.string().optional()
+ });
+
+ export const PhoneSchema = z.object({
+ PhoneType: z.enum(["DDI", "DEFAULT", "FAX", "MOBILE"]),
+ PhoneNumber: z.string().optional(),
+ PhoneAreaCode: z.string().optional(),
+ PhoneCountryCode: z.string().optional()
+ });
+
+ export const BalancesSchema = z.object({
+ AccountsReceivable: z.object({
+ Outstanding: z.number(),
+ Overdue: z.number()
+ }),
+ AccountsPayable: z.object({
+ Outstanding: z.number(),
+ Overdue: z.number()
+ })
+ });
+
+ export const BrandingThemeSchema = z.object({
+ BrandingThemeID: z.string().uuid(),
+ Name: z.string()
+ });
+
+ export const BatchPaymentsSchema = z.object({
+ BankAccountNumber: z.string(),
+ BankAccountName: z.string(),
+ Details: z.string(),
+ Code: z.string().optional(),
+ Reference: z.string().optional()
+ });
+
+ export const ContactSchema = z.object({
+ ContactID: z.string().uuid(),
+ ContactStatus: z.literal("ACTIVE"),
+
+ Name: z.string(),
+ Website: z.string().optional(),
+
+ FirstName: z.string().optional(),
+ LastName: z.string().optional(),
+
+ EmailAddress: z.string().email().optional(),
+ ContactNumber: z.string().optional(),
+
+ BankAccountDetails: z.string().optional(),
+ TaxNumber: z.string().optional(),
+
+ AccountsReceivableTaxType: z.string().optional(),
+ AccountsPayableTaxType: z.string().optional(),
+
+ Addresses: z.array(AddressSchema),
+ Phones: z.array(PhoneSchema),
+
+ UpdatedDateUTC: z.string(), // serialized /Date(...)/
+
+ ContactGroups: z.array(z.unknown()),
+
+ IsSupplier: z.boolean(),
+ IsCustomer: z.boolean(),
+
+ DefaultCurrency: z.string().optional(),
+
+ BrandingTheme: BrandingThemeSchema.optional(),
+ BatchPayments: BatchPaymentsSchema.optional(),
+
+ Balances: BalancesSchema.optional(),
+
+ ContactPersons: z.array(z.unknown()),
+
+ HasAttachments: z.boolean(),
+ HasValidationErrors: z.boolean()
+ });
+
+ export type Contact = z.infer<typeof ContactSchema>;
+
+ // Employee schema for Xero Accounting API Employees endpoint
+ // Note: This is from the deprecated Accounting API endpoint, not PayrollAU/UK/NZ
+ export const EmployeeSchema = z.object({
+ EmployeeID: z.string().uuid(),
+ Status: z.enum(["ACTIVE", "DELETED"]).optional(),
+ FirstName: z.string(),
+ LastName: z.string(),
+ ExternalLink: z
+ .object({
+ Url: z.string().url().optional(),
+ Description: z.string().optional()
+ })
+ .optional(),
+ UpdatedDateUTC: z.string() // serialized /Date(...)/
+ });
+
+ export type Employee = z.infer<typeof EmployeeSchema>;
+
+ // Item schemas for Xero Accounting API Items endpoint
+ export const PurchaseDetailsSchema = z.object({
+ UnitPrice: z.number().optional(),
+ AccountCode: z.string().optional(),
+ COGSAccountCode: z.string().optional(),
+ TaxType: z.string().optional()
+ });
+
+ export const SalesDetailsSchema = z.object({
+ UnitPrice: z.number().optional(),
+ AccountCode: z.string().optional(),
+ TaxType: z.string().optional()
+ });
+
+ export const ItemSchema = z.object({
+ ItemID: z.string().uuid(),
+ Code: z.string().max(30),
+ Name: z.string().max(50).optional(),
+ Description: z.string().max(4000).optional(),
+ PurchaseDescription: z.string().optional(),
+ PurchaseDetails: PurchaseDetailsSchema.optional(),
+ SalesDetails: SalesDetailsSchema.optional(),
+ IsTrackedAsInventory: z.boolean().optional(),
+ IsSold: z.boolean().optional(),
+ IsPurchased: z.boolean().optional(),
+ QuantityOnHand: z.number().optional(),
+ TotalCostPool: z.number().optional(),
+ UpdatedDateUTC: z.string()
+ });
+
+ export type PurchaseDetails = z.infer<typeof PurchaseDetailsSchema>;
+ export type SalesDetails = z.infer<typeof SalesDetailsSchema>;
+ export type Item = z.infer<typeof ItemSchema>;
+
+ // Invoice/Bill schemas for Xero Accounting API
+ // Type: ACCPAY = Accounts Payable (Bill/Purchase Invoice)
+ // Type: ACCREC = Accounts Receivable (Sales Invoice)
+ export const InvoiceLineItemSchema = z.object({
+ LineItemID: z.string().uuid().optional(),
+ Description: z.string().optional(),
+ Quantity: z.number().optional(),
+ UnitAmount: z.number().optional(),
+ ItemCode: z.string().optional(),
+ AccountCode: z.string().optional(),
+ TaxType: z.string().optional(),
+ TaxAmount: z.number().optional(),
+ LineAmount: z.number().optional(),
+ DiscountRate: z.number().optional(),
+ Tracking: z.array(z.unknown()).optional()
+ });
+
+ export const InvoiceContactSchema = z.object({
+ ContactID: z.string().uuid(),
+ Name: z.string().optional()
+ });
+
+ export const InvoiceSchema = z.object({
+ InvoiceID: z.string().uuid(),
+ Type: z.enum(["ACCPAY", "ACCREC"]), // ACCPAY = Bill, ACCREC = Sales Invoice
+ InvoiceNumber: z.string().optional(),
+ Reference: z.string().optional(),
+ Contact: InvoiceContactSchema,
+ Date: z.string().optional(), // YYYY-MM-DD
+ DueDate: z.string().optional(),
+ Status: z.enum([
+ "DRAFT",
+ "SUBMITTED",
+ "AUTHORISED",
+ "PAID",
+ "VOIDED",
+ "DELETED"
+ ]),
+ LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
+ LineItems: z.array(InvoiceLineItemSchema),
+ SubTotal: z.number().optional(),
+ TotalTax: z.number().optional(),
+ Total: z.number().optional(),
+ AmountDue: z.number().optional(),
+ AmountPaid: z.number().optional(),
+ CurrencyCode: z.string().optional(),
+ CurrencyRate: z.number().optional(),
+ UpdatedDateUTC: z.string()
+ });
+
+ export type Invoice = z.infer<typeof InvoiceSchema>;
+ export type InvoiceLineItem = z.infer<typeof InvoiceLineItemSchema>;
+ export type InvoiceContact = z.infer<typeof InvoiceContactSchema>;
+
+ // Purchase Order schemas for Xero Accounting API
+ export const PurchaseOrderLineItemSchema = z.object({
+ LineItemID: z.string().uuid().optional(),
+ Description: z.string().optional(),
+ Quantity: z.number().optional(),
+ UnitAmount: z.number().optional(),
+ ItemCode: z.string().optional(),
+ AccountCode: z.string().optional(),
+ TaxType: z.string().optional(),
+ TaxAmount: z.number().optional(),
+ LineAmount: z.number().optional(),
+ DiscountRate: z.number().optional(),
+ Tracking: z.array(z.unknown()).optional()
+ });
+
+ export const PurchaseOrderContactSchema = z.object({
+ ContactID: z.string().uuid(),
+ Name: z.string().optional()
+ });
+
+ export const PurchaseOrderSchema = z.object({
+ PurchaseOrderID: z.string().uuid(),
+ PurchaseOrderNumber: z.string().optional(),
+ Reference: z.string().optional(),
+ Contact: PurchaseOrderContactSchema,
+ Date: z.string().optional(), // YYYY-MM-DD
+ DeliveryDate: z.string().optional(),
+ DeliveryAddress: z.string().optional(),
+ AttentionTo: z.string().optional(),
+ Telephone: z.string().optional(),
+ DeliveryInstructions: z.string().optional(),
+ Status: z.enum(["DRAFT", "SUBMITTED", "AUTHORISED", "BILLED", "DELETED"]),
+ LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
+ LineItems: z.array(PurchaseOrderLineItemSchema),
+ SubTotal: z.number().optional(),
+ TotalTax: z.number().optional(),
+ Total: z.number().optional(),
+ CurrencyCode: z.string().optional(),
+ CurrencyRate: z.number().optional(),
+ UpdatedDateUTC: z.string()
+ });
+
+ export type PurchaseOrder = z.infer<typeof PurchaseOrderSchema>;
+ export type PurchaseOrderLineItem = z.infer<
+ typeof PurchaseOrderLineItemSchema
+ >;
+ export type PurchaseOrderContact = z.infer<typeof PurchaseOrderContactSchema>;
+
+ // Manual Journal schemas for Xero Accounting API ManualJournals endpoint
+ export const ManualJournalLineSchema = z.object({
+ LineAmount: z.number(),
+ AccountCode: z.string(),
+ Description: z.string().optional(),
+ TaxType: z.string().optional(),
+ TaxAmount: z.number().optional(),
+ IsBlank: z.boolean().optional()
+ });
+
+ export const ManualJournalSchema = z.object({
+ ManualJournalID: z.string().uuid(),
+ Narration: z.string(),
+ Date: z.string().optional(),
+ Status: z.enum(["DRAFT", "POSTED", "DELETED", "VOIDED", "ARCHIVED"]),
+ LineAmountTypes: z.string().optional(),
+ Url: z.string().optional(),
+ ShowOnCashBasisReports: z.boolean().optional(),
+ JournalLines: z.array(ManualJournalLineSchema).optional(),
+ UpdatedDateUTC: z.string()
+ });
+
+ export type ManualJournalLine = z.infer<typeof ManualJournalLineSchema>;
+ export type ManualJournal = z.infer<typeof ManualJournalSchema>;
+
+ // Quote schemas for Xero Accounting API Quotes endpoint
+ // Xero Quotes are the closest equivalent to Sales Orders
+ export const QuoteLineItemSchema = z.object({
+ LineItemID: z.string().uuid().optional(),
+ Description: z.string().optional(),
+ Quantity: z.number().optional(),
+ UnitAmount: z.number().optional(),
+ ItemCode: z.string().max(30).optional(),
+ AccountCode: z.string().optional(),
+ TaxType: z.string().optional(),
+ TaxAmount: z.number().optional(),
+ LineAmount: z.number().optional(),
+ DiscountRate: z.number().optional(),
+ DiscountAmount: z.number().optional()
+ });
+
+ export const QuoteContactSchema = z.object({
+ ContactID: z.string().uuid()
+ });
+
+ export const QuoteSchema = z.object({
+ QuoteID: z.string().uuid(),
+ QuoteNumber: z.string().max(255).optional(),
+ Reference: z.string().max(4000).optional(),
+ Terms: z.string().max(4000).optional(),
+ Contact: QuoteContactSchema,
+ LineItems: z.array(QuoteLineItemSchema).optional(),
+ Date: z.string().optional(),
+ ExpiryDate: z.string().optional(),
+ Status: z.enum([
+ "DRAFT",
+ "SENT",
+ "DECLINED",
+ "ACCEPTED",
+ "INVOICED",
+ "DELETED"
+ ]),
+ CurrencyCode: z.string().optional(),
+ CurrencyRate: z.number().optional(),
+ SubTotal: z.number().optional(),
+ TotalTax: z.number().optional(),
+ Total: z.number().optional(),
+ TotalDiscount: z.number().optional(),
+ Title: z.string().max(100).optional(),
+ Summary: z.string().max(3000).optional(),
+ LineAmountTypes: z.string().optional(),
+ UpdatedDateUTC: z.string()
+ });
+
+ export type QuoteLineItem = z.infer<typeof QuoteLineItemSchema>;
+ export type QuoteContact = z.infer<typeof QuoteContactSchema>;
+ export type Quote = z.infer<typeof QuoteSchema>;
+}
+
+export const parseDotnetDate = (date: Date | string) => {
+ if (typeof date === "string") {
+ const value = date.replace(/\/Date\((\d+)([-+]\d+)?\)\//, "$1");
+ return new Date(parseInt(value));
+ }
+
+ return date;
+};
+
+export const transformXeroPhones = (
+ contact: Xero.Contact
+): Pick<
+ Accounting.Contact,
+ "homePhone" | "workPhone" | "mobilePhone" | "fax"
+> => {
+ const phones = contact.Phones ?? [];
+
+ const homePhone = phones.find((p) => p.PhoneType === "DDI" && p.PhoneNumber);
+
+ const workPhone = phones.find(
+ (p) => p.PhoneType === "DEFAULT" && p.PhoneNumber
+ );
+ const mobilePhone = phones.find(
+ (p) => p.PhoneType === "MOBILE" && p.PhoneNumber
+ );
+ const fax = phones.find((p) => p.PhoneType === "FAX" && p.PhoneNumber);
+
+ return {
+ workPhone: workPhone?.PhoneNumber,
+ mobilePhone: mobilePhone?.PhoneNumber,
+ homePhone: homePhone?.PhoneNumber,
+ fax: fax?.PhoneNumber
+ };
+};
+
+export const transformXeroContact = (
+ contact: Xero.Contact,
+ companyId: string
+): Accounting.Contact => {
+ const firstName = contact.FirstName || "";
+ const lastName = contact.LastName || "";
+
+ const addresses = contact.Addresses ?? [];
+
+ const { workPhone, mobilePhone, homePhone } = transformXeroPhones(contact);
+
+ return {
+ id: contact.ContactID,
+ name: contact.Name,
+ firstName,
+ lastName,
+ companyId,
+ website: contact.Website,
+ currencyCode: contact.DefaultCurrency ?? "USD",
+ taxId: contact.TaxNumber,
+ email: contact.EmailAddress,
+ isCustomer: contact.IsCustomer,
+ isVendor: contact.IsSupplier,
+ addresses: addresses.map((a) => ({
+ label: a.AttentionTo,
+ line1: a.AddressLine1,
+ line2: a.AddressLine2,
+ city: a.City,
+ region: a.Region,
+ country: a.Country,
+ postalCode: a.PostalCode
+ })),
+ workPhone,
+ mobilePhone,
+ homePhone,
+ updatedAt: parseDotnetDate(contact.UpdatedDateUTC).toISOString(),
+ raw: contact
+ };
+};
diff --git a/packages/ee/src/accounting/providers/xero/provider.ts b/packages/ee/src/accounting/providers/xero/provider.ts
new file mode 100644
index 0000000000..5d943619a3
--- /dev/null
+++ b/packages/ee/src/accounting/providers/xero/provider.ts
@@ -0,0 +1,226 @@
+import { ProviderID } from "../../core/models";
+import type {
+ AccountingEntityType,
+ AuthProvider,
+ BaseProvider,
+ GlobalSyncConfig,
+ ProviderConfig,
+ ProviderCredentials
+} from "../../core/types";
+import { createOAuthClient, HTTPClient } from "../../core/utils";
+import type { Xero } from "./models";
+
+export interface ListContactsOptions {
+ page?: number;
+ modifiedSince?: Date;
+ includeArchived?: boolean;
+ summaryOnly?: boolean;
+}
+
+export interface ListContactsResponse {
+ contacts: Xero.Contact[];
+ hasMore: boolean;
+ page: number;
+}
+
+export interface ListItemsOptions {
+ page?: number;
+ modifiedSince?: Date;
+}
+
+export interface ListItemsResponse {
+ items: Xero.Item[];
+ hasMore: boolean;
+ page: number;
+}
+
+type XeroProviderConfig = ProviderConfig<{
+ clientId: string;
+ clientSecret: string;
+ redirectUri?: string;
+ tenantId?: string;
+}> & {
+ id: ProviderID.XERO;
+ accessToken?: string;
+ refreshToken?: string;
+};
+
+export class XeroProvider implements BaseProvider {
+ static id = ProviderID.XERO;
+
+ http: HTTPClient;
+ auth: AuthProvider;
+
+ private readonly syncConfig!: GlobalSyncConfig;
+
+ constructor(public config: Omit<XeroProviderConfig, "id">) {
+ this.syncConfig = config.syncConfig;
+ this.http = new HTTPClient("https://api.xero.com/api.xro/2.0");
+ this.auth = createOAuthClient({
+ clientId: config.clientId,
+ clientSecret: config.clientSecret,
+ accessToken: config.accessToken,
+ refreshToken: config.refreshToken,
+ redirectUri: config.redirectUri,
+ tokenUrl: "https://identity.xero.com/connect/token",
+ onTokenRefresh: config.onTokenRefresh,
+ getAuthUrl(scopes: string[], redirectURL: string): string {
+ const params = new URLSearchParams({
+ response_type: "code",
+ client_id: config.clientId,
+ redirect_uri: redirectURL,
+ scope: scopes.join(" "),
+ state: crypto.randomUUID()
+ });
+
+ return `https://login.xero.com/identity/connect/authorize?${params.toString()}`;
+ }
+ });
+ }
+
+ get id(): ProviderID.XERO {
+ // @ts-expect-error
+ return this.constructor.id;
+ }
+
+ getSyncConfig(entity: AccountingEntityType) {
+ return this.syncConfig.entities[entity];
+ }
+
+ authenticate(
+ code: string,
+ redirectUri: string
+ ): Promise<ProviderCredentials> {
+ return this.auth.exchangeCode(code, redirectUri);
+ }
+
+ async request<T>(method: string, url: string, options?: RequestInit) {
+ const { accessToken, ...creds } = this.auth.getCredentials();
+
+ const tenantId = creds.tenantId || this.config.tenantId;
+
+ const headers: Record<string, string> = {
+ Authorization: `Bearer ${accessToken}`,
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ ...((options?.headers ?? {}) as Record<string, string>)
+ };
+
+ if (tenantId) {
+ headers["xero-tenant-id"] = tenantId;
+ }
+
+ const response = await this.http.request<T>(method, url, {
+ ...options,
+ headers: headers
+ });
+
+ if (response.code === 401) {
+ await this.auth.refresh();
+
+ const c = this.auth.getCredentials();
+
+ const retryHeaders: Record<string, string> = {
+ ...headers,
+ Authorization: `Bearer ${c.accessToken}`
+ };
+
+ if (tenantId) {
+ retryHeaders["xero-tenant-id"] = tenantId;
+ }
+
+ return this.http.request<T>(method, url, {
+ ...options,
+ headers: retryHeaders
+ });
+ }
+
+ return response;
+ }
+
+ async validate(): Promise<boolean> {
+ try {
+ const response = await this.request("GET", `/Organisation`);
+ return !response.error;
+ } catch (error) {
+ console.error("Xero validate error:", error);
+ return false;
+ }
+ }
+
+ /**
+ * List all contacts from Xero with pagination support.
+ * Xero returns 100 contacts per page by default.
+ */
+ async listContacts(
+ options?: ListContactsOptions
+ ): Promise<ListContactsResponse> {
+ const page = options?.page ?? 1;
+ const params = new URLSearchParams();
+ params.set("page", String(page));
+
+ if (options?.summaryOnly) {
+ params.set("summarizeErrors", "true");
+ }
+
+ if (options?.includeArchived) {
+ params.set("includeArchived", "true");
+ }
+
+ // Only fetch contacts that are customers or suppliers — skip
+ // contacts that are neither (e.g. plain address book entries)
+ params.set("where", "IsCustomer==true OR IsSupplier==true");
+
+ const headers: Record<string, string> = {};
+ if (options?.modifiedSince) {
+ headers["If-Modified-Since"] = options.modifiedSince.toUTCString();
+ }
+
+ const response = await this.request<{ Contacts: Xero.Contact[] }>(
+ "GET",
+ `/Contacts?${params.toString()}`,
+ { headers }
+ );
+
+ if (response.error || !response.data?.Contacts) {
+ return { contacts: [], hasMore: false, page };
+ }
+
+ const contacts = response.data.Contacts;
+ // Xero returns 100 contacts per page - if we get exactly 100, there may be more
+ const hasMore = contacts.length === 100;
+
+ return { contacts, hasMore, page };
+ }
+
+ /**
+ * List all items from Xero with pagination support.
+ * Xero returns 100 items per page by default.
+ */
+ async listItems(options?: ListItemsOptions): Promise<ListItemsResponse> {
+ const page = options?.page ?? 1;
+ const params = new URLSearchParams();
+ params.set("page", String(page));
+
+ const headers: Record<string, string> = {};
+ if (options?.modifiedSince) {
+ headers["If-Modified-Since"] = options.modifiedSince.toUTCString();
+ }
+
+ const response = await this.request<{ Items: Xero.Item[] }>(
+ "GET",
+ `/Items?${params.toString()}`,
+ { headers }
+ );
+
+ if (response.error || !response.data?.Items) {
+ return { items: [], hasMore: false, page };
+ }
+
+ const items = response.data.Items;
+ // Xero returns 100 items per page - if we get exactly 100, there may be more
+ const hasMore = items.length === 100;
+
+ return { items, hasMore, page };
+ }
+}
diff --git a/packages/ee/src/exchange-rates/config.tsx b/packages/ee/src/exchange-rates/config.tsx
index 31d8b06141..e78cb10b3c 100644
--- a/packages/ee/src/exchange-rates/config.tsx
+++ b/packages/ee/src/exchange-rates/config.tsx
@@ -1,9 +1,9 @@
import { cn } from "@carbon/react";
import type { SVGProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const ExchangeRates: IntegrationConfig = {
+export const ExchangeRates = defineIntegration({
name: "Exchange Rates",
id: "exchange-rates-v1",
active: true,
@@ -16,7 +16,7 @@ export const ExchangeRates: IntegrationConfig = {
images: [],
settings: [],
schema: z.object({})
-};
+});
function Logo(props: SVGProps<SVGSVGElement>) {
return (
diff --git a/packages/ee/src/fns.ts b/packages/ee/src/fns.ts
new file mode 100644
index 0000000000..de3da25e49
--- /dev/null
+++ b/packages/ee/src/fns.ts
@@ -0,0 +1,72 @@
+import type { Integration, IntegrationOptions } from "./types";
+
+/**
+ * Ensures the code is running on the server.
+ * Throws an error if called from the browser.
+ */
+const withServerOnly = () => {
+ if (typeof document !== "undefined") {
+ throw new Error(
+ `Server only integration hooks cannot be used in the browser`
+ );
+ }
+};
+
+/**
+ * Defines an integration with type-safe configuration and server-only hook protection.
+ *
+ * This function:
+ * - Validates required fields at definition time
+ * - Wraps server-only hooks (onInstall, onUninstall, onHealthcheck) with browser guards
+ * - Preserves full type information for the integration config
+ *
+ * @example
+ * ```ts
+ * const MyIntegration = defineIntegration({
+ * name: "My Integration",
+ * id: "my-integration",
+ * active: true,
+ * category: "Tools",
+ * logo: MyLogo,
+ * description: "...",
+ * shortDescription: "...",
+ * images: [],
+ * settings: [],
+ * schema: z.object({}),
+ * onInstall: async (companyId) => { ... },
+ * onHealthcheck: async (companyId, metadata) => { ... },
+ * });
+ * ```
+ */
+export function defineIntegration<T extends IntegrationOptions>(
+ options: T
+): Integration<T> {
+ // Validate required fields at definition time
+ if (!options.id) {
+ throw new Error(`Integration must have an 'id' defined`);
+ }
+ if (!options.name) {
+ throw new Error(`Integration '${options.id}' must have a 'name' defined`);
+ }
+ if (options.oauth && !options.oauth.clientId) {
+ throw new Error(
+ `Integration '${options.id}' has OAuth config but missing clientId`
+ );
+ }
+
+ return {
+ ...options,
+ get onInstall() {
+ withServerOnly();
+ return options.onInstall;
+ },
+ get onUninstall() {
+ withServerOnly();
+ return options.onUninstall;
+ },
+ get onHealthcheck() {
+ withServerOnly();
+ return options.onHealthcheck;
+ }
+ } as Integration<T>;
+}
diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.ts
index 066f85e2f3..0f467f2bda 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -7,11 +7,23 @@ import { QuickBooks } from "./quickbooks/config";
import { Resend } from "./resend/config";
import { Sage } from "./sage/config";
import { Slack } from "./slack/config";
+
import { Xero } from "./xero/config";
import { Zapier } from "./zapier/config";
+export { defineIntegration } from "./fns";
export { Resend } from "./resend/config";
-export type { IntegrationConfig } from "./types";
+export type {
+ Integration,
+ IntegrationAction,
+ IntegrationClientHooks,
+ IntegrationConfig,
+ IntegrationOptions,
+ IntegrationServerHooks,
+ IntegrationSetting,
+ IntegrationSettingOption,
+ OAuthConfig
+} from "./types";
export const integrations = [
ExchangeRates,
@@ -34,3 +46,12 @@ export { QuickBooks } from "./quickbooks/config";
export { Slack } from "./slack/config";
export * from "./slack/lib/messages";
export { Xero } from "./xero/config";
+
+/**
+ * Retrieves an integration configuration by its unique ID.
+ * @param id - The unique identifier of the integration
+ * @returns The integration configuration if found, undefined otherwise
+ */
+export const getIntegrationConfigById = (id: string) => {
+ return integrations.find((integration) => integration.id === id);
+};
diff --git a/packages/ee/src/linear/config.tsx b/packages/ee/src/linear/config.tsx
index a30a0e735d..fe56a37270 100644
--- a/packages/ee/src/linear/config.tsx
+++ b/packages/ee/src/linear/config.tsx
@@ -2,10 +2,10 @@ import { Copy, Input, InputGroup, InputRightElement } from "@carbon/react";
import { isBrowser } from "@carbon/utils";
import type { SVGProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
import { getLinearClient } from "./lib";
-export const Linear: IntegrationConfig = {
+export const Linear = defineIntegration({
name: "Linear",
id: "linear",
active: true,
@@ -25,7 +25,7 @@ export const Linear: IntegrationConfig = {
value: ""
}
],
- healthcheck,
+ onHealthcheck: healthcheck,
schema: z.object({
apiKey: z
.string()
@@ -34,7 +34,7 @@ export const Linear: IntegrationConfig = {
message: "Linear API Key must start with 'lin_api'"
})
})
-};
+});
function SetupInstructions({ companyId }: { companyId: string }) {
const webhookUrl = isBrowser
diff --git a/packages/ee/src/linear/lib/service.ts b/packages/ee/src/linear/lib/service.ts
index d29f285104..4d8226aac6 100644
--- a/packages/ee/src/linear/lib/service.ts
+++ b/packages/ee/src/linear/lib/service.ts
@@ -35,7 +35,7 @@ export async function getLinearIntegration(
.limit(1);
}
-export function linkActionToLinearIssue(
+export async function linkActionToLinearIssue(
client: SupabaseClient<Database>,
companyId: string,
input: {
@@ -60,9 +60,6 @@ export function linkActionToLinearIssue(
}
const updateData: Record<string, any> = {
- externalId: {
- linear: data
- },
assignee: input.assignee,
status: mapLinearStatusToCarbonStatus(data.state.type!),
dueDate: data.dueDate
@@ -73,12 +70,32 @@ export function linkActionToLinearIssue(
updateData.notes = notes;
}
- return client
+ // Update the task fields
+ const result = await client
.from("nonConformanceActionTask")
.update(updateData)
.eq("companyId", companyId)
.eq("id", input.actionId)
.select("nonConformanceId");
+
+ // Upsert the Linear mapping in externalIntegrationMapping
+ await client
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", input.actionId)
+ .eq("integration", "linear");
+
+ await client.from("externalIntegrationMapping").insert({
+ entityType: "nonConformanceActionTask",
+ entityId: input.actionId,
+ integration: "linear",
+ externalId: data.id,
+ metadata: data as any,
+ companyId
+ });
+
+ return result;
}
export const getCompanyEmployees = async (
@@ -96,7 +113,7 @@ export const getCompanyEmployees = async (
return users.data ?? [];
};
-export function unlinkActionFromLinearIssue(
+export async function unlinkActionFromLinearIssue(
client: SupabaseClient<Database>,
companyId: string,
input: {
@@ -104,16 +121,20 @@ export function unlinkActionFromLinearIssue(
assignee?: string | null;
}
) {
+ // Delete the Linear mapping from externalIntegrationMapping
+ await client
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", input.actionId)
+ .eq("integration", "linear");
+
+ // Return the nonConformanceId for the action task
return client
.from("nonConformanceActionTask")
- .update({
- externalId: {
- linear: undefined
- }
- })
+ .select("nonConformanceId")
.eq("companyId", companyId)
- .eq("id", input.actionId)
- .select("nonConformanceId");
+ .eq("id", input.actionId);
}
export const getLinearIssueFromExternalId = async (
@@ -121,18 +142,18 @@ export const getLinearIssueFromExternalId = async (
companyId: string,
actionId: string
) => {
- const { data: action } = await client
- .from("nonConformanceActionTask")
- .select("externalId")
+ const { data: mapping } = await client
+ .from("externalIntegrationMapping")
+ .select("metadata")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("entityId", actionId)
+ .eq("integration", "linear")
.eq("companyId", companyId)
- .eq("id", actionId)
.maybeSingle();
- if (!action) return null;
+ if (!mapping) return null;
- const { data } = LinearIssueSchema.safeParse(
- (action.externalId as any)?.linear
- );
+ const { data } = LinearIssueSchema.safeParse(mapping.metadata);
if (!data) return null;
diff --git a/packages/ee/src/notifications/services/linear.ts b/packages/ee/src/notifications/services/linear.ts
index b84ce2581d..c34030e516 100644
--- a/packages/ee/src/notifications/services/linear.ts
+++ b/packages/ee/src/notifications/services/linear.ts
@@ -1,11 +1,13 @@
import { getUser } from "@carbon/auth";
import type { Database } from "@carbon/database";
import type { SupabaseClient } from "@supabase/supabase-js";
+import type {
+ TiptapDocument,
+} from "../../linear/lib";
import {
getLinearClient,
getLinearIssueFromExternalId,
mapCarbonStatusToLinearStatus,
- type TiptapDocument,
tiptapToMarkdown
} from "../../linear/lib";
import type { NotificationEvent, NotificationService } from "../types";
diff --git a/packages/ee/src/onshape/config.tsx b/packages/ee/src/onshape/config.tsx
index 97a833be8b..a40da5af4e 100644
--- a/packages/ee/src/onshape/config.tsx
+++ b/packages/ee/src/onshape/config.tsx
@@ -1,9 +1,9 @@
import { Badge } from "@carbon/react";
import type { SVGProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Onshape: IntegrationConfig = {
+export const Onshape = defineIntegration({
name: "Onshape",
id: "onshape",
active: true,
@@ -57,7 +57,7 @@ export const Onshape: IntegrationConfig = {
secretKey: z.string().min(1, { message: "Secret Key is required" }),
companyId: z.string().min(1, { message: "Company ID is required" })
})
-};
+});
function SetupInstructions({ companyId }: { companyId: string }) {
return (
diff --git a/packages/ee/src/paperless-parts/config.tsx b/packages/ee/src/paperless-parts/config.tsx
index 44865e77c4..ff2b62d283 100644
--- a/packages/ee/src/paperless-parts/config.tsx
+++ b/packages/ee/src/paperless-parts/config.tsx
@@ -3,9 +3,9 @@ import { isBrowser } from "@carbon/utils";
import type { SVGProps } from "react";
import { z } from "zod";
import { zfd } from "zod-form-data";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const PaperlessParts: IntegrationConfig = {
+export const PaperlessParts = defineIntegration({
name: "Paperless Parts",
id: "paperless-parts",
active: true,
@@ -73,7 +73,7 @@ export const PaperlessParts: IntegrationConfig = {
billOfProcessBlackList: z.array(z.string()).optional(),
usePaperlessOrderNumber: zfd.checkbox()
})
-};
+});
function SetupInstructions({ companyId }: { companyId: string }) {
const webhookUrl = isBrowser
diff --git a/packages/ee/src/paperless-parts/lib/lib.ts b/packages/ee/src/paperless-parts/lib/lib.ts
index 0ef4094085..dc4506d760 100644
--- a/packages/ee/src/paperless-parts/lib/lib.ts
+++ b/packages/ee/src/paperless-parts/lib/lib.ts
@@ -28,6 +28,49 @@ import type {
} from "./schemas";
import { calculatePromisedDate } from "./utils";
+async function lookupEntityByPaperlessId(
+ carbon: SupabaseClient<Database>,
+ entityType: string,
+ integration: string,
+ externalId: string,
+ companyId: string
+): Promise<string | null> {
+ const { data } = await carbon
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("entityType", entityType)
+ .eq("integration", integration)
+ .eq("externalId", externalId)
+ .eq("companyId", companyId)
+ .maybeSingle();
+ return data?.entityId ?? null;
+}
+
+async function createPaperlessMapping(
+ carbon: SupabaseClient<Database>,
+ entityType: string,
+ entityId: string,
+ integration: string,
+ externalId: string,
+ companyId: string
+): Promise<void> {
+ await carbon
+ .from("externalIntegrationMapping")
+ .delete()
+ .eq("entityType", entityType)
+ .eq("entityId", entityId)
+ .eq("integration", integration);
+
+ await carbon.from("externalIntegrationMapping").insert({
+ entityType,
+ entityId,
+ integration,
+ externalId: String(externalId),
+ companyId,
+ allowDuplicateExternalId: false
+ });
+}
+
/**
* Strip special characters from filename for safe storage
*/
@@ -975,15 +1018,16 @@ export async function getCustomerIdAndContactId(
if (contact.account) {
const paperlessPartsCustomerId = contact.account?.id;
- const existingCustomer = await carbon
- .from("customer")
- .select("id")
- .eq("companyId", company.id)
- .eq("externalId->>paperlessPartsId", String(paperlessPartsCustomerId!))
- .maybeSingle();
+ const existingCustomerId = await lookupEntityByPaperlessId(
+ carbon,
+ "customer",
+ "paperlessPartsId",
+ String(paperlessPartsCustomerId!),
+ company.id
+ );
- if (existingCustomer.data) {
- customerId = existingCustomer.data.id;
+ if (existingCustomerId) {
+ customerId = existingCustomerId;
} else {
const customerName = contact.account?.name!;
@@ -996,27 +1040,17 @@ export async function getCustomerIdAndContactId(
.maybeSingle();
if (existingCustomerByName.data) {
- // Update the existing customer with the external ID
- const updatedCustomer = await carbon
- .from("customer")
- .update({
- externalId: {
- paperlessPartsId: contact.account.id
- }
- })
- .eq("id", existingCustomerByName.data.id)
- .select()
- .single();
-
- if (updatedCustomer.error || !updatedCustomer.data) {
- console.error(
- "Failed to update customer externalId in Carbon",
- updatedCustomer.error
- );
- throw new Error("Failed to update customer externalId in Carbon");
- }
+ customerId = existingCustomerByName.data.id;
- customerId = updatedCustomer.data.id;
+ // Create the mapping for the existing customer
+ await createPaperlessMapping(
+ carbon,
+ "customer",
+ customerId,
+ "paperlessPartsId",
+ String(contact.account.id),
+ company.id
+ );
} else {
const newCustomer = await carbon
.from("customer")
@@ -1024,9 +1058,6 @@ export async function getCustomerIdAndContactId(
{
companyId: company.id,
name: customerName,
- externalId: {
- paperlessPartsId: contact.account.id
- },
currencyCode: company.baseCurrencyCode,
createdBy
},
@@ -1046,6 +1077,16 @@ export async function getCustomerIdAndContactId(
}
customerId = newCustomer.data.id;
+
+ // Create the mapping for the new customer
+ await createPaperlessMapping(
+ carbon,
+ "customer",
+ customerId,
+ "paperlessPartsId",
+ String(contact.account.id),
+ company.id
+ );
}
}
} else {
@@ -1181,18 +1222,19 @@ export async function getCustomerIdAndContactId(
}
// Check if customer already exists in Carbon with this paperless account ID (if we have one)
- let existingCustomerByPaperlessId = null;
+ let existingCustomerIdByPaperless: string | null = null;
if (paperlessPartsAccountId > 0) {
- existingCustomerByPaperlessId = await carbon
- .from("customer")
- .select("id")
- .eq("companyId", company.id)
- .eq("externalId->>paperlessPartsId", String(paperlessPartsAccountId))
- .maybeSingle();
+ existingCustomerIdByPaperless = await lookupEntityByPaperlessId(
+ carbon,
+ "customer",
+ "paperlessPartsId",
+ String(paperlessPartsAccountId),
+ company.id
+ );
}
- if (existingCustomerByPaperlessId?.data) {
- customerId = existingCustomerByPaperlessId.data.id;
+ if (existingCustomerIdByPaperless) {
+ customerId = existingCustomerIdByPaperless;
} else {
// Try to find existing customer by name in Carbon
const existingCustomerByName = await carbon
@@ -1203,30 +1245,18 @@ export async function getCustomerIdAndContactId(
.maybeSingle();
if (existingCustomerByName.data) {
- // Update the existing customer with the external ID (if we have a valid Paperless Parts account ID)
- if (paperlessPartsAccountId > 0) {
- const updatedCustomer = await carbon
- .from("customer")
- .update({
- externalId: {
- paperlessPartsId: paperlessPartsAccountId
- }
- })
- .eq("id", existingCustomerByName.data.id)
- .select()
- .single();
+ customerId = existingCustomerByName.data.id;
- if (updatedCustomer.error || !updatedCustomer.data) {
- console.error(
- "Failed to update customer externalId in Carbon",
- updatedCustomer.error
- );
- throw new Error("Failed to update customer externalId in Carbon");
- }
-
- customerId = updatedCustomer.data.id;
- } else {
- customerId = existingCustomerByName.data.id;
+ // Create the mapping if we have a valid Paperless Parts account ID
+ if (paperlessPartsAccountId > 0) {
+ await createPaperlessMapping(
+ carbon,
+ "customer",
+ customerId,
+ "paperlessPartsId",
+ String(paperlessPartsAccountId),
+ company.id
+ );
}
} else {
// Create a new customer in Carbon
@@ -1237,13 +1267,6 @@ export async function getCustomerIdAndContactId(
createdBy
};
- // Only add externalId if we have a valid Paperless Parts account ID
- if (paperlessPartsAccountId > 0) {
- customerData.externalId = {
- paperlessPartsId: paperlessPartsAccountId
- };
- }
-
const newCustomer = await carbon
.from("customer")
.upsert(customerData, {
@@ -1261,34 +1284,48 @@ export async function getCustomerIdAndContactId(
}
customerId = newCustomer.data.id;
+
+ // Create the mapping if we have a valid Paperless Parts account ID
+ if (paperlessPartsAccountId > 0) {
+ await createPaperlessMapping(
+ carbon,
+ "customer",
+ customerId,
+ "paperlessPartsId",
+ String(paperlessPartsAccountId),
+ company.id
+ );
+ }
}
}
}
// Get the contact ID from Carbon based on the Paperless Parts ID
const paperlessPartsContactId = contact.id;
- const existingCustomerContact = await carbon
- .from("customerContact")
- .select(
- `
- id,
- contact!inner (
- id,
- companyId,
- externalId
- )
- `
- )
- .eq("contact.companyId", company.id)
- .eq(
- "contact.externalId->>paperlessPartsId",
- String(paperlessPartsContactId!)
- )
- .maybeSingle();
- if (existingCustomerContact.data) {
- customerContactId = existingCustomerContact.data.id;
- } else {
+ // Look up the contact via the mapping table
+ const existingContactId = await lookupEntityByPaperlessId(
+ carbon,
+ "contact",
+ "paperlessPartsId",
+ String(paperlessPartsContactId!),
+ company.id
+ );
+
+ if (existingContactId) {
+ // Find the customerContact for this contact
+ const existingCustomerContact = await carbon
+ .from("customerContact")
+ .select("id")
+ .eq("contactId", existingContactId)
+ .maybeSingle();
+
+ if (existingCustomerContact.data) {
+ customerContactId = existingCustomerContact.data.id;
+ }
+ }
+
+ if (!customerContactId) {
// If there is no matching contact in Carbon, check if contact exists by email first
const existingContactByEmail = await carbon
.from("contact")
@@ -1301,15 +1338,12 @@ export async function getCustomerIdAndContactId(
let contactId: string;
if (existingContactByEmail.data) {
- // Update the existing contact with the external ID
+ // Update the existing contact
const updatedContact = await carbon
.from("contact")
.update({
firstName: contact.first_name!,
- lastName: contact.last_name!,
- externalId: {
- paperlessPartsId: contact.id
- }
+ lastName: contact.last_name!
})
.eq("id", existingContactByEmail.data.id)
.select()
@@ -1324,6 +1358,16 @@ export async function getCustomerIdAndContactId(
}
contactId = updatedContact.data.id;
+
+ // Create the mapping for the existing contact
+ await createPaperlessMapping(
+ carbon,
+ "contact",
+ contactId,
+ "paperlessPartsId",
+ String(contact.id),
+ company.id
+ );
} else {
// Create a new contact in Carbon
const newContact = await carbon
@@ -1333,10 +1377,7 @@ export async function getCustomerIdAndContactId(
firstName: contact.first_name!,
lastName: contact.last_name!,
email: contact.email!,
- isCustomer: true,
- externalId: {
- paperlessPartsId: contact.id
- }
+ isCustomer: true
})
.select()
.single();
@@ -1350,6 +1391,16 @@ export async function getCustomerIdAndContactId(
}
contactId = newContact.data.id;
+
+ // Create the mapping for the new contact
+ await createPaperlessMapping(
+ carbon,
+ "contact",
+ contactId,
+ "paperlessPartsId",
+ String(contact.id),
+ company.id
+ );
}
// Check if customerContact already exists for this customer and contact
@@ -1408,15 +1459,16 @@ export async function getCustomerLocationIds(
if (billingInfo) {
const paperlessPartsBillingId = billingInfo.id;
- const existingInvoiceLocation = await carbon
- .from("customerLocation")
- .select("id")
- .eq("customerId", customerId)
- .eq("externalId->>paperlessPartsId", String(paperlessPartsBillingId!))
- .maybeSingle();
+ const existingInvoiceLocationId = await lookupEntityByPaperlessId(
+ carbon,
+ "customerLocation",
+ "paperlessPartsId",
+ String(paperlessPartsBillingId!),
+ company.id
+ );
- if (existingInvoiceLocation.data) {
- invoiceLocationId = existingInvoiceLocation.data.id;
+ if (existingInvoiceLocationId) {
+ invoiceLocationId = existingInvoiceLocationId;
} else {
// Try to find existing address by addressLine1 and city
const existingAddress = await carbon
@@ -1500,10 +1552,7 @@ export async function getCustomerLocationIds(
? `${billingInfo.city}, ${billingInfo.state}`
: billingInfo.city || billingInfo.state || "",
customerId,
- addressId,
- externalId: {
- paperlessPartsId: billingInfo.id
- }
+ addressId
})
.select()
.single();
@@ -1515,6 +1564,16 @@ export async function getCustomerLocationIds(
}
invoiceLocationId = newCustomerLocation.data.id;
+
+ // Create the mapping for the new billing location
+ await createPaperlessMapping(
+ carbon,
+ "customerLocation",
+ invoiceLocationId,
+ "paperlessPartsId",
+ String(billingInfo.id),
+ company.id
+ );
}
}
}
@@ -1523,15 +1582,16 @@ export async function getCustomerLocationIds(
if (shippingInfo) {
const paperlessPartsShippingId = shippingInfo.id;
- const existingShipmentLocation = await carbon
- .from("customerLocation")
- .select("id")
- .eq("customerId", customerId)
- .eq("externalId->>paperlessPartsId", String(paperlessPartsShippingId!))
- .maybeSingle();
+ const existingShipmentLocationId = await lookupEntityByPaperlessId(
+ carbon,
+ "customerLocation",
+ "paperlessPartsId",
+ String(paperlessPartsShippingId!),
+ company.id
+ );
- if (existingShipmentLocation.data) {
- shipmentLocationId = existingShipmentLocation.data.id;
+ if (existingShipmentLocationId) {
+ shipmentLocationId = existingShipmentLocationId;
} else {
// Try to find existing address by addressLine1 and city
const existingAddress = await carbon
@@ -1615,10 +1675,7 @@ export async function getCustomerLocationIds(
.insert({
name,
customerId,
- addressId,
- externalId: {
- paperlessPartsId: shippingInfo.id
- }
+ addressId
})
.select()
.single();
@@ -1630,6 +1687,16 @@ export async function getCustomerLocationIds(
}
shipmentLocationId = newCustomerLocation.data.id;
+
+ // Create the mapping for the new shipping location
+ await createPaperlessMapping(
+ carbon,
+ "customerLocation",
+ shipmentLocationId,
+ "paperlessPartsId",
+ String(shippingInfo.id),
+ company.id
+ );
}
}
}
@@ -1755,19 +1822,28 @@ export async function getPaperlessPart(
paperlessPartName
} = args;
- const existingPart = await carbon
- .from("item")
- .select("id, readableId, revision")
- .eq("companyId", companyId)
- .eq("externalId->>paperlessPartsId", String(paperlessPartsId))
- .maybeSingle();
+ const existingItemId = await lookupEntityByPaperlessId(
+ carbon,
+ "item",
+ "paperlessPartsId",
+ String(paperlessPartsId),
+ companyId
+ );
- if (existingPart.data) {
- return {
- itemId: existingPart.data.id,
- partId: existingPart.data.readableId,
- revision: existingPart.data.revision
- };
+ if (existingItemId) {
+ const existingItem = await carbon
+ .from("item")
+ .select("id, readableId, revision")
+ .eq("id", existingItemId)
+ .single();
+
+ if (existingItem.data) {
+ return {
+ itemId: existingItem.data.id,
+ partId: existingItem.data.readableId,
+ revision: existingItem.data.revision
+ };
+ }
}
if (paperlessPartNumber && paperlessPartRevision && paperlessPartName) {
@@ -2151,10 +2227,7 @@ export async function createPartFromComponent(
unitOfMeasureCode: "EA",
active: true,
companyId,
- createdBy,
- externalId: {
- paperlessPartsId: component.part_uuid
- }
+ createdBy
})
.select("id")
.single();
@@ -2166,6 +2239,16 @@ export async function createPartFromComponent(
const itemId = itemInsert.data.id;
+ // Create the mapping for the new item
+ await createPaperlessMapping(
+ carbon,
+ "item",
+ itemId,
+ "paperlessPartsId",
+ String(component.part_uuid),
+ companyId
+ );
+
// Update itemCost for purchased components
if (isPurchased && (component as any).purchased_component?.piece_price) {
const unitCost = parseFloat(
@@ -2229,11 +2312,19 @@ export async function createPartFromComponent(
const partInsert = await carbon.from("part").upsert({
id: partId,
companyId,
- createdBy,
- externalId: {
- paperlessPartsId: component.part_uuid
- }
+ createdBy
});
+
+ // Create the mapping for the part
+ await createPaperlessMapping(
+ carbon,
+ "part",
+ partId,
+ "paperlessPartsId",
+ String(component.part_uuid),
+ companyId
+ );
+
let makeMethod: { data?: { id: string } | null; error?: any } = {
data: null
};
diff --git a/packages/ee/src/quickbooks/config.tsx b/packages/ee/src/quickbooks/config.tsx
index 61f9c540ae..cfde7d942f 100644
--- a/packages/ee/src/quickbooks/config.tsx
+++ b/packages/ee/src/quickbooks/config.tsx
@@ -1,9 +1,9 @@
import { QUICKBOOKS_CLIENT_ID } from "@carbon/auth";
import type { ComponentProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const QuickBooks: IntegrationConfig = {
+export const QuickBooks = defineIntegration({
name: "QuickBooks",
id: "quickbooks",
active: false,
@@ -18,7 +18,7 @@ export const QuickBooks: IntegrationConfig = {
schema: z.object({}),
oauth: {
authUrl: "https://appcenter.intuit.com/connect/oauth2",
- clientId: QUICKBOOKS_CLIENT_ID!,
+ clientId: QUICKBOOKS_CLIENT_ID ?? "",
redirectUri: "/api/integrations/quickbooks/oauth",
scopes: [
"com.intuit.quickbooks.accounting",
@@ -26,7 +26,7 @@ export const QuickBooks: IntegrationConfig = {
],
tokenUrl: "https://oauth.platform.intuit.com/oauth2/v1/tokens/bearer"
}
-};
+});
function Logo(props: ComponentProps<"svg">) {
return (
diff --git a/packages/ee/src/radan/config.tsx b/packages/ee/src/radan/config.tsx
index 2ac82f97d1..1e8af176b8 100644
--- a/packages/ee/src/radan/config.tsx
+++ b/packages/ee/src/radan/config.tsx
@@ -1,8 +1,8 @@
import type { SVGProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Radan: IntegrationConfig = {
+export const Radan = defineIntegration({
name: "Radan",
id: "radan",
active: true,
@@ -29,7 +29,7 @@ export const Radan: IntegrationConfig = {
.min(1, { message: "Processes are required" })
.optional()
})
-};
+});
function SetupInstructions({ companyId }: { companyId: string }) {
return (
diff --git a/packages/ee/src/resend/config.tsx b/packages/ee/src/resend/config.tsx
index a550dbb9e1..af5b92c26e 100644
--- a/packages/ee/src/resend/config.tsx
+++ b/packages/ee/src/resend/config.tsx
@@ -1,9 +1,9 @@
import { cn } from "@carbon/react";
import type { SVGProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Resend: IntegrationConfig = {
+export const Resend = defineIntegration({
name: "Resend",
id: "resend",
active: true,
@@ -34,7 +34,7 @@ export const Resend: IntegrationConfig = {
apiKey: z.string().min(1, { message: "API Key is required" }),
fromEmail: z.string().email()
})
-};
+});
function Logo(props: SVGProps<SVGSVGElement>) {
return (
diff --git a/packages/ee/src/sage/config.tsx b/packages/ee/src/sage/config.tsx
index 97f8868e3e..cd98264f55 100644
--- a/packages/ee/src/sage/config.tsx
+++ b/packages/ee/src/sage/config.tsx
@@ -1,8 +1,8 @@
import type { ComponentProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Sage: IntegrationConfig = {
+export const Sage = defineIntegration({
name: "Sage Intacct",
id: "sage",
active: false,
@@ -15,7 +15,7 @@ export const Sage: IntegrationConfig = {
images: [],
settings: [],
schema: z.object({})
-};
+});
function Logo(props: ComponentProps<"svg">) {
return (
diff --git a/packages/ee/src/slack/config.tsx b/packages/ee/src/slack/config.tsx
index 827c853c55..d4ad41cee6 100644
--- a/packages/ee/src/slack/config.tsx
+++ b/packages/ee/src/slack/config.tsx
@@ -1,8 +1,8 @@
import { CONTROLLED_ENVIRONMENT } from "@carbon/auth";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Slack: IntegrationConfig = {
+export const Slack = defineIntegration({
name: "Slack",
id: "slack",
category: "Assistant",
@@ -14,7 +14,7 @@ export const Slack: IntegrationConfig = {
images: [],
settings: [],
schema: z.object({}),
- onInitialize: async () => {
+ onClientInstall: async () => {
const response = await fetch("/api/integrations/slack/install").then(
(res) => res.json()
);
@@ -46,10 +46,8 @@ export const Slack: IntegrationConfig = {
};
window.addEventListener("message", listener);
- },
- // biome-ignore lint/suspicious/noEmptyBlockStatements: suppressed due to migration
- onUninstall: () => {}
-};
+ }
+});
function Logo() {
return (
diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.ts
index fc25231244..c22ab9df3c 100644
--- a/packages/ee/src/types.ts
+++ b/packages/ee/src/types.ts
@@ -1,35 +1,153 @@
import type { ZodType } from "zod";
+export type IntegrationAction = {
+ id: string;
+ label: string;
+ description: string;
+ endpoint: string;
+};
+
+/**
+ * Enhanced option type for select fields.
+ * Supports both simple strings (backwards compatible) and objects with label/description.
+ */
+export type IntegrationSettingOption =
+ | string
+ | {
+ value: string;
+ label: string;
+ description?: string;
+ };
+
+/**
+ * Definition for an integration setting field.
+ */
+export type IntegrationSetting = {
+ /** Field name used in form data and metadata storage */
+ name: string;
+ /** Display label for the field */
+ label: string;
+ /** Optional help text shown below the field */
+ description?: string;
+ /** Optional group name for organizing settings into collapsible sections */
+ group?: string;
+ /** Field input type */
+ type: "text" | "switch" | "processes" | "options" | "array";
+ /** Options for 'options' type fields */
+ listOptions?: IntegrationSettingOption[];
+ /** Whether the field is required */
+ required: boolean;
+ /** Default value for the field */
+ value: unknown;
+};
+
+/**
+ * OAuth configuration for integrations that require OAuth authentication.
+ * All fields are required to ensure proper OAuth flow.
+ */
+export type OAuthConfig = {
+ /** The OAuth authorization URL */
+ authUrl: string;
+ /** The OAuth client ID (must be defined, not undefined) */
+ clientId: string;
+ /** The redirect URI path (relative to the app origin) */
+ redirectUri: string;
+ /** The OAuth scopes required by the integration */
+ scopes: string[];
+ /** The OAuth token exchange URL */
+ tokenUrl: string;
+};
+
+/**
+ * Client-side lifecycle hooks.
+ * These run in the browser when the user interacts with integration install/uninstall.
+ */
+export type IntegrationClientHooks = {
+ /**
+ * Called on the client when user clicks Install button (before any server action).
+ * Use this for OAuth popup flows, custom UI, or client-side initialization.
+ */
+ onClientInstall?: () => void | Promise<void>;
+ /**
+ * Called on the client when user clicks Uninstall button (before server action).
+ * Use this for client-side cleanup or confirmation flows.
+ */
+ onClientUninstall?: () => void | Promise<void>;
+};
+
+/**
+ * Server-side lifecycle hooks.
+ * These run only on the server and are protected from browser execution.
+ */
+export type IntegrationServerHooks = {
+ /**
+ * Server-side hook called after the integration is activated/installed.
+ * Use this for creating database subscriptions, webhooks, or other server setup.
+ */
+ onInstall?: (companyId: string) => void | Promise<void>;
+ /**
+ * Server-side hook called after the integration is deactivated/uninstalled.
+ * Use this for cleaning up server resources, webhooks, etc.
+ */
+ onUninstall?: (companyId: string) => void | Promise<void>;
+ /**
+ * Server-side validation hook to check integration health/credentials.
+ * Returns true if the integration is healthy, false otherwise.
+ */
+ onHealthcheck?: (
+ companyId: string,
+ metadata: Record<string, unknown>
+ ) => Promise<boolean>;
+};
+
+/**
+ * Base configuration for an integration (UI and metadata only).
+ */
export type IntegrationConfig = {
+ /** Display name of the integration */
name: string;
+ /** Unique identifier used in database and URLs */
id: string;
+ /** Whether the integration is available for use */
active: boolean;
+ /** Category for grouping in the UI (e.g., "Accounting", "CAD", "Email") */
category: string;
+ /** Logo component for the integration */
logo: React.FC<React.ComponentProps<"svg">>;
+ /** Brief one-liner description */
shortDescription: string;
+ /** Full description explaining the integration */
description: string;
+ /** Optional component rendering setup instructions */
setupInstructions?: React.FC<{ companyId: string }>;
+ /** Marketing/preview images */
images: string[];
- settings: {
- name: string;
- label: string;
- type: "text" | "switch" | "processes" | "options" | "array";
- listOptions?: string[];
- required: boolean;
- value: unknown;
- }[];
+ /** Configurable settings fields */
+ settings: IntegrationSetting[];
+ /** Zod schema for validating settings */
schema: ZodType;
- oauth?: {
- authUrl: string;
- clientId: string;
- redirectUri: string;
- scopes: string[];
- tokenUrl: string;
- };
- healthcheck?: (
- companyId: string,
- metadata: Record<string, unknown>
- ) => Promise<boolean>;
- onInitialize?: () => void | Promise<void>;
- onUninstall?: () => void | Promise<void>;
+ /** OAuth configuration (if the integration uses OAuth) */
+ oauth?: OAuthConfig;
+ /** Available actions that can be triggered on an installed integration */
+ actions?: IntegrationAction[];
};
+
+/**
+ * Full integration options including all hooks.
+ * This is what you pass to defineIntegration().
+ */
+export interface IntegrationOptions
+ extends IntegrationConfig,
+ IntegrationClientHooks,
+ IntegrationServerHooks {}
+
+/**
+ * The return type of defineIntegration().
+ * Server hooks are wrapped with getters that enforce server-only execution.
+ */
+export type Integration<T extends IntegrationOptions = IntegrationOptions> =
+ Omit<T, keyof IntegrationServerHooks> & {
+ readonly onInstall: T["onInstall"];
+ readonly onUninstall: T["onUninstall"];
+ readonly onHealthcheck: T["onHealthcheck"];
+ };
diff --git a/packages/ee/src/xero/config.tsx b/packages/ee/src/xero/config.tsx
index 19678d0760..48740e2d78 100644
--- a/packages/ee/src/xero/config.tsx
+++ b/packages/ee/src/xero/config.tsx
@@ -1,12 +1,39 @@
-import { XERO_CLIENT_ID } from "@carbon/auth";
+import { getCarbonServiceRole, NODE_ENV, XERO_CLIENT_ID } from "@carbon/auth";
+import type { CreateSubscriptionParams } from "@carbon/database/event";
+import {
+ createEventSystemSubscription,
+ deleteEventSystemSubscriptionsByName
+} from "@carbon/database/event";
+import {
+ getProviderIntegration,
+ ProviderID,
+ type ProviderIntegrationMetadata
+} from "@carbon/ee/accounting";
+import { PostgresDriver } from "kysely";
import type { ComponentProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Xero: IntegrationConfig = {
+const coerceBoolean = z.preprocess(
+ (v) =>
+ v === "true" || v === "on" ? true : v === "false" || v === "" ? false : v,
+ z.boolean()
+);
+
+const XeroSettingsSchema = z.object({
+ backfillCustomers: coerceBoolean.optional().default(true),
+ backfillVendors: coerceBoolean.optional().default(true),
+ backfillItems: coerceBoolean.optional().default(true),
+ conflictResolution: z
+ .enum(["skip", "overwrite", "merge"])
+ .optional()
+ .default("merge")
+});
+
+export const Xero = defineIntegration({
name: "Xero",
id: "xero",
- active: false,
+ active: NODE_ENV !== "production",
category: "Accounting",
logo: Logo,
description:
@@ -14,8 +41,63 @@ export const Xero: IntegrationConfig = {
shortDescription:
"Automatically post transactions from sales and purchase invoices.",
images: [],
- settings: [],
- schema: z.object({}),
+ settings: [
+ {
+ name: "backfillCustomers",
+ label: "Customers",
+ description: "Include customers in sync",
+ group: "Entities to Sync",
+ type: "switch" as const,
+ required: false,
+ value: true
+ },
+ {
+ name: "backfillVendors",
+ label: "Vendors",
+ description: "Include vendors/suppliers in sync",
+ group: "Entities to Sync",
+ type: "switch" as const,
+ required: false,
+ value: true
+ },
+ {
+ name: "backfillItems",
+ label: "Items",
+ description: "Include items/products in sync",
+ group: "Entities to Sync",
+ type: "switch" as const,
+ required: false,
+ value: true
+ },
+ {
+ name: "conflictResolution",
+ label: "Conflict Resolution",
+ description:
+ "Determines how to handle records that exist in both systems",
+ group: "Sync Settings",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "skip",
+ label: "Skip",
+ description: "Keep existing Carbon data unchanged"
+ },
+ {
+ value: "overwrite",
+ label: "Overwrite",
+ description: "Replace Carbon data with Xero data"
+ },
+ {
+ value: "merge",
+ label: "Merge",
+ description: "Combine data from both systems"
+ }
+ ],
+ required: false,
+ value: "merge"
+ }
+ ],
+ schema: XeroSettingsSchema,
oauth: {
authUrl: "https://login.xero.com/identity/connect/authorize",
clientId: XERO_CLIENT_ID!,
@@ -27,8 +109,66 @@ export const Xero: IntegrationConfig = {
"accounting.settings"
],
tokenUrl: "https://login.xero.com/identity/connect/token"
+ },
+ actions: [
+ {
+ id: "sync-data",
+ label: "Run Initial Sync",
+ description: "Runs the initial backfill for the selected entities above",
+ endpoint: "/api/integrations/xero/backfill"
+ }
+ ],
+ async onHealthcheck(companyId, metadata) {
+ const provider = getProviderIntegration(
+ getCarbonServiceRole(),
+ companyId,
+ ProviderID.XERO,
+ metadata as ProviderIntegrationMetadata
+ );
+
+ return await provider.validate();
+ },
+ async onInstall(companyId) {
+ const { getPostgresClient, getPostgresConnectionPool } = await import(
+ "@carbon/database/client"
+ );
+
+ const pg = getPostgresClient(getPostgresConnectionPool(1), PostgresDriver);
+
+ const tables: CreateSubscriptionParams["table"][] = [
+ "address",
+ "contact",
+ "customer",
+ "supplier",
+ "item",
+ "salesInvoice",
+ "purchaseInvoice"
+ ];
+
+ for (const table of tables) {
+ await createEventSystemSubscription(pg, {
+ table,
+ companyId,
+ name: "xero-sync",
+ operations: ["INSERT", "UPDATE", "DELETE"],
+ type: "SYNC",
+ config: {
+ provider: ProviderID.XERO
+ }
+ });
+ }
+ },
+ async onUninstall(companyId) {
+ const { getPostgresClient, getPostgresConnectionPool } = await import(
+ "@carbon/database/client"
+ );
+
+ const pg = getPostgresClient(getPostgresConnectionPool(1), PostgresDriver);
+
+ // Delete all Xero sync subscriptions for this company
+ await deleteEventSystemSubscriptionsByName(pg, companyId, "xero-sync");
}
-};
+});
function Logo(props: ComponentProps<"svg">) {
return (
diff --git a/packages/ee/src/zapier/config.tsx b/packages/ee/src/zapier/config.tsx
index 47f00d9840..e78b5a03d0 100644
--- a/packages/ee/src/zapier/config.tsx
+++ b/packages/ee/src/zapier/config.tsx
@@ -1,8 +1,8 @@
import type { ComponentProps } from "react";
import { z } from "zod";
-import type { IntegrationConfig } from "../types";
+import { defineIntegration } from "../fns";
-export const Zapier: IntegrationConfig = {
+export const Zapier = defineIntegration({
name: "Zapier",
id: "zapier",
active: false,
@@ -14,7 +14,7 @@ export const Zapier: IntegrationConfig = {
images: [],
settings: [],
schema: z.object({})
-};
+});
function Logo(props: ComponentProps<"svg">) {
return (
diff --git a/packages/ee/tsconfig.json b/packages/ee/tsconfig.json
index a53b926833..7b6080821c 100644
--- a/packages/ee/tsconfig.json
+++ b/packages/ee/tsconfig.json
@@ -1,9 +1,9 @@
{
+ "extends": "@carbon/tsconfig/react-library.json",
"compilerOptions": {
"lib": ["dom", "ES2015"],
"strict": true
},
"include": ["src", "../../apps/erp/app/components/OnshapeSync.tsx"],
- "exclude": ["node_modules"],
- "extends": "@carbon/tsconfig/react-library.json"
+ "exclude": ["node_modules"]
}
diff --git a/packages/form/src/ValidatedForm.tsx b/packages/form/src/ValidatedForm.tsx
index f390f8bbd5..6b755e8943 100644
--- a/packages/form/src/ValidatedForm.tsx
+++ b/packages/form/src/ValidatedForm.tsx
@@ -1,6 +1,7 @@
import { useIsomorphicLayoutEffect } from "@carbon/react";
import type { ComponentProps, FormEvent, RefObject } from "react";
-import React, {
+import type React from "react";
+import {
useCallback,
useEffect,
useMemo,
diff --git a/packages/form/src/internal/state/fieldArray.tsx b/packages/form/src/internal/state/fieldArray.tsx
index f97edf441c..2ca4ccd804 100644
--- a/packages/form/src/internal/state/fieldArray.tsx
+++ b/packages/form/src/internal/state/fieldArray.tsx
@@ -1,5 +1,6 @@
import { nanoid } from "nanoid";
-import React, { useCallback, useMemo, useRef } from "react";
+import type React from "react";
+import { useCallback, useMemo, useRef } from "react";
import invariant from "tiny-invariant";
import type { InternalFormContextValue } from "../formContext";
import {
diff --git a/packages/form/src/zod.ts b/packages/form/src/zod.ts
index 006e666253..4690075621 100644
--- a/packages/form/src/zod.ts
+++ b/packages/form/src/zod.ts
@@ -1,5 +1,5 @@
import * as R from "remeda";
-import { z } from "zod";
+import type { z } from "zod";
import { stringToPathArray } from "./utils";
import { createValidator } from "./validation/createValidator";
import type { FieldErrors, Validator } from "./validation/types";
diff --git a/packages/jobs/package.json b/packages/jobs/package.json
index 983d806a3e..6a1cc6c5fe 100644
--- a/packages/jobs/package.json
+++ b/packages/jobs/package.json
@@ -10,12 +10,11 @@
},
"dependencies": {
"@ai-sdk/openai": "^2.0.60",
- "@trigger.dev/sdk": "4.0.6",
"@carbon/auth": "*",
"@carbon/database": "*",
"@carbon/documents": "*",
- "@carbon/lib": "*",
"@carbon/ee": "*",
+ "@carbon/lib": "*",
"@carbon/notifications": "*",
"@internationalized/date": "^3.5.2",
"@novu/node": "^2.0.1",
@@ -23,7 +22,9 @@
"@slack/web-api": "~7.10.0",
"@supabase/functions-js": "2.1.5",
"@supabase/supabase-js": "2.80.0",
+ "@trigger.dev/sdk": "4.0.6",
"ai": "^5.0.88",
+ "kysely": "^0.28.10",
"nanoid": "5.0.4",
"resend": "^3.1.0",
"zod": "^3.25.76"
diff --git a/packages/jobs/trigger/accounting-backfill.ts b/packages/jobs/trigger/accounting-backfill.ts
new file mode 100644
index 0000000000..e15daf6eaa
--- /dev/null
+++ b/packages/jobs/trigger/accounting-backfill.ts
@@ -0,0 +1,561 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ getPostgresClient,
+ getPostgresConnectionPool,
+} from "@carbon/database/client";
+import {
+ createMappingService,
+ getAccountingIntegration,
+ getProviderIntegration,
+ ProviderID,
+ SyncFactory,
+ type AccountingEntityType,
+ type XeroProvider,
+} from "@carbon/ee/accounting";
+import { logger, task, wait } from "@trigger.dev/sdk/v3";
+import { PostgresDriver } from "kysely";
+import z from "zod";
+
+// ============================================================
+// SCHEMAS
+// ============================================================
+
+const BackfillPayloadSchema = z.object({
+ companyId: z.string(),
+ provider: z.nativeEnum(ProviderID),
+ batchSize: z.number().default(25), // Smaller batches to avoid rate limits
+ entityTypes: z
+ .object({
+ customers: z.boolean().default(true),
+ vendors: z.boolean().default(true),
+ items: z.boolean().default(true),
+ })
+ .default({}),
+});
+
+const PullPagePayloadSchema = z.object({
+ companyId: z.string(),
+ provider: z.nativeEnum(ProviderID),
+ entityType: z.enum(["contact", "item"]),
+ page: z.number(),
+ includeCustomers: z.boolean().default(true),
+ includeVendors: z.boolean().default(true),
+});
+
+const PushBatchPayloadSchema = z.object({
+ companyId: z.string(),
+ provider: z.nativeEnum(ProviderID),
+ entityType: z.enum(["customer", "supplier", "item"]),
+ entityIds: z.array(z.string()),
+});
+
+export type BackfillPayload = z.input<typeof BackfillPayloadSchema>;
+type ParsedBackfillPayload = z.output<typeof BackfillPayloadSchema>;
+
+// ============================================================
+// PULL PAGE TASK - Pulls a single page from external system
+// ============================================================
+
+export const accountingPullPageTask = task({
+ id: "accounting-pull-page",
+ retry: {
+ maxAttempts: 5,
+ factor: 2,
+ minTimeoutInMs: 2000,
+ maxTimeoutInMs: 120000, // Up to 2 minutes for rate limit recovery
+ randomize: true,
+ },
+ run: async (input: z.input<typeof PullPagePayloadSchema>) => {
+ const payload = PullPagePayloadSchema.parse(input);
+ const client = getCarbonServiceRole();
+
+ const integration = await getAccountingIntegration(
+ client,
+ payload.companyId,
+ payload.provider
+ );
+
+ const provider = getProviderIntegration(
+ client,
+ payload.companyId,
+ integration.id,
+ integration.metadata
+ ) as XeroProvider;
+
+ const pool = getPostgresConnectionPool(5);
+ const kysely = getPostgresClient(pool, PostgresDriver);
+
+ try {
+ if (payload.entityType === "contact") {
+ logger.info(`[PULL] Fetching contacts page ${payload.page}`);
+ const response = await provider.listContacts({
+ page: payload.page,
+ summaryOnly: true,
+ });
+
+ logger.info(`[PULL] Contacts page ${payload.page} response`, {
+ count: response.contacts.length,
+ hasMore: response.hasMore,
+ contacts: response.contacts.map((c) => ({
+ id: c.ContactID,
+ name: c.Name,
+ isCustomer: c.IsCustomer,
+ isSupplier: c.IsSupplier,
+ })),
+ });
+
+ if (response.contacts.length === 0) {
+ return { hasMore: false, pulled: { customers: 0, vendors: 0 } };
+ }
+
+ let customersPulled = 0;
+ let vendorsPulled = 0;
+
+ // Pull customers
+ if (payload.includeCustomers) {
+ const customers = response.contacts.filter((c) => c.IsCustomer);
+ if (customers.length > 0) {
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider,
+ config: provider.getSyncConfig("customer"),
+ entityType: "customer",
+ });
+ const ids = customers.map((c) => c.ContactID);
+ const result = await syncer.pullBatchFromAccounting(ids);
+ customersPulled = result.successCount;
+ logger.info(
+ `[PULL] Page ${payload.page}: pulled ${customersPulled} customers`,
+ {
+ results: result.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error,
+ })),
+ }
+ );
+ }
+ }
+
+ // Pull vendors
+ if (payload.includeVendors) {
+ const vendors = response.contacts.filter((c) => c.IsSupplier);
+ if (vendors.length > 0) {
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider,
+ config: provider.getSyncConfig("vendor"),
+ entityType: "vendor",
+ });
+ const ids = vendors.map((c) => c.ContactID);
+ const result = await syncer.pullBatchFromAccounting(ids);
+ vendorsPulled = result.successCount;
+ logger.info(
+ `[PULL] Page ${payload.page}: pulled ${vendorsPulled} vendors`,
+ {
+ results: result.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error,
+ })),
+ }
+ );
+ }
+ }
+
+ return {
+ hasMore: response.hasMore,
+ pulled: { customers: customersPulled, vendors: vendorsPulled },
+ };
+ } else {
+ // Items
+ logger.info(`[PULL] Fetching items page ${payload.page}`);
+ const response = await provider.listItems({ page: payload.page });
+
+ logger.info(`[PULL] Items page ${payload.page} response`, {
+ count: response.items.length,
+ hasMore: response.hasMore,
+ items: response.items.map((i) => ({
+ id: i.ItemID,
+ code: i.Code,
+ name: i.Name,
+ })),
+ });
+
+ if (response.items.length === 0) {
+ return { hasMore: false, pulled: { items: 0 } };
+ }
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider,
+ config: provider.getSyncConfig("item"),
+ entityType: "item",
+ });
+ const ids = response.items.map((item) => item.ItemID);
+ const result = await syncer.pullBatchFromAccounting(ids);
+
+ logger.info(
+ `[PULL] Page ${payload.page}: pulled ${result.successCount} items`,
+ {
+ results: result.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error,
+ })),
+ }
+ );
+
+ return {
+ hasMore: response.hasMore,
+ pulled: { items: result.successCount },
+ };
+ }
+ } finally {
+ await pool.end();
+ }
+ },
+});
+
+// ============================================================
+// PUSH BATCH TASK - Pushes a batch of entities to external system
+// ============================================================
+
+export const accountingPushBatchTask = task({
+ id: "accounting-push-batch",
+ retry: {
+ maxAttempts: 5,
+ factor: 2,
+ minTimeoutInMs: 2000,
+ maxTimeoutInMs: 120000,
+ randomize: true,
+ },
+ run: async (input: z.input<typeof PushBatchPayloadSchema>) => {
+ const payload = PushBatchPayloadSchema.parse(input);
+ const client = getCarbonServiceRole();
+
+ const integration = await getAccountingIntegration(
+ client,
+ payload.companyId,
+ payload.provider
+ );
+
+ const provider = getProviderIntegration(
+ client,
+ payload.companyId,
+ integration.id,
+ integration.metadata
+ ) as XeroProvider;
+
+ const pool = getPostgresConnectionPool(5);
+ const kysely = getPostgresClient(pool, PostgresDriver);
+
+ try {
+ // Map entity type to accounting entity type
+ const entityType: AccountingEntityType =
+ payload.entityType === "supplier" ? "vendor" : payload.entityType;
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider,
+ config: provider.getSyncConfig(entityType),
+ entityType,
+ });
+
+ const result = await syncer.pushBatchToAccounting(payload.entityIds);
+
+ logger.info(
+ `[PUSH] Pushed ${result.successCount}/${payload.entityIds.length} ${payload.entityType} entities`,
+ {
+ entityIds: payload.entityIds,
+ results: result.results.map((r) => ({
+ status: r.status,
+ action: r.action,
+ localId: r.localId,
+ remoteId: r.remoteId,
+ error: r.error,
+ })),
+ }
+ );
+
+ return {
+ successCount: result.successCount,
+ errorCount: result.errorCount,
+ };
+ } finally {
+ await pool.end();
+ }
+ },
+});
+
+// ============================================================
+// ORCHESTRATOR TASK - Coordinates the entire backfill process
+// ============================================================
+
+export const accountingBackfillTask = task({
+ id: "accounting-backfill",
+ retry: {
+ maxAttempts: 3,
+ factor: 2,
+ minTimeoutInMs: 5000,
+ maxTimeoutInMs: 60000,
+ randomize: true,
+ },
+ run: async (input: BackfillPayload) => {
+ const payload: ParsedBackfillPayload = BackfillPayloadSchema.parse(input);
+ const client = getCarbonServiceRole();
+
+ const integration = await getAccountingIntegration(
+ client,
+ payload.companyId,
+ payload.provider
+ );
+
+ const provider = getProviderIntegration(
+ client,
+ payload.companyId,
+ integration.id,
+ integration.metadata
+ ) as XeroProvider;
+
+ const result = {
+ customers: { pulled: 0, pushed: 0 },
+ vendors: { pulled: 0, pushed: 0 },
+ items: { pulled: 0, pushed: 0 },
+ totalPulled: 0,
+ totalPushed: 0,
+ };
+
+ // ============================================================
+ // PHASE 1: Pull from accounting
+ // ============================================================
+
+ // Pull contacts (customers and vendors)
+ if (payload.entityTypes.customers || payload.entityTypes.vendors) {
+ let page = 1;
+ let hasMore = true;
+
+ while (hasMore) {
+ const pullResult = await accountingPullPageTask.triggerAndWait({
+ companyId: payload.companyId,
+ provider: payload.provider,
+ entityType: "contact",
+ page,
+ includeCustomers: payload.entityTypes.customers,
+ includeVendors: payload.entityTypes.vendors,
+ });
+
+ if (pullResult.ok) {
+ result.customers.pulled += pullResult.output.pulled.customers ?? 0;
+ result.vendors.pulled += pullResult.output.pulled.vendors ?? 0;
+ hasMore = pullResult.output.hasMore;
+ } else {
+ logger.error(`[PULL] Failed to pull contacts page ${page}`, {
+ error: pullResult.error,
+ });
+ hasMore = false;
+ }
+
+ page++;
+
+ // Small delay between pages to avoid rate limits
+ if (hasMore) {
+ await wait.for({ seconds: 1 });
+ }
+ }
+ }
+
+ // Pull items
+ if (payload.entityTypes.items) {
+ let page = 1;
+ let hasMore = true;
+
+ while (hasMore) {
+ const pullResult = await accountingPullPageTask.triggerAndWait({
+ companyId: payload.companyId,
+ provider: payload.provider,
+ entityType: "item",
+ page,
+ });
+
+ if (pullResult.ok) {
+ result.items.pulled += pullResult.output.pulled.items ?? 0;
+ hasMore = pullResult.output.hasMore;
+ } else {
+ logger.error(`[PULL] Failed to pull items page ${page}`, {
+ error: pullResult.error,
+ });
+ hasMore = false;
+ }
+
+ page++;
+
+ if (hasMore) {
+ await wait.for({ seconds: 1 });
+ }
+ }
+ }
+
+ // ============================================================
+ // PHASE 2: Push to accounting
+ // ============================================================
+
+ const pool = getPostgresConnectionPool(5);
+ const kysely = getPostgresClient(pool, PostgresDriver);
+
+ try {
+ const mappingService = createMappingService(kysely, payload.companyId);
+
+ // Push customers
+ if (payload.entityTypes.customers) {
+ let hasMore = true;
+
+ while (hasMore) {
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "customer",
+ "customer",
+ provider.id,
+ payload.batchSize
+ );
+
+ if (unsyncedIds.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const pushResult = await accountingPushBatchTask.triggerAndWait({
+ companyId: payload.companyId,
+ provider: payload.provider,
+ entityType: "customer",
+ entityIds: unsyncedIds,
+ });
+
+ if (pushResult.ok) {
+ result.customers.pushed += pushResult.output.successCount;
+ } else {
+ logger.error("[PUSH] Failed to push customers batch", {
+ error: pushResult.error,
+ });
+ }
+
+ if (unsyncedIds.length < payload.batchSize) {
+ hasMore = false;
+ }
+
+ // Delay between batches
+ if (hasMore) {
+ await wait.for({ seconds: 2 });
+ }
+ }
+ }
+
+ // Push vendors
+ if (payload.entityTypes.vendors) {
+ let hasMore = true;
+
+ while (hasMore) {
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "supplier",
+ "supplier",
+ provider.id,
+ payload.batchSize
+ );
+
+ if (unsyncedIds.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const pushResult = await accountingPushBatchTask.triggerAndWait({
+ companyId: payload.companyId,
+ provider: payload.provider,
+ entityType: "supplier",
+ entityIds: unsyncedIds,
+ });
+
+ if (pushResult.ok) {
+ result.vendors.pushed += pushResult.output.successCount;
+ } else {
+ logger.error("[PUSH] Failed to push vendors batch", {
+ error: pushResult.error,
+ });
+ }
+
+ if (unsyncedIds.length < payload.batchSize) {
+ hasMore = false;
+ }
+
+ if (hasMore) {
+ await wait.for({ seconds: 2 });
+ }
+ }
+ }
+
+ // Push items
+ if (payload.entityTypes.items) {
+ let hasMore = true;
+
+ while (hasMore) {
+ const unsyncedIds = await mappingService.getUnsyncedEntityIds(
+ "item",
+ "item",
+ provider.id,
+ payload.batchSize
+ );
+
+ if (unsyncedIds.length === 0) {
+ hasMore = false;
+ break;
+ }
+
+ const pushResult = await accountingPushBatchTask.triggerAndWait({
+ companyId: payload.companyId,
+ provider: payload.provider,
+ entityType: "item",
+ entityIds: unsyncedIds,
+ });
+
+ if (pushResult.ok) {
+ result.items.pushed += pushResult.output.successCount;
+ } else {
+ logger.error("[PUSH] Failed to push items batch", {
+ error: pushResult.error,
+ });
+ }
+
+ if (unsyncedIds.length < payload.batchSize) {
+ hasMore = false;
+ }
+
+ if (hasMore) {
+ await wait.for({ seconds: 2 });
+ }
+ }
+ }
+ } finally {
+ await pool.end();
+ }
+
+ // Calculate totals
+ result.totalPulled =
+ result.customers.pulled + result.vendors.pulled + result.items.pulled;
+ result.totalPushed =
+ result.customers.pushed + result.vendors.pushed + result.items.pushed;
+
+ logger.info(
+ `[COMPLETE] Backfill finished. Pulled: ${result.totalPulled}, Pushed: ${result.totalPushed}`
+ );
+
+ return result;
+ },
+});
diff --git a/packages/jobs/trigger/accounting-sync.ts b/packages/jobs/trigger/accounting-sync.ts
deleted file mode 100644
index 6f05938f77..0000000000
--- a/packages/jobs/trigger/accounting-sync.ts
+++ /dev/null
@@ -1,1057 +0,0 @@
-import { getCarbonServiceRole } from "@carbon/auth";
-import type { Database } from "@carbon/database";
-import {
- AccountingEntity,
- AccountingProvider,
- ProviderCredentialsSchema,
- ProviderID,
- AccountingSyncSchema,
- ProviderCredentials,
- type ProviderConfig,
-} from "@carbon/ee/accounting";
-import { QuickBooksProvider } from "@carbon/ee/quickbooks";
-import { XeroProvider } from "@carbon/ee/xero";
-
-import type { SupabaseClient } from "@supabase/supabase-js";
-import { task } from "@trigger.dev/sdk/v3";
-import z from "zod";
-
-export const accountingSyncTask = task({
- id: "accounting-sync",
- run: async (input) => {
- const payload = AccountingSyncSchema.parse(input);
-
- const { companyId, provider, syncDirection, entities, metadata } = payload;
-
- const client = getCarbonServiceRole();
-
- // Get the company integration details
- const companyIntegration = await client
- .from("companyIntegration")
- .select("*")
- .eq("companyId", companyId)
- .eq("id", provider)
- .single();
-
- if (companyIntegration.error || !companyIntegration.data) {
- throw new Error(
- `No ${provider} integration found for company ${companyId}`
- );
- }
-
- const providerConfig = ProviderCredentialsSchema.safeParse(
- companyIntegration.data.metadata
- );
-
- if (!providerConfig.success) {
- console.error(providerConfig.error);
- throw new Error("Invalid provider config");
- }
-
- const accountingProvider = await initializeProvider(
- client,
- companyId,
- provider,
- providerConfig.data
- );
-
- const results = {
- success: [] as any[],
- failed: [] as { entity: AccountingEntity; error: string }[],
- };
-
- for (const entity of entities) {
- try {
- const result = await processEntity(
- client,
- accountingProvider,
- entity,
- syncDirection,
- companyId,
- metadata
- );
- results.success.push(result);
- } catch (error) {
- results.failed.push({
- entity,
- error: error instanceof Error ? error.message : "Unknown error",
- });
- console.error(
- `Failed to process ${entity.entityType} ${entity.entityId}:`,
- error
- );
- }
- }
-
- return results;
- },
-});
-
-async function initializeProvider(
- client: SupabaseClient<Database>,
- companyId: string,
- provider: string,
- config: z.infer<typeof metadataSchema>
-) {
- const { accessToken, refreshToken, tenantId } = config;
-
- // Create a callback function to update the integration metadata when tokens are refreshed
- const onTokenRefresh = async (auth: ProviderCredentials) => {
- try {
- const update = {
- accessToken: auth.accessToken,
- refreshToken: auth.refreshToken,
- expiresAt:
- auth.expiresAt?.toISOString() ||
- new Date(Date.now() + 3600000).toISOString(), // Default to 1 hour if not provided
- tenantId: auth.tenantId || tenantId,
- };
-
- await client
- .from("companyIntegration")
- .update({ metadata: update })
- .eq("companyId", companyId)
- .eq("id", provider);
-
- console.log(
- `Updated ${provider} integration metadata for company ${companyId}`
- );
- } catch (error) {
- console.error(
- `Failed to update ${provider} integration metadata:`,
- error
- );
- }
- };
-
- switch (provider) {
- case "quickbooks": {
- const environment = process.env.QUICKBOOKS_ENVIRONMENT as
- | "production"
- | "sandbox";
-
- return new QuickBooksProvider({
- companyId,
- tenantId,
- environment: environment || "sandbox",
- clientId: process.env.QUICKBOOKS_CLIENT_ID!,
- clientSecret: process.env.QUICKBOOKS_CLIENT_SECRET!,
- redirectUri: process.env.QUICKBOOKS_REDIRECT_URI,
- onTokenRefresh,
- });
- }
- case "xero":
- return new XeroProvider({
- companyId,
- tenantId,
- accessToken,
- refreshToken,
- clientId: process.env.XERO_CLIENT_ID!,
- clientSecret: process.env.XERO_CLIENT_SECRET!,
- redirectUri: process.env.XERO_REDIRECT_URI,
- onTokenRefresh,
- });
- // Add other providers as needed
- // case "sage":
- // return new SageProvider(config);
- default:
- throw new Error(`Unsupported provider: ${provider}`);
- }
-}
-
-async function processEntity(
- client: SupabaseClient<Database>,
- provider: AccountingProvider,
- entity: AccountingEntity,
- syncDirection: "fromAccounting" | "toAccounting" | "bidirectional",
- companyId: string,
- metadata?: any
-): Promise<any> {
- const { entityType, entityId, operation, data, lastSyncedAt } = entity;
-
- if (syncDirection === "fromAccounting" || syncDirection === "bidirectional") {
- if (
- operation === "create" ||
- operation === "update" ||
- operation === "sync"
- ) {
- switch (entityType) {
- case "customer":
- return await syncCustomerFromAccounting(
- client,
- provider,
- entityId,
- companyId,
- operation
- );
- case "vendor":
- return await syncVendorFromAccounting(
- client,
- provider,
- entityId,
- companyId,
- operation
- );
- }
- } else if (operation === "delete") {
- switch (entityType) {
- case "customer":
- return await deactivateCustomer(client, companyId);
- case "vendor":
- return await deactivateSupplier(client, companyId);
- }
- }
- }
-
- if (syncDirection === "toAccounting" || syncDirection === "bidirectional") {
- if (operation === "create" || operation === "update") {
- switch (entityType) {
- case "customer":
- return await syncCustomerToAccounting(
- client,
- provider,
- entityId,
- companyId
- );
- case "vendor":
- return await syncVendorToAccounting(
- client,
- provider,
- entityId,
- companyId
- );
- }
- }
- }
-
- throw new Error(
- `Unsupported operation ${operation} for ${entityType} in direction ${syncDirection}`
- );
-}
-
-async function syncCustomerFromAccounting(
- client: SupabaseClient<Database>,
- provider: AccountingProvider,
- externalId: string,
- companyId: string,
- operation: "create" | "update" | "sync"
-): Promise<any> {
- const customer = await provider.contacts.get(externalId);
-
- const existing = await client
- .from("customer")
- .select("*")
- .eq("companyId", companyId)
- .eq("externalId->>externalId", externalId)
- .single();
-
- const externalIdKey = `${provider.id}Id`;
-
- const customerData: Database["public"]["Tables"]["customer"]["Insert"] = {
- companyId,
- name: customer.firstName,
- phone: customer.phones?.[0].phone || null,
- website: customer.website || null,
- taxId: customer.taxId || null,
- currencyCode: customer.currencyCode,
- externalId: {
- [externalIdKey]: externalId,
- syncToken: (customer as any).syncToken,
- accountingProvider: provider.id,
- lastSyncedAt: new Date().toISOString(),
- accountingData: {
- displayName: customer.name,
- balance: customer.balance,
- creditLimit: customer.creditLimit,
- paymentTerms: customer.paymentTerms,
- },
- },
- updatedAt: new Date().toISOString(),
- };
-
- let customerId: string;
-
- if (existing.data) {
- // Update existing customer
- const result = await client
- .from("customer")
- .update(customerData)
- .eq("id", existing.data.id)
- .select()
- .single();
-
- if (result.error) throw result.error;
- customerId = result.data.id;
- } else {
- // Create new customer
- const result = await client
- .from("customer")
- .insert({
- ...customerData,
- createdAt: new Date().toISOString(),
- })
- .select()
- .single();
-
- if (result.error) throw result.error;
- customerId = result.data.id;
- }
-
- // Sync contact information if email is available
- if (customerId) {
- try {
- // Check if contact already exists by external ID
- const existingContactQuery = await client
- .from("contact")
- .select(
- `
- id,
- customerContact!inner(
- id,
- customerId
- )
- `
- )
- .eq("companyId", companyId)
- .eq(`externalId->>${externalIdKey}`, externalId)
- .single();
-
- let contactId: string;
-
- if (!existingContactQuery.data) {
- // Try to find contact by email
- const contactByEmail = await client
- .from("contact")
- .select("id")
- .eq("companyId", companyId)
- .eq("email", customer.email)
- .eq("isCustomer", true)
- .maybeSingle();
-
- if (contactByEmail.data) {
- contactId = contactByEmail.data.id;
-
- // Update the contact with external ID
- await client
- .from("contact")
- .update({
- externalId: {
- [externalIdKey]: externalId,
- },
- })
- .eq("id", contactId);
- } else {
- // Create new contact
- const firstName = customer.firstName;
- const lastName = customer.lastName;
-
- const newContact = await client
- .from("contact")
- .insert({
- companyId,
- firstName,
- lastName,
- email: customer.email,
- isCustomer: true,
- workPhone: customer.phones.find((p) => p.isPrimary).phone || null,
- externalId: {
- [externalIdKey]: externalId,
- },
- })
- .select()
- .single();
-
- if (newContact.error) {
- console.error("Failed to create contact:", newContact.error);
- } else {
- contactId = newContact.data.id;
- }
- }
-
- // Create customerContact relationship if contact was created/found
- if (contactId) {
- // Check if customerContact already exists
- const existingCustomerContact = await client
- .from("customerContact")
- .select("id")
- .eq("customerId", customerId)
- .eq("contactId", contactId)
- .maybeSingle();
-
- if (!existingCustomerContact.data) {
- const newCustomerContact = await client
- .from("customerContact")
- .insert({
- customerId,
- contactId,
- })
- .select()
- .single();
-
- if (newCustomerContact.error) {
- console.error(
- "Failed to create customerContact:",
- newCustomerContact.error
- );
- }
- }
- }
- } else {
- // Contact exists, check if linked to this customer
- const customerContact = existingContactQuery.data.customerContact?.find(
- (cc: any) => cc.customerId === customerId
- );
-
- if (!customerContact) {
- // Link existing contact to customer
- const newCustomerContact = await client
- .from("customerContact")
- .insert({
- customerId,
- contactId: existingContactQuery.data.id,
- })
- .select()
- .single();
-
- if (newCustomerContact.error) {
- console.error(
- "Failed to link contact to customer:",
- newCustomerContact.error
- );
- }
- }
- }
- } catch (error) {
- console.error("Error syncing customer contact:", error);
- }
- }
-
- // Sync addresses if available
- if (customer.addresses && customer.addresses.length > 0) {
- for (const address of customer.addresses) {
- // Skip if no valid address data (need at least street and city or state)
- if (!address.street || (!address.city && !address.state)) {
- console.log(
- "Skipping address creation - missing required fields (street and city/state)"
- );
- continue;
- }
-
- if (address.country && address.country.length === 3) {
- const country = await client
- .from("country")
- .select("alpha2")
- .eq("alpha3", address.country)
- .maybeSingle();
- if (country.data) {
- address.country = country.data?.alpha2;
- }
- }
-
- if (address.country && address.country.length > 3) {
- const country = await client
- .from("country")
- .select("alpha2")
- .eq("name", address.country)
- .maybeSingle();
- if (country.data) {
- address.country = country.data?.alpha2;
- }
- }
-
- const addressData = {
- companyId,
- addressLine1: address.street,
- addressLine2: address.street2 || null,
- city: address.city || "",
- stateProvince: address.state || null,
- postalCode: address.postalCode || null,
- countryCode: address.country || null,
- };
-
- // Check if address exists
- const existingAddress = await client
- .from("address")
- .select("*")
- .eq("companyId", companyId)
- .eq("addressLine1", addressData.addressLine1)
- .eq("city", addressData.city)
- .maybeSingle();
-
- let addressId: string;
-
- if (existingAddress?.data) {
- addressId = existingAddress.data.id;
- } else {
- const newAddress = await client
- .from("address")
- .insert(addressData)
- .select()
- .single();
-
- if (newAddress.error) throw newAddress.error;
- addressId = newAddress.data.id;
- }
-
- // Link address to customer
- const locationType = address.type === "billing" ? "Billing" : "Shipping";
-
- const customerLocation = await client.from("customerLocation").upsert(
- {
- customerId,
- addressId,
- name: locationType,
- },
- {
- onConflict: "addressId,customerId",
- ignoreDuplicates: true,
- }
- );
-
- if (customerLocation.error) console.error(customerLocation.error);
- }
- }
-
- return {
- customerId,
- externalId,
- operation,
- status: "success",
- };
-}
-
-async function syncVendorFromAccounting(
- client: SupabaseClient<Database>,
- provider: CoreProvider,
- externalId: string,
- companyId: string,
- operation: "create" | "update" | "sync"
-): Promise<any> {
- // Fetch vendor from accounting system
- const accountingVendor = await provider.getVendor(externalId);
-
- // Check if supplier exists in Carbon (by external ID)
- const existingSupplier = await client
- .from("supplier")
- .select("*")
- .eq("companyId", companyId)
- .eq("externalId->>externalId", externalId)
- .single();
-
- const providerName = provider.getProviderInfo().name.toLowerCase();
-
- const supplierData: Database["public"]["Tables"]["supplier"]["Insert"] = {
- companyId,
- name: accountingVendor.name ?? accountingVendor.displayName,
- phone: accountingVendor.phone?.number || null,
- website: accountingVendor.website || null,
- taxId: accountingVendor.taxNumber || null,
- currencyCode: accountingVendor.currency || "USD",
- externalId: {
- externalId,
- syncToken: (accountingVendor as any).syncToken,
- accountingProvider: provider.getProviderInfo().name,
- lastSyncedAt: new Date().toISOString(),
- accountingData: {
- displayName: accountingVendor.displayName,
- balance: accountingVendor.balance,
- paymentTerms: accountingVendor.paymentTerms,
- },
- },
- updatedAt: new Date().toISOString(),
- };
-
- let supplierId: string;
-
- if (existingSupplier.data) {
- // Update existing supplier
- const result = await client
- .from("supplier")
- .update(supplierData)
- .eq("id", existingSupplier.data.id)
- .select()
- .single();
-
- if (result.error) throw result.error;
- supplierId = result.data.id;
- } else {
- // Create new supplier
- const result = await client
- .from("supplier")
- .insert({
- ...supplierData,
- createdAt: new Date().toISOString(),
- })
- .select()
- .single();
-
- if (result.error) throw result.error;
- supplierId = result.data.id;
- }
-
- // Sync contact information if email is available
- if (accountingVendor.email) {
- try {
- // Check if contact already exists by external ID
- const existingContactQuery = await client
- .from("contact")
- .select(
- `
- id,
- supplierContact!inner(
- id,
- supplierId
- )
- `
- )
- .eq("companyId", companyId)
- .eq(`externalId->>${providerName}Id`, externalId)
- .single();
-
- let contactId: string;
-
- if (!existingContactQuery.data) {
- // Try to find contact by email
- const contactByEmail = await client
- .from("contact")
- .select("id")
- .eq("companyId", companyId)
- .eq("email", accountingVendor.email)
- .eq("isCustomer", false)
- .maybeSingle();
-
- if (contactByEmail.data) {
- contactId = contactByEmail.data.id;
-
- // Update the contact with external ID
- await client
- .from("contact")
- .update({
- externalId: {
- [`${providerName}Id`]: externalId,
- },
- })
- .eq("id", contactId);
- } else {
- // Create new contact
- const firstName = accountingVendor.firstName;
- const lastName = accountingVendor.lastName;
-
- const newContact = await client
- .from("contact")
- .insert({
- companyId,
- firstName,
- lastName,
- email: accountingVendor.email,
- isCustomer: false,
- workPhone: accountingVendor.phone?.number || null,
- externalId: {
- [`${providerName}Id`]: externalId,
- },
- })
- .select()
- .single();
-
- if (newContact.error) {
- console.error("Failed to create contact:", newContact.error);
- } else {
- contactId = newContact.data.id;
- }
- }
-
- // Create supplierContact relationship if contact was created/found
- if (contactId) {
- // Check if supplierContact already exists
- const existingSupplierContact = await client
- .from("supplierContact")
- .select("id")
- .eq("supplierId", supplierId)
- .eq("contactId", contactId)
- .maybeSingle();
-
- if (!existingSupplierContact.data) {
- const newSupplierContact = await client
- .from("supplierContact")
- .insert({
- supplierId,
- contactId,
- })
- .select()
- .single();
-
- if (newSupplierContact.error) {
- console.error(
- "Failed to create supplierContact:",
- newSupplierContact.error
- );
- }
- }
- }
- } else {
- // Contact exists, check if linked to this supplier
- const supplierContact = existingContactQuery.data.supplierContact?.find(
- (sc: any) => sc.supplierId === supplierId
- );
-
- if (!supplierContact) {
- // Link existing contact to supplier
- const newSupplierContact = await client
- .from("supplierContact")
- .insert({
- supplierId,
- contactId: existingContactQuery.data.id,
- })
- .select()
- .single();
-
- if (newSupplierContact.error) {
- console.error(
- "Failed to link contact to supplier:",
- newSupplierContact.error
- );
- }
- }
- }
- } catch (error) {
- console.error("Error syncing supplier contact:", error);
- }
- }
-
- if (accountingVendor.addresses && accountingVendor.addresses.length > 0) {
- for (const address of accountingVendor.addresses) {
- // Skip if no valid address data (need at least street and city or state)
- if (!address.street || (!address.city && !address.state)) {
- console.log(
- "Skipping address creation - missing required fields (street and city/state)"
- );
- continue;
- }
-
- if (address.country && address.country.length === 3) {
- const country = await client
- .from("country")
- .select("alpha2")
- .eq("alpha3", address.country)
- .maybeSingle();
- if (country.data) {
- address.country = country.data?.alpha2;
- }
- }
-
- if (address.country && address.country.length > 3) {
- const country = await client
- .from("country")
- .select("alpha2")
- .eq("name", address.country)
- .maybeSingle();
- if (country.data) {
- address.country = country.data?.alpha2;
- }
- }
- const addressData = {
- companyId,
- addressLine1: address.street,
- addressLine2: address.street2 || null,
- city: address.city || "",
- stateProvince: address.state || null,
- postalCode: address.postalCode || null,
- countryCode: address.country || null,
- };
-
- // Check if address exists
- const existingAddress = await client
- .from("address")
- .select("*")
- .eq("companyId", companyId)
- .eq("addressLine1", addressData.addressLine1)
- .eq("city", addressData.city)
- .maybeSingle();
-
- let addressId: string;
-
- if (existingAddress?.data) {
- addressId = existingAddress.data.id;
- } else {
- const newAddress = await client
- .from("address")
- .insert(addressData)
- .select()
- .single();
-
- if (newAddress.error) throw newAddress.error;
- addressId = newAddress.data.id;
- }
-
- // Link address to supplier
- const locationType = address.type === "billing" ? "Billing" : "Shipping";
-
- const supplierLocation = await client.from("supplierLocation").upsert(
- {
- supplierId,
- addressId,
- name: locationType,
- },
- {
- onConflict: "addressId,supplierId",
- }
- );
-
- if (supplierLocation.error) console.error(supplierLocation.error);
- }
- }
-
- return {
- supplierId,
- externalId,
- operation,
- status: "success",
- };
-}
-
-async function syncCustomerToAccounting(
- client: SupabaseClient<Database>,
- provider: CoreProvider,
- customerId: string,
- companyId: string,
- externalId?: string
-): Promise<any> {
- // Fetch customer from Carbon
- const customer = await client
- .from("customer")
- .select("*, customerLocation(*, address(*))")
- .eq("id", customerId)
- .eq("companyId", companyId)
- .single();
-
- if (customer.error || !customer.data) {
- throw new Error(`Customer ${customerId} not found`);
- }
-
- // Transform Carbon customer to accounting format
- const accountingCustomerData = {
- name: customer.data.name,
- phone: customer.data.phone
- ? { number: customer.data.phone, type: "work" as any }
- : undefined,
- website: customer.data.website || undefined,
- taxNumber: customer.data.taxId || undefined,
- currency: customer.data.currencyCode || "USD",
- isActive: true,
- addresses: (customer.data.customerLocation || [])
- .map((loc: any) => ({
- type: loc.name === "Billing" ? "billing" : "shipping",
- street: loc.address?.addressLine1,
- street2: loc.address?.addressLine2,
- city: loc.address?.city,
- state: loc.address?.state,
- postalCode: loc.address?.postalCode,
- country: loc.address?.country,
- }))
- .filter((addr: any) => addr.street),
- };
-
- let result;
- if (externalId) {
- // Update existing customer in accounting system
- result = await provider.updateCustomer(externalId, accountingCustomerData);
- } else {
- // Create new customer in accounting system
- result = await provider.createCustomer(accountingCustomerData);
- }
-
- // Update Carbon customer with external ID
- await client
- .from("customer")
- .update({
- externalId: {
- ...((customer.data.externalId as any) || {}),
- externalId: result.id,
- syncToken: (result as any).syncToken,
- accountingProvider: provider.getProviderInfo().name,
- lastSyncedAt: new Date().toISOString(),
- },
- updatedAt: new Date().toISOString(),
- })
- .eq("id", customerId);
-
- return {
- customerId,
- externalId: result.id,
- operation: externalId ? "update" : "create",
- status: "success",
- };
-}
-
-async function syncVendorToAccounting(
- client: SupabaseClient<Database>,
- provider: CoreProvider,
- supplierId: string,
- companyId: string,
- externalId?: string
-): Promise<any> {
- // Fetch supplier from Carbon
- const supplier = await client
- .from("supplier")
- .select("*, supplierLocation(*, address(*))")
- .eq("id", supplierId)
- .eq("companyId", companyId)
- .single();
-
- if (supplier.error || !supplier.data) {
- throw new Error(`Supplier ${supplierId} not found`);
- }
-
- // Transform Carbon supplier to accounting vendor format
- const accountingVendorData = {
- name: supplier.data.name,
- email: undefined,
- phone: supplier.data.phone
- ? { number: supplier.data.phone, type: "work" as any }
- : undefined,
- website: supplier.data.website || undefined,
- taxNumber: supplier.data.taxId || undefined,
- currency: supplier.data.currencyCode || "USD",
- isActive: true,
- addresses: (supplier.data.supplierLocation || [])
- .map((loc: any) => ({
- type: "billing" as any,
- street: loc.address?.addressLine1,
- street2: loc.address?.addressLine2,
- city: loc.address?.city,
- state: loc.address?.state,
- postalCode: loc.address?.postalCode,
- country: loc.address?.country,
- }))
- .filter((addr: any) => addr.street),
- };
-
- let result;
- if (externalId) {
- // Update existing vendor in accounting system
- result = await provider.updateVendor(externalId, accountingVendorData);
- } else {
- // Create new vendor in accounting system
- result = await provider.createVendor(accountingVendorData);
- }
-
- // Update Carbon supplier with external ID
- await client
- .from("supplier")
- .update({
- externalId: {
- ...((supplier.data.externalId as any) || {}),
- externalId: result.id,
- syncToken: (result as any).syncToken,
- accountingProvider: provider.getProviderInfo().name,
- lastSyncedAt: new Date().toISOString(),
- },
- updatedAt: new Date().toISOString(),
- })
- .eq("id", supplierId);
-
- return {
- supplierId,
- externalId: result.id,
- operation: externalId ? "update" : "create",
- status: "success",
- };
-}
-
-async function deactivateCustomer(
- client: SupabaseClient<Database>,
- companyId: string,
- externalId?: string
-): Promise<any> {
- if (!externalId) {
- throw new Error("External ID required for deactivation");
- }
-
- const result = await client
- .from("customer")
- .update({
- active: false,
- updatedAt: new Date().toISOString(),
- })
- .eq("companyId", companyId)
- .eq("externalId->>externalId", externalId)
- .select()
- .single();
-
- if (result.error) throw result.error;
-
- return {
- customerId: result.data.id,
- externalId,
- operation: "delete",
- status: "deactivated",
- };
-}
-
-async function deactivateSupplier(
- client: SupabaseClient<Database>,
- companyId: string,
- externalId?: string
-): Promise<any> {
- if (!externalId) {
- throw new Error("External ID required for deactivation");
- }
-
- const result = await client
- .from("supplier")
- .update({
- active: false,
- updatedAt: new Date().toISOString(),
- })
- .eq("companyId", companyId)
- .eq("externalId->>externalId", externalId)
- .select()
- .single();
-
- if (result.error) throw result.error;
-
- return {
- supplierId: result.data.id,
- externalId,
- operation: "delete",
- status: "deactivated",
- };
-}
-
-async function syncInvoiceFromAccounting(
- client: SupabaseClient<Database>,
- provider: CoreProvider,
- externalId: string,
- companyId: string,
- operation: "create" | "update" | "sync"
-): Promise<any> {
- // Fetch invoice from accounting system
- const invoiceData = await provider.getInvoice(externalId);
- const accountingInvoice = invoiceData.Invoices?.[0];
-
- if (!accountingInvoice) {
- throw new Error(`Invoice ${externalId} not found`);
- }
-
- console.log(
- `Processing invoice ${externalId} of type ${accountingInvoice.Type} for contact ${accountingInvoice.Contact?.ContactID}`
- );
-
- // Invoice processing would typically include:
- // 1. Creating/updating the invoice record
- // 2. Processing line items
- // 3. Handling payments and status updates
-
- // For now, we'll focus on ensuring the related contact is synced
- // The actual invoice sync logic would be implemented based on your invoice table schema
-
- return {
- invoiceId: externalId,
- contactId: accountingInvoice.Contact?.ContactID,
- invoiceType: accountingInvoice.Type,
- operation,
- status: "processed",
- message:
- "Invoice processed, related contact should be synced via webhook handler",
- };
-}
diff --git a/packages/jobs/trigger/event/queue.ts b/packages/jobs/trigger/event/queue.ts
new file mode 100644
index 0000000000..d076ac619f
--- /dev/null
+++ b/packages/jobs/trigger/event/queue.ts
@@ -0,0 +1,154 @@
+import {
+ getPostgresClient,
+ getPostgresConnectionPool,
+ KyselyDatabase,
+} from "@carbon/database/client";
+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 { syncTask } from "./sync.ts";
+import { webhookTask } from "./webhook.ts";
+import { workflowDispatchTask } from "./workflow.ts";
+
+const QUEUE_NAME = "event_system"; // Name of the PGMQ queue
+const BATCH_SIZE = 250; // Number of messages to process per run
+const VISIBILITY_TIMEOUT = 30; // Seconds a message is hidden after being read
+
+const getDatabaseClient = (size: number) => {
+ const pool = getPostgresConnectionPool(size);
+ return getPostgresClient(
+ pool,
+ PostgresDriver
+ ) as unknown as Kysely<KyselyDatabase>;
+};
+
+const pg = getDatabaseClient(1);
+
+type QueueJob = {
+ msg_id: number;
+ message: QueueMessage;
+};
+
+export const eventQueueTask = schedules.task({
+ id: "event-queue",
+ description: "Polls PGMQ and routes events",
+ cron: "* * * * *",
+ retry: {
+ maxAttempts: 2,
+ randomize: true,
+ },
+ async run() {
+ // 1. Read Batch (PGMQ returns these sorted by ID/Time)
+ const { rows: jobs } =
+ await sql<QueueJob>`SELECT * FROM pgmq.read(${QUEUE_NAME}, ${VISIBILITY_TIMEOUT}, ${BATCH_SIZE})`.execute(
+ pg
+ );
+
+ if (jobs.length === 0) return { processed: 0 };
+
+ let total: number[] = [];
+
+ // Arrays for batching
+ const grouped: Record<HandlerType, QueueJob[]> = {
+ WEBHOOK: [],
+ WORKFLOW: [],
+ SYNC: [],
+ };
+
+ // 2. Sort into Buckets
+ for (const job of jobs) {
+ grouped[job.message.handlerType].push(job);
+ }
+
+ const { webhooks, syncs, workflows } = await all({
+ async webhooks() {
+ let queue: number[] = [];
+
+ if (grouped.WEBHOOK.length === 0) return queue;
+
+ const tasks = grouped.WEBHOOK.map((job) => {
+ const event = job.message.event;
+ queue.push(job.msg_id);
+
+ return {
+ payload: {
+ url: job.message.handlerConfig.url,
+ config: job.message.handlerConfig,
+ data: event,
+ },
+ options: {
+ idempotencyKey: `wh_${job.msg_id}`,
+ // This tells Trigger.dev: "Queue this, but don't run it until
+ // any previous tasks for this specific record are finished."
+ concurrencyKey: `record_${event.table}_${event.recordId}`,
+ },
+ };
+ });
+
+ await webhookTask.batchTrigger(tasks);
+
+ return queue;
+ },
+ async workflows() {
+ let queue: number[] = [];
+
+ if (grouped.WORKFLOW.length === 0) return queue;
+
+ const tasks = grouped.WORKFLOW.map((job) => {
+ const event = job.message.event;
+ queue.push(job.msg_id);
+
+ return {
+ payload: {
+ workflowId: job.message.handlerConfig.workflowId,
+ data: event,
+ },
+ options: {
+ idempotencyKey: `wf_${job.msg_id}`,
+ concurrencyKey: `record_${event.table}_${event.recordId}`,
+ },
+ };
+ });
+
+ await workflowDispatchTask.batchTrigger(tasks);
+
+ return queue;
+ },
+ async syncs() {
+ let queue: number[] = [];
+
+ if (grouped.SYNC.length === 0) return queue;
+
+ const records = grouped.SYNC.map((job) => {
+ queue.push(job.msg_id);
+
+ return {
+ event: job.message.event,
+ companyId: job.message.companyId,
+ handlerConfig: job.message.handlerConfig,
+ };
+ });
+
+ await syncTask.trigger({
+ records,
+ });
+
+ return queue;
+ },
+ });
+
+ total = total.concat(webhooks, workflows, syncs);
+
+ // 5. Delete from PGMQ
+ // We delete immediately because we have successfully offloaded
+ // the ordering responsibility to Trigger.dev's internal queue.
+ if (total.length > 0) {
+ await sql`SELECT pgmq.delete(${QUEUE_NAME}, id::bigint) FROM unnest(${total}::bigint[]) AS id`.execute(
+ pg
+ );
+ }
+
+ return { routed: total.length };
+ },
+});
diff --git a/packages/jobs/trigger/event/sync.ts b/packages/jobs/trigger/event/sync.ts
new file mode 100644
index 0000000000..e72dbe3d1b
--- /dev/null
+++ b/packages/jobs/trigger/event/sync.ts
@@ -0,0 +1,190 @@
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ getPostgresClient,
+ getPostgresConnectionPool,
+} from "@carbon/database/client";
+import { EventSchema } from "@carbon/database/event";
+import {
+ AccountingEntityType,
+ BatchSyncResult,
+ getAccountingIntegration,
+ getProviderIntegration,
+ ProviderID,
+ SyncFactory,
+} from "@carbon/ee/accounting";
+import { groupBy } from "@carbon/utils";
+import { logger, task } from "@trigger.dev/sdk";
+import { PostgresDriver } from "kysely";
+import { z } from "zod";
+
+const SyncRecordSchema = z.object({
+ event: EventSchema,
+ companyId: z.string(),
+ handlerConfig: z.object({
+ provider: z.nativeEnum(ProviderID),
+ }),
+});
+
+const SyncPayloadSchema = z.object({
+ records: z.array(SyncRecordSchema),
+});
+
+export type SyncPayload = z.infer<typeof SyncPayloadSchema>;
+
+// Map database table names to accounting entity types
+const TABLE_TO_ENTITY_MAP: Partial<Record<string, AccountingEntityType>> = {
+ customer: "customer",
+ supplier: "vendor",
+ item: "item",
+ purchaseOrder: "purchaseOrder",
+ purchaseInvoice: "bill",
+ salesInvoice: "invoice",
+};
+
+function getEntityTypeFromTable(table: string): AccountingEntityType | null {
+ return TABLE_TO_ENTITY_MAP[table] ?? null;
+}
+
+export const syncTask = task({
+ id: "event-handler-sync",
+ maxDuration: 5 * 60 * 1000, // 5 minutes
+ run: async (input: unknown) => {
+ const payload = SyncPayloadSchema.parse(input);
+
+ logger.info(`Processing ${payload.records.length} sync events`);
+
+ const results = {
+ success: [] as BatchSyncResult[],
+ failed: [] as { recordId: string; error: string }[],
+ skipped: [] as { recordId: string; reason: string }[],
+ };
+
+ // Group records by (companyId, provider) for efficient batch processing
+ const byCompanyProvider = groupBy(payload.records, (r) => {
+ const companyId = r.companyId;
+ const provider = r.handlerConfig.provider;
+ return `${companyId}:${provider}`;
+ });
+
+ const pool = getPostgresConnectionPool(10);
+ const kysely = getPostgresClient(pool, PostgresDriver);
+ const client = getCarbonServiceRole();
+
+ try {
+ for (const [key, records] of Object.entries(byCompanyProvider)) {
+ const [companyId, provider] = key.split(":");
+
+ if (!companyId || companyId === "undefined" || !provider) {
+ for (const r of records) {
+ results.skipped.push({
+ recordId: r.event.recordId,
+ reason: "Missing companyId or provider",
+ });
+ }
+ continue;
+ }
+
+ try {
+ // Get integration and provider instance
+ const integration = await getAccountingIntegration(
+ client,
+ companyId,
+ provider as ProviderID
+ );
+
+ const providerInstance = getProviderIntegration(
+ client,
+ companyId,
+ provider as ProviderID,
+ integration.metadata
+ );
+
+ // Group by entity type
+ const byEntityType = groupBy(records, (r) => {
+ const entityType = getEntityTypeFromTable(r.event.table);
+ return entityType ?? "unknown";
+ });
+
+ for (const [entityType, entityRecords] of Object.entries(
+ byEntityType
+ )) {
+ if (entityType === "unknown") {
+ for (const r of entityRecords) {
+ results.skipped.push({
+ recordId: r.event.recordId,
+ reason: `Table '${r.event.table}' has no entity mapping`,
+ });
+ }
+ continue;
+ }
+
+ // Separate by operation
+ const inserts = entityRecords.filter(
+ (r) => r.event.operation === "INSERT"
+ );
+ const updates = entityRecords.filter(
+ (r) => r.event.operation === "UPDATE"
+ );
+ const deletes = entityRecords.filter(
+ (r) => r.event.operation === "DELETE"
+ );
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId,
+ provider: providerInstance,
+ config: providerInstance.getSyncConfig(
+ entityType as AccountingEntityType
+ ),
+ entityType: entityType as AccountingEntityType,
+ });
+
+ // Process INSERTs and UPDATEs (push to accounting)
+ const toSync = [...inserts, ...updates];
+ if (toSync.length > 0) {
+ const entityIds = toSync.map((r) => r.event.recordId);
+
+ logger.info(
+ `Pushing ${entityIds.length} ${entityType} entities to accounting`
+ );
+
+ const result = await syncer.pushBatchToAccounting(entityIds);
+
+ logger.info("Sync result:", { entityType, result });
+
+ results.success.push(result);
+ }
+
+ // Handle DELETEs (log for now, not yet implemented in syncers)
+ for (const del of deletes) {
+ results.skipped.push({
+ recordId: del.event.recordId,
+ reason: "DELETE operations not yet implemented",
+ });
+ }
+ }
+ } catch (error) {
+ logger.error(`Failed to process sync for ${key}:`, error);
+ for (const r of records) {
+ results.failed.push({
+ recordId: r.event.recordId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }
+ }
+ } catch (error) {
+ logger.error("Sync task failed:", error);
+ } finally {
+ await pool.end();
+ }
+
+ logger.info("Sync task completed", {
+ successCount: results.success.reduce((acc, r) => acc + r.successCount, 0),
+ failedCount: results.failed.length,
+ skippedCount: results.skipped.length,
+ });
+
+ return results;
+ },
+});
diff --git a/packages/jobs/trigger/event/webhook.ts b/packages/jobs/trigger/event/webhook.ts
new file mode 100644
index 0000000000..948f4941d5
--- /dev/null
+++ b/packages/jobs/trigger/event/webhook.ts
@@ -0,0 +1,32 @@
+import { logger, task } from "@trigger.dev/sdk/v3";
+import axios from "axios";
+import { z } from "zod";
+
+const webhookPayloadSchema = z.object({
+ url: z.string().url(),
+ data: z.any(),
+ config: z
+ .object({
+ headers: z.record(z.string()).optional(),
+ })
+ .passthrough(),
+});
+
+export type WebhookPayload = z.infer<typeof webhookPayloadSchema>;
+
+// 1. Generic Webhook Worker
+export const webhookTask = task({
+ id: "event-handler-webhook",
+ retry: {
+ maxAttempts: 3, // Auto-retry on 500s or timeouts
+ factor: 2,
+ randomize: true,
+ },
+ run: async (payload: WebhookPayload) => {
+ logger.info(`Firing webhook to ${payload.url}`);
+
+ await axios.post(payload.url, payload.data, {
+ headers: payload.config.headers,
+ });
+ },
+});
\ No newline at end of file
diff --git a/packages/jobs/trigger/event/workflow.ts b/packages/jobs/trigger/event/workflow.ts
new file mode 100644
index 0000000000..195c4a4efd
--- /dev/null
+++ b/packages/jobs/trigger/event/workflow.ts
@@ -0,0 +1,20 @@
+import { logger, task } from "@trigger.dev/sdk";
+import { z } from "zod";
+
+const workflowPayloadSchema = z.object({
+ workflowId: z.string(),
+ data: z.any(),
+});
+
+export type WorkflowPayload = z.infer<typeof workflowPayloadSchema>;
+
+// 2. Workflow Trigger Worker
+export const workflowDispatchTask = task({
+ id: "event-handler-workflow",
+ run: async (payload: WorkflowPayload) => {
+ logger.info(`Triggering workflow ${payload.workflowId}`);
+
+ // Here you would trigger another business logic task
+ // e.g., await tasks.trigger(payload.workflowId, payload.data);
+ },
+});
diff --git a/packages/jobs/trigger/from-accounting-sync.ts b/packages/jobs/trigger/from-accounting-sync.ts
deleted file mode 100644
index 837cf5a3df..0000000000
--- a/packages/jobs/trigger/from-accounting-sync.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-/**
- * Task to sync entities from accounting providers to Carbon
- */
-import { getCarbonServiceRole } from "@carbon/auth";
-import {
- AccountingEntity,
- AccountingSyncSchema,
- EntityMap,
- getAccountingIntegration,
- getEntityWithExternalId,
- getProviderIntegration,
- SyncFn,
-} from "@carbon/ee/accounting";
-import { logger, task } from "@trigger.dev/sdk";
-import z from "zod";
-
-const PayloadSchema = AccountingSyncSchema.extend({
- syncDirection: AccountingSyncSchema.shape.syncDirection.exclude([
- "to-accounting",
- ]),
-});
-
-type Payload = z.infer<typeof PayloadSchema>;
-
-const UPSERT_MAP: Record<keyof EntityMap, SyncFn> = {
- async customer({ client, entity, payload, provider }) {
- const customer = await getEntityWithExternalId(
- client,
- "customer",
- payload.companyId,
- provider.id,
- { externalId: entity.entityId }
- );
-
- if (!customer && customer) {
- logger.info(`Customer ${entity.entityId} found, updating...`);
-
- const id = customer.externalId[provider.id].id;
-
- const remote = await provider.contacts.get(id);
-
- return {
- id: entity.entityId,
- message: "Updated successfully",
- };
- }
-
- logger.info(`Customer ${entity.entityId} not found, creating...`);
-
- // If not found, fetch from provider and create a new customer
- const remote = await provider.contacts.get(entity.entityId);
-
- if (!remote.isCustomer) {
- return {
- id: entity.entityId,
- message: "Skipped: Contact is not a customer",
- };
- }
-
- logger.info(`Inserting customer with contact id: ${remote.id}`, remote);
-
- try {
- } catch (error) {
- logger.error(
- `Failed to create customer for contact id: ${remote.id} ${error.message}`
- );
-
- return {
- id: entity.entityId,
- message: `Failed to create customer: ${
- error instanceof Error ? error.message : "Unknown error"
- }`,
- };
- }
-
- return {
- id: entity.entityId,
- message: "Created successfully",
- };
- },
- async vendor({ client, entity, payload, provider }) {},
-};
-
-const DELETE_MAP: Record<keyof EntityMap, SyncFn> = {
- async customer({ client, entity, payload, provider }) {
- const customer = await getEntityWithExternalId(
- client,
- "customer",
- payload.companyId,
- provider.id,
- { id: entity.entityId }
- );
-
- // if (customer.error || !customer.data) {
- // throw new Error(`Customer ${entity.entityId} not found`);
- // }
-
- // const externalId = customer.data.externalId[provider.id];
-
- return {
- id: entity.entityId,
- message: "Deleted successfully",
- };
- },
- async vendor({ client, entity, payload, provider }) {},
-};
-
-export const fromAccountsSyncTask = task({
- id: "from-accounting-sync",
- run: async (input: Payload) => {
- const payload = PayloadSchema.parse(input);
-
- const client = getCarbonServiceRole();
-
- const integration = await getAccountingIntegration(
- client,
- payload.companyId,
- payload.provider
- );
-
- const provider = getProviderIntegration(
- client,
- payload.companyId,
- integration.id,
- integration.config
- );
-
- const results = {
- success: [] as any[],
- failed: [] as { entity: AccountingEntity; error: string }[],
- };
-
- for (const entity of payload.entities) {
- try {
- const isUpsert =
- entity.operation === "create" ||
- entity.operation === "update" ||
- entity.operation === "sync";
-
- const handler = isUpsert
- ? UPSERT_MAP[entity.entityType]
- : DELETE_MAP[entity.entityType];
-
- const result = await handler({
- client,
- entity,
- provider,
- payload: { syncDirection: payload.syncDirection, ...payload },
- });
-
- results.success.push(result);
- } catch (error) {
- console.error(
- `Failed to process ${entity.entityType} ${entity.entityId}:`,
- error
- );
-
- results.failed.push({
- entity,
- error: error instanceof Error ? error.message : "Unknown error",
- });
- }
- }
-
- return results;
- },
-});
diff --git a/packages/jobs/trigger/linear.ts b/packages/jobs/trigger/linear.ts
index a7164535b0..536ce82d87 100644
--- a/packages/jobs/trigger/linear.ts
+++ b/packages/jobs/trigger/linear.ts
@@ -54,13 +54,20 @@ export const syncIssueFromLinear = task({
throw new Error("Failed to fetch integration from Carbon");
}
- const action = await carbon
- .from("nonConformanceActionTask")
- .select("id")
- .eq("externalId->linear->>id", payload.event.data.id)
+ // Look up the action task via the mapping table
+ const mapping = await carbon
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("entityType", "nonConformanceActionTask")
+ .eq("integration", "linear")
+ .eq("externalId", payload.event.data.id)
.eq("companyId", payload.companyId)
.maybeSingle();
+ const action = mapping.data
+ ? { data: { id: mapping.data.entityId } }
+ : { data: null };
+
if (!action.data) {
return {
success: false,
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index c435a4e55e..f0d89cab47 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -204,16 +204,18 @@ export const paperlessPartsTask = task({
);
}
- // Check if quote already exists
- const existingQuote = await carbon
- .from("quote")
- .select("id")
- .eq("externalId->>paperlessId", quotePayload.uuid)
+ // Check if quote already exists via the mapping table
+ const existingQuoteMapping = await carbon
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("entityType", "quote")
+ .eq("integration", "paperlessId")
+ .eq("externalId", quotePayload.uuid)
.eq("companyId", payload.companyId)
.maybeSingle();
- if (existingQuote?.data?.id) {
- console.log("Quote already exists", existingQuote.data.id);
+ if (existingQuoteMapping?.data?.entityId) {
+ console.log("Quote already exists", existingQuoteMapping.data.entityId);
result = {
success: true,
message: "Quote already exists",
@@ -281,9 +283,6 @@ export const paperlessPartsTask = task({
exchangeRateUpdatedAt: undefined as string | undefined,
expirationDate: undefined as string | undefined,
revisionId: ppQuoteRevisionNumber ?? 0,
- externalId: {
- paperlessId: quotePayload.uuid,
- },
};
const [quoteCustomerPayment, quoteCustomerShipping, quoteOpportunity] =
@@ -345,6 +344,16 @@ export const paperlessPartsTask = task({
const quoteId = insert.data?.[0]?.id;
if (!quoteId) return insert;
+ // Create the mapping for the new quote
+ await carbon.from("externalIntegrationMapping").insert({
+ entityType: "quote",
+ entityId: quoteId,
+ integration: "paperlessId",
+ externalId: quotePayload.uuid,
+ companyId: payload.companyId,
+ allowDuplicateExternalId: false
+ });
+
const [quoteShipment, quotePayment, quoteExternalLink] =
await Promise.all([
carbon.from("quoteShipment").insert([
@@ -444,23 +453,25 @@ export const paperlessPartsTask = task({
const orderData = OrderSchema.parse(order.data);
- // Check if order already exists
- const existingOrder = await carbon
- .from("salesOrder")
- .select("id")
- .eq("externalId->>paperlessId", orderPayload.uuid)
+ // Check if order already exists via the mapping table
+ const existingOrderMapping = await carbon
+ .from("externalIntegrationMapping")
+ .select("entityId")
+ .eq("entityType", "salesOrder")
+ .eq("integration", "paperlessId")
+ .eq("externalId", orderPayload.uuid)
.eq("companyId", payload.companyId)
.maybeSingle();
- if (existingOrder?.data?.id) {
- console.log("Order already exists", existingOrder.data.id);
+ if (existingOrderMapping?.data?.entityId) {
+ console.log("Order already exists", existingOrderMapping.data.entityId);
const status = getCarbonOrderStatus(orderData.status);
const update = await carbon
.from("salesOrder")
.update({ status })
- .eq("id", existingOrder.data.id);
+ .eq("id", existingOrderMapping.data.entityId);
if (update.error) {
console.log("Failed to update sales order", update.error);
@@ -601,9 +612,6 @@ export const paperlessPartsTask = task({
],
}
: null,
- externalId: {
- paperlessId: orderData.uuid,
- },
},
])
.select("id, salesOrderId");
@@ -626,6 +634,16 @@ export const paperlessPartsTask = task({
break;
}
+ // Create the mapping for the new sales order
+ await carbon.from("externalIntegrationMapping").insert({
+ entityType: "salesOrder",
+ entityId: salesOrderId,
+ integration: "paperlessId",
+ externalId: orderData.uuid,
+ companyId: payload.companyId,
+ allowDuplicateExternalId: false
+ });
+
const [orderShipment, orderPayment] = await Promise.all([
carbon.from("salesOrderShipment").insert([
{
diff --git a/packages/jobs/trigger/sync-external-accounting.ts b/packages/jobs/trigger/sync-external-accounting.ts
new file mode 100644
index 0000000000..7ad293a368
--- /dev/null
+++ b/packages/jobs/trigger/sync-external-accounting.ts
@@ -0,0 +1,118 @@
+/**
+ * Task to sync entities from accounting providers to Carbon
+ */
+import { getCarbonServiceRole } from "@carbon/auth";
+import {
+ getPostgresClient,
+ getPostgresConnectionPool,
+} from "@carbon/database/client";
+import {
+ AccountingEntity,
+ BatchSyncResult,
+ getAccountingIntegration,
+ getProviderIntegration,
+ SyncFactory,
+} from "@carbon/ee/accounting";
+
+import { groupBy } from "@carbon/utils";
+import { logger, task } from "@trigger.dev/sdk";
+import { PostgresDriver } from "kysely";
+import z from "zod";
+import { AccountingSyncSchema } from "../../ee/src/accounting/core/models.ts";
+
+const PayloadSchema = AccountingSyncSchema.extend({
+ syncDirection: AccountingSyncSchema.shape.syncDirection,
+});
+
+type Payload = z.infer<typeof PayloadSchema>;
+
+export const syncExternalAccountingTask = task({
+ id: "sync-external-accounting",
+ maxDuration: 5 * 60 * 1000, // 5 minutes
+ run: async (input: Payload) => {
+ const payload = PayloadSchema.parse(input);
+
+ const client = getCarbonServiceRole();
+
+ const integration = await getAccountingIntegration(
+ client,
+ payload.companyId,
+ payload.provider
+ );
+
+ const provider = getProviderIntegration(
+ client,
+ payload.companyId,
+ integration.id,
+ integration.metadata
+ );
+
+ const pool = getPostgresConnectionPool(10);
+ const kysely = getPostgresClient(pool, PostgresDriver);
+
+ const results = {
+ success: [] as BatchSyncResult[],
+ failed: [] as { entities: AccountingEntity[]; error: string }[],
+ };
+
+ try {
+ const group = groupBy(payload.entities, (e) => e.entityType);
+
+ for (const [entityType, entities] of Object.entries(group)) {
+ const type = entityType as AccountingEntity["entityType"];
+
+ try {
+ logger.info(
+ `Starting sync for ${entities.length} ${entityType} entities`
+ );
+
+ const syncer = SyncFactory.getSyncer({
+ database: kysely,
+ companyId: payload.companyId,
+ provider,
+ config: provider.getSyncConfig(type),
+ entityType: type,
+ });
+
+ if (entities.length === 0) {
+ logger.info(`No entities to sync for type ${entityType}`);
+ continue;
+ }
+
+ if (input.syncDirection === "push-to-accounting") {
+ const result = await syncer.pushBatchToAccounting(
+ entities.map((e) => e.entityId)
+ );
+
+ logger.info("Sync result:", { entityType, result });
+
+ results.success.push(result);
+ }
+
+ if (input.syncDirection === "pull-from-accounting") {
+ const result = await syncer.pullBatchFromAccounting(
+ entities.map((e) => e.entityId)
+ );
+
+ logger.info("Sync result:", { entityType, result });
+
+ results.success.push(result);
+ }
+ } catch (error) {
+ console.error(`Failed to process ${entityType} entities:`, error);
+
+ results.failed.push({
+ entities: entities,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+ }
+ } catch (error) {
+ logger.error("Sync task failed:", error);
+ } finally {
+ await pool.end();
+ }
+
+ return results;
+ },
+});
diff --git a/packages/jobs/trigger/to-accounting-sync.ts b/packages/jobs/trigger/to-accounting-sync.ts
deleted file mode 100644
index 635e1b745c..0000000000
--- a/packages/jobs/trigger/to-accounting-sync.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * Task to sync entities to accounting providers from Carbon
- */
-import { getCarbonServiceRole } from "@carbon/auth";
-import {
- AccountingEntity,
- AccountingSyncSchema,
- EntityMap,
- getAccountingIntegration,
- getEntityWithExternalId,
- getProviderIntegration,
- SyncFn,
-} from "@carbon/ee/accounting";
-import { task } from "@trigger.dev/sdk";
-import z from "zod";
-
-const PayloadSchema = AccountingSyncSchema.extend({
- syncDirection: AccountingSyncSchema.shape.syncDirection.exclude([
- "from-accounting",
- ]),
-});
-
-type Payload = z.infer<typeof PayloadSchema>;
-
-const UPSERT_MAP: Record<keyof EntityMap, SyncFn> = {
- async customer({ client, entity, payload, provider }) {
- const customer = await getEntityWithExternalId(
- client,
- "customer",
- payload.companyId,
- provider.id,
- { id: entity.entityId }
- );
-
- // const data = {
- // ...entity.data,
- // id: customer ? customer.data.externalId[provider.id].id : undefined,
- // };
-
- // await provider.contacts.upsert(data);
-
- return {
- id: entity.entityId,
- message: "Upserted successfully",
- };
- },
- async vendor({ client, entity, payload, provider }) {},
-};
-
-const DELETE_MAP: Record<keyof EntityMap, SyncFn> = {
- async customer({ client, entity, payload, provider }) {
- const customer = await getEntityWithExternalId(
- client,
- "customer",
- payload.companyId,
- provider.id,
- { id: entity.entityId }
- );
-
- // if (customer.error || !customer.data) {
- // throw new Error(`Customer ${entity.entityId} not found`);
- // }
-
- // const externalId = customer.data.externalId[provider.id];
-
- // await provider.contacts.delete(externalId.id);
-
- return {
- id: entity.entityId,
- message: "Deleted successfully",
- };
- },
- async vendor({ client, entity, payload, provider }) {},
-};
-
-export const toAccountsSyncTask = task({
- id: "to-accounting-sync",
- run: async (input: Payload) => {
- const payload = PayloadSchema.parse(input);
-
- const client = getCarbonServiceRole();
-
- const integration = await getAccountingIntegration(
- client,
- payload.companyId,
- payload.provider
- );
-
- const provider = getProviderIntegration(
- client,
- payload.companyId,
- integration.id,
- integration.config
- );
-
- const results = {
- success: [] as any[],
- failed: [] as { entity: AccountingEntity; error: string }[],
- };
-
- for (const entity of payload.entities) {
- try {
- const isUpsert =
- entity.operation === "create" ||
- entity.operation === "update" ||
- entity.operation === "sync";
-
- const handler = isUpsert
- ? UPSERT_MAP[entity.entityType]
- : DELETE_MAP[entity.entityType];
-
- const result = await handler({
- client,
- entity,
- provider,
- payload: { syncDirection: payload.syncDirection, ...payload },
- });
-
- results.success.push(result);
- } catch (error) {
- console.error(
- `Failed to process ${entity.entityType} ${entity.entityId}:`,
- error
- );
-
- results.failed.push({
- entity,
- error: error instanceof Error ? error.message : "Unknown error",
- });
- }
- }
-
- return results;
- },
-});
diff --git a/packages/jobs/tsconfig.json b/packages/jobs/tsconfig.json
index a173f9cefc..b49ffca084 100644
--- a/packages/jobs/tsconfig.json
+++ b/packages/jobs/tsconfig.json
@@ -3,6 +3,7 @@
"lib": ["ES2015"],
"outDir": "./dist",
"rootDir": "./trigger",
+ "sourceMap": true,
"allowImportingTsExtensions": true
},
"references": [
diff --git a/packages/react/src/ActionBar.tsx b/packages/react/src/ActionBar.tsx
index 4d230717b7..4beedf63ed 100644
--- a/packages/react/src/ActionBar.tsx
+++ b/packages/react/src/ActionBar.tsx
@@ -7,8 +7,8 @@ import {
useRef,
useState
} from "react";
-
-import { Button, type ButtonProps } from "./Button";
+import type { ButtonProps } from "./Button";
+import { Button, } from "./Button";
import { cn } from "./utils/cn";
type Position = { x: number; y: number };
diff --git a/packages/react/src/Alert.tsx b/packages/react/src/Alert.tsx
index aa7c100b06..c87bd34448 100644
--- a/packages/react/src/Alert.tsx
+++ b/packages/react/src/Alert.tsx
@@ -1,4 +1,5 @@
-import { cva, type VariantProps } from "class-variance-authority";
+import type { VariantProps } from "class-variance-authority";
+import { cva, } from "class-variance-authority";
import type { HTMLAttributes } from "react";
import { forwardRef } from "react";
diff --git a/packages/react/src/Badge.tsx b/packages/react/src/Badge.tsx
index d42fd664cc..89aff49813 100644
--- a/packages/react/src/Badge.tsx
+++ b/packages/react/src/Badge.tsx
@@ -1,4 +1,5 @@
-import { cva, type VariantProps } from "class-variance-authority";
+import type { VariantProps } from "class-variance-authority";
+import { cva } from "class-variance-authority";
import type {
ComponentPropsWithoutRef,
ElementRef,
diff --git a/packages/react/src/Button.tsx b/packages/react/src/Button.tsx
index a0ee42ad39..08630b38bc 100644
--- a/packages/react/src/Button.tsx
+++ b/packages/react/src/Button.tsx
@@ -10,15 +10,19 @@ export const buttonVariants = cva(
[
"relative font-medium shrink-0 group inline-flex items-center justify-center select-none transform-gpu initial:border-none disabled:opacity-50",
"focus:!outline-none focus:!ring-0 active:!outline-none active:!ring-0 whitespace-nowrap",
- "after:pointer-events-none after:absolute after:-inset-[3px] after:rounded-lg after:border after:border-blue-500 after:opacity-0 after:ring-2 after:ring-blue-500/20 after:transition-opacity focus-visible:after:opacity-100 active:after:opacity-0",
- "before:pointer-events-none before:bg-gradient-to-b before:transition-opacity before:from-white/[0.12] before:absolute before:inset-0 before:z-[1] before:rounded before:opacity-0",
- "hover:scale-95 transform-gpu will-change-auto focus-visible:scale-95 transition-all duration-150 ease-in-out"
+ "after:pointer-events-none after:absolute after:-inset-[3px] after:rounded-lg after:border after:border-blue-500 after:opacity-0 after:ring-2 after:ring-blue-500/20 after:transition-opacity after:duration-150 after:ease-out focus-visible:after:opacity-100 active:after:opacity-0",
+ // Transition: background/colors use 'ease' (150ms), transform uses 'ease-out' for responsive press feel
+ "transform-gpu transition-[background-color,color,transform,box-shadow] duration-150 ease",
+ // Active state: subtle scale down for tactile press feedback
+ "active:scale-[0.97] active:duration-75 active:ease-out",
+ // Accessibility: respect reduced motion preferences
+ "motion-reduce:transform-none motion-reduce:transition-[background-color,color,box-shadow]"
],
{
variants: {
variant: {
primary:
- "bg-gradient-to-br from-primary/90 to-primary text-primary-foreground hover:bg-primary/90 saturate-[105%] shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)]",
+ "bg-gradient-to-br from-primary/90 to-primary text-primary-foreground hover:bg-primary/90 saturate-[105%] shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)] before:pointer-events-none before:bg-gradient-to-b before:transition-opacity before:duration-100 before:ease before:from-white/[0.12] before:absolute before:inset-0 before:z-[1] before:rounded before:opacity-0 hover:before:opacity-100 active:before:opacity-0",
active:
"bg-active text-active-foreground hover:bg-active/90 hover:text-active-foreground shadow-button-base",
secondary:
@@ -26,7 +30,7 @@ export const buttonVariants = cva(
solid:
"bg-accent text-accent-foreground hover:bg-accent/90 shadow-button-base",
destructive:
- "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)]",
+ "bg-destructive text-destructive-foreground hover:bg-destructive/90 shadow-[inset_0px_0.5px_0px_rgb(255_255_255_/_0.32)] before:pointer-events-none before:bg-gradient-to-b before:transition-opacity before:duration-100 before:ease before:from-white/[0.12] before:absolute before:inset-0 before:z-[1] before:rounded before:opacity-0 hover:before:opacity-100 active:before:opacity-0",
ghost:
"bg-transparent hover:bg-primary/10 text-accent-foreground hover:text-accent-foreground/90",
link: "text-foreground hover:text-foreground underline-offset-4 hover:underline px-0 py-0"
diff --git a/packages/react/src/Command.tsx b/packages/react/src/Command.tsx
index 68b1084e11..9d9cb4286d 100644
--- a/packages/react/src/Command.tsx
+++ b/packages/react/src/Command.tsx
@@ -1,6 +1,6 @@
"use client";
-import { type DialogProps } from "@radix-ui/react-dialog";
+import type { DialogProps } from "@radix-ui/react-dialog";
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import { Command as CommandPrimitive } from "cmdk";
diff --git a/packages/react/src/Drawer.tsx b/packages/react/src/Drawer.tsx
index f1207dea7d..e648ce2dc0 100644
--- a/packages/react/src/Drawer.tsx
+++ b/packages/react/src/Drawer.tsx
@@ -1,7 +1,8 @@
"use client";
import * as DialogPrimitive from "@radix-ui/react-dialog";
-import { cva, type VariantProps } from "class-variance-authority";
+import type { VariantProps } from "class-variance-authority";
+import { cva, } from "class-variance-authority";
import type {
ComponentPropsWithoutRef,
ElementRef,
diff --git a/packages/react/src/Label.tsx b/packages/react/src/Label.tsx
index 4f64f07f94..73b3b88f4d 100644
--- a/packages/react/src/Label.tsx
+++ b/packages/react/src/Label.tsx
@@ -1,5 +1,6 @@
import * as LabelPrimitive from "@radix-ui/react-label";
-import { cva, type VariantProps } from "class-variance-authority";
+import type { VariantProps } from "class-variance-authority";
+import { cva, } from "class-variance-authority";
import type { ComponentPropsWithoutRef, ElementRef } from "react";
import { forwardRef } from "react";
diff --git a/packages/react/src/Number.tsx b/packages/react/src/Number.tsx
index 6e435dd3f0..3228e97c47 100644
--- a/packages/react/src/Number.tsx
+++ b/packages/react/src/Number.tsx
@@ -1,6 +1,7 @@
import { forwardRef } from "react";
import * as ReactAria from "react-aria-components";
-import { Input, type InputProps } from "./Input";
+import type { InputProps } from "./Input";
+import { Input, } from "./Input";
import { cn } from "./utils/cn";
export type NumberFieldProps = ReactAria.NumberFieldProps;
diff --git a/packages/react/src/Sidebar.tsx b/packages/react/src/Sidebar.tsx
index c1aae414f0..2822c82c56 100644
--- a/packages/react/src/Sidebar.tsx
+++ b/packages/react/src/Sidebar.tsx
@@ -226,7 +226,7 @@ const Sidebar = React.forwardRef<
{/* This is what handles the sidebar gap on desktop */}
<div
className={cn(
- "duration-200 relative h-svh w-[--sidebar-width] bg-transparent transition-[width] ease-linear",
+ "relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-[cubic-bezier(0.165,0.84,0.44,1)] motion-reduce:transition-none",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
@@ -236,7 +236,7 @@ const Sidebar = React.forwardRef<
/>
<div
className={cn(
- "duration-200 fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] ease-linear md:flex",
+ "fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-[cubic-bezier(0.165,0.84,0.44,1)] motion-reduce:transition-none md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
@@ -300,7 +300,7 @@ const SidebarRail = React.forwardRef<
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
- "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
+ "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all duration-150 ease-out motion-reduce:transition-none after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
"[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
@@ -439,7 +439,7 @@ const SidebarGroupLabel = React.forwardRef<
ref={ref}
data-sidebar="group-label"
className={cn(
- "duration-200 flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opa] ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-[cubic-bezier(0.165,0.84,0.44,1)] motion-reduce:transition-none focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
)}
@@ -460,7 +460,7 @@ const SidebarGroupAction = React.forwardRef<
ref={ref}
data-sidebar="group-action"
className={cn(
- "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
+ "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-[transform,background-color,color] duration-150 ease hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 motion-reduce:transition-none [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"group-data-[collapsible=icon]:hidden",
@@ -512,7 +512,7 @@ const SidebarMenuItem = React.forwardRef<
SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
- "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
+ "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding,background-color,color] duration-150 ease hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 motion-reduce:transition-none [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
{
variants: {
variant: {
@@ -606,7 +606,7 @@ const SidebarMenuAction = React.forwardRef<
ref={ref}
data-sidebar="menu-action"
className={cn(
- "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
+ "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-[transform,background-color,color,opacity] duration-150 ease hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground motion-reduce:transition-none [&>svg]:size-4 [&>svg]:shrink-0",
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 after:md:hidden",
"peer-data-[size=sm]/menu-button:top-1",
@@ -722,7 +722,7 @@ const SidebarMenuSubButton = React.forwardRef<
data-size={size}
data-active={isActive}
className={cn(
- "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
+ "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring transition-[background-color,color] duration-150 ease hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 motion-reduce:transition-none [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
diff --git a/packages/react/src/TextShimmer.tsx b/packages/react/src/TextShimmer.tsx
index 2c4eff1a17..5a08bb43cb 100644
--- a/packages/react/src/TextShimmer.tsx
+++ b/packages/react/src/TextShimmer.tsx
@@ -1,6 +1,7 @@
"use client";
import { motion } from "framer-motion";
-import { type JSX, memo, useMemo } from "react";
+import type { JSX, } from "react";
+import { memo, useMemo } from "react";
import { cn } from "./utils/cn";
export type TextShimmerProps = {
diff --git a/packages/react/src/Toggle.tsx b/packages/react/src/Toggle.tsx
index 12d3c9abc8..6f9e68f0a8 100644
--- a/packages/react/src/Toggle.tsx
+++ b/packages/react/src/Toggle.tsx
@@ -1,7 +1,8 @@
"use client";
import * as TogglePrimitive from "@radix-ui/react-toggle";
-import { cva, type VariantProps } from "class-variance-authority";
+import type { VariantProps } from "class-variance-authority";
+import { cva, } from "class-variance-authority";
import type { ComponentPropsWithoutRef, ElementRef } from "react";
import { forwardRef } from "react";
diff --git a/packages/react/src/utils/cn.ts b/packages/react/src/utils/cn.ts
index 137908a85c..dd05c910bf 100644
--- a/packages/react/src/utils/cn.ts
+++ b/packages/react/src/utils/cn.ts
@@ -1,4 +1,5 @@
-import { type ClassValue, clsx } from "clsx";
+import type { ClassValue, } from "clsx";
+import { clsx } from "clsx";
import { extendTailwindMerge } from "tailwind-merge";
const customTwMerge = extendTailwindMerge({});
diff --git a/packages/remix/src/helper.ts b/packages/remix/src/helper.ts
index fc358cee35..33bf5d27da 100644
--- a/packages/remix/src/helper.ts
+++ b/packages/remix/src/helper.ts
@@ -1,4 +1,4 @@
-import { OperatingSystemPlatform } from "@carbon/react";
+import type { OperatingSystemPlatform } from "@carbon/react";
import { parseAcceptLanguage } from "intl-parse-accept-language";
export const getPreferenceHeaders = (request: Request) => {
diff --git a/packages/remix/src/hooks/useNanoStore.ts b/packages/remix/src/hooks/useNanoStore.ts
index 6312aeecc8..b7c8078ee9 100644
--- a/packages/remix/src/hooks/useNanoStore.ts
+++ b/packages/remix/src/hooks/useNanoStore.ts
@@ -1,5 +1,5 @@
import { useStore } from "@nanostores/react";
-import { type WritableAtom } from "nanostores";
+import type { WritableAtom } from "nanostores";
import { useCallback } from "react";
export function useNanoStore<T>(atom: WritableAtom<T>, idbKey?: string) {
diff --git a/packages/tailwind/package.json b/packages/tailwind/package.json
index 9f1fbca5fa..72b2763498 100644
--- a/packages/tailwind/package.json
+++ b/packages/tailwind/package.json
@@ -1,8 +1,6 @@
{
"name": "@carbon/tailwind",
- "files": [
- "eslint-preset.js"
- ],
+ "files": [],
"main": "index.js",
"peerDependencies": {
"@tailwindcss/container-queries": "^0.1.1",
diff --git a/packages/tiptap/src/extensions/ai-highlight.ts b/packages/tiptap/src/extensions/ai-highlight.ts
index 5c4cd34db1..a09b326fa7 100644
--- a/packages/tiptap/src/extensions/ai-highlight.ts
+++ b/packages/tiptap/src/extensions/ai-highlight.ts
@@ -1,5 +1,7 @@
+import type {
+ Editor,
+} from "@tiptap/core";
import {
- type Editor,
Mark,
markInputRule,
markPasteRule,
diff --git a/packages/tiptap/src/extensions/mention.tsx b/packages/tiptap/src/extensions/mention.tsx
index d528d6595a..4a7be728d3 100644
--- a/packages/tiptap/src/extensions/mention.tsx
+++ b/packages/tiptap/src/extensions/mention.tsx
@@ -7,7 +7,8 @@ import type {
} from "@tiptap/suggestion";
import type { RefObject } from "react";
import tippy, { type Instance, type Props } from "tippy.js";
-import { MentionList, type MentionListRef } from "../components/mention-list";
+import type { MentionListRef } from "../components/mention-list";
+import { MentionList, } from "../components/mention-list";
export interface MentionSuggestion {
id: string;
diff --git a/packages/tiptap/src/plugins/upload-images.tsx b/packages/tiptap/src/plugins/upload-images.tsx
index 546d413d08..985e77ac18 100644
--- a/packages/tiptap/src/plugins/upload-images.tsx
+++ b/packages/tiptap/src/plugins/upload-images.tsx
@@ -1,5 +1,7 @@
-import { type EditorState, Plugin, PluginKey } from "@tiptap/pm/state";
-import { Decoration, DecorationSet, type EditorView } from "@tiptap/pm/view";
+import type { EditorState, } from "@tiptap/pm/state";
+import { Plugin, PluginKey } from "@tiptap/pm/state";
+import type { EditorView } from "@tiptap/pm/view";
+import { Decoration, DecorationSet, } from "@tiptap/pm/view";
const uploadKey = new PluginKey("upload-image");
diff --git a/packages/tiptap/src/utils/index.ts b/packages/tiptap/src/utils/index.ts
index ef27c64065..4c1c55b39c 100644
--- a/packages/tiptap/src/utils/index.ts
+++ b/packages/tiptap/src/utils/index.ts
@@ -1,4 +1,5 @@
-import { Fragment, type Node } from "@tiptap/pm/model";
+import type { Node } from "@tiptap/pm/model";
+import { Fragment, } from "@tiptap/pm/model";
import type { EditorInstance } from "../components";
export function isValidUrl(url: string) {
diff --git a/packages/utils/src/all.ts b/packages/utils/src/all.ts
new file mode 100644
index 0000000000..0b04afac1e
--- /dev/null
+++ b/packages/utils/src/all.ts
@@ -0,0 +1,200 @@
+/**
+ * Promise.all with automatic dependency optimization and full type inference
+ *
+ * Usage:
+ * const { a, b, c } = await all({
+ * a() { return 1 },
+ * async b() { return 'hello' },
+ * async c() { return (await this.$.a) + 10 }
+ * })
+ *
+ * Credits: https://github.com/shuding/better-all/blob/main/lib/index.ts
+ */
+
+// Extract the resolved return type from task functions
+type TaskResult<T> = T extends (...args: any[]) => infer R ? Awaited<R> : never;
+
+// The $ proxy type - all task results as promises
+type DepProxy<T extends Record<string, (...args: any[]) => any>> = {
+ readonly [K in keyof T]: Promise<TaskResult<T[K]>>;
+};
+
+// Context available to each task via `this`
+type TaskContext<T extends Record<string, (...args: any[]) => any>> = {
+ $: DepProxy<T>;
+};
+
+// Result type - all tasks resolved to their return values
+type AllResult<T extends Record<string, (...args: any[]) => any>> = {
+ [K in keyof T]: TaskResult<T[K]>;
+};
+
+// Settled result types for allSettled
+type SettledFulfilled<T> = {
+ status: "fulfilled";
+ value: T;
+};
+
+type SettledRejected = {
+ status: "rejected";
+ reason: any;
+};
+
+type SettledResult<T> = SettledFulfilled<T> | SettledRejected;
+
+// Result type for allSettled - all tasks as settled results
+type AllSettledResult<T extends Record<string, (...args: any[]) => any>> = {
+ [K in keyof T]: SettledResult<TaskResult<T[K]>>;
+};
+
+/**
+ * Internal core implementation for executing tasks with automatic dependency resolution.
+ * This is shared between `all` and `allSettled`.
+ */
+function executeTasksInternal<T extends Record<string, any>>(
+ tasks: T,
+ handleSettled: boolean
+): Promise<any> {
+ const taskNames = Object.keys(tasks) as (keyof T)[];
+ const results = new Map<keyof T, any>();
+ const errors = new Map<keyof T, any>();
+ const resolvers = new Map<
+ keyof T,
+ [(value: any) => void, (reason?: any) => void][]
+ >();
+ const returnValue: Record<string, any> = {};
+
+ const waitForDep = (depName: keyof T): Promise<any> => {
+ if (!(depName in tasks)) {
+ return Promise.reject(new Error(`Unknown task "${String(depName)}"`));
+ }
+ if (results.has(depName)) {
+ return Promise.resolve(results.get(depName));
+ }
+ if (errors.has(depName)) {
+ return Promise.reject(errors.get(depName));
+ }
+ return new Promise((resolve, reject) => {
+ if (!resolvers.has(depName)) {
+ resolvers.set(depName, []);
+ }
+ resolvers.get(depName)!.push([resolve, reject]);
+ });
+ };
+
+ const handleResult = (name: keyof T, value: any) => {
+ results.set(name, value);
+ if (handleSettled) {
+ returnValue[name as string] = { status: "fulfilled", value };
+ } else {
+ returnValue[name as string] = value;
+ }
+ if (resolvers.has(name)) {
+ for (const [resolve] of resolvers.get(name)!) {
+ resolve(value);
+ }
+ }
+ };
+
+ const handleError = (name: keyof T, err: any) => {
+ errors.set(name, err);
+ if (handleSettled) {
+ returnValue[name as string] = { status: "rejected", reason: err };
+ }
+ if (resolvers.has(name)) {
+ for (const [, reject] of resolvers.get(name)!) {
+ reject(err);
+ }
+ }
+ };
+
+ // Create dep proxy
+ const depProxy = new Proxy({} as DepProxy<T>, {
+ get(_, depName: string) {
+ return waitForDep(depName as keyof T);
+ }
+ });
+
+ // Create context with $ proxy
+ const context: TaskContext<T> = { $: depProxy };
+
+ // Run all tasks in parallel
+ const promises = taskNames.map(async (name) => {
+ try {
+ const taskFn = tasks[name];
+ if (typeof taskFn !== "function") {
+ throw new Error(`Task "${String(name)}" is not a function`);
+ }
+
+ const result = await taskFn.call(context);
+ handleResult(name, result);
+ } catch (err) {
+ handleError(name, err);
+ if (!handleSettled) {
+ throw err;
+ }
+ }
+ });
+
+ if (handleSettled) {
+ // For allSettled, wait for all promises to settle (never rejects)
+ return Promise.allSettled(promises).then(() => returnValue);
+ } else {
+ // For all, reject on first error (like Promise.all)
+ return Promise.all(promises).then(() => returnValue);
+ }
+}
+
+/**
+ * Execute tasks with automatic dependency resolution.
+ *
+ * @example
+ * const { a, b, c } = await all({
+ * async a() { return 1 },
+ * async b() { return 'hello' },
+ * async c() { return (await this.$.a) + 10 }
+ * })
+ */
+export function all<T extends Record<string, any>>(
+ tasks: T &
+ ThisType<{
+ $: {
+ [K in keyof T]: ReturnType<T[K]> extends Promise<infer R>
+ ? Promise<R>
+ : Promise<ReturnType<T[K]>>;
+ };
+ }> & {
+ [P in keyof T]: T[P] extends (...args: any[]) => any ? T[P] : never;
+ }
+): Promise<AllResult<T>> {
+ return executeTasksInternal(tasks, false) as Promise<AllResult<T>>;
+}
+
+/**
+ * Execute tasks with automatic dependency resolution, returning settled results for all tasks.
+ * Unlike `all`, this will never reject - failed tasks will be included in the result with their error.
+ *
+ * @example
+ * const { a, b, c } = await allSettled({
+ * async a() { return 1 },
+ * async b() { throw new Error('failed') },
+ * async c() { return (await this.$.a) + 10 }
+ * })
+ * // a: { status: 'fulfilled', value: 1 }
+ * // b: { status: 'rejected', reason: Error('failed') }
+ * // c: { status: 'fulfilled', value: 11 }
+ */
+export function allSettled<T extends Record<string, any>>(
+ tasks: T &
+ ThisType<{
+ $: {
+ [K in keyof T]: ReturnType<T[K]> extends Promise<infer R>
+ ? Promise<R>
+ : Promise<ReturnType<T[K]>>;
+ };
+ }> & {
+ [P in keyof T]: T[P] extends (...args: any[]) => any ? T[P] : never;
+ }
+): Promise<AllSettledResult<T>> {
+ return executeTasksInternal(tasks, true) as Promise<AllSettledResult<T>>;
+}
diff --git a/packages/utils/src/arrays.ts b/packages/utils/src/arrays.ts
index 2b2cc8c753..3f4eddba94 100644
--- a/packages/utils/src/arrays.ts
+++ b/packages/utils/src/arrays.ts
@@ -19,3 +19,12 @@ export const filterEmpty = <
return acc;
}, []);
+
+// Chunk
+export function chunkArray<T>(array: T[], chunkSize: number): T[][] {
+ const chunks: T[][] = [];
+ for (let i = 0; i < array.length; i += chunkSize) {
+ chunks.push(array.slice(i, i + chunkSize));
+ }
+ return chunks;
+}
diff --git a/packages/utils/src/index.ts b/packages/utils/src/index.ts
index fbf9cc8840..8069204c62 100644
--- a/packages/utils/src/index.ts
+++ b/packages/utils/src/index.ts
@@ -1,5 +1,6 @@
export * from "./accounting";
export * from "./address";
+export * from "./all";
export * from "./arrays";
export * from "./bom";
export * from "./color";
@@ -13,6 +14,7 @@ export * from "./keyboard";
export * from "./labels";
export * from "./llm";
export * from "./math";
+export * from "./object";
export * from "./ssr";
export * from "./status";
export * from "./string";
diff --git a/packages/utils/src/object.ts b/packages/utils/src/object.ts
new file mode 100644
index 0000000000..b65d36f242
--- /dev/null
+++ b/packages/utils/src/object.ts
@@ -0,0 +1,40 @@
+export const groupBy = <T, K extends keyof any>(
+ array: T[],
+ getKey: (item: T) => K
+): Record<K, T[]> => {
+ return array.reduce(
+ (result, item) => {
+ const key = getKey(item);
+ if (!result[key]) {
+ result[key] = [];
+ }
+ result[key].push(item);
+ return result;
+ },
+ {} as Record<K, T[]>
+ );
+};
+
+export const pick = <T extends Record<string, any>, K extends keyof T>(
+ obj: T,
+ keys: K[]
+): Pick<T, K> => {
+ const result = {} as Pick<T, K>;
+ for (const key of keys) {
+ if (key in obj) {
+ result[key] = obj[key];
+ }
+ }
+ return result;
+};
+
+export const get = <T extends Record<string, any>, K extends keyof T>(
+ obj: T,
+ key: K,
+ defaultValue: T[K]
+): T[K] => {
+ if (obj[key] === undefined) {
+ return defaultValue;
+ }
+ return obj[key];
+};