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.

Add per-entity owner settings and group UI

Sidwebworksb873a610bc2c
diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
index 0cca81265f..4a6479d73a 100644
--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx
@@ -1,6 +1,7 @@
import type {
IntegrationAction,
IntegrationSetting,
+ IntegrationSettingGroup,
IntegrationSettingOption
} from "@carbon/ee";
import { integrations as availableIntegrations } from "@carbon/ee";
@@ -189,7 +190,7 @@ function SettingField({ setting }: { setting: IntegrationSetting }) {
// Build a simpler label that works well with Radix Select
const label = (
- <span className="flex items-center gap-2">
+ <span key={normalized.value} className="flex items-center gap-2">
{icon}
<span className="font-medium">{normalized.label}</span>
{normalized.description && (
@@ -228,9 +229,11 @@ function SettingField({ setting }: { setting: IntegrationSetting }) {
*/
function SettingsGroup({
name,
+ description,
settings
}: {
name: string;
+ description?: string;
settings: IntegrationSetting[];
}) {
const [isOpen, setIsOpen] = useState(true);
@@ -247,6 +250,9 @@ function SettingsGroup({
}`}
/>
</CollapsibleTrigger>
+ {description && (
+ <p className="text-sm text-muted-foreground">{description}</p>
+ )}
<CollapsibleContent>
<VStack spacing={4} className="pt-2">
{settings.map((setting) => (
@@ -287,33 +293,45 @@ export function IntegrationForm({
// 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 { ungroupedSettings, groupedSettings, groupNames, groupDescriptions } =
+ useMemo(() => {
+ if (!integration) {
+ return {
+ ungroupedSettings: [] as IntegrationSetting[],
+ groupedSettings: new Map<string, IntegrationSetting[]>(),
+ groupNames: [] as string[],
+ groupDescriptions: new Map<string, string | undefined>()
+ };
+ }
- const ungrouped: IntegrationSetting[] = [];
- const grouped = new Map<string, IntegrationSetting[]>();
+ 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]);
+ 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]);
+ }
+ }
+
+ // Build group descriptions map from settingGroups
+ const descriptions = new Map<string, string | undefined>();
+ const settingGroups =
+ (integration as { settingGroups?: IntegrationSettingGroup[] })
+ .settingGroups ?? [];
+ for (const group of settingGroups) {
+ descriptions.set(group.name, group.description);
}
- }
- return {
- ungroupedSettings: ungrouped,
- groupedSettings: grouped,
- groupNames: [...grouped.keys()]
- };
- }, [integration]);
+ return {
+ ungroupedSettings: ungrouped,
+ groupedSettings: grouped,
+ groupNames: [...grouped.keys()],
+ groupDescriptions: descriptions
+ };
+ }, [integration]);
const initialValues = useMemo(() => {
if (!integration) return {};
@@ -407,6 +425,7 @@ export function IntegrationForm({
<SettingsGroup
key={groupName}
name={groupName}
+ description={groupDescriptions.get(groupName)}
settings={groupedSettings.get(groupName) ?? []}
/>
))}
diff --git a/apps/erp/app/routes/api+/integrations.xero.backfill.ts b/apps/erp/app/routes/api+/integrations.xero.backfill.ts
index 45dd163cdc..6c47e0e04a 100644
--- a/apps/erp/app/routes/api+/integrations.xero.backfill.ts
+++ b/apps/erp/app/routes/api+/integrations.xero.backfill.ts
@@ -8,11 +8,10 @@ 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")
+ backfillItems: z.boolean().optional().default(true)
+ // Note: syncConfig.entities.{entity}.owner settings are read directly
+ // by the provider from the integration metadata, so we don't need to
+ // pass them explicitly to the backfill task
});
export const config = {
@@ -72,19 +71,19 @@ export async function action({ request }: ActionFunctionArgs) {
try {
// Trigger the backfill task with settings
+ // Note: Entity owner settings (syncConfig) are read directly by the
+ // provider from integration metadata, so we only pass entity toggles
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()}`,
diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
index c8c02b153f..6676e6d8c5 100644
--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx
@@ -9,6 +9,93 @@ import { getIntegration, IntegrationForm } from "~/modules/settings";
import { upsertCompanyIntegration } from "~/modules/settings/settings.server";
import { path } from "~/utils/path";
+/**
+ * Transforms flat owner settings (customerOwner, vendorOwner, etc.) into
+ * the nested syncConfig.entities structure expected by the accounting sync.
+ */
+function buildIntegrationMetadata(
+ existingMetadata: Record<string, unknown>,
+ formData: Record<string, unknown>
+): Record<string, unknown> {
+ // Extract owner settings from form data
+ const ownerSettings = {
+ customerOwner: formData.customerOwner as string | undefined,
+ vendorOwner: formData.vendorOwner as string | undefined,
+ itemOwner: formData.itemOwner as string | undefined,
+ invoiceOwner: formData.invoiceOwner as string | undefined,
+ billOwner: formData.billOwner as string | undefined
+ };
+
+ // Check if any owner settings are present
+ const hasOwnerSettings = Object.values(ownerSettings).some(
+ (v) => v !== undefined
+ );
+
+ if (!hasOwnerSettings) {
+ // No owner settings, just merge as-is
+ return { ...existingMetadata, ...formData };
+ }
+
+ // Build syncConfig.entities from owner settings
+ const existingSyncConfig =
+ (existingMetadata.syncConfig as Record<string, unknown>) ?? {};
+ const existingEntities =
+ (existingSyncConfig.entities as Record<string, unknown>) ?? {};
+
+ const syncConfig = {
+ ...existingSyncConfig,
+ entities: {
+ ...existingEntities,
+ ...(ownerSettings.customerOwner && {
+ customer: {
+ ...(existingEntities.customer as Record<string, unknown>),
+ owner: ownerSettings.customerOwner
+ }
+ }),
+ ...(ownerSettings.vendorOwner && {
+ vendor: {
+ ...(existingEntities.vendor as Record<string, unknown>),
+ owner: ownerSettings.vendorOwner
+ }
+ }),
+ ...(ownerSettings.itemOwner && {
+ item: {
+ ...(existingEntities.item as Record<string, unknown>),
+ owner: ownerSettings.itemOwner
+ }
+ }),
+ ...(ownerSettings.invoiceOwner && {
+ invoice: {
+ ...(existingEntities.invoice as Record<string, unknown>),
+ owner: ownerSettings.invoiceOwner
+ }
+ }),
+ ...(ownerSettings.billOwner && {
+ bill: {
+ ...(existingEntities.bill as Record<string, unknown>),
+ owner: ownerSettings.billOwner
+ }
+ })
+ }
+ };
+
+ // Remove owner settings from formData since they're now in syncConfig
+ const {
+ customerOwner,
+ vendorOwner,
+ itemOwner,
+ invoiceOwner,
+ billOwner,
+ ...restFormData
+ } = formData;
+
+ return {
+ ...existingMetadata,
+ ...restFormData,
+ syncConfig
+ };
+}
+
export async function loader({ request, params }: LoaderFunctionArgs) {
const { client, companyId } = await requirePermissions(request, {
update: "settings"
@@ -33,9 +120,42 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
};
}
+ // Extract owner settings from syncConfig back into flat fields for the form
+ const metadata = (integrationData.data.metadata ?? {}) as Record<
+ string,
+ unknown
+ >;
+ const flattenedMetadata = flattenSyncConfigToOwnerSettings(metadata);
+
return {
installed: integrationData.data.active,
- metadata: (integrationData.data.metadata ?? {}) as Record<string, unknown>
+ metadata: flattenedMetadata
+ };
+}
+
+/**
+ * Extracts owner settings from nested syncConfig.entities back into
+ * flat fields (customerOwner, vendorOwner, etc.) for the form.
+ */
+function flattenSyncConfigToOwnerSettings(
+ metadata: Record<string, unknown>
+): Record<string, unknown> {
+ const syncConfig = metadata.syncConfig as Record<string, unknown> | undefined;
+ const entities = syncConfig?.entities as
+ | Record<string, Record<string, unknown>>
+ | undefined;
+
+ if (!entities) {
+ return metadata;
+ }
+
+ return {
+ ...metadata,
+ customerOwner: entities.customer?.owner,
+ vendorOwner: entities.vendor?.owner,
+ itemOwner: entities.item?.owner,
+ invoiceOwner: entities.invoice?.owner,
+ billOwner: entities.bill?.owner
};
}
@@ -69,13 +189,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
const existingMetadata =
(existing.data?.metadata as Record<string, unknown>) ?? {};
+ // Build metadata, transforming owner settings into syncConfig structure
+ const metadata = buildIntegrationMetadata(existingMetadata, d);
+
const update = await upsertCompanyIntegration(client, {
id: integrationId,
active: true,
- metadata: {
- ...existingMetadata,
- ...d
- },
+ metadata,
companyId,
updatedBy: userId
});
diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.ts
index 9be841afd9..325168b937 100644
--- a/packages/ee/src/accounting/core/service.ts
+++ b/packages/ee/src/accounting/core/service.ts
@@ -60,7 +60,25 @@ export const getProviderIntegration = (
) => {
const { accessToken, refreshToken, tenantId } = config?.credentials || {};
- const syncConfig = DEFAULT_SYNC_CONFIG; // TODO use config?.syncConfig to make it configurable
+ // Merge user's sync config with defaults (user settings override defaults)
+ const syncConfig = config?.syncConfig
+ ? {
+ entities: {
+ ...DEFAULT_SYNC_CONFIG.entities,
+ ...Object.fromEntries(
+ Object.entries(config.syncConfig.entities).map(([key, value]) => [
+ key,
+ {
+ ...DEFAULT_SYNC_CONFIG.entities[
+ key as keyof typeof DEFAULT_SYNC_CONFIG.entities
+ ],
+ ...value
+ }
+ ])
+ )
+ }
+ }
+ : DEFAULT_SYNC_CONFIG;
// Create a callback function to update the integration metadata when tokens are refreshed
const onTokenRefresh = async (auth: ProviderCredentials) => {
diff --git a/packages/ee/src/fns.ts b/packages/ee/src/fns.ts
index 35577fc3e0..5e99ef1c76 100644
--- a/packages/ee/src/fns.ts
+++ b/packages/ee/src/fns.ts
@@ -17,6 +17,7 @@ const withServerOnly = () => {
*
* This function:
* - Validates required fields at definition time
+ * - Computes `active` from OAuth config if not explicitly set
* - Wraps server-only hooks (onInstall, onUninstall, onHealthcheck) with browser guards
* - Preserves full type information for the integration config
*
@@ -25,7 +26,7 @@ const withServerOnly = () => {
* const MyIntegration = defineIntegration({
* name: "My Integration",
* id: "my-integration",
- * active: true,
+ * active: true, // must be true AND clientId must be set for OAuth integrations
* category: "Tools",
* logo: MyLogo,
* description: "...",
@@ -33,6 +34,10 @@ const withServerOnly = () => {
* images: [],
* settings: [],
* schema: z.object({}),
+ * oauth: {
+ * clientId: SOME_CLIENT_ID, // if empty/undefined, integration will be inactive
+ * ...
+ * },
* onInstall: async (companyId) => { ... },
* onHealthcheck: async (companyId, metadata) => { ... },
* });
@@ -48,14 +53,30 @@ export function defineIntegration<T extends IntegrationOptions>(
if (!options.name) {
throw new Error(`Integration '${options.id}' must have a 'name' defined`);
}
- if (options.active && options.oauth && !options.oauth.clientId) {
- throw new Error(
- `Integration '${options.id}' has OAuth config but missing clientId`
- );
- }
return {
...options,
+ /**
+ * Computes whether an integration should be active based on its configuration.
+ * - If `active` is explicitly false, return false
+ * - If the integration has OAuth config, also require clientId to be set and non-empty
+ * - Otherwise, use the `active` value (defaults to true)
+ */
+ get active() {
+ const isActive = options.active ?? true;
+
+ // If explicitly inactive, return false
+ if (!isActive) {
+ return false;
+ }
+
+ // If the integration has OAuth config, also require clientId to be configured
+ if (options.oauth) {
+ return !!options.oauth.clientId;
+ }
+
+ return isActive;
+ },
get onInstall() {
withServerOnly();
return options.onInstall;
diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.ts
index 0f467f2bda..924ac61666 100644
--- a/packages/ee/src/index.ts
+++ b/packages/ee/src/index.ts
@@ -21,6 +21,7 @@ export type {
IntegrationOptions,
IntegrationServerHooks,
IntegrationSetting,
+ IntegrationSettingGroup,
IntegrationSettingOption,
OAuthConfig
} from "./types";
diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.ts
index c22ab9df3c..30e60dc3d8 100644
--- a/packages/ee/src/types.ts
+++ b/packages/ee/src/types.ts
@@ -41,6 +41,16 @@ export type IntegrationSetting = {
value: unknown;
};
+/**
+ * Definition for a settings group with optional description.
+ */
+export type IntegrationSettingGroup = {
+ /** Group name (must match the group property in settings) */
+ name: string;
+ /** Optional description shown below the group header */
+ description?: string;
+};
+
/**
* OAuth configuration for integrations that require OAuth authentication.
* All fields are required to ensure proper OAuth flow.
@@ -108,8 +118,12 @@ export type IntegrationConfig = {
name: string;
/** Unique identifier used in database and URLs */
id: string;
- /** Whether the integration is available for use */
- active: boolean;
+ /**
+ * Whether the integration is available for use.
+ * For OAuth integrations, this must be true AND the OAuth clientId must be configured.
+ * Defaults to true if not specified.
+ */
+ active?: boolean;
/** Category for grouping in the UI (e.g., "Accounting", "CAD", "Email") */
category: string;
/** Logo component for the integration */
@@ -124,6 +138,8 @@ export type IntegrationConfig = {
images: string[];
/** Configurable settings fields */
settings: IntegrationSetting[];
+ /** Optional group definitions with descriptions */
+ settingGroups?: IntegrationSettingGroup[];
/** Zod schema for validating settings */
schema: ZodType;
/** OAuth configuration (if the integration uses OAuth) */
@@ -144,9 +160,12 @@ export interface IntegrationOptions
/**
* The return type of defineIntegration().
* Server hooks are wrapped with getters that enforce server-only execution.
+ * The `active` property is computed: must be true AND (if OAuth) clientId must be configured.
*/
export type Integration<T extends IntegrationOptions = IntegrationOptions> =
- Omit<T, keyof IntegrationServerHooks> & {
+ Omit<T, keyof IntegrationServerHooks | "active"> & {
+ /** Whether the integration is available for use (computed from OAuth config if not set) */
+ readonly active: boolean;
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 95211a6b6d..c46ccc2494 100644
--- a/packages/ee/src/xero/config.tsx
+++ b/packages/ee/src/xero/config.tsx
@@ -9,7 +9,6 @@ import {
ProviderID,
type ProviderIntegrationMetadata
} from "@carbon/ee/accounting";
-import { PostgresDriver } from "kysely";
import type { ComponentProps } from "react";
import { z } from "zod";
import { defineIntegration } from "../fns";
@@ -20,14 +19,18 @@ const coerceBoolean = z.preprocess(
z.boolean()
);
+const SystemOfRecordSchema = z.enum(["carbon", "accounting"]);
+
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")
+ // Per-entity system of record settings
+ customerOwner: SystemOfRecordSchema.optional().default("accounting"),
+ vendorOwner: SystemOfRecordSchema.optional().default("accounting"),
+ itemOwner: SystemOfRecordSchema.optional().default("carbon"),
+ invoiceOwner: SystemOfRecordSchema.optional().default("accounting"),
+ billOwner: SystemOfRecordSchema.optional().default("accounting")
});
export const Xero = defineIntegration({
@@ -41,6 +44,12 @@ export const Xero = defineIntegration({
shortDescription:
"Automatically post transactions from sales and purchase invoices.",
images: [],
+ settingGroups: [
+ {
+ name: "Source of Truth",
+ description: "Which system's data takes priority when there are conflicts"
+ }
+ ],
settings: [
{
name: "backfillCustomers",
@@ -70,31 +79,104 @@ export const Xero = defineIntegration({
value: true
},
{
- name: "conflictResolution",
- label: "Conflict Resolution",
- description:
- "Determines how to handle records that exist in both systems",
- group: "Sync Settings",
+ name: "customerOwner",
+ label: "Customers",
+ group: "Source of Truth",
type: "options" as const,
listOptions: [
{
- value: "skip",
- label: "Skip",
- description: "Keep existing Carbon data unchanged"
+ value: "accounting",
+ label: "Xero",
+ description: "Xero data overwrites Carbon data"
},
{
- value: "overwrite",
- label: "Overwrite",
- description: "Replace Carbon data with Xero data"
+ value: "carbon",
+ label: "Carbon",
+ description: "Carbon data overwrites Xero data"
+ }
+ ],
+ required: false,
+ value: "accounting"
+ },
+ {
+ name: "vendorOwner",
+ label: "Vendors",
+ group: "Source of Truth",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "accounting",
+ label: "Xero",
+ description: "Xero data overwrites Carbon data"
+ },
+ {
+ value: "carbon",
+ label: "Carbon",
+ description: "Carbon data overwrites Xero data"
+ }
+ ],
+ required: false,
+ value: "accounting"
+ },
+ {
+ name: "itemOwner",
+ label: "Items",
+ group: "Source of Truth",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "carbon",
+ label: "Carbon",
+ description: "Carbon data overwrites Xero data"
},
{
- value: "merge",
- label: "Merge",
- description: "Combine data from both systems"
+ value: "accounting",
+ label: "Xero",
+ description: "Xero data overwrites Carbon data"
}
],
required: false,
- value: "merge"
+ value: "carbon"
+ },
+ {
+ name: "invoiceOwner",
+ label: "Invoices",
+ group: "Source of Truth",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "accounting",
+ label: "Xero",
+ description: "Xero data overwrites Carbon data"
+ },
+ {
+ value: "carbon",
+ label: "Carbon",
+ description: "Carbon data overwrites Xero data"
+ }
+ ],
+ required: false,
+ value: "accounting"
+ },
+ {
+ name: "billOwner",
+ label: "Bills",
+ group: "Source of Truth",
+ type: "options" as const,
+ listOptions: [
+ {
+ value: "accounting",
+ label: "Xero",
+ description: "Xero data overwrites Carbon data"
+ },
+ {
+ value: "carbon",
+ label: "Carbon",
+ description: "Carbon data overwrites Xero data"
+ }
+ ],
+ required: false,
+ value: "accounting"
}
],
schema: XeroSettingsSchema,
@@ -129,11 +211,7 @@ export const Xero = defineIntegration({
return await provider.validate();
},
async onInstall(companyId) {
- const { getPostgresClient, getPostgresConnectionPool } = await import(
- "@carbon/database/client"
- );
-
- const pg = getPostgresClient(getPostgresConnectionPool(1), PostgresDriver);
+ const client = getCarbonServiceRole();
const tables: CreateSubscriptionParams["table"][] = [
"address",
@@ -146,7 +224,7 @@ export const Xero = defineIntegration({
];
for (const table of tables) {
- await createEventSystemSubscription(pg, {
+ await createEventSystemSubscription(client, {
table,
companyId,
name: "xero-sync",
@@ -159,14 +237,10 @@ export const Xero = defineIntegration({
}
},
async onUninstall(companyId) {
- const { getPostgresClient, getPostgresConnectionPool } = await import(
- "@carbon/database/client"
- );
-
- const pg = getPostgresClient(getPostgresConnectionPool(1), PostgresDriver);
+ const client = getCarbonServiceRole();
// Delete all Xero sync subscriptions for this company
- await deleteEventSystemSubscriptionsByName(pg, companyId, "xero-sync");
+ await deleteEventSystemSubscriptionsByName(client, companyId, "xero-sync");
}
});