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
// SPDX-License-Identifier: LicenseRef-Carbon-Commercial
// Carbon Enterprise file, licensed only under the Carbon Commercial License
// (packages/ee/LICENSE). Not AGPL. Running, modifying, or copying it beyond those terms requires a commercial license.
import { z } from "zod";
import type { Accounting } from "../../core/types";
export namespace Xero {
// Shared address schema for contacts and employees
export const AddressSchema = z.object({
AddressType: z.enum(["POBOX", "STREET", "DELIVERY"]),
AddressLine1: z.string().optional(),
AddressLine2: z.string().optional(),
AddressLine3: z.string().optional(),
AddressLine4: z.string().optional(),
City: z.string().optional(),
Region: z.string().optional(),
PostalCode: z.string().optional(),
Country: z.string().optional(),
AttentionTo: z.string().optional()
});
export const PhoneSchema = z.object({
PhoneType: z.enum(["DDI", "DEFAULT", "FAX", "MOBILE"]),
PhoneNumber: z.string().optional(),
PhoneAreaCode: z.string().optional(),
PhoneCountryCode: z.string().optional()
});
export const BalancesSchema = z.object({
AccountsReceivable: z.object({
Outstanding: z.number(),
Overdue: z.number()
}),
AccountsPayable: z.object({
Outstanding: z.number(),
Overdue: z.number()
})
});
export const BrandingThemeSchema = z.object({
BrandingThemeID: z.string().uuid(),
Name: z.string()
});
export const BatchPaymentsSchema = z.object({
BankAccountNumber: z.string(),
BankAccountName: z.string(),
Details: z.string(),
Code: z.string().optional(),
Reference: z.string().optional()
});
export const ContactSchema = z.object({
ContactID: z.string().uuid(),
ContactStatus: z.literal("ACTIVE"),
Name: z.string(),
Website: z.string().optional(),
FirstName: z.string().optional(),
LastName: z.string().optional(),
EmailAddress: z.string().email().optional(),
ContactNumber: z.string().optional(),
BankAccountDetails: z.string().optional(),
TaxNumber: z.string().optional(),
AccountsReceivableTaxType: z.string().optional(),
AccountsPayableTaxType: z.string().optional(),
Addresses: z.array(AddressSchema),
Phones: z.array(PhoneSchema),
UpdatedDateUTC: z.string(), // serialized /Date(...)/
ContactGroups: z.array(z.unknown()),
IsSupplier: z.boolean(),
IsCustomer: z.boolean(),
DefaultCurrency: z.string().optional(),
BrandingTheme: BrandingThemeSchema.optional(),
BatchPayments: BatchPaymentsSchema.optional(),
Balances: BalancesSchema.optional(),
ContactPersons: z.array(z.unknown()),
HasAttachments: z.boolean(),
HasValidationErrors: z.boolean()
});
export type Contact = z.infer<typeof ContactSchema>;
// Employee schema for Xero Accounting API Employees endpoint
// Note: This is from the deprecated Accounting API endpoint, not PayrollAU/UK/NZ
export const EmployeeSchema = z.object({
EmployeeID: z.string().uuid(),
Status: z.enum(["ACTIVE", "DELETED"]).optional(),
FirstName: z.string(),
LastName: z.string(),
ExternalLink: z
.object({
Url: z.string().url().optional(),
Description: z.string().optional()
})
.optional(),
UpdatedDateUTC: z.string() // serialized /Date(...)/
});
export type Employee = z.infer<typeof EmployeeSchema>;
// Item schemas for Xero Accounting API Items endpoint
export const PurchaseDetailsSchema = z.object({
UnitPrice: z.number().optional(),
AccountCode: z.string().optional(),
COGSAccountCode: z.string().optional(),
TaxType: z.string().optional()
});
export const SalesDetailsSchema = z.object({
UnitPrice: z.number().optional(),
AccountCode: z.string().optional(),
TaxType: z.string().optional()
});
export const ItemSchema = z.object({
ItemID: z.string().uuid(),
Code: z.string().max(30),
Name: z.string().max(50).optional(),
Description: z.string().max(4000).optional(),
PurchaseDescription: z.string().optional(),
PurchaseDetails: PurchaseDetailsSchema.optional(),
SalesDetails: SalesDetailsSchema.optional(),
IsTrackedAsInventory: z.boolean().optional(),
IsSold: z.boolean().optional(),
IsPurchased: z.boolean().optional(),
QuantityOnHand: z.number().optional(),
TotalCostPool: z.number().optional(),
UpdatedDateUTC: z.string()
});
export type PurchaseDetails = z.infer<typeof PurchaseDetailsSchema>;
export type SalesDetails = z.infer<typeof SalesDetailsSchema>;
export type Item = z.infer<typeof ItemSchema>;
// Invoice/Bill schemas for Xero Accounting API
// Type: ACCPAY = Accounts Payable (Bill/Purchase Invoice)
// Type: ACCREC = Accounts Receivable (Sales Invoice)
export const InvoiceLineItemSchema = z.object({
LineItemID: z.string().uuid().optional(),
Description: z.string().optional(),
Quantity: z.number().optional(),
UnitAmount: z.number().optional(),
ItemCode: z.string().optional(),
AccountCode: z.string().optional(),
TaxType: z.string().optional(),
TaxAmount: z.number().optional(),
LineAmount: z.number().optional(),
DiscountRate: z.number().optional(),
Tracking: z.array(z.unknown()).optional()
});
export const InvoiceContactSchema = z.object({
ContactID: z.string().uuid(),
Name: z.string().optional()
});
export const InvoiceSchema = z.object({
InvoiceID: z.string().uuid(),
Type: z.enum(["ACCPAY", "ACCREC"]), // ACCPAY = Bill, ACCREC = Sales Invoice
InvoiceNumber: z.string().optional(),
Reference: z.string().optional(),
Contact: InvoiceContactSchema,
Date: z.string().optional(), // YYYY-MM-DD
DueDate: z.string().optional(),
Status: z.enum([
"DRAFT",
"SUBMITTED",
"AUTHORISED",
"PAID",
"VOIDED",
"DELETED"
]),
LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
LineItems: z.array(InvoiceLineItemSchema),
SubTotal: z.number().optional(),
TotalTax: z.number().optional(),
Total: z.number().optional(),
AmountDue: z.number().optional(),
AmountPaid: z.number().optional(),
CurrencyCode: z.string().optional(),
CurrencyRate: z.number().optional(),
UpdatedDateUTC: z.string()
});
export type Invoice = z.infer<typeof InvoiceSchema>;
export type InvoiceLineItem = z.infer<typeof InvoiceLineItemSchema>;
export type InvoiceContact = z.infer<typeof InvoiceContactSchema>;
// Credit note schemas for the Xero Accounting API /CreditNotes endpoint.
// Type: ACCRECCREDIT = a credit issued TO a customer (reduces AR)
// Type: ACCPAYCREDIT = a credit received FROM a supplier (reduces AP)
//
// Three Xero rules this shape encodes:
// 1. A credit note must be AUTHORISED before Xero will allocate it, and Xero
// forbids create-and-allocate in ONE request — allocation is always the
// separate PUT /CreditNotes/{id}/Allocations round-trip.
// 2. ACCPAYCREDIT has NO `Reference` field (only ACCRECCREDIT does), so the
// Carbon document number travels in `CreditNoteNumber` for BOTH types.
// 3. `Contact` must carry `ContactID` ONLY — sending other contact fields
// mutates the contact record and deletes its ContactPersons.
//
// The line shape is identical to an invoice line (Xero shares it), so the
// schema is aliased rather than duplicated.
export const CreditNoteLineItemSchema = InvoiceLineItemSchema;
export const CreditNoteAllocationInvoiceSchema = z
.object({
InvoiceID: z.string(),
InvoiceNumber: z.string().optional()
})
.passthrough();
/**
* One allocation of a credit note against one invoice. `Date` is documented
* read-only but the OpenAPI spec marks it required on write, so it is sent.
* Lenient (passthrough, optional ids) — Xero does not guarantee AllocationID
* on every response shape and the caller has a deterministic fallback.
*/
export const CreditNoteAllocationSchema = z
.object({
AllocationID: z.string().optional(),
Amount: z.number().optional(),
Date: z.string().optional(),
Invoice: CreditNoteAllocationInvoiceSchema.optional()
})
.passthrough();
export const CreditNoteSchema = z.object({
CreditNoteID: z.string().uuid(),
Type: z.enum(["ACCPAYCREDIT", "ACCRECCREDIT"]),
/** Carries the Carbon memo document number (ACCPAYCREDIT has no Reference). */
CreditNoteNumber: z.string().optional(),
/** ACCRECCREDIT only — Xero rejects it on an ACCPAYCREDIT. */
Reference: z.string().optional(),
Contact: InvoiceContactSchema,
Date: z.string().optional(), // YYYY-MM-DD
Status: z.enum([
"DRAFT",
"SUBMITTED",
"AUTHORISED",
"PAID",
"VOIDED",
"DELETED"
]),
LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
LineItems: z.array(CreditNoteLineItemSchema),
SubTotal: z.number().optional(),
TotalTax: z.number().optional(),
Total: z.number().optional(),
/** Unallocated balance — what is still available to allocate. */
RemainingCredit: z.number().optional(),
Allocations: z.array(CreditNoteAllocationSchema).optional(),
CurrencyCode: z.string().optional(),
CurrencyRate: z.number().optional(),
UpdatedDateUTC: z.string()
});
export type CreditNote = z.infer<typeof CreditNoteSchema>;
export type CreditNoteLineItem = z.infer<typeof CreditNoteLineItemSchema>;
export type CreditNoteAllocation = z.infer<typeof CreditNoteAllocationSchema>;
// Payment schemas for the Xero Accounting API /Payments endpoint.
// A Payment settles exactly ONE invoice — `Invoice.Type` (ACCPAY = bill /
// AP, ACCREC = sales invoice / AR) is the family discriminator; the settled
// document is `Invoice.InvoiceID`. `PaymentType` is ACCPAYPAYMENT /
// ACCRECPAYMENT. `Status` is AUTHORISED (settled) or DELETED (voided).
// Kept lenient (passthrough + string enums) — Xero adds fields freely and
// the syncer only reads the ids/amount/date/status it needs.
export const PaymentInvoiceSchema = z
.object({
InvoiceID: z.string(),
// ACCPAY = Bill (AP), ACCREC = Sales Invoice (AR)
Type: z.enum(["ACCPAY", "ACCREC"]).optional(),
InvoiceNumber: z.string().optional(),
CurrencyCode: z.string().optional()
})
.passthrough();
export const PaymentSchema = z
.object({
PaymentID: z.string(),
Date: z.string().optional(), // YYYY-MM-DD (or serialized /Date(...)/)
Amount: z.number().optional(),
Reference: z.string().optional(),
CurrencyRate: z.number().optional(),
// ACCRECPAYMENT (AR) | ACCPAYPAYMENT (AP) | ... — lenient
PaymentType: z.string().optional(),
// AUTHORISED (settled) | DELETED (void) — lenient
Status: z.string().optional(),
Invoice: PaymentInvoiceSchema.optional(),
UpdatedDateUTC: z.string() // serialized /Date(...)/
})
.passthrough();
export type PaymentInvoice = z.infer<typeof PaymentInvoiceSchema>;
export type Payment = z.infer<typeof PaymentSchema>;
// Purchase Order schemas for Xero Accounting API
export const PurchaseOrderLineItemSchema = z.object({
LineItemID: z.string().uuid().optional(),
Description: z.string().optional(),
Quantity: z.number().optional(),
UnitAmount: z.number().optional(),
ItemCode: z.string().optional(),
AccountCode: z.string().optional(),
TaxType: z.string().optional(),
TaxAmount: z.number().optional(),
LineAmount: z.number().optional(),
DiscountRate: z.number().optional(),
Tracking: z.array(z.unknown()).optional()
});
export const PurchaseOrderContactSchema = z.object({
ContactID: z.string().uuid(),
Name: z.string().optional()
});
export const PurchaseOrderSchema = z.object({
PurchaseOrderID: z.string().uuid(),
PurchaseOrderNumber: z.string().optional(),
Reference: z.string().optional(),
Contact: PurchaseOrderContactSchema,
Date: z.string().optional(), // YYYY-MM-DD
DeliveryDate: z.string().optional(),
DeliveryAddress: z.string().optional(),
AttentionTo: z.string().optional(),
Telephone: z.string().optional(),
DeliveryInstructions: z.string().optional(),
Status: z.enum(["DRAFT", "SUBMITTED", "AUTHORISED", "BILLED", "DELETED"]),
LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
LineItems: z.array(PurchaseOrderLineItemSchema),
SubTotal: z.number().optional(),
TotalTax: z.number().optional(),
Total: z.number().optional(),
CurrencyCode: z.string().optional(),
CurrencyRate: z.number().optional(),
UpdatedDateUTC: z.string()
});
export type PurchaseOrder = z.infer<typeof PurchaseOrderSchema>;
export type PurchaseOrderLineItem = z.infer<
typeof PurchaseOrderLineItemSchema
>;
export type PurchaseOrderContact = z.infer<typeof PurchaseOrderContactSchema>;
// Tracking category schemas for the Xero TrackingCategories endpoint —
// Xero's journal analytics (org-wide limit: 2 active categories)
export const TrackingOptionSchema = z.object({
TrackingOptionID: z.string().uuid(),
Name: z.string(),
Status: z.enum(["ACTIVE", "ARCHIVED", "DELETED"]).optional()
});
export type TrackingOption = z.infer<typeof TrackingOptionSchema>;
export const TrackingCategorySchema = z.object({
TrackingCategoryID: z.string().uuid(),
Name: z.string(),
Status: z.enum(["ACTIVE", "ARCHIVED", "DELETED"]).optional(),
Options: z.array(TrackingOptionSchema).optional()
});
export type TrackingCategory = z.infer<typeof TrackingCategorySchema>;
/** Tracking assignment on a manual-journal line (ids, never names). */
export const ManualJournalTrackingSchema = z.object({
TrackingCategoryID: z.string(),
TrackingOptionID: z.string()
});
export type ManualJournalTracking = z.infer<
typeof ManualJournalTrackingSchema
>;
// Manual Journal schemas for Xero Accounting API ManualJournals endpoint
export const ManualJournalLineSchema = z.object({
LineAmount: z.number(),
AccountCode: z.string(),
Description: z.string().optional(),
TaxType: z.string().optional(),
TaxAmount: z.number().optional(),
/** Max 2 entries (one per active tracking category). */
Tracking: z.array(ManualJournalTrackingSchema).optional(),
IsBlank: z.boolean().optional()
});
export const ManualJournalSchema = z.object({
ManualJournalID: z.string().uuid(),
Narration: z.string(),
Date: z.string().optional(),
Status: z.enum(["DRAFT", "POSTED", "DELETED", "VOIDED", "ARCHIVED"]),
LineAmountTypes: z.string().optional(),
Url: z.string().optional(),
ShowOnCashBasisReports: z.boolean().optional(),
JournalLines: z.array(ManualJournalLineSchema).optional(),
UpdatedDateUTC: z.string()
});
export type ManualJournalLine = z.infer<typeof ManualJournalLineSchema>;
export type ManualJournal = z.infer<typeof ManualJournalSchema>;
// Bank Transaction schemas for the Xero Accounting API BankTransactions
// endpoint — spend/receive money against a BANK-type account. Xero models a
// credit card as a bank account (BankAccountType CREDITCARD), so a card
// Charge is a SPEND and a merchant refund (Credit) a RECEIVE on the card
// account. There is no DELETE verb: a POST carrying Status DELETED deletes
// an unreconciled spend/receive money transaction.
export const BankTransactionLineItemSchema = z.object({
LineItemID: z.string().uuid().optional(),
Description: z.string().optional(),
Quantity: z.number().optional(),
UnitAmount: z.number().optional(),
ItemCode: z.string().optional(),
AccountCode: z.string().optional(),
TaxType: z.string().optional(),
TaxAmount: z.number().optional(),
LineAmount: z.number().optional(),
/** Max 2 entries (one per active tracking category). */
Tracking: z.array(ManualJournalTrackingSchema).optional()
});
/** Only AccountID or Code is required. */
export const BankTransactionBankAccountSchema = z.object({
AccountID: z.string().optional(),
Code: z.string().optional()
});
export const BankTransactionSchema = z.object({
BankTransactionID: z.string().uuid(),
// SPEND = money out (a card charge), RECEIVE = money in (a refund); the
// overpayment/prepayment/transfer subtypes are read-only for us
Type: z.enum([
"SPEND",
"RECEIVE",
"SPEND-OVERPAYMENT",
"SPEND-PREPAYMENT",
"RECEIVE-OVERPAYMENT",
"RECEIVE-PREPAYMENT",
"SPEND-TRANSFER",
"RECEIVE-TRANSFER"
]),
Contact: InvoiceContactSchema.optional(),
LineItems: z.array(BankTransactionLineItemSchema),
BankAccount: BankTransactionBankAccountSchema,
IsReconciled: z.boolean().optional(),
Date: z.string().optional(), // YYYY-MM-DD
Reference: z.string().optional(),
CurrencyCode: z.string().optional(),
CurrencyRate: z.number().optional(),
Url: z.string().optional(),
Status: z.enum(["AUTHORISED", "DELETED"]).optional(),
LineAmountTypes: z.enum(["Exclusive", "Inclusive", "NoTax"]).optional(),
SubTotal: z.number().optional(),
TotalTax: z.number().optional(),
Total: z.number().optional(),
UpdatedDateUTC: z.string()
});
export type BankTransactionLineItem = z.infer<
typeof BankTransactionLineItemSchema
>;
export type BankTransaction = z.infer<typeof BankTransactionSchema>;
// Quote schemas for Xero Accounting API Quotes endpoint
// Xero Quotes are the closest equivalent to Sales Orders
export const QuoteLineItemSchema = z.object({
LineItemID: z.string().uuid().optional(),
Description: z.string().optional(),
Quantity: z.number().optional(),
UnitAmount: z.number().optional(),
ItemCode: z.string().max(30).optional(),
AccountCode: z.string().optional(),
TaxType: z.string().optional(),
TaxAmount: z.number().optional(),
LineAmount: z.number().optional(),
DiscountRate: z.number().optional(),
DiscountAmount: z.number().optional()
});
export const QuoteContactSchema = z.object({
ContactID: z.string().uuid()
});
export const QuoteSchema = z.object({
QuoteID: z.string().uuid(),
QuoteNumber: z.string().max(255).optional(),
Reference: z.string().max(4000).optional(),
Terms: z.string().max(4000).optional(),
Contact: QuoteContactSchema,
LineItems: z.array(QuoteLineItemSchema).optional(),
Date: z.string().optional(),
ExpiryDate: z.string().optional(),
Status: z.enum([
"DRAFT",
"SENT",
"DECLINED",
"ACCEPTED",
"INVOICED",
"DELETED"
]),
CurrencyCode: z.string().optional(),
CurrencyRate: z.number().optional(),
SubTotal: z.number().optional(),
TotalTax: z.number().optional(),
Total: z.number().optional(),
TotalDiscount: z.number().optional(),
Title: z.string().max(100).optional(),
Summary: z.string().max(3000).optional(),
LineAmountTypes: z.string().optional(),
UpdatedDateUTC: z.string()
});
export type QuoteLineItem = z.infer<typeof QuoteLineItemSchema>;
export type QuoteContact = z.infer<typeof QuoteContactSchema>;
export type Quote = z.infer<typeof QuoteSchema>;
// 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(),
// Lock dates (serialized /Date(...)/): transactions dated on or before
// these are locked. PeriodLockDate stops non-advisors; EndOfYearLockDate
// stops everyone. Posting sync treats the max of both as THE lock date.
PeriodLockDate: z.string().optional(),
EndOfYearLockDate: 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) => {
if (typeof date === "string") {
const value = date.replace(/\/Date\((\d+)([-+]\d+)?\)\//, "$1");
return new Date(parseInt(value));
}
return date;
};
export const transformXeroPhones = (
contact: Xero.Contact
): Pick<
Accounting.Contact,
"homePhone" | "workPhone" | "mobilePhone" | "fax"
> => {
const phones = contact.Phones ?? [];
const homePhone = phones.find((p) => p.PhoneType === "DDI" && p.PhoneNumber);
const workPhone = phones.find(
(p) => p.PhoneType === "DEFAULT" && p.PhoneNumber
);
const mobilePhone = phones.find(
(p) => p.PhoneType === "MOBILE" && p.PhoneNumber
);
const fax = phones.find((p) => p.PhoneType === "FAX" && p.PhoneNumber);
return {
workPhone: workPhone?.PhoneNumber,
mobilePhone: mobilePhone?.PhoneNumber,
homePhone: homePhone?.PhoneNumber,
fax: fax?.PhoneNumber
};
};
export const transformXeroContact = (
contact: Xero.Contact,
companyId: string
): Accounting.Contact => {
const firstName = contact.FirstName || "";
const lastName = contact.LastName || "";
const addresses = contact.Addresses ?? [];
const { workPhone, mobilePhone, homePhone } = transformXeroPhones(contact);
return {
id: contact.ContactID,
name: contact.Name,
firstName,
lastName,
companyId,
website: contact.Website,
currencyCode: contact.DefaultCurrency ?? "USD",
taxId: contact.TaxNumber,
email: contact.EmailAddress,
isCustomer: contact.IsCustomer,
isVendor: contact.IsSupplier,
addresses: addresses.map((a) => ({
label: a.AttentionTo,
line1: a.AddressLine1,
line2: a.AddressLine2,
city: a.City,
region: a.Region,
country: a.Country,
postalCode: a.PostalCode
})),
workPhone,
mobilePhone,
homePhone,
updatedAt: parseDotnetDate(contact.UpdatedDateUTC).toISOString(),
raw: contact
};
};