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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix: Accounting integration improvements and feature changes (#494)
Sidaf01ab812511
diff --git a/apps/erp/app/modules/purchasing/purchasing.models.ts b/apps/erp/app/modules/purchasing/purchasing.models.tsindex c993abb4d7..c4f32f4f91 100644--- a/apps/erp/app/modules/purchasing/purchasing.models.ts+++ b/apps/erp/app/modules/purchasing/purchasing.models.ts@@ -474,3 +474,195 @@ export function isRfqLocked(status: string | null | undefined): boolean {status as (typeof PURCHASING_RFQ_LOCKED_STATUSES)[number]);}++// Purchase Order Locked Status Validation++import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";++/**+ * Purchase Order statuses that indicate the PO has been finalized/approved+ * and is now "locked" - meaning only privileged users can make limited edits+ */+export const PURCHASE_ORDER_LOCKED_STATUSES = [+ "To Receive",+ "To Receive and Invoice",+ "To Invoice",+ "Completed"+] as const;++/**+ * Purchase Order statuses that allow normal editing+ */+export const PURCHASE_ORDER_EDITABLE_STATUSES = [+ "Draft",+ "Planned",+ "Needs Approval",+ "Rejected"+] as const;++export type PurchaseOrderLockedStatus =+ (typeof PURCHASE_ORDER_LOCKED_STATUSES)[number];+export type PurchaseOrderEditableStatus =+ (typeof PURCHASE_ORDER_EDITABLE_STATUSES)[number];++/**+ * Check if a PO status is "locked" (finalized/approved)+ */+export function isPurchaseOrderLocked(+ status: (typeof purchaseOrderStatusType)[number] | null | undefined+): boolean {+ return PURCHASE_ORDER_LOCKED_STATUSES.includes(+ status as PurchaseOrderLockedStatus+ );+}++/**+ * Check if a PO status allows normal editing+ */+export function isPurchaseOrderEditable(+ status: (typeof purchaseOrderStatusType)[number] | null | undefined+): boolean {+ return PURCHASE_ORDER_EDITABLE_STATUSES.includes(+ status as PurchaseOrderEditableStatus+ );+}++export type PurchaseOrderLineForValidation = {+ id: string;+ purchaseQuantity: number | null;+ supplierUnitPrice: number | null;+ supplierTaxAmount: number | null;+ supplierShippingCost: number | null;+};++export type ValidateLockedPOEditResult = {+ allowed: boolean;+ error?: string;+};++/**+ * Validates edits to a locked (finalized/approved) Purchase Order.+ *+ * Rules:+ * - If PO is not locked, all edits are allowed (returns allowed: true)+ * - If PO is locked and user doesn't have delete permission, no edits are allowed+ * - If PO is locked and user has delete permission, only changes that REDUCE+ * the total amount are allowed (price reductions, quantity reductions, line removals)+ *+ * @param currentLines - The current lines on the PO+ * @param updatedLines - The lines after the proposed edit (for line updates)+ * @param deletedLineIds - IDs of lines being deleted (for line deletions)+ */+export function validateLockedPOLineEdit(+ currentLines: PurchaseOrderLineForValidation[],+ updatedLines: PurchaseOrderLineForValidation[],+ deletedLineIds: string[] = []+): ValidateLockedPOEditResult {+ const currentTotal = calculateLinesTotal(currentLines);+ const newTotal = calculateLinesTotal(+ updatedLines.filter((line) => !deletedLineIds.includes(line.id))+ );++ if (newTotal > currentTotal) {+ return {+ allowed: false,+ error:+ "Cannot increase the total amount on a finalized purchase order. Only price reductions are allowed. To increase the amount, please cancel this PO and create a new one."+ };+ }++ return { allowed: true };+}++/**+ * Validates a single line edit against the locked PO rules.+ * Compares the original line with the updated line to ensure the total doesn't increase.+ */+export function validateLockedPOSingleLineEdit(+ originalLine: PurchaseOrderLineForValidation,+ updatedLine: Partial<PurchaseOrderLineForValidation>+): ValidateLockedPOEditResult {+ const originalLineTotal = calculateLineTotal(originalLine);+ const newLineTotal = calculateLineTotal({+ ...originalLine,+ ...updatedLine+ });++ if (newLineTotal > originalLineTotal) {+ return {+ allowed: false,+ error:+ "Cannot increase the line total on a finalized purchase order. Only price reductions are allowed. To increase the amount, please cancel this PO and create a new one."+ };+ }++ return { allowed: true };+}++/**+ * Calculate the total for a single PO line+ */+function calculateLineTotal(line: PurchaseOrderLineForValidation): number {+ const quantity = line.purchaseQuantity ?? 0;+ const unitPrice = line.supplierUnitPrice ?? 0;+ const taxAmount = line.supplierTaxAmount ?? 0;+ const shippingCost = line.supplierShippingCost ?? 0;++ return quantity * unitPrice + taxAmount + shippingCost;+}++/**+ * Calculate the total for all PO lines+ */+function calculateLinesTotal(lines: PurchaseOrderLineForValidation[]): number {+ return lines.reduce((sum, line) => sum + calculateLineTotal(line), 0);+}++/**+ * Fetches the current PO and its lines to validate an edit.+ * Returns the PO status and whether the edit is allowed.+ */+export async function getPurchaseOrderForValidation(+ client: SupabaseClient<Database>,+ purchaseOrderId: string+): Promise<{+ status: (typeof purchaseOrderStatusType)[number] | null;+ lines: PurchaseOrderLineForValidation[];+ error?: string;+}> {+ const [poResult, linesResult] = await Promise.all([+ client+ .from("purchaseOrder")+ .select("status")+ .eq("id", purchaseOrderId)+ .single(),+ client+ .from("purchaseOrderLine")+ .select(+ "id, purchaseQuantity, supplierUnitPrice, supplierTaxAmount, supplierShippingCost"+ )+ .eq("purchaseOrderId", purchaseOrderId)+ ]);++ if (poResult.error) {+ return {+ status: null,+ lines: [],+ error: `Failed to fetch purchase order: ${poResult.error.message}`+ };+ }++ if (linesResult.error) {+ return {+ status: poResult.data?.status ?? null,+ lines: [],+ error: `Failed to fetch purchase order lines: ${linesResult.error.message}`+ };+ }++ return {+ status: poResult.data?.status ?? null,+ lines: linesResult.data ?? []+ };+}diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsxindex 7833e3c79d..b479076eb5 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderExplorer.tsx@@ -34,6 +34,7 @@ import type { MethodItemType } from "~/modules/shared";import { methodItemType } from "~/modules/shared";import { useItems } from "~/stores";import { path } from "~/utils/path";+import { isPurchaseOrderLocked } from "../../purchasing.models";import type { PurchaseOrder, PurchaseOrderLine, Supplier } from "../../types";import DeletePurchaseOrderLine from "./DeletePurchaseOrderLine";import PurchaseOrderLineForm from "./PurchaseOrderLineForm";@@ -65,7 +66,16 @@ export default function PurchaseOrderExplorer() {const newPurchaseOrderLineDisclosure = useDisclosure();const deleteLineDisclosure = useDisclosure();const [deleteLine, setDeleteLine] = useState<PurchaseOrderLine | null>(null);- const isDisabled = purchaseOrderData?.purchaseOrder?.status !== "Draft";++ // Check if PO is in a locked state (finalized/approved)+ const isLocked = isPurchaseOrderLocked(+ purchaseOrderData?.purchaseOrder?.status+ );+ // Adding new lines is NOT allowed on locked POs (would increase total)+ // For unlocked POs, only Draft status allows adding new lines+ const isDisabled = isLocked+ ? true // No new lines on locked POs+ : purchaseOrderData?.purchaseOrder?.status !== "Draft";const onDeleteLine = (line: PurchaseOrderLine) => {setDeleteLine(line);@@ -222,7 +232,7 @@ function PurchaseOrderLineItem({<DropdownMenuContent><DropdownMenuItemdestructive- disabled={isDisabled || !permissions.can("update", "sales")}+ disabled={!permissions.can("delete", "purchasing")}onClick={(e) => {e.stopPropagation();onDelete(line);diff --git a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsxindex 4a04e1fa5c..ff311ac918 100644--- a/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx+++ b/apps/erp/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderHeader.tsx@@ -42,6 +42,7 @@ import { ShipmentStatus } from "~/modules/inventory/ui/Shipments";import PurchaseInvoicingStatus from "~/modules/invoicing/ui/PurchaseInvoice/PurchaseInvoicingStatus";import type { ApprovalDecision } from "~/modules/shared/types";import { path } from "~/utils/path";+import { isPurchaseOrderLocked } from "../../purchasing.models";import type { PurchaseOrder, PurchaseOrderLine } from "../../types";import PurchaseOrderApprovalModal from "./PurchaseOrderApprovalModal";import PurchaseOrderFinalizeModal from "./PurchaseOrderFinalizeModal";@@ -79,6 +80,7 @@ const PurchaseOrderHeader = () => {const isNeedsApproval = routeData?.purchaseOrder?.status === "Needs Approval";const hasApprovalRequest = !!routeData?.approvalRequest;const canApprove = routeData?.canApprove ?? false;+ const isLocked = isPurchaseOrderLocked(routeData?.purchaseOrder?.status);const { receipts, invoices, shipments } = usePurchaseOrderRelatedDocuments(routeData?.purchaseOrder?.supplierInteractionId ?? "",routeData?.purchaseOrder?.purchaseOrderType === "Outside Processing"@@ -459,7 +461,7 @@ const PurchaseOrderHeader = () => {routeData?.purchaseOrder?.status ?? "") ||statusFetcher.state !== "idle" ||- !permissions.can("update", "production")+ !permissions.can("delete", "purchasing")}leftIcon={<LuCircleStop />}variant="secondary"@@ -479,7 +481,10 @@ const PurchaseOrderHeader = () => {isDisabled={["Draft"].includes(routeData?.purchaseOrder?.status ?? "") ||statusFetcher.state !== "idle" ||- !permissions.can("update", "purchasing") ||+ // Locked POs require delete permission to reopen+ (isLocked+ ? !permissions.can("delete", "purchasing")+ : !permissions.can("update", "purchasing")) ||(isNeedsApproval && !routeData?.canReopen)}isLoading={diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex 4a6479d73a..c8ddba5787 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -268,12 +268,18 @@ interface IntegrationFormProps {metadata: Record<string, unknown>;installed: boolean;onClose: () => void;+ /** Dynamic options to merge into settings (e.g., fetched from external APIs) */+ dynamicOptions?: Record<+ string,+ Array<{ value: string; label: string; description?: string }>+ >;}export function IntegrationForm({installed,metadata,- onClose+ onClose,+ dynamicOptions = {}}: IntegrationFormProps) {const permissions = usePermissions();const isDisabled = !permissions.can("update", "settings");@@ -293,6 +299,7 @@ export function IntegrationForm({// Group settings by their group property// Settings without a group appear first (ungrouped)+ // Also merges dynamic options into settings that have themconst { ungroupedSettings, groupedSettings, groupNames, groupDescriptions } =useMemo(() => {if (!integration) {@@ -307,7 +314,15 @@ export function IntegrationForm({const ungrouped: IntegrationSetting[] = [];const grouped = new Map<string, IntegrationSetting[]>();- for (const setting of integration.settings) {+ for (const baseSetting of integration.settings) {+ // Merge dynamic options if available for this setting+ const setting: IntegrationSetting = dynamicOptions[baseSetting.name]+ ? {+ ...baseSetting,+ listOptions: dynamicOptions[baseSetting.name]+ }+ : (baseSetting as IntegrationSetting);+if (!setting.group) {ungrouped.push(setting);} else {@@ -331,7 +346,7 @@ export function IntegrationForm({groupNames: [...grouped.keys()],groupDescriptions: descriptions};- }, [integration]);+ }, [integration, dynamicOptions]);const initialValues = useMemo(() => {if (!integration) return {};diff --git a/apps/erp/app/routes/api+/integrations.xero.accounts.ts b/apps/erp/app/routes/api+/integrations.xero.accounts.tsnew file mode 100644index 0000000000..3b62e70506--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.xero.accounts.ts@@ -0,0 +1,65 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import {+ getAccountingIntegration,+ getProviderIntegration,+ ProviderID,+ type XeroProvider+} from "@carbon/ee/accounting";+import type { LoaderFunctionArgs } from "react-router";+import { data } from "react-router";++export const config = {+ runtime: "nodejs"+};++/**+ * GET: Fetch chart of accounts from Xero+ * Returns accounts formatted for use in select dropdowns+ */+export async function loader({ request }: LoaderFunctionArgs) {+ const { client, companyId } = await requirePermissions(request, {+ view: "settings"+ });++ try {+ // Get Xero integration+ const integration = await getAccountingIntegration(+ client,+ companyId,+ ProviderID.XERO+ );++ // Create provider instance+ const provider = getProviderIntegration(+ client,+ companyId,+ integration.id,+ integration.metadata+ ) as XeroProvider;++ // Fetch accounts from Xero+ const accounts = await provider.listChartOfAccounts();++ // Format accounts for dropdown options+ const options = accounts.map((account) => ({+ value: account.Code ?? account.AccountID,+ label: account.Code ? `${account.Code} - ${account.Name}` : account.Name,+ description: account.Type,+ // Include metadata for filtering+ type: account.Type,+ class: account.Class+ }));++ return data({ accounts: options });+ } catch (error) {+ console.error("Failed to fetch Xero accounts:", error);+ return data(+ {+ error:+ error instanceof Error ? error.message : "Failed to fetch accounts",+ accounts: []+ },+ { status: 500 }+ );+ }+}diff --git a/apps/erp/app/routes/api+/integrations.xero.backfill.ts b/apps/erp/app/routes/api+/integrations.xero.backfill.tsindex 6c47e0e04a..414628c124 100644--- a/apps/erp/app/routes/api+/integrations.xero.backfill.ts+++ b/apps/erp/app/routes/api+/integrations.xero.backfill.ts@@ -9,9 +9,9 @@ const BackfillSettingsSchema = z.object({backfillCustomers: z.boolean().optional().default(true),backfillVendors: z.boolean().optional().default(true),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+ // Note: The backfill task now respects each entity's sync direction config+ // (pull-from-accounting, push-to-accounting, or two-way) rather than using+ // a global pullOnly flag. This is configured per-entity in syncConfig.});export const config = {@@ -71,8 +71,8 @@ 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+ // The backfill task respects each entity's sync direction config from+ // the integration metadata (pull-from-accounting, push-to-accounting, two-way)const handle = await tasks.trigger("accounting-backfill",{diff --git a/apps/erp/app/routes/api+/integrations.xero.oauth.ts b/apps/erp/app/routes/api+/integrations.xero.oauth.tsindex 90c903196a..e2356cf324 100644--- a/apps/erp/app/routes/api+/integrations.xero.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.xero.oauth.ts@@ -93,6 +93,76 @@ export async function loader({ request }: LoaderFunctionArgs) {);}+ // Fetch Carbon company's base currency+ const { data: company, error: companyError } = await client+ .from("company")+ .select("baseCurrencyCode")+ .eq("id", companyId)+ .single();++ if (companyError || !company?.baseCurrencyCode) {+ return data(+ { error: "Company base currency not configured" },+ { status: 400 }+ );+ }++ // Fetch Xero organisation to get base currency+ const xeroOrgResponse = await fetch(+ "https://api.xero.com/api.xro/2.0/Organisation",+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${auth.accessToken}`,+ Accept: "application/json",+ "Content-Type": "application/json",+ "xero-tenant-id": tenantId+ }+ }+ );++ if (!xeroOrgResponse.ok) {+ console.error(+ "Xero Organisation API error:",+ xeroOrgResponse.status,+ await xeroOrgResponse.text()+ );+ return data(+ { error: "Failed to fetch Xero organization details" },+ { status: 500 }+ );+ }++ let xeroOrgData;+ try {+ xeroOrgData = await xeroOrgResponse.json();+ } catch (parseError) {+ console.error("Failed to parse Xero Organisation response:", parseError);+ return data(+ { error: "Invalid response from Xero organization API" },+ { status: 500 }+ );+ }++ const xeroBaseCurrency = xeroOrgData?.Organisations?.[0]?.BaseCurrency;++ if (!xeroBaseCurrency) {+ return data(+ { error: "Could not determine Xero organization base currency" },+ { status: 500 }+ );+ }++ // Check if Carbon's base currency matches Xero's base currency+ if (company.baseCurrencyCode !== xeroBaseCurrency) {+ return data(+ {+ error: `Currency mismatch: Your Carbon company uses ${company.baseCurrencyCode}, but your Xero organization uses ${xeroBaseCurrency}. Please ensure both systems use the same base currency before connecting.`+ },+ { status: 400 }+ );+ }+const createdXeroIntegration = await upsertCompanyIntegration(client, {id: Xero.id,active: true,diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsxindex c8e9799ec9..97b26b542f 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.$lineId.details.tsx@@ -17,10 +17,13 @@ import {import { CadModel } from "~/components";import { usePermissions } from "~/hooks";import {+ getPurchaseOrder,getPurchaseOrderLine,getSupplierInteractionLineDocuments,+ isPurchaseOrderLocked,purchaseOrderLineValidator,- upsertPurchaseOrderLine+ upsertPurchaseOrderLine,+ validateLockedPOSingleLineEdit} from "~/modules/purchasing";import { PurchaseOrderLineForm } from "~/modules/purchasing/ui/PurchaseOrder";import {@@ -57,14 +60,49 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {- create: "purchasing"- });const { orderId, lineId } = params;if (!orderId) throw new Error("Could not find orderId");if (!lineId) throw new Error("Could not find lineId");+ // First check with view permission to get the PO status+ const { client: viewClient } = await requirePermissions(request, {+ view: "purchasing"+ });++ // Get PO status and current line data+ const [purchaseOrder, currentLine] = await Promise.all([+ getPurchaseOrder(viewClient, orderId),+ getPurchaseOrderLine(viewClient, lineId)+ ]);++ if (purchaseOrder.error) {+ throw redirect(+ path.to.purchaseOrderLine(orderId, lineId),+ await flash(+ request,+ error(purchaseOrder.error, "Failed to load purchase order")+ )+ );+ }++ if (currentLine.error || !currentLine.data) {+ throw redirect(+ path.to.purchaseOrderLine(orderId, lineId),+ await flash(+ request,+ error(currentLine.error, "Failed to load purchase order line")+ )+ );+ }++ const isLocked = isPurchaseOrderLocked(purchaseOrder.data?.status);++ // If locked, require delete permission; otherwise require update permission+ const { client, userId } = await requirePermissions(request, {+ ...(isLocked ? { delete: "purchasing" } : { update: "purchasing" })+ });+const formData = await request.formData();const validation = await validator(purchaseOrderLineValidator).validate(formData@@ -77,21 +115,31 @@ export async function action({ request, params }: ActionFunctionArgs) {// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migrationconst { id, ...d } = validation.data;- // if (d.purchaseOrderLineType === "G/L Account") {- // d.assetId = undefined;- // d.itemId = undefined;- // } else if (d.purchaseOrderLineType === "Fixed Asset") {- // d.accountNumber = undefined;- // d.itemId = undefined;- // } else- // if (d.purchaseOrderLineType === "Comment") {- // d.accountNumber = undefined;- // d.assetId = undefined;- // d.itemId = undefined;- // } else {- // d.accountNumber = undefined;- // d.assetId = undefined;- // }+ // If locked, validate that changes only reduce the line total+ if (isLocked) {+ const validationResult = validateLockedPOSingleLineEdit(+ {+ id: lineId,+ purchaseQuantity: currentLine.data.purchaseQuantity,+ supplierUnitPrice: currentLine.data.supplierUnitPrice,+ supplierTaxAmount: currentLine.data.supplierTaxAmount,+ supplierShippingCost: currentLine.data.supplierShippingCost+ },+ {+ purchaseQuantity: d.purchaseQuantity,+ supplierUnitPrice: d.supplierUnitPrice,+ supplierTaxAmount: d.supplierTaxAmount,+ supplierShippingCost: d.supplierShippingCost+ }+ );++ if (!validationResult.allowed) {+ throw redirect(+ path.to.purchaseOrderLine(orderId, lineId),+ await flash(request, error(null, validationResult.error))+ );+ }+ }const updatePurchaseOrderLine = await upsertPurchaseOrderLine(client, {id: lineId,diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsxindex ff31f31eee..e0b21913b4 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.details.tsx@@ -18,6 +18,7 @@ import type {import {getPurchaseOrder,getPurchaseOrderPayment,+ isPurchaseOrderLocked,purchaseOrderValidator,upsertPurchaseOrder} from "~/modules/purchasing";@@ -70,13 +71,48 @@ export async function loader({ request, params }: LoaderFunctionArgs) {export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId } = await requirePermissions(request, {- update: "purchasing"- });const { orderId } = params;if (!orderId) throw new Error("Could not find orderId");+ // First check with basic update permission to get the PO+ const { client: viewClient } = await requirePermissions(request, {+ view: "purchasing"+ });++ // Check if PO is locked+ const purchaseOrder = await getPurchaseOrder(viewClient, orderId);+ if (purchaseOrder.error) {+ throw redirect(+ path.to.purchaseOrder(orderId),+ await flash(+ request,+ error(purchaseOrder.error, "Failed to load purchase order")+ )+ );+ }++ const isLocked = isPurchaseOrderLocked(purchaseOrder.data?.status);++ // If locked, require delete permission; otherwise require update permission+ const { client, userId } = await requirePermissions(request, {+ ...(isLocked ? { delete: "purchasing" } : { update: "purchasing" })+ });++ // If locked, block all edits (no header changes allowed on locked POs)+ if (isLocked) {+ throw redirect(+ path.to.purchaseOrder(orderId),+ await flash(+ request,+ error(+ null,+ "Cannot modify a finalized purchase order. To make changes, please cancel this PO and create a new one."+ )+ )+ );+ }+const formData = await request.formData();const validation = await validator(purchaseOrderValidator).validate(formData);diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsxindex 6b4989d1c0..c209396c66 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.finalize.tsx@@ -7,8 +7,10 @@ import {import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { PurchaseOrderEmail } from "@carbon/documents/email";+import { ProviderID } from "@carbon/ee/accounting";import { validationError, validator } from "@carbon/form";import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend"; // Assuming you have a sendEmail task defined+import type { syncExternalAccountingTask } from "@carbon/jobs/trigger/sync-external-accounting";import { NotificationEvent } from "@carbon/notifications";import { renderAsync } from "@react-email/components";import { FunctionRegion } from "@supabase/supabase-js";@@ -343,6 +345,26 @@ export async function action(args: ActionFunctionArgs) {throw new Error("Invalid notification type");}+ // Trigger Xero sync for the finalized purchase order+ // This runs asynchronously - failures won't block the finalization+ try {+ await tasks.trigger<typeof syncExternalAccountingTask>(+ "sync-external-accounting",+ {+ companyId,+ provider: ProviderID.XERO,+ syncType: "trigger",+ syncDirection: "push-to-accounting",+ entities: [+ { entityType: "purchaseOrder", entityId: orderId, operation: "sync" }+ ]+ }+ );+ } catch (syncError) {+ // Log but don't fail - Xero sync is optional and may not be configured+ console.error("Failed to trigger Xero sync for purchase order:", syncError);+ }+throw redirect(requestReferrer(request) ?? path.to.purchaseOrder(orderId),await flash(request, success("Purchase order finalized"))diff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsxindex 844b4cbe33..371331853a 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.status.tsx@@ -10,6 +10,7 @@ import type { ActionFunctionArgs } from "react-router";import { redirect } from "react-router";import { runMRP } from "~/modules/production";import {+ isPurchaseOrderLocked,purchaseOrderStatusType,updatePurchaseOrderStatus} from "~/modules/purchasing";@@ -18,9 +19,6 @@ import { path, requestReferrer } from "~/utils/path";export async function action({ request, params }: ActionFunctionArgs) {assertIsPost(request);- const { client, userId, companyId } = await requirePermissions(request, {- update: "purchasing"- });const { orderId: id } = params;if (!id) throw new Error("Could not find id");@@ -37,16 +35,34 @@ export async function action({ request, params }: ActionFunctionArgs) {);}- const serviceRole = getCarbonServiceRole();+ // First get current PO status with view permission+ const { client: viewClient } = await requirePermissions(request, {+ view: "purchasing"+ });- // Get current PO status before updating- const currentPo = await client+ const currentPo = await viewClient.from("purchaseOrder").select("status").eq("id", id).single();const currentStatus = currentPo.data?.status;+ const isCurrentlyLocked = isPurchaseOrderLocked(currentStatus);++ // Determine required permission:+ // - Reopening (Draft) from a locked status requires delete permission+ // - Closing from any status requires delete permission+ // - Other status changes require update permission+ const requiresDeletePermission =+ (status === "Draft" && isCurrentlyLocked) || status === "Closed";++ const { client, userId, companyId } = await requirePermissions(request, {+ ...(requiresDeletePermission+ ? { delete: "purchasing" }+ : { update: "purchasing" })+ });++ const serviceRole = getCarbonServiceRole();// Cancel pending approval requests when closing the PO// Closed POs are terminal - no approvals should remain pendingdiff --git a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsxindex 3665097e94..16ceb9b5ce 100644--- a/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx+++ b/apps/erp/app/routes/x+/purchase-order+/$orderId.tsx@@ -7,8 +7,10 @@ import {import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { PurchaseOrderEmail } from "@carbon/documents/email";+import { ProviderID } from "@carbon/ee/accounting";import { validationError, validator } from "@carbon/form";import type { sendEmailResendTask } from "@carbon/jobs/trigger/send-email-resend";+import type { syncExternalAccountingTask } from "@carbon/jobs/trigger/sync-external-accounting";import { NotificationEvent } from "@carbon/notifications";import { VStack } from "@carbon/react";import { renderAsync } from "@react-email/components";@@ -308,6 +310,33 @@ export async function action(args: ActionFunctionArgs) {);}}++ // Trigger Xero sync for the approved purchase order+ // This runs asynchronously - failures won't block the approval+ try {+ await tasks.trigger<typeof syncExternalAccountingTask>(+ "sync-external-accounting",+ {+ companyId,+ provider: ProviderID.XERO,+ syncType: "trigger",+ syncDirection: "push-to-accounting",+ entities: [+ {+ entityType: "purchaseOrder",+ entityId: orderId,+ operation: "sync"+ }+ ]+ }+ );+ } catch (syncError) {+ // Log but don't fail - Xero sync is optional and may not be configured+ console.error(+ "Failed to trigger Xero sync for purchase order:",+ syncError+ );+ }}}diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex 6676e6d8c5..f7e04e5aa0 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -2,6 +2,12 @@ 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 {+ getAccountingIntegration,+ getProviderIntegration,+ ProviderID,+ type XeroProvider+} from "@carbon/ee/accounting";import { validationError, validator } from "@carbon/form";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";import { redirect, useLoaderData, useNavigate } from "react-router";@@ -80,12 +86,13 @@ function buildIntegrationMetadata(};// Remove owner settings from formData since they're now in syncConfig+ // biome-ignore lint/correctness/noUnusedVariables: destructuring to exclude from restFormDataconst {- customerOwner,- vendorOwner,- itemOwner,- invoiceOwner,- billOwner,+ customerOwner: _customerOwner,+ vendorOwner: _vendorOwner,+ itemOwner: _itemOwner,+ invoiceOwner: _invoiceOwner,+ billOwner: _billOwner,...restFormData} = formData;@@ -116,7 +123,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {if (integrationData.error || !integrationData.data) {return {installed: false,- metadata: {}+ metadata: {},+ dynamicOptions: {}};}@@ -127,9 +135,51 @@ export async function loader({ request, params }: LoaderFunctionArgs) {>;const flattenedMetadata = flattenSyncConfigToOwnerSettings(metadata);+ // Fetch dynamic options for Xero integration (chart of accounts)+ let dynamicOptions: Record<+ string,+ Array<{ value: string; label: string; description?: string }>+ > = {};++ if (integrationId === "xero" && integrationData.data.active) {+ try {+ const xeroIntegration = await getAccountingIntegration(+ client,+ companyId,+ ProviderID.XERO+ );++ const provider = getProviderIntegration(+ client,+ companyId,+ xeroIntegration.id,+ xeroIntegration.metadata+ ) as XeroProvider;++ const accounts = await provider.listChartOfAccounts();++ const accountOptions = accounts.map((account) => ({+ value: account.Code ?? account.AccountID,+ label: account.Code+ ? `${account.Code} - ${account.Name}`+ : account.Name,+ description: account.Type+ }));++ dynamicOptions = {+ defaultSalesAccountCode: accountOptions,+ defaultPurchaseAccountCode: accountOptions+ };+ } catch (error) {+ console.error("Failed to fetch Xero accounts for settings:", error);+ // Continue without dynamic options - form will show empty selects+ }+ }+return {installed: integrationData.data.active,- metadata: flattenedMetadata+ metadata: flattenedMetadata,+ dynamicOptions};}@@ -213,7 +263,8 @@ export async function action({ request, params }: ActionFunctionArgs) {}export default function IntegrationRoute() {- const { installed, metadata } = useLoaderData<typeof loader>();+ const { installed, metadata, dynamicOptions } =+ useLoaderData<typeof loader>();const navigate = useNavigate();@@ -221,6 +272,7 @@ export default function IntegrationRoute() {<IntegrationForminstalled={installed}metadata={metadata}+ dynamicOptions={dynamicOptions}onClose={() => navigate(path.to.integrations)}/>);diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex c85942b4d4..a03a071f2f 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -48677,14 +48677,14 @@ export type Database = {Relationships: [{foreignKeyName: "address_countryCode_fkey"- columns: ["supplierCountryCode"]+ columns: ["customerCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]},{foreignKeyName: "address_countryCode_fkey"- columns: ["customerCountryCode"]+ columns: ["supplierCountryCode"]isOneToOne: falsereferencedRelation: "country"referencedColumns: ["alpha2"]diff --git a/packages/database/supabase/migrations/20260210171712_attach-contact-location-event-triggers.sql b/packages/database/supabase/migrations/20260210171712_attach-contact-location-event-triggers.sqlnew file mode 100644index 0000000000..08df96e691--- /dev/null+++ b/packages/database/supabase/migrations/20260210171712_attach-contact-location-event-triggers.sql@@ -0,0 +1,76 @@+-- Sync interceptor to update linked customer/supplier's updatedAt when contact or address changes+-- This triggers the existing event system to sync them to Xero++CREATE OR REPLACE FUNCTION sync_contact_to_parent(+ table_name TEXT,+ operation TEXT,+ new_data JSONB,+ old_data JSONB+)+RETURNS VOID+LANGUAGE plpgsql+AS $$+DECLARE+ contact_id TEXT;+BEGIN+ -- Skip if we're in a sync operation (prevents loops when pulling from Xero)+ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ contact_id := COALESCE(new_data->>'id', old_data->>'id');++ -- Update customers linked to this contact+ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerContact" cc+ WHERE cc."contactId" = contact_id+ AND cc."customerId" = c.id;++ -- Update suppliers linked to this contact+ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierContact" sc+ WHERE sc."contactId" = contact_id+ AND sc."supplierId" = s.id;+END;+$$;++CREATE OR REPLACE FUNCTION sync_address_to_parent(+ table_name TEXT,+ operation TEXT,+ new_data JSONB,+ old_data JSONB+)+RETURNS VOID+LANGUAGE plpgsql+AS $$+DECLARE+ address_id TEXT;+BEGIN+ -- Skip if we're in a sync operation (prevents loops when pulling from Xero)+ IF current_setting('app.sync_in_progress', true) = 'true' THEN+ RETURN;+ END IF;++ address_id := COALESCE(new_data->>'id', old_data->>'id');++ -- Update customers linked to this address via customerLocation+ UPDATE "customer" c+ SET "updatedAt" = NOW()+ FROM "customerLocation" cl+ WHERE cl."addressId" = address_id+ AND cl."customerId" = c.id;++ -- Update suppliers linked to this address via supplierLocation+ UPDATE "supplier" s+ SET "updatedAt" = NOW()+ FROM "supplierLocation" sl+ WHERE sl."addressId" = address_id+ AND sl."supplierId" = s.id;+END;+$$;++-- Attach sync interceptors to contact and address tables+SELECT attach_event_trigger('contact', ARRAY['sync_contact_to_parent']);+SELECT attach_event_trigger('address', ARRAY['sync_address_to_parent']);diff --git a/packages/ee/src/accounting/core/models.ts b/packages/ee/src/accounting/core/models.tsindex 3f36083eb1..3f20b85139 100644--- a/packages/ee/src/accounting/core/models.ts+++ b/packages/ee/src/accounting/core/models.ts@@ -138,9 +138,9 @@ export const DEFAULT_SYNC_CONFIG: GlobalSyncConfig = {owner: "carbon"},purchaseOrder: {- enabled: false,- direction: "two-way",- owner: "accounting"+ enabled: true,+ direction: "push-to-accounting",+ owner: "carbon"},bill: { enabled: true, direction: "two-way", owner: "accounting" },salesOrder: {@@ -207,30 +207,38 @@ export function validateSyncConfig(config: GlobalSyncConfig): string[] {const createEntityConfigSchema = () =>z.object({- enabled: z.boolean(),- direction: SyncDirectionSchema,- owner: z.enum(["carbon", "accounting"]),+ enabled: z.boolean().optional().default(true),+ direction: SyncDirectionSchema.optional().default("two-way"),+ owner: z.enum(["carbon", "accounting"]).optional().default("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()+export const SyncConfigSchema = z+ .object({+ entities: z+ .object({+ customer: createEntityConfigSchema().optional(),+ vendor: createEntityConfigSchema().optional(),+ item: createEntityConfigSchema().optional(),+ employee: createEntityConfigSchema().optional(),+ purchaseOrder: createEntityConfigSchema().optional(),+ bill: createEntityConfigSchema().optional(),+ salesOrder: createEntityConfigSchema().optional(),+ invoice: createEntityConfigSchema().optional(),+ payment: createEntityConfigSchema().optional(),+ inventoryAdjustment: createEntityConfigSchema().optional()+ })+ .optional()})-});+ .optional();export const ProviderIntegrationMetadataSchema = z.object({- syncConfig: SyncConfigSchema,- credentials: ProviderCredentialsSchema.optional()+ syncConfig: SyncConfigSchema.optional(),+ credentials: ProviderCredentialsSchema.optional(),+ // Integration-specific settings (e.g., default account codes for Xero)+ // These are stored at the top level of metadata and passed through to the provider+ defaultSalesAccountCode: z.string().optional(),+ defaultPurchaseAccountCode: z.string().optional()});// /********************************************************\diff --git a/packages/ee/src/accounting/core/service.ts b/packages/ee/src/accounting/core/service.tsindex 325168b937..65ee2e4da2 100644--- a/packages/ee/src/accounting/core/service.ts+++ b/packages/ee/src/accounting/core/service.ts@@ -60,25 +60,8 @@ export const getProviderIntegration = () => {const { accessToken, refreshToken, tenantId } = config?.credentials || {};- // 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;+ // For now don't use the company level sync config+ const syncConfig = DEFAULT_SYNC_CONFIG;// Create a callback function to update the integration metadata when tokens are refreshedconst onTokenRefresh = async (auth: ProviderCredentials) => {@@ -119,7 +102,16 @@ export const getProviderIntegration = (// onTokenRefresh// });// }- case "xero":+ case "xero": {+ const settings = {+ defaultSalesAccountCode: config?.defaultSalesAccountCode,+ defaultPurchaseAccountCode: config?.defaultPurchaseAccountCode+ };+ console.log(+ "[getProviderIntegration] Creating XeroProvider with settings:",+ settings+ );+ console.log("[getProviderIntegration] Full config received:", config);return new XeroProvider({companyId,tenantId,@@ -129,8 +121,10 @@ export const getProviderIntegration = (clientSecret: process.env.XERO_CLIENT_SECRET!,redirectUri: process.env.XERO_REDIRECT_URI,syncConfig,- onTokenRefresh+ onTokenRefresh,+ settings});+ }// Add other providers as needed// case "sage":// return new SageProvider(config);diff --git a/packages/ee/src/accounting/core/utils.ts b/packages/ee/src/accounting/core/utils.tsindex 502072a9b9..f31ae89338 100644--- a/packages/ee/src/accounting/core/utils.ts+++ b/packages/ee/src/accounting/core/utils.ts@@ -37,7 +37,8 @@ export class HTTPClient {response = await this.fetch(method, path, opts);if (response.status === 429) {- throw new RatelimitError("Rate limit exceeded", response);+ const rateLimitInfo = parseRateLimitInfo(response);+ throw new RatelimitError("Rate limit exceeded", rateLimitInfo);}return this.parseResponse<T>(response);@@ -134,17 +135,65 @@ export class NotImplementedError extends Error {}}+export interface RateLimitInfo {+ /** Seconds to wait before retrying */+ retryAfterSeconds: number;+ /** Which limit was hit (e.g., "minute", "day") */+ limitType?: string;+ /** Provider-specific details */+ details?: Record<string, unknown>;+}+export class RatelimitError extends Error {- constructor(- message: string,- public response: Response- ) {+ public rateLimitInfo: RateLimitInfo;++ constructor(message: string, rateLimitInfo: RateLimitInfo) {super(message);this.name = "RatelimitError";- this.response = response;+ this.rateLimitInfo = rateLimitInfo;+ }++ get retryAfterSeconds(): number {+ return this.rateLimitInfo.retryAfterSeconds;}}+/**+ * Parse rate limit info from a 429 response.+ * Handles Xero-specific headers but can be extended for other providers.+ */+export function parseRateLimitInfo(response: Response): RateLimitInfo {+ // Parse Retry-After header (standard HTTP header, value in seconds)+ const retryAfter = response.headers.get("Retry-After");+ let retryAfterSeconds = retryAfter ? parseInt(retryAfter, 10) : 60;++ // Fallback to 60 seconds if parsing fails+ if (isNaN(retryAfterSeconds) || retryAfterSeconds <= 0) {+ retryAfterSeconds = 60;+ }++ // Parse provider-specific headers+ const limitType = response.headers.get("X-Rate-Limit-Problem") ?? undefined;++ const details: Record<string, unknown> = {};++ // Xero-specific headers+ const minuteRemaining = response.headers.get("X-MinLimit-Remaining");+ const dayRemaining = response.headers.get("X-DayLimit-Remaining");+ const appMinuteRemaining = response.headers.get("X-AppMinLimit-Remaining");++ if (minuteRemaining) details.minuteRemaining = parseInt(minuteRemaining, 10);+ if (dayRemaining) details.dayRemaining = parseInt(dayRemaining, 10);+ if (appMinuteRemaining)+ details.appMinuteRemaining = parseInt(appMinuteRemaining, 10);++ return {+ retryAfterSeconds,+ limitType,+ details: Object.keys(details).length > 0 ? details : undefined+ };+}+/** Structured details from an accounting provider API error */export interface ApiErrorDetails {/** HTTP status code (e.g., 400, 401, 500) */diff --git a/packages/ee/src/accounting/index.ts b/packages/ee/src/accounting/index.tsindex bf9759ce32..10d1bb0e84 100644--- a/packages/ee/src/accounting/index.ts+++ b/packages/ee/src/accounting/index.ts@@ -3,4 +3,5 @@ export * from "./core/models";export * from "./core/service";export * from "./core/sync";export * from "./core/types";+export * from "./core/utils";export * from "./providers";diff --git a/packages/ee/src/accounting/providers/xero/entities/bill.ts b/packages/ee/src/accounting/providers/xero/entities/bill.tsindex ce3e8b3f01..369cbbe9fd 100644--- a/packages/ee/src/accounting/providers/xero/entities/bill.ts+++ b/packages/ee/src/accounting/providers/xero/entities/bill.ts@@ -1,8 +1,10 @@import type { KyselyTx } from "@carbon/database/client";+import { sql } from "kysely";import { createMappingService } from "../../../core/external-mapping";import { type Accounting, BaseEntitySyncer } from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "bill"@@ -230,24 +232,24 @@ export class BillSyncer extends BaseEntitySyncer<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,+ exchangeRate: Number(row.exchangeRate) || 1,+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,supplierReference: row.supplierReference,lines: lines.map((line) => ({id: line.id,description: line.description,- quantity: line.quantity,- unitPrice: line.unitPrice ?? 0,+ quantity: Number(line.quantity) || 0,+ unitPrice: Number(line.unitPrice) || 0,itemId: line.itemId,itemCode: line.itemCode,accountNumber: line.accountNumber,- taxPercent: line.taxPercent,- taxAmount: line.taxAmount,- totalAmount: line.totalAmount ?? 0,+ taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,+ taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,+ totalAmount: Number(line.totalAmount) || 0,purchaseOrderLineId: line.purchaseOrderLineId})),updatedAt: row.updatedAt ?? new Date().toISOString(),@@ -328,6 +330,11 @@ export class BillSyncer extends BaseEntitySyncer<);}+ // Get default account code from provider settings+ const xeroProvider = this.provider as XeroProvider;+ const defaultAccountCode =+ xeroProvider.settings?.defaultPurchaseAccountCode;+// Map line itemsconst lineItems: Xero.InvoiceLineItem[] = await Promise.all(local.lines.map(async (line) => {@@ -350,18 +357,39 @@ export class BillSyncer extends BaseEntitySyncer<description = description ? `${description} ${ref}` : ref;}+ // Determine if line has tax+ const hasTax =+ (line.taxPercent != null && line.taxPercent > 0) ||+ (line.taxAmount != null && line.taxAmount > 0);+return {Description: description,Quantity: line.quantity,UnitAmount: line.unitPrice,ItemCode: itemCode?.slice(0, 30) ?? undefined,- AccountCode: line.accountNumber ?? undefined,+ // Use line's account number if specified, otherwise use default from settings+ AccountCode: line.accountNumber ?? defaultAccountCode,TaxAmount: line.taxAmount ?? undefined,- LineAmount: line.totalAmount+ LineAmount: line.totalAmount,+ // TaxType is required by Xero: INPUT for purchase tax, NONE for zero tax+ TaxType: hasTax ? "INPUT" : "NONE"};}));+ // Calculate due date: use dateDue if provided, otherwise default to Net 30+ let dueDate = local.dateDue;+ if (!dueDate && local.dateIssued) {+ const issued = new Date(local.dateIssued);+ issued.setDate(issued.getDate() + 30);+ dueDate = issued.toISOString().split("T")[0]; // YYYY-MM-DD format+ } else if (!dueDate) {+ // If no dateIssued either, default to 30 days from now+ const now = new Date();+ now.setDate(now.getDate() + 30);+ dueDate = now.toISOString().split("T")[0];+ }+return {InvoiceID: existingRemoteId!,Type: "ACCPAY",@@ -369,7 +397,7 @@ export class BillSyncer extends BaseEntitySyncer<Reference: local.supplierReference ?? undefined,Contact: { ContactID: contactId },Date: local.dateIssued ?? undefined,- DueDate: local.dateDue ?? undefined,+ DueDate: dueDate,Status: CARBON_TO_XERO_STATUS[local.status],CurrencyCode: local.currencyCode,CurrencyRate: local.exchangeRate !== 1 ? local.exchangeRate : undefined,@@ -509,11 +537,102 @@ export class BillSyncer extends BaseEntitySyncer<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.`- );+ // Create new purchase invoice from Xero+ // This requires: supplierInteractionId, invoiceId (sequence), createdBy, companyId++ if (!supplierId) {+ throw new Error(+ `Cannot create purchase invoice from Xero: Supplier with Xero ContactID ${data.supplierExternalId} not found in Carbon. Sync the vendor first.`+ );+ }++ // Get a default user for createdBy (company owner or first admin)+ const defaultUser = await this.getDefaultUser(tx);+ if (!defaultUser) {+ throw new Error(+ `Cannot create purchase invoice from Xero: No default user found for company ${this.companyId}`+ );+ }++ // Create supplier interaction for this invoice+ const supplierInteraction = await tx+ .insertInto("supplierInteraction")+ .values({+ companyId: this.companyId,+ supplierId+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ // Get next invoice ID from sequence+ const sequenceResult = await sql<{ get_next_sequence: string }>`+ SELECT get_next_sequence('purchaseInvoice', ${this.companyId}) as get_next_sequence+ `.execute(tx);++ const invoiceId =+ sequenceResult.rows[0]?.get_next_sequence ??+ data.invoiceId ??+ `XERO-${remoteId.slice(0, 8)}`;++ // Insert the new purchase invoice+ const newInvoice = await tx+ .insertInto("purchaseInvoice")+ .values({+ invoiceId,+ companyId: this.companyId,+ createdBy: defaultUser,+ supplierId,+ supplierInteractionId: supplierInteraction.id,+ status: data.status ?? "Draft",+ dateIssued: data.dateIssued ?? null,+ dateDue: data.dateDue ?? null,+ datePaid: data.datePaid ?? null,+ currencyCode: data.currencyCode ?? "USD",+ exchangeRate: data.exchangeRate ?? 1,+ subtotal: data.subtotal ?? 0,+ totalTax: data.totalTax ?? 0,+ totalDiscount: data.totalDiscount ?? 0,+ totalAmount: data.totalAmount ?? 0,+ balance: data.balance ?? 0,+ supplierReference: data.supplierReference ?? null+ })+ .returning("id")+ .executeTakeFirstOrThrow();++ // Insert lines for the new invoice+ await this.upsertLines(tx, newInvoice.id, data.lines ?? []);++ return newInvoice.id;+ }++ /**+ * Get a default user for system-generated records.+ * Tries company owner first, then falls back to first active employee.+ */+ private async getDefaultUser(tx: KyselyTx): Promise<string | null> {+ // Try company owner first+ const company = await tx+ .selectFrom("company")+ .select("ownerId")+ .where("id", "=", this.companyId)+ .executeTakeFirst();++ if (company?.ownerId) {+ return company.ownerId;+ }++ // Fall back to first active employee for this company (by user creation date)+ const employee = await tx+ .selectFrom("employeeJob")+ .innerJoin("user", "user.id", "employeeJob.id")+ .select("employeeJob.id")+ .where("employeeJob.companyId", "=", this.companyId)+ .where("user.active", "=", true)+ .orderBy("user.createdAt", "asc")+ .limit(1)+ .executeTakeFirst();++ return employee?.id ?? null;}private async upsertLines(diff --git a/packages/ee/src/accounting/providers/xero/entities/contact.ts b/packages/ee/src/accounting/providers/xero/entities/contact.tsindex 5075da1e37..d76d8e393b 100644--- a/packages/ee/src/accounting/providers/xero/entities/contact.ts+++ b/packages/ee/src/accounting/providers/xero/entities/contact.ts@@ -4,7 +4,7 @@ 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 for rows returned from customer/supplier queries with address and contact joinstype EntityRow = {id: string;name: string;@@ -20,6 +20,13 @@ type EntityRow = {addressLine2: string | null;city: string | null;postalCode: string | null;+ // Contact details (from first linked contact)+ contactFirstName: string | null;+ contactLastName: string | null;+ contactEmail: string | null;+ contactMobilePhone: string | null;+ contactHomePhone: string | null;+ contactWorkPhone: string | null;};export class ContactSyncer extends BaseEntitySyncer<@@ -130,6 +137,8 @@ export class ContactSyncer extends BaseEntitySyncer<): Promise<Map<string, Accounting.Contact>> {if (ids.length === 0) return new Map();+ // First, get the first contact ID for each customer (subquery)+ // We use a lateral join pattern to get the first contact per customerconst rows = await this.database.selectFrom("customer").leftJoin(@@ -138,6 +147,8 @@ export class ContactSyncer extends BaseEntitySyncer<"customer.id").leftJoin("address", "address.id", "customerLocation.addressId")+ .leftJoin("customerContact", "customerContact.customerId", "customer.id")+ .leftJoin("contact", "contact.id", "customerContact.contactId").select(["customer.id","customer.name",@@ -152,13 +163,20 @@ export class ContactSyncer extends BaseEntitySyncer<"address.addressLine1","address.addressLine2","address.city",- "address.postalCode"+ "address.postalCode",+ // Contact details from linked contact+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"]).where("customer.id", "in", ids).where("customer.companyId", "=", this.companyId).execute();- return this.groupAndTransformRows(rows, true);+ return this.groupAndTransformRows(rows as EntityRow[], true);}private async fetchSuppliersByIds(@@ -174,6 +192,8 @@ export class ContactSyncer extends BaseEntitySyncer<"supplier.id").leftJoin("address", "address.id", "supplierLocation.addressId")+ .leftJoin("supplierContact", "supplierContact.supplierId", "supplier.id")+ .leftJoin("contact", "contact.id", "supplierContact.contactId").select(["supplier.id","supplier.name",@@ -188,13 +208,20 @@ export class ContactSyncer extends BaseEntitySyncer<"address.addressLine1","address.addressLine2","address.city",- "address.postalCode"+ "address.postalCode",+ // Contact details from linked contact+ "contact.firstName as contactFirstName",+ "contact.lastName as contactLastName",+ "contact.email as contactEmail",+ "contact.mobilePhone as contactMobilePhone",+ "contact.homePhone as contactHomePhone",+ "contact.workPhone as contactWorkPhone"]).where("supplier.id", "in", ids).where("supplier.companyId", "=", this.companyId).execute();- return this.groupAndTransformRows(rows, false);+ return this.groupAndTransformRows(rows as EntityRow[], false);}private groupAndTransformRows(@@ -244,10 +271,11 @@ export class ContactSyncer extends BaseEntitySyncer<return {id: row.id,name: row.name,- firstName: "",- lastName: "",+ // Use contact details from linked contact if available+ firstName: row.contactFirstName ?? "",+ lastName: row.contactLastName ?? "",companyId: row.companyId,- email: undefined,+ email: row.contactEmail ?? undefined,website: row.website ?? null,taxId: row.taxId ?? null,currencyCode: row.currencyCode ?? "USD",@@ -255,10 +283,11 @@ export class ContactSyncer extends BaseEntitySyncer<creditLimit: null,paymentTerms: null,updatedAt: row.updatedAt ?? new Date().toISOString(),- workPhone: row.phone ?? null,- mobilePhone: null,+ // Prefer contact's phone numbers, fall back to customer/supplier phone+ workPhone: row.contactWorkPhone ?? row.phone ?? null,+ mobilePhone: row.contactMobilePhone ?? null,fax: row.fax ?? null,- homePhone: null,+ homePhone: row.contactHomePhone ?? null,isVendor: !isCustomer,isCustomer,addresses,diff --git a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.tsindex 98f848fe75..a11028c074 100644--- a/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts+++ b/packages/ee/src/accounting/providers/xero/entities/inventory-adjustment.ts@@ -123,9 +123,9 @@ export class InventoryAdjustmentSyncer extends BaseEntitySyncer<entryType: row.entryType,itemId: row.itemId,locationId: row.locationId,- quantity: row.quantity,+ quantity: Number(row.quantity) || 0,companyId: row.companyId,- unitCost: row.unitCost ?? 0,+ unitCost: Number(row.unitCost) || 0,inventoryAccount: row.inventoryAccount,adjustmentVarianceAccount: row.adjustmentVarianceAccount,updatedAt: row.createdAt ?? new Date().toISOString(),diff --git a/packages/ee/src/accounting/providers/xero/entities/invoice.ts b/packages/ee/src/accounting/providers/xero/entities/invoice.tsindex 3aa7df03af..4101fb2139 100644--- a/packages/ee/src/accounting/providers/xero/entities/invoice.ts+++ b/packages/ee/src/accounting/providers/xero/entities/invoice.ts@@ -7,6 +7,7 @@ import {} from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "invoice"@@ -230,27 +231,32 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<customerExternalId: null, // Will be resolved during mapToRemotestatus: row.status,currencyCode: row.currencyCode,- exchangeRate: row.exchangeRate,+ exchangeRate: Number(row.exchangeRate) || 1,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- })),+ subtotal: Number(row.subtotal) || 0,+ totalTax: Number(row.totalTax) || 0,+ totalDiscount: Number(row.totalDiscount) || 0,+ totalAmount: Number(row.totalAmount) || 0,+ balance: Number(row.balance) || 0,+ lines: lines.map((line) => {+ const quantity = Number(line.quantity) || 0;+ const unitPrice = Number(line.unitPrice) || 0;+ const taxPercent = Number(line.taxPercent) || 0;+ return {+ id: line.id,+ invoiceLineType: line.invoiceLineType,+ itemId: line.itemId,+ itemCode: line.itemReadableIdWithRevision,+ description: line.description,+ quantity,+ unitPrice,+ taxPercent,+ lineAmount: quantity * unitPrice+ };+ }),updatedAt: row.updatedAt ?? new Date().toISOString(),raw: row});@@ -310,15 +316,35 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<local.customerId);+ // Get default account code from provider settings+ const xeroProvider = this.provider as XeroProvider;+ const defaultAccountCode = xeroProvider.settings?.defaultSalesAccountCode;++ console.log(+ "[SalesInvoiceSyncer] Provider settings:",+ xeroProvider.settings+ );+ console.log(+ "[SalesInvoiceSyncer] Default sales account code:",+ defaultAccountCode+ );+// Build line items, resolving item dependenciesconst lineItems: Xero.InvoiceLineItem[] = [];for (const line of local.lines) {+ const taxAmount =+ (line.quantity * line.unitPrice * line.taxPercent) / 100;+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+ TaxAmount: taxAmount,+ LineAmount: line.quantity * line.unitPrice,+ // Use default account code from settings if no account specified+ AccountCode: defaultAccountCode,+ // TaxType is required by Xero: OUTPUT for sales tax, NONE for zero tax+ TaxType: line.taxPercent > 0 ? "OUTPUT" : "NONE"};// If line has an item, ensure it's synced and get the ItemCode@@ -334,6 +360,19 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<lineItems.push(lineItem);}+ // Calculate due date: use dateDue if provided, otherwise default to Net 30+ let dueDate = local.dateDue;+ if (!dueDate && local.dateIssued) {+ const issued = new Date(local.dateIssued);+ issued.setDate(issued.getDate() + 30);+ dueDate = issued.toISOString().split("T")[0]; // YYYY-MM-DD format+ } else if (!dueDate) {+ // If no dateIssued either, default to 30 days from now+ const now = new Date();+ now.setDate(now.getDate() + 30);+ dueDate = now.toISOString().split("T")[0];+ }+return {InvoiceID: existingRemoteId!,Type: "ACCREC", // Accounts Receivable = Sales Invoice@@ -343,7 +382,7 @@ export class SalesInvoiceSyncer extends BaseEntitySyncer<ContactID: customerRemoteId},Date: local.dateIssued ?? undefined,- DueDate: local.dateDue ?? undefined,+ DueDate: dueDate,Status: CARBON_TO_XERO_STATUS[local.status],LineAmountTypes: "Exclusive", // Tax is calculated separatelyLineItems: lineItems,diff --git a/packages/ee/src/accounting/providers/xero/entities/item.ts b/packages/ee/src/accounting/providers/xero/entities/item.tsindex 264c65a7bf..2f48719751 100644--- a/packages/ee/src/accounting/providers/xero/entities/item.ts+++ b/packages/ee/src/accounting/providers/xero/entities/item.ts@@ -102,8 +102,8 @@ export class ItemSyncer extends BaseEntitySyncer<companyId: row.companyId!,type: row.type,unitOfMeasureCode: row.unitOfMeasureCode,- unitCost: row.unitCost ?? 0,- unitSalePrice: row.unitSalePrice ?? 0,+ unitCost: Number(row.unitCost) || 0,+ unitSalePrice: Number(row.unitSalePrice) || 0,isPurchased,isSold,isTrackedAsInventory,diff --git a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts b/packages/ee/src/accounting/providers/xero/entities/purchase-order.tsindex 5f29099df1..9c6e4c1dde 100644--- a/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts+++ b/packages/ee/src/accounting/providers/xero/entities/purchase-order.ts@@ -7,6 +7,7 @@ import {} from "../../../core/types";import { throwXeroApiError } from "../../../core/utils";import { parseDotnetDate, type Xero } from "../models";+import type { XeroProvider } from "../provider";// Note: This syncer uses the default ID mapping from BaseEntitySyncer// which uses the externalIntegrationMapping table with entityType "purchaseOrder"@@ -193,12 +194,12 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<for (const row of orderRows) {const lines = linesByOrder.get(row.id) ?? [];- // Calculate totals from lines+ // Calculate totals from lines (parse to numbers since NUMERIC comes as strings)let subtotal = 0;let totalTax = 0;for (const line of lines) {- subtotal += line.extendedPrice ?? 0;- totalTax += line.taxAmount ?? 0;+ subtotal += Number(line.extendedPrice) || 0;+ totalTax += Number(line.taxAmount) || 0;}result.set(row.id, {@@ -213,7 +214,7 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<deliveryAddress: null,deliveryInstructions: null,currencyCode: row.currencyCode,- exchangeRate: row.exchangeRate,+ exchangeRate: Number(row.exchangeRate) || 1,subtotal,totalTax,totalAmount: subtotal + totalTax,@@ -221,16 +222,20 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<lines: lines.map((line) => ({id: line.id,description: line.description,- quantity: line.purchaseQuantity ?? 0,- unitPrice: line.unitPrice ?? 0,+ quantity: Number(line.purchaseQuantity) || 0,+ unitPrice: Number(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+ taxPercent: line.taxPercent != null ? Number(line.taxPercent) : null,+ taxAmount: line.taxAmount != null ? Number(line.taxAmount) : null,+ totalAmount: Number(line.extendedPrice) || 0,+ quantityReceived:+ line.quantityReceived != null+ ? Number(line.quantityReceived)+ : null,+ quantityInvoiced:+ line.quantityInvoiced != null ? Number(line.quantityInvoiced) : null})),updatedAt: row.updatedAt ?? new Date().toISOString(),raw: row@@ -302,29 +307,46 @@ export class PurchaseOrderSyncer extends BaseEntitySyncer<);}+ // Get default account code from provider settings+ const xeroProvider = this.provider as XeroProvider;+ const defaultAccountCode =+ xeroProvider.settings?.defaultPurchaseAccountCode;+// Map line itemsconst 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;+ // If line has an item, ensure it's synced to Xero first+ if (line.itemId) {+ await this.ensureDependencySynced("item", line.itemId);+ // If we don't have the itemCode, fetch it from the item table+ if (!itemCode) {+ const item = await this.database+ .selectFrom("item")+ .select("readableId")+ .where("id", "=", line.itemId)+ .executeTakeFirst();+ itemCode = item?.readableId ?? null;+ }}+ // Determine tax percent from taxAmount if available+ const hasTax =+ (line.taxPercent != null && line.taxPercent > 0) ||+ (line.taxAmount != null && line.taxAmount > 0);+return {Description: line.description ?? undefined,Quantity: line.quantity,UnitAmount: line.unitPrice,ItemCode: itemCode?.slice(0, 30) ?? undefined,- AccountCode: line.accountNumber ?? undefined,+ // Use line's account number if specified, otherwise use default from settings+ AccountCode: line.accountNumber ?? defaultAccountCode,TaxAmount: line.taxAmount ?? undefined,- LineAmount: line.totalAmount+ LineAmount: line.totalAmount,+ // TaxType is required by Xero: INPUT for purchase tax, NONE for zero tax+ TaxType: hasTax ? "INPUT" : "NONE"};}));diff --git a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts b/packages/ee/src/accounting/providers/xero/entities/sales-order.tsindex fb9905196a..fb5a70c4ea 100644--- a/packages/ee/src/accounting/providers/xero/entities/sales-order.ts+++ b/packages/ee/src/accounting/providers/xero/entities/sales-order.ts@@ -183,12 +183,12 @@ export class SalesOrderSyncer extends BaseEntitySyncer<status: row.status,orderDate: row.orderDate,currencyCode: row.currencyCode,- exchangeRate: row.exchangeRate,+ exchangeRate: Number(row.exchangeRate) || 1,customerReference: row.customerReference,lines: lines.map((line) => {- const unitPrice = line.unitPrice ?? 0;- const setupPrice = line.setupPrice ?? 0;- const quantity = line.saleQuantity;+ const unitPrice = Number(line.unitPrice) || 0;+ const setupPrice = Number(line.setupPrice) || 0;+ const quantity = Number(line.saleQuantity) || 0;return {id: line.id,salesOrderLineType: line.salesOrderLineType,diff --git a/packages/ee/src/accounting/providers/xero/models.ts b/packages/ee/src/accounting/providers/xero/models.tsindex 04d76ffe63..fd0cb5f6f1 100644--- a/packages/ee/src/accounting/providers/xero/models.ts+++ b/packages/ee/src/accounting/providers/xero/models.ts@@ -322,6 +322,61 @@ export namespace Xero {export type QuoteLineItem = z.infer<typeof QuoteLineItemSchema>;export type QuoteContact = z.infer<typeof QuoteContactSchema>;export type Quote = z.infer<typeof QuoteSchema>;++ // Organisation schema for Xero Accounting API Organisation endpoint+ export const OrganisationSchema = z.object({+ OrganisationID: z.string().uuid(),+ Name: z.string(),+ LegalName: z.string().optional(),+ BaseCurrency: z.string(),+ CountryCode: z.string().optional(),+ IsDemoCompany: z.boolean().optional(),+ OrganisationType: z.string().optional(),+ OrganisationStatus: z.string().optional(),+ TaxNumber: z.string().optional(),+ FinancialYearEndDay: z.number().optional(),+ FinancialYearEndMonth: z.number().optional(),+ DefaultSalesTax: z.string().optional(),+ DefaultPurchasesTax: z.string().optional(),+ ShortCode: z.string().optional(),+ Edition: z.string().optional(),+ Class: z.string().optional(),+ Timezone: z.string().optional(),+ CreatedDateUTC: z.string().optional(),+ UpdatedDateUTC: z.string().optional()+ });++ export type Organisation = z.infer<typeof OrganisationSchema>;++ // Currency schema for Xero Accounting API Currencies endpoint+ export const CurrencySchema = z.object({+ Code: z.string(),+ Description: z.string().optional()+ });++ export type Currency = z.infer<typeof CurrencySchema>;++ // Account schema for Xero Accounting API Accounts (Chart of Accounts) endpoint+ export const AccountSchema = z.object({+ AccountID: z.string().uuid(),+ Code: z.string().optional(),+ Name: z.string(),+ Type: z.string(), // e.g., "REVENUE", "EXPENSE", "DIRECTCOSTS", "BANK", etc.+ Status: z.enum(["ACTIVE", "ARCHIVED"]).optional(),+ Description: z.string().optional(),+ TaxType: z.string().optional(),+ Class: z.string().optional(), // "REVENUE", "EXPENSE", "ASSET", "LIABILITY", "EQUITY"+ EnablePaymentsToAccount: z.boolean().optional(),+ ShowInExpenseClaims: z.boolean().optional(),+ BankAccountNumber: z.string().optional(),+ BankAccountType: z.string().optional(),+ CurrencyCode: z.string().optional(),+ ReportingCode: z.string().optional(),+ ReportingCodeName: z.string().optional(),+ UpdatedDateUTC: z.string().optional()+ });++ export type Account = z.infer<typeof AccountSchema>;}export const parseDotnetDate = (date: Date | string) => {diff --git a/packages/ee/src/accounting/providers/xero/provider.ts b/packages/ee/src/accounting/providers/xero/provider.tsindex 5d943619a3..6b5182b60e 100644--- a/packages/ee/src/accounting/providers/xero/provider.ts+++ b/packages/ee/src/accounting/providers/xero/provider.ts@@ -34,11 +34,17 @@ export interface ListItemsResponse {page: number;}+export interface XeroSettings {+ defaultSalesAccountCode?: string;+ defaultPurchaseAccountCode?: string;+}+type XeroProviderConfig = ProviderConfig<{clientId: string;clientSecret: string;redirectUri?: string;tenantId?: string;+ settings?: XeroSettings;}> & {id: ProviderID.XERO;accessToken?: string;@@ -52,9 +58,12 @@ export class XeroProvider implements BaseProvider {auth: AuthProvider;private readonly syncConfig!: GlobalSyncConfig;+ private readonly _settings: XeroSettings;constructor(public config: Omit<XeroProviderConfig, "id">) {this.syncConfig = config.syncConfig;+ this._settings = config.settings ?? {};+ console.log("[XeroProvider] Initialized with settings:", this._settings);this.http = new HTTPClient("https://api.xero.com/api.xro/2.0");this.auth = createOAuthClient({clientId: config.clientId,@@ -83,6 +92,13 @@ export class XeroProvider implements BaseProvider {return this.constructor.id;}+ /**+ * Get integration settings (e.g., default account codes).+ */+ get settings(): XeroSettings {+ return this._settings;+ }+getSyncConfig(entity: AccountingEntityType) {return this.syncConfig.entities[entity];}@@ -148,6 +164,60 @@ export class XeroProvider implements BaseProvider {}}+ /**+ * Fetch the Xero organisation details including base currency.+ */+ async getOrganisation(): Promise<Xero.Organisation | null> {+ const response = await this.request<{ Organisations: Xero.Organisation[] }>(+ "GET",+ "/Organisation"+ );++ if (response.error || !response.data?.Organisations?.[0]) {+ return null;+ }++ return response.data.Organisations[0];+ }++ /**+ * Fetch all currencies enabled/subscribed in the Xero organisation.+ */+ async listCurrencies(): Promise<Xero.Currency[]> {+ const response = await this.request<{ Currencies: Xero.Currency[] }>(+ "GET",+ "/Currencies"+ );++ if (response.error) {+ return [];+ }++ const data = response.data as { Currencies: Xero.Currency[] } | null;+ return data?.Currencies ?? [];+ }++ /**+ * Fetch chart of accounts from Xero.+ * Returns all active accounts by default.+ */+ async listChartOfAccounts(): Promise<Xero.Account[]> {+ const response = await this.request<{ Accounts: Xero.Account[] }>(+ "GET",+ "/Accounts"+ );++ if (response.error) {+ console.error("Failed to fetch Xero accounts:", response);+ return [];+ }++ // Filter to only active accounts+ return (response.data?.Accounts ?? []).filter(+ (account) => account.Status === "ACTIVE"+ );+ }+/*** List all contacts from Xero with pagination support.* Xero returns 100 contacts per page by default.diff --git a/packages/ee/src/xero/config.tsx b/packages/ee/src/xero/config.tsxindex c46ccc2494..e7fd36cbaf 100644--- a/packages/ee/src/xero/config.tsx+++ b/packages/ee/src/xero/config.tsx@@ -30,13 +30,16 @@ const XeroSettingsSchema = z.object({vendorOwner: SystemOfRecordSchema.optional().default("accounting"),itemOwner: SystemOfRecordSchema.optional().default("carbon"),invoiceOwner: SystemOfRecordSchema.optional().default("accounting"),- billOwner: SystemOfRecordSchema.optional().default("accounting")+ billOwner: SystemOfRecordSchema.optional().default("accounting"),+ // Default account codes for line items+ defaultSalesAccountCode: z.string().optional(),+ defaultPurchaseAccountCode: z.string().optional()});export const Xero = defineIntegration({name: "Xero",id: "xero",- active: false,+ active: true,category: "Accounting",logo: Logo,description:@@ -48,6 +51,10 @@ export const Xero = defineIntegration({{name: "Source of Truth",description: "Which system's data takes priority when there are conflicts"+ },+ {+ name: "Account Mapping",+ description: "Default accounts for syncing transactions to Xero"}],settings: [@@ -177,6 +184,26 @@ export const Xero = defineIntegration({],required: false,value: "accounting"+ },+ {+ name: "defaultSalesAccountCode",+ label: "Default Sales Account",+ description: "Account code to use for sales invoice line items",+ group: "Account Mapping",+ type: "options" as const,+ listOptions: [], // Populated dynamically from Xero+ required: true,+ value: ""+ },+ {+ name: "defaultPurchaseAccountCode",+ label: "Default Purchase Account",+ description: "Account code to use for purchase order and bill line items",+ group: "Account Mapping",+ type: "options" as const,+ listOptions: [], // Populated dynamically from Xero+ required: true,+ value: ""}],schema: XeroSettingsSchema,@@ -215,7 +242,6 @@ export const Xero = defineIntegration({const tables: CreateSubscriptionParams["table"][] = ["address",- "contact","customer","supplier","item",diff --git a/packages/jobs/trigger/accounting-backfill.ts b/packages/jobs/trigger/accounting-backfill.tsindex e15daf6eaa..87340de631 100644--- a/packages/jobs/trigger/accounting-backfill.ts+++ b/packages/jobs/trigger/accounting-backfill.ts@@ -1,3 +1,14 @@+/**+ * Backfill task for syncing entities between Carbon and accounting providers.+ *+ * This task respects the per-entity sync direction configuration:+ * - "pull-from-accounting": Only pull entities from the provider+ * - "push-to-accounting": Only push Carbon entities to the provider+ * - "two-way": Pull from provider AND push unsynced Carbon entities+ *+ * This prevents unnecessary syncing (e.g., items configured as push-only+ * won't be pulled from Xero, and POs configured as push-only won't try to pull).+ */import { getCarbonServiceRole } from "@carbon/auth";import {getPostgresClient,@@ -8,14 +19,48 @@ import {getAccountingIntegration,getProviderIntegration,ProviderID,+ RatelimitError,SyncFactory,type AccountingEntityType,+ type SyncDirection,type XeroProvider,} from "@carbon/ee/accounting";import { logger, task, wait } from "@trigger.dev/sdk/v3";import { PostgresDriver } from "kysely";import z from "zod";+// ============================================================+// HELPERS+// ============================================================++/**+ * Execute an async operation with rate limit handling.+ * If a RatelimitError is thrown, wait for the specified retry period and retry once.+ */+async function withRateLimitRetry<T>(+ operation: () => Promise<T>,+ operationName: string+): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ if (error instanceof RatelimitError) {+ const { retryAfterSeconds, limitType, details } = error.rateLimitInfo;+ logger.warn(`[RATE LIMIT] ${operationName} hit rate limit`, {+ limitType,+ retryAfterSeconds,+ ...details,+ });+ await wait.for({ seconds: retryAfterSeconds });+ logger.info(+ `[RATE LIMIT] Retrying ${operationName} after ${retryAfterSeconds}s wait`+ );+ return await operation();+ }+ throw error;+ }+}+// ============================================================// SCHEMAS// ============================================================@@ -33,6 +78,20 @@ const BackfillPayloadSchema = z.object({.default({}),});+/**+ * Helper to determine if we should pull for a given direction config+ */+function shouldPull(direction: SyncDirection): boolean {+ return direction === "pull-from-accounting" || direction === "two-way";+}++/**+ * Helper to determine if we should push for a given direction config+ */+function shouldPush(direction: SyncDirection): boolean {+ return direction === "push-to-accounting" || direction === "two-way";+}+const PullPagePayloadSchema = z.object({companyId: z.string(),provider: z.nativeEnum(ProviderID),@@ -88,10 +147,14 @@ export const accountingPullPageTask = task({try {if (payload.entityType === "contact") {logger.info(`[PULL] Fetching contacts page ${payload.page}`);- const response = await provider.listContacts({- page: payload.page,- summaryOnly: true,- });+ const response = await withRateLimitRetry(+ () =>+ provider.listContacts({+ page: payload.page,+ summaryOnly: true,+ }),+ `listContacts page ${payload.page}`+ );logger.info(`[PULL] Contacts page ${payload.page} response`, {count: response.contacts.length,@@ -123,7 +186,10 @@ export const accountingPullPageTask = task({entityType: "customer",});const ids = customers.map((c) => c.ContactID);- const result = await syncer.pullBatchFromAccounting(ids);+ const result = await withRateLimitRetry(+ () => syncer.pullBatchFromAccounting(ids),+ `pullBatchFromAccounting customers page ${payload.page}`+ );customersPulled = result.successCount;logger.info(`[PULL] Page ${payload.page}: pulled ${customersPulled} customers`,@@ -152,7 +218,10 @@ export const accountingPullPageTask = task({entityType: "vendor",});const ids = vendors.map((c) => c.ContactID);- const result = await syncer.pullBatchFromAccounting(ids);+ const result = await withRateLimitRetry(+ () => syncer.pullBatchFromAccounting(ids),+ `pullBatchFromAccounting vendors page ${payload.page}`+ );vendorsPulled = result.successCount;logger.info(`[PULL] Page ${payload.page}: pulled ${vendorsPulled} vendors`,@@ -176,7 +245,10 @@ export const accountingPullPageTask = task({} else {// Itemslogger.info(`[PULL] Fetching items page ${payload.page}`);- const response = await provider.listItems({ page: payload.page });+ const response = await withRateLimitRetry(+ () => provider.listItems({ page: payload.page }),+ `listItems page ${payload.page}`+ );logger.info(`[PULL] Items page ${payload.page} response`, {count: response.items.length,@@ -200,7 +272,10 @@ export const accountingPullPageTask = task({entityType: "item",});const ids = response.items.map((item) => item.ItemID);- const result = await syncer.pullBatchFromAccounting(ids);+ const result = await withRateLimitRetry(+ () => syncer.pullBatchFromAccounting(ids),+ `pullBatchFromAccounting items page ${payload.page}`+ );logger.info(`[PULL] Page ${payload.page}: pulled ${result.successCount} items`,@@ -272,7 +347,10 @@ export const accountingPushBatchTask = task({entityType,});- const result = await syncer.pushBatchToAccounting(payload.entityIds);+ const result = await withRateLimitRetry(+ () => syncer.pushBatchToAccounting(payload.entityIds),+ `pushBatchToAccounting ${payload.entityType}`+ );logger.info(`[PUSH] Pushed ${result.successCount}/${payload.entityIds.length} ${payload.entityType} entities`,@@ -328,6 +406,11 @@ export const accountingBackfillTask = task({integration.metadata) as XeroProvider;+ // Get sync direction config for each entity type+ const customerConfig = provider.getSyncConfig("customer");+ const vendorConfig = provider.getSyncConfig("vendor");+ const itemConfig = provider.getSyncConfig("item");+const result = {customers: { pulled: 0, pushed: 0 },vendors: { pulled: 0, pushed: 0 },@@ -336,23 +419,63 @@ export const accountingBackfillTask = task({totalPushed: 0,};+ // Log the sync directions for visibility+ logger.info("[BACKFILL] Starting with entity sync directions:", {+ customer: {+ enabled: customerConfig?.enabled,+ direction: customerConfig?.direction,+ shouldPull:+ customerConfig?.enabled && shouldPull(customerConfig.direction),+ shouldPush:+ customerConfig?.enabled && shouldPush(customerConfig.direction),+ },+ vendor: {+ enabled: vendorConfig?.enabled,+ direction: vendorConfig?.direction,+ shouldPull: vendorConfig?.enabled && shouldPull(vendorConfig.direction),+ shouldPush: vendorConfig?.enabled && shouldPush(vendorConfig.direction),+ },+ item: {+ enabled: itemConfig?.enabled,+ direction: itemConfig?.direction,+ shouldPull: itemConfig?.enabled && shouldPull(itemConfig.direction),+ shouldPush: itemConfig?.enabled && shouldPush(itemConfig.direction),+ },+ });+// ============================================================- // PHASE 1: Pull from accounting+ // PHASE 1: Pull from accounting (respecting direction config)// ============================================================- // Pull contacts (customers and vendors)- if (payload.entityTypes.customers || payload.entityTypes.vendors) {+ // Determine which contact types to pull based on their direction config+ const pullCustomers =+ payload.entityTypes.customers &&+ customerConfig?.enabled &&+ shouldPull(customerConfig.direction);++ const pullVendors =+ payload.entityTypes.vendors &&+ vendorConfig?.enabled &&+ shouldPull(vendorConfig.direction);++ // Pull contacts (customers and vendors) if their config allows pulling+ if (pullCustomers || pullVendors) {let page = 1;let hasMore = true;+ logger.info("[PULL] Starting contact pull phase", {+ pullCustomers,+ pullVendors,+ });+while (hasMore) {const pullResult = await accountingPullPageTask.triggerAndWait({companyId: payload.companyId,provider: payload.provider,entityType: "contact",page,- includeCustomers: payload.entityTypes.customers,- includeVendors: payload.entityTypes.vendors,+ includeCustomers: pullCustomers,+ includeVendors: pullVendors,});if (pullResult.ok) {@@ -360,9 +483,7 @@ export const accountingBackfillTask = task({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,- });+ logger.error(`[PULL] Failed to pull contacts page ${page}`);hasMore = false;}@@ -373,13 +494,24 @@ export const accountingBackfillTask = task({await wait.for({ seconds: 1 });}}+ } else {+ logger.info(+ "[PULL] Skipping contact pull - not enabled or direction is push-only"+ );}- // Pull items- if (payload.entityTypes.items) {+ // Pull items if their config allows pulling+ const pullItems =+ payload.entityTypes.items &&+ itemConfig?.enabled &&+ shouldPull(itemConfig.direction);++ if (pullItems) {let page = 1;let hasMore = true;+ logger.info("[PULL] Starting items pull phase");+while (hasMore) {const pullResult = await accountingPullPageTask.triggerAndWait({companyId: payload.companyId,@@ -392,9 +524,7 @@ export const accountingBackfillTask = task({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,- });+ logger.error(`[PULL] Failed to pull items page ${page}`);hasMore = false;}@@ -404,10 +534,14 @@ export const accountingBackfillTask = task({await wait.for({ seconds: 1 });}}+ } else {+ logger.info(+ "[PULL] Skipping items pull - not enabled or direction is push-only"+ );}// ============================================================- // PHASE 2: Push to accounting+ // PHASE 2: Push to accounting (respecting direction config)// ============================================================const pool = getPostgresConnectionPool(5);@@ -416,10 +550,17 @@ export const accountingBackfillTask = task({try {const mappingService = createMappingService(kysely, payload.companyId);- // Push customers- if (payload.entityTypes.customers) {+ // Push customers if their config allows pushing+ const pushCustomers =+ payload.entityTypes.customers &&+ customerConfig?.enabled &&+ shouldPush(customerConfig.direction);++ if (pushCustomers) {let hasMore = true;+ logger.info("[PUSH] Starting customers push phase");+while (hasMore) {const unsyncedIds = await mappingService.getUnsyncedEntityIds("customer",@@ -443,9 +584,7 @@ export const accountingBackfillTask = task({if (pushResult.ok) {result.customers.pushed += pushResult.output.successCount;} else {- logger.error("[PUSH] Failed to push customers batch", {- error: pushResult.error,- });+ logger.error("[PUSH] Failed to push customers batch");}if (unsyncedIds.length < payload.batchSize) {@@ -457,15 +596,26 @@ export const accountingBackfillTask = task({await wait.for({ seconds: 2 });}}+ } else {+ logger.info(+ "[PUSH] Skipping customers push - not enabled or direction is pull-only"+ );}- // Push vendors- if (payload.entityTypes.vendors) {+ // Push vendors if their config allows pushing+ const pushVendors =+ payload.entityTypes.vendors &&+ vendorConfig?.enabled &&+ shouldPush(vendorConfig.direction);++ if (pushVendors) {let hasMore = true;+ logger.info("[PUSH] Starting vendors push phase");+while (hasMore) {const unsyncedIds = await mappingService.getUnsyncedEntityIds(- "supplier",+ "vendor","supplier",provider.id,payload.batchSize@@ -486,9 +636,7 @@ export const accountingBackfillTask = task({if (pushResult.ok) {result.vendors.pushed += pushResult.output.successCount;} else {- logger.error("[PUSH] Failed to push vendors batch", {- error: pushResult.error,- });+ logger.error("[PUSH] Failed to push vendors batch");}if (unsyncedIds.length < payload.batchSize) {@@ -499,12 +647,23 @@ export const accountingBackfillTask = task({await wait.for({ seconds: 2 });}}+ } else {+ logger.info(+ "[PUSH] Skipping vendors push - not enabled or direction is pull-only"+ );}- // Push items- if (payload.entityTypes.items) {+ // Push items if their config allows pushing+ const pushItems =+ payload.entityTypes.items &&+ itemConfig?.enabled &&+ shouldPush(itemConfig.direction);++ if (pushItems) {let hasMore = true;+ logger.info("[PUSH] Starting items push phase");+while (hasMore) {const unsyncedIds = await mappingService.getUnsyncedEntityIds("item",@@ -528,9 +687,7 @@ export const accountingBackfillTask = task({if (pushResult.ok) {result.items.pushed += pushResult.output.successCount;} else {- logger.error("[PUSH] Failed to push items batch", {- error: pushResult.error,- });+ logger.error("[PUSH] Failed to push items batch");}if (unsyncedIds.length < payload.batchSize) {@@ -541,6 +698,10 @@ export const accountingBackfillTask = task({await wait.for({ seconds: 2 });}}+ } else {+ logger.info(+ "[PUSH] Skipping items push - not enabled or direction is pull-only"+ );}} finally {await pool.end();diff --git a/packages/jobs/trigger/event/sync.ts b/packages/jobs/trigger/event/sync.tsindex e72dbe3d1b..807a0b1392 100644--- a/packages/jobs/trigger/event/sync.ts+++ b/packages/jobs/trigger/event/sync.ts@@ -10,10 +10,11 @@ import {getAccountingIntegration,getProviderIntegration,ProviderID,+ RatelimitError,SyncFactory,} from "@carbon/ee/accounting";import { groupBy } from "@carbon/utils";-import { logger, task } from "@trigger.dev/sdk";+import { logger, task, wait } from "@trigger.dev/sdk";import { PostgresDriver } from "kysely";import { z } from "zod";@@ -45,6 +46,41 @@ function getEntityTypeFromTable(table: string): AccountingEntityType | null {return TABLE_TO_ENTITY_MAP[table] ?? null;}+function getDeduplicatedIds<T>(+ records: T[],+ getId: (r: T) => string+): string[] {+ return [...new Set(records.map(getId))];+}++/**+ * Execute an async operation with rate limit handling.+ * If a RatelimitError is thrown, wait for the specified retry period and retry once.+ */+async function withRateLimitRetry<T>(+ operation: () => Promise<T>,+ operationName: string+): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ if (error instanceof RatelimitError) {+ const { retryAfterSeconds, limitType, details } = error.rateLimitInfo;+ logger.warn(`[RATE LIMIT] ${operationName} hit rate limit`, {+ limitType,+ retryAfterSeconds,+ ...details,+ });+ await wait.for({ seconds: retryAfterSeconds });+ logger.info(+ `[RATE LIMIT] Retrying ${operationName} after ${retryAfterSeconds}s wait`+ );+ return await operation();+ }+ throw error;+ }+}+export const syncTask = task({id: "event-handler-sync",maxDuration: 5 * 60 * 1000, // 5 minutes@@ -142,13 +178,19 @@ export const syncTask = task({// Process INSERTs and UPDATEs (push to accounting)const toSync = [...inserts, ...updates];if (toSync.length > 0) {- const entityIds = toSync.map((r) => r.event.recordId);+ const entityIds = getDeduplicatedIds(+ toSync,+ (r) => r.event.recordId+ );logger.info(`Pushing ${entityIds.length} ${entityType} entities to accounting`);- const result = await syncer.pushBatchToAccounting(entityIds);+ const result = await withRateLimitRetry(+ () => syncer.pushBatchToAccounting(entityIds),+ `pushBatchToAccounting ${entityType}`+ );logger.info("Sync result:", { entityType, result });diff --git a/packages/jobs/trigger/sync-external-accounting.ts b/packages/jobs/trigger/sync-external-accounting.tsindex 7ad293a368..37eb7ef4bd 100644--- a/packages/jobs/trigger/sync-external-accounting.ts+++ b/packages/jobs/trigger/sync-external-accounting.ts@@ -1,5 +1,17 @@/**- * Task to sync entities from accounting providers to Carbon+ * Task to sync entities between accounting providers and Carbon.+ *+ * Handles three sync directions:+ * - "push-to-accounting": Push Carbon entities to the accounting provider+ * - "pull-from-accounting": Pull entities from the accounting provider to Carbon+ * - "two-way": Intelligently sync based on entity state and config+ *+ * For "two-way" sync:+ * - If entity has local ID but no remote mapping -> Push to accounting+ * - If entity has remote ID but no local mapping -> Pull from accounting+ * - If entity has both -> Use the entity config's "owner" to determine direction+ *+ * Includes cooldown protection to prevent redundant syncs of the same entity.*/import { getCarbonServiceRole } from "@carbon/auth";import {@@ -9,9 +21,12 @@ import {import {AccountingEntity,BatchSyncResult,+ createMappingService,getAccountingIntegration,getProviderIntegration,SyncFactory,+ type AccountingEntityType,+ type SyncResult,} from "@carbon/ee/accounting";import { groupBy } from "@carbon/utils";@@ -20,6 +35,10 @@ import { PostgresDriver } from "kysely";import z from "zod";import { AccountingSyncSchema } from "../../ee/src/accounting/core/models.ts";+// Cooldown period in milliseconds to prevent redundant syncs+// If an entity was synced within this period, skip syncing it again+const SYNC_COOLDOWN_MS = 60000; // 1 minute+const PayloadSchema = AccountingSyncSchema.extend({syncDirection: AccountingSyncSchema.shape.syncDirection,});@@ -49,6 +68,7 @@ export const syncExternalAccountingTask = task({const pool = getPostgresConnectionPool(10);const kysely = getPostgresClient(pool, PostgresDriver);+ const mappingService = createMappingService(kysely, payload.companyId);const results = {success: [] as BatchSyncResult[],@@ -59,18 +79,28 @@ export const syncExternalAccountingTask = task({const group = groupBy(payload.entities, (e) => e.entityType);for (const [entityType, entities] of Object.entries(group)) {- const type = entityType as AccountingEntity["entityType"];+ const type = entityType as AccountingEntityType;+ const entityConfig = provider.getSyncConfig(type);++ if (!entityConfig?.enabled) {+ logger.info(`Sync disabled for ${entityType}, skipping`);+ continue;+ }try {logger.info(- `Starting sync for ${entities.length} ${entityType} entities`+ `Starting sync for ${entities.length} ${entityType} entities`,+ {+ direction: input.syncDirection,+ configDirection: entityConfig.direction,+ });const syncer = SyncFactory.getSyncer({database: kysely,companyId: payload.companyId,provider,- config: provider.getSyncConfig(type),+ config: entityConfig,entityType: type,});@@ -79,24 +109,74 @@ export const syncExternalAccountingTask = task({continue;}- if (input.syncDirection === "push-to-accounting") {- const result = await syncer.pushBatchToAccounting(- entities.map((e) => e.entityId)+ // Determine the effective sync direction+ const effectiveDirection =+ input.syncDirection === "two-way"+ ? entityConfig.direction // Use the entity's configured direction+ : input.syncDirection;++ if (effectiveDirection === "push-to-accounting") {+ // Filter out entities that were synced recently (cooldown)+ const entitiesToSync = await filterByCooldown(+ mappingService,+ type,+ entities,+ provider.id);- logger.info("Sync result:", { entityType, result });+ if (entitiesToSync.length === 0) {+ logger.info(+ `All ${entityType} entities were synced recently, skipping`+ );+ continue;+ }+ const result = await syncer.pushBatchToAccounting(+ entitiesToSync.map((e) => e.entityId)+ );++ logger.info("Push sync result:", { entityType, result });results.success.push(result);- }+ } else if (effectiveDirection === "pull-from-accounting") {+ // Filter out entities that were synced recently (cooldown)+ const entitiesToSync = await filterByCooldown(+ mappingService,+ type,+ entities,+ provider.id+ );++ if (entitiesToSync.length === 0) {+ logger.info(+ `All ${entityType} entities were synced recently, skipping`+ );+ continue;+ }- if (input.syncDirection === "pull-from-accounting") {const result = await syncer.pullBatchFromAccounting(- entities.map((e) => e.entityId)+ entitiesToSync.map((e) => e.entityId));- logger.info("Sync result:", { entityType, result });-+ logger.info("Pull sync result:", { entityType, result });results.success.push(result);+ } else if (effectiveDirection === "two-way") {+ // For two-way sync, we need to determine direction per-entity+ // based on whether it has a local ID, remote ID, or both+ const twoWayResult = await handleTwoWaySync(+ syncer,+ mappingService,+ type,+ entities,+ provider.id,+ entityConfig.owner+ );++ logger.info("Two-way sync result:", {+ entityType,+ ...twoWayResult,+ });+ results.success.push(twoWayResult.pushed);+ results.success.push(twoWayResult.pulled);}} catch (error) {console.error(`Failed to process ${entityType} entities:`, error);@@ -116,3 +196,112 @@ export const syncExternalAccountingTask = task({return results;},});++/**+ * Filter entities that were synced within the cooldown period.+ * Returns only entities that are eligible for syncing.+ */+async function filterByCooldown(+ mappingService: ReturnType<typeof createMappingService>,+ entityType: AccountingEntityType,+ entities: AccountingEntity[],+ integration: string+): Promise<AccountingEntity[]> {+ const now = Date.now();+ const eligibleEntities: AccountingEntity[] = [];++ for (const entity of entities) {+ const mapping = await mappingService.getByEntity(+ entityType,+ entity.entityId,+ integration+ );++ // If no mapping exists or lastSyncedAt is old enough, include it+ if (!mapping?.lastSyncedAt) {+ eligibleEntities.push(entity);+ continue;+ }++ const lastSyncedAt = new Date(mapping.lastSyncedAt).getTime();+ if (now - lastSyncedAt > SYNC_COOLDOWN_MS) {+ eligibleEntities.push(entity);+ } else {+ logger.debug(+ `Skipping ${entityType} ${entity.entityId} - synced ${+ now - lastSyncedAt+ }ms ago`+ );+ }+ }++ return eligibleEntities;+}++/**+ * Handle two-way sync by determining the appropriate direction for each entity.+ *+ * Logic:+ * - If entity has entityId (Carbon ID) but no remote mapping -> Push to accounting+ * - If entity has entityId that is actually a remote ID (no local entity) -> Pull from accounting+ * - If entity has both local and remote -> Use "owner" config to determine winner+ */+async function handleTwoWaySync(+ syncer: ReturnType<typeof SyncFactory.getSyncer>,+ mappingService: ReturnType<typeof createMappingService>,+ entityType: AccountingEntityType,+ entities: AccountingEntity[],+ integration: string,+ owner: "carbon" | "accounting"+): Promise<{ pushed: BatchSyncResult; pulled: BatchSyncResult }> {+ const toPush: string[] = [];+ const toPull: string[] = [];+ const now = Date.now();++ for (const entity of entities) {+ // Check if this entity was synced recently+ const mapping = await mappingService.getByEntity(+ entityType,+ entity.entityId,+ integration+ );++ if (mapping?.lastSyncedAt) {+ const lastSyncedAt = new Date(mapping.lastSyncedAt).getTime();+ if (now - lastSyncedAt <= SYNC_COOLDOWN_MS) {+ logger.debug(+ `Skipping two-way sync for ${entityType} ${entity.entityId} - synced recently`+ );+ continue;+ }+ }++ if (mapping) {+ // Entity exists in both systems - use owner to determine direction+ if (owner === "carbon") {+ toPush.push(entity.entityId);+ } else {+ // owner === "accounting"+ toPull.push(mapping.externalId);+ }+ } else {+ // No mapping exists - this is likely a Carbon-only entity that needs pushing+ // Or it could be a remote ID that needs pulling+ // For now, assume entityId is a Carbon ID and push it+ toPush.push(entity.entityId);+ }+ }++ // Execute push and pull operations+ const pushResult =+ toPush.length > 0+ ? await syncer.pushBatchToAccounting(toPush)+ : { results: [], successCount: 0, errorCount: 0, skippedCount: 0 };++ const pullResult =+ toPull.length > 0+ ? await syncer.pullBatchFromAccounting(toPull)+ : { results: [], successCount: 0, errorCount: 0, skippedCount: 0 };++ return { pushed: pushResult, pulled: pullResult };+}