Skip to content

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

2.0 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
// including ports, remain AGPLv3; serving them over a network requires releasing their source.

import { requirePermissions } from "@carbon/auth/auth.server";
import {
  getAccountingIntegration,
  getProviderIntegration,
  ProviderID,
  type XeroProvider
} from "@carbon/ee/accounting";
import { getLogger } from "@carbon/logger";
import type { LoaderFunctionArgs } from "react-router";
import { data } from "react-router";

const logger = getLogger("erp", "integrations-xero-accounts");

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) {
    logger.error("Failed to fetch Xero accounts", { error: error });
    return data(
      {
        error:
          error instanceof Error ? error.message : "Failed to fetch accounts",
        accounts: []
      },
      { status: 500 }
    );
  }
}