Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

feat(xero): connect new Xero apps and add AI actions, reports and invoice tools (#16136)

Odai Ahmadce7d26487c7a
diff --git a/bun.lock b/bun.lock
index 28bcfceccfc..cd802cbe8dc 100644
--- a/bun.lock
+++ b/bun.lock
@@ -10068,16 +10068,16 @@
},
"packages/pieces/community/xero": {
"name": "@activepieces/piece-xero",
- "version": "0.7.1",
+ "version": "0.8.0",
"dependencies": {
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*",
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
- "dayjs": "1.11.9",
},
"devDependencies": {
"tslib": "2.6.2",
+ "vitest": "3.2.6",
},
},
"packages/pieces/community/xquik": {
diff --git a/docs/install/reference/breaking-changes.mdx b/docs/install/reference/breaking-changes.mdx
index 8a005a7cd16..7e8c08e4f88 100644
--- a/docs/install/reference/breaking-changes.mdx
+++ b/docs/install/reference/breaking-changes.mdx
@@ -18,6 +18,16 @@ Get File used to return a `file_url` that contained the bot token, which put the
If a flow branches on Get Chat or Get Chat Member returning `ok: false`, handle the failure with the step's error handling options instead. If a later step reads Get File's `file_url`, turn on **Download File** and use `file_content_base64`. Steps keep running on the version they were built with until you upgrade them.
+#### Xero connections request Xero's granular scopes
+
+Since 2 March 2026 Xero refuses the broad scopes `accounting.transactions`, `accounting.reports.read` and `accounting.journals.read` for newly created Xero apps, so connecting such an app failed with `invalid_scope`. From Xero 0.8.0, new connections request the granular scopes instead: `accounting.invoices`, `accounting.payments`, `accounting.banktransactions`, `accounting.manualjournals` and the per-report scopes (aged, balance sheet, bank summary, executive summary, profit and loss, tax and trial balance reports). Existing connections are unaffected: Xero keeps the permissions granted at sign-in, and token refresh sends no scope.
+
+New connections no longer have Xero's Receipts, Expense Claims or Journals permissions, because Xero does not grant `accounting.classicexpenses` or `accounting.journals.read` to new apps. On those connections, Upload Attachment with the Receipt resource type fails with a message saying so, and Custom API Call to `/Receipts`, `/ExpenseClaims` or `/Journals` returns 401 or 403.
+
+#### What you need to do
+
+Nothing for existing Xero connections. To connect a Xero app created on or after 2 March 2026, upgrade the Xero step to 0.8.0 or later before creating the connection; a connection created from a step still on an earlier version requests the old scopes. Keep a connection created before 0.8.0 if your flows attach files to Receipts or call the Receipts, Expense Claims or Journals endpoints.
+
#### Helm chart 0.5.0 uses the cluster's default StorageClass again
Chart 0.4.0 set the app's cache volume to the `local-path` StorageClass whenever `persistence.storageClassName` was unset, which only exists on k3s-style clusters, so new installs elsewhere stayed `Pending`. From 0.5.0 an unset value uses the cluster's default StorageClass again, as chart 0.3.x did. A StatefulSet's volume class cannot change after it is created, so `helm upgrade` keeps the class your release already uses.
diff --git a/packages/pieces/community/xero/package.json b/packages/pieces/community/xero/package.json
index 21eafdbde34..0ffc67a3c63 100644
--- a/packages/pieces/community/xero/package.json
+++ b/packages/pieces/community/xero/package.json
@@ -1,21 +1,22 @@
{
"name": "@activepieces/piece-xero",
- "version": "0.7.1",
+ "version": "0.8.0",
"main": "./dist/src/index.js",
"types": "./dist/src/index.d.ts",
"scripts": {
"build": "tsc -p tsconfig.lib.json && cp package.json dist/",
"bundle": "node ../../../../dist/packages/cli/src/index.js pieces bundle",
- "lint": "eslint 'src/**/*.ts'"
+ "lint": "eslint 'src/**/*.ts'",
+ "test": "vitest run"
},
"dependencies": {
"@activepieces/pieces-common": "workspace:*",
"@activepieces/pieces-framework": "workspace:*",
- "dayjs": "1.11.9",
"@activepieces/core-piece-types": "workspace:*",
"@activepieces/core-utils": "workspace:*"
},
"devDependencies": {
- "tslib": "2.6.2"
+ "tslib": "2.6.2",
+ "vitest": "3.2.6"
}
}
diff --git a/packages/pieces/community/xero/src/i18n/translation.json b/packages/pieces/community/xero/src/i18n/translation.json
index 485c8d20a22..78bc22b9f8a 100644
--- a/packages/pieces/community/xero/src/i18n/translation.json
+++ b/packages/pieces/community/xero/src/i18n/translation.json
@@ -1,6 +1,6 @@
{
"Beautiful accounting software": "Beautiful accounting software",
- "\n 1. Log in to Xero.\n 2. Go to [Developer portal](https://developer.xero.com/app/manage/).\n 3. Click on the App you want to integrate.\n 4. On the left, click on `Configuration`.\n 5. Enter your `redirect url`.\n 6. Copy the `Client Id` and `Client Secret`.\n ": "\n 1. Log in to Xero.\n 2. Go to [Developer portal](https://developer.xero.com/app/manage/).\n 3. Click on the App you want to integrate.\n 4. On the left, click on `Configuration`.\n 5. Enter your `redirect url`.\n 6. Copy the `Client Id` and `Client Secret`.\n ",
+ "\n 1. Log in to Xero.\n 2. Go to [Developer portal](https://developer.xero.com/app/manage/).\n 3. Click on the App you want to integrate.\n 4. On the left, click on `Configuration`.\n 5. Enter your `redirect url`.\n 6. Copy the `Client Id` and `Client Secret`.\n\n The connection requests Xero's granular scopes (for example `accounting.invoices` and `accounting.payments` instead of `accounting.transactions`), which apps created on or after 2 March 2026 require. Receipts, Expense Claims and Journals are not av": "\n 1. Log in to Xero.\n 2. Go to [Developer portal](https://developer.xero.com/app/manage/).\n 3. Click on the App you want to integrate.\n 4. On the left, click on `Configuration`.\n 5. Enter your `redirect url`.\n 6. Copy the `Client Id` and `Client Secret`.\n\n The connection requests Xero's granular scopes (for example `accounting.invoices` and `accounting.payments` instead of `accounting.transactions`), which apps created on or after 2 March 2026 require. Receipts, Expense Claims and Journals are not available on connections created with this version.\n ",
"Create or Update Contact": "Create or Update Contact",
"Create or Update Invoice": "Create or Update Invoice",
"Allocate Credit Note to Invoice": "Allocate Credit Note to Invoice",
@@ -25,6 +25,34 @@
"Get Invoice History": "Get Invoice History",
"Create Bank Transaction": "Create Bank Transaction",
"Find or Create Contact": "Find or Create Contact",
+ "List Organisations": "List Organisations",
+ "Get Organisation Details": "Get Organisation Details",
+ "Get Invoice": "Get Invoice",
+ "Search Invoices": "Search Invoices",
+ "Download Invoice PDF": "Download Invoice PDF",
+ "Get Contact": "Get Contact",
+ "Archive Contact": "Archive Contact",
+ "Create or Update Item": "Create or Update Item",
+ "Search Payments": "Search Payments",
+ "Delete Payment": "Delete Payment",
+ "Void or Delete Invoice": "Void or Delete Invoice",
+ "Search Bank Transactions": "Search Bank Transactions",
+ "Create Manual Journal": "Create Manual Journal",
+ "List Accounts": "List Accounts",
+ "List Tax Rates": "List Tax Rates",
+ "List Tracking Categories": "List Tracking Categories",
+ "Get Profit and Loss": "Get Profit and Loss",
+ "Get Balance Sheet": "Get Balance Sheet",
+ "Get Bank Summary": "Get Bank Summary",
+ "Get Trial Balance": "Get Trial Balance",
+ "Get Executive Summary": "Get Executive Summary",
+ "Get Aged Receivables for Contact": "Get Aged Receivables for Contact",
+ "Get Aged Payables for Contact": "Get Aged Payables for Contact",
+ "Create Invoice or Bill": "Create Invoice or Bill",
+ "Update Invoice or Bill": "Update Invoice or Bill",
+ "Email Invoice": "Email Invoice",
+ "Record Payment": "Record Payment",
+ "Create Quote": "Create Quote",
"Custom API Call": "Custom API Call",
"Create Xero Contact": "Create Xero Contact",
"Create Xero Invoice": "Create Xero Invoice",
@@ -50,6 +78,39 @@
"Returns a list of history records for a given invoice ID.": "Returns a list of history records for a given invoice ID.",
"Creates a new Spend/Receive Money bank transaction.": "Creates a new Spend/Receive Money bank transaction.",
"Finds or creates a specific contact.": "Finds or creates a specific contact.",
+ "Lists the Xero organisations this connection can access.": "Lists the Xero organisations this connection can access.",
+ "Gets the settings of a Xero organisation, such as base currency, tax settings and financial year end.": "Gets the settings of a Xero organisation, such as base currency, tax settings and financial year end.",
+ "Gets one invoice or bill by its ID or invoice number, including line items.": "Gets one invoice or bill by its ID or invoice number, including line items.",
+ "Searches sales invoices and bills by type, status, contact, date range or text, one page at a time.": "Searches sales invoices and bills by type, status, contact, date range or text, one page at a time.",
+ "Downloads the PDF of an invoice or bill so you can attach or send it in later steps.": "Downloads the PDF of an invoice or bill so you can attach or send it in later steps.",
+ "Gets one contact by ID, with addresses and phone numbers.": "Gets one contact by ID, with addresses and phone numbers.",
+ "Archives a contact so it no longer appears in contact lists.": "Archives a contact so it no longer appears in contact lists.",
+ "Creates a product or service item, or updates the item that already has this code.": "Creates a product or service item, or updates the item that already has this code.",
+ "Searches payments by invoice, status, payment type or date range, one page at a time.": "Searches payments by invoice, status, payment type or date range, one page at a time.",
+ "Deletes (reverses) a payment so the invoice or bill is unpaid again.": "Deletes (reverses) a payment so the invoice or bill is unpaid again.",
+ "Voids an approved invoice or bill, or deletes it while it is still a draft or awaiting approval.": "Voids an approved invoice or bill, or deletes it while it is still a draft or awaiting approval.",
+ "Searches spend and receive money transactions by type, status, bank account, contact or date range.": "Searches spend and receive money transactions by type, status, bank account, contact or date range.",
+ "Creates a manual journal with balanced debit and credit lines.": "Creates a manual journal with balanced debit and credit lines.",
+ "Lists the chart of accounts, optionally filtered by type, class or status.": "Lists the chart of accounts, optionally filtered by type, class or status.",
+ "Lists the tax rates of the organisation and the TaxType codes to use on line items.": "Lists the tax rates of the organisation and the TaxType codes to use on line items.",
+ "Lists tracking categories (such as Region or Department) and their options.": "Lists tracking categories (such as Region or Department) and their options.",
+ "Runs the Profit and Loss report for a date range, with optional comparison periods.": "Runs the Profit and Loss report for a date range, with optional comparison periods.",
+ "Runs the Balance Sheet report as at a date, with optional comparison periods.": "Runs the Balance Sheet report as at a date, with optional comparison periods.",
+ "Runs the Bank Summary report: opening balance, cash in, cash out and closing balance per bank account.": "Runs the Bank Summary report: opening balance, cash in, cash out and closing balance per bank account.",
+ "Runs the Trial Balance report as at a date.": "Runs the Trial Balance report as at a date.",
+ "Runs the Executive Summary report: cash, profitability, balance sheet and performance ratios for a month.": "Runs the Executive Summary report: cash, profitability, balance sheet and performance ratios for a month.",
+ "Runs the Aged Receivables report for one customer: what they owe, by invoice and age.": "Runs the Aged Receivables report for one customer: what they owe, by invoice and age.",
+ "Runs the Aged Payables report for one supplier: what you owe them, by bill and age.": "Runs the Aged Payables report for one supplier: what you owe them, by bill and age.",
+ "Creates a sales invoice or a supplier bill for a contact ID with line items.": "Creates a sales invoice or a supplier bill for a contact ID with line items.",
+ "Updates fields or line items of an existing invoice or bill by ID.": "Updates fields or line items of an existing invoice or bill by ID.",
+ "Emails a sales invoice to its contact through Xero.": "Emails a sales invoice to its contact through Xero.",
+ "Records a payment against an approved invoice or bill from a bank account.": "Records a payment against an approved invoice or bill from a bank account.",
+ "Creates a customer or supplier credit note for a contact ID with line items.": "Creates a customer or supplier credit note for a contact ID with line items.",
+ "Applies part or all of a credit note to an invoice or bill.": "Applies part or all of a credit note to an invoice or bill.",
+ "Creates a quote for a contact ID with line items.": "Creates a quote for a contact ID with line items.",
+ "Creates a purchase order to a supplier contact ID with line items.": "Creates a purchase order to a supplier contact ID with line items.",
+ "Records a spend money or receive money transaction on a bank account.": "Records a spend money or receive money transaction on a bank account.",
+ "Attaches a file to an existing invoice, bill, credit note, quote, purchase order, contact or other record.": "Attaches a file to an existing invoice, bill, credit note, quote, purchase order, contact or other record.",
"Make a custom API call to a specific endpoint": "Make a custom API call to a specific endpoint",
"Organization": "Organization",
"Contact ID": "Contact ID",
@@ -65,7 +126,8 @@
"Credit Note": "Credit Note",
"Amount": "Amount",
"Allocation Date": "Allocation Date",
- "Bank Account": "Bank Account",
+ "From Bank Account": "From Bank Account",
+ "To Bank Account": "To Bank Account",
"Transfer Date": "Transfer Date",
"Reference": "Reference",
"From Is Reconciled": "From Is Reconciled",
@@ -80,6 +142,7 @@
"Sales Invoice (Sendable)": "Sales Invoice (Sendable)",
"Bill Number (Reference)": "Bill Number (Reference)",
"Invoice (Authorised)": "Invoice (Authorised)",
+ "Bank Account": "Bank Account",
"Payment Date": "Payment Date",
"Is Reconciled": "Is Reconciled",
"Delivery Date": "Delivery Date",
@@ -147,21 +210,78 @@
"Date To (YYYY-MM-DD)": "Date To (YYYY-MM-DD)",
"Order (e.g., Date DESC)": "Order (e.g., Date DESC)",
"Page Size (1-1000)": "Page Size (1-1000)",
+ "Invoice ID or Number": "Invoice ID or Number",
+ "Invoice Date From (YYYY-MM-DD)": "Invoice Date From (YYYY-MM-DD)",
+ "Invoice Date To (YYYY-MM-DD)": "Invoice Date To (YYYY-MM-DD)",
+ "Search Term": "Search Term",
+ "Summary Only": "Summary Only",
+ "Page Size": "Page Size",
+ "Invoice ID": "Invoice ID",
+ "File Name": "File Name",
+ "Sales Unit Price": "Sales Unit Price",
+ "Sales Account Code": "Sales Account Code",
+ "Sales Tax Type": "Sales Tax Type",
+ "Purchase Unit Price": "Purchase Unit Price",
+ "Purchase Account Code": "Purchase Account Code",
+ "Purchase Tax Type": "Purchase Tax Type",
+ "COGS Account Code": "COGS Account Code",
+ "Inventory Asset Account Code": "Inventory Asset Account Code",
+ "Payment Type": "Payment Type",
+ "Reference (exact)": "Reference (exact)",
+ "Payment Date From (YYYY-MM-DD)": "Payment Date From (YYYY-MM-DD)",
+ "Payment Date To (YYYY-MM-DD)": "Payment Date To (YYYY-MM-DD)",
+ "Payment ID": "Payment ID",
+ "Bank Account ID": "Bank Account ID",
+ "Reconciled": "Reconciled",
+ "Narration": "Narration",
+ "Journal Lines": "Journal Lines",
+ "Date (YYYY-MM-DD)": "Date (YYYY-MM-DD)",
+ "Show on Cash Basis Reports": "Show on Cash Basis Reports",
+ "Class": "Class",
+ "Only Accounts That Accept Payments": "Only Accounts That Accept Payments",
+ "Tax Type": "Tax Type",
+ "Active Only": "Active Only",
+ "From Date (YYYY-MM-DD)": "From Date (YYYY-MM-DD)",
+ "To Date (YYYY-MM-DD)": "To Date (YYYY-MM-DD)",
+ "Period Length": "Period Length",
+ "Comparison Periods": "Comparison Periods",
+ "Standard Layout": "Standard Layout",
+ "Cash Basis (Payments Only)": "Cash Basis (Payments Only)",
+ "As At Date (YYYY-MM-DD)": "As At Date (YYYY-MM-DD)",
+ "Month Date (YYYY-MM-DD)": "Month Date (YYYY-MM-DD)",
+ "Aged As At (YYYY-MM-DD)": "Aged As At (YYYY-MM-DD)",
+ "Show Invoices From (YYYY-MM-DD)": "Show Invoices From (YYYY-MM-DD)",
+ "Show Invoices To (YYYY-MM-DD)": "Show Invoices To (YYYY-MM-DD)",
+ "Organisation ID": "Organisation ID",
+ "Branding Theme ID": "Branding Theme ID",
+ "Merge Line Items": "Merge Line Items",
+ "Account ID": "Account ID",
+ "Account Code": "Account Code",
+ "Payment Date (YYYY-MM-DD)": "Payment Date (YYYY-MM-DD)",
+ "Currency Rate": "Currency Rate",
+ "Credit Note ID": "Credit Note ID",
+ "Quote Date (YYYY-MM-DD)": "Quote Date (YYYY-MM-DD)",
+ "Expiry Date (YYYY-MM-DD)": "Expiry Date (YYYY-MM-DD)",
+ "Delivery Date (YYYY-MM-DD)": "Delivery Date (YYYY-MM-DD)",
+ "Bank Account Code": "Bank Account Code",
+ "Mark as Reconciled": "Mark as Reconciled",
+ "Record ID": "Record ID",
+ "Include Online": "Include Online",
"Method": "Method",
"Headers": "Headers",
"Query Parameters": "Query Parameters",
"Body Type": "Body Type",
"Body": "Body",
- "Response is Binary ?": "Response is Binary ?",
- "No Error on Failure": "No Error on Failure",
- "Timeout (in seconds)": "Timeout (in seconds)",
+ "Response is Binary": "Response is Binary",
+ "Return Error as Output": "Return Error as Output",
+ "Timeout": "Timeout",
"Follow redirects": "Follow redirects",
"ID of the contact to create invoice for.": "ID of the contact to create invoice for.",
"Contact name, in full.": "Contact name, in full.",
"Email address of the contact.": "Email address of the contact.",
"Select an invoice": "Select an invoice",
"Select a contact": "Select a contact",
- "Invoice line items": "Invoice line items",
+ "One invoice line as key/value pairs, e.g. Description, Quantity, UnitAmount, AccountCode (such as 200 for Sales) and TaxType. Use List Accounts and List Tax Rates to find valid codes.": "One invoice line as key/value pairs, e.g. Description, Quantity, UnitAmount, AccountCode (such as 200 for Sales) and TaxType. Use List Accounts and List Tax Rates to find valid codes.",
"Date the invoice was created. Format example: 2019-03-11": "Date the invoice was created. Format example: 2019-03-11",
"Due date of the invoice. Format example: 2019-03-11": "Due date of the invoice. Format example: 2019-03-11",
"Reference number of the Invoice": "Reference number of the Invoice",
@@ -169,7 +289,8 @@
"Select a credit note to allocate from": "Select a credit note to allocate from",
"The amount of the credit to allocate.": "The amount of the credit to allocate.",
"Date of allocation. Format: YYYY-MM-DD. Optional.": "Date of allocation. Format: YYYY-MM-DD. Optional.",
- "Select a bank account": "Select a bank account",
+ "The bank account the money leaves.": "The bank account the money leaves.",
+ "The bank account the money arrives in.": "The bank account the money arrives in.",
"Amount to transfer. Currencies must match between accounts.": "Amount to transfer. Currencies must match between accounts.",
"YYYY-MM-DD. Defaults to today if not provided.": "YYYY-MM-DD. Defaults to today if not provided.",
"Reference for the transfer.": "Reference for the transfer.",
@@ -182,6 +303,7 @@
"Date the bill was issued (YYYY-MM-DD). Optional.": "Date the bill was issued (YYYY-MM-DD). Optional.",
"Date the bill is due (YYYY-MM-DD). Optional.": "Date the bill is due (YYYY-MM-DD). Optional.",
"Select an authorised invoice (sales or bill) to apply payment to.": "Select an authorised invoice (sales or bill) to apply payment to.",
+ "Select a bank account": "Select a bank account",
"Payment amount (must be <= amount due).": "Payment amount (must be <= amount due).",
"YYYY-MM-DD.": "YYYY-MM-DD.",
"Mark payment as reconciled (optional).": "Mark payment as reconciled (optional).",
@@ -190,7 +312,7 @@
"Select a branding theme": "Select a branding theme",
"YYYY-MM-DD. Optional.": "YYYY-MM-DD. Optional.",
"Select a purchase order to update": "Select a purchase order to update",
- "The Xero resource to attach the file to.": "The Xero resource to attach the file to.",
+ "The Xero resource to attach the file to. Receipt works only on connections created before version 0.8.0.": "The Xero resource to attach the file to. Receipt works only on connections created before version 0.8.0.",
"Select the specific resource to attach the file to.": "Select the specific resource to attach the file to.",
"The file to upload. Max 10MB per Xero limits.": "The file to upload. Max 10MB per Xero limits.",
"Optional file name to use in Xero. Avoid characters: < > : \" / \\ | ? *": "Optional file name to use in Xero. Avoid characters: < > : \" / \\ | ? *",
@@ -217,8 +339,76 @@
"Date the transaction occurred (YYYY-MM-DD). Optional.": "Date the transaction occurred (YYYY-MM-DD). Optional.",
"Reference for the transaction.": "Reference for the transaction.",
"Mark the transaction as reconciled.": "Mark the transaction as reconciled.",
+ "The Xero InvoiceID (a GUID) or the invoice number, for example INV-0042.": "The Xero InvoiceID (a GUID) or the invoice number, for example INV-0042.",
+ "Leave empty to include both sales invoices and bills.": "Leave empty to include both sales invoices and bills.",
+ "Only invoices for this Xero ContactID. Use Find Contact to get it.": "Only invoices for this Xero ContactID. Use Find Contact to get it.",
+ "Matches invoice number and reference (case-insensitive, partial).": "Matches invoice number and reference (case-insensitive, partial).",
+ "Leave on for faster results without line items; use Get Invoice for the full invoice.": "Leave on for faster results without line items; use Get Invoice for the full invoice.",
+ "Page number, starting at 1.": "Page number, starting at 1.",
+ "Invoices per page, 1 to 100.": "Invoices per page, 1 to 100.",
+ "The Xero InvoiceID (a GUID). Use Search Invoices or Get Invoice to find it.": "The Xero InvoiceID (a GUID). Use Search Invoices or Get Invoice to find it.",
+ "Defaults to invoice-<InvoiceID>.pdf.": "Defaults to invoice-<InvoiceID>.pdf.",
+ "The Xero ContactID (a GUID). Use Find Contact to get it.": "The Xero ContactID (a GUID). Use Find Contact to get it.",
+ "The Xero ContactID (a GUID) of the contact to archive.": "The Xero ContactID (a GUID) of the contact to archive.",
+ "Unique code of the item (max 30 characters).": "Unique code of the item (max 30 characters).",
+ "Item name (max 50 characters).": "Item name (max 50 characters).",
+ "Up to 4 decimal places.": "Up to 4 decimal places.",
+ "Revenue account code, e.g. 200. Use List Accounts to find codes.": "Revenue account code, e.g. 200. Use List Accounts to find codes.",
+ "Tax type from List Tax Rates, e.g. OUTPUT.": "Tax type from List Tax Rates, e.g. OUTPUT.",
+ "Expense account code, e.g. 400. Not used for tracked inventory items.": "Expense account code, e.g. 400. Not used for tracked inventory items.",
+ "Tax type from List Tax Rates, e.g. INPUT.": "Tax type from List Tax Rates, e.g. INPUT.",
+ "Cost of goods sold account code; required for tracked inventory items.": "Cost of goods sold account code; required for tracked inventory items.",
+ "Inventory asset account code. Setting it makes the item a tracked inventory item.": "Inventory asset account code. Setting it makes the item a tracked inventory item.",
+ "Only payments on this Xero InvoiceID (a GUID).": "Only payments on this Xero InvoiceID (a GUID).",
+ "Payments per page, 1 to 100.": "Payments per page, 1 to 100.",
+ "The Xero PaymentID (a GUID) to delete.": "The Xero PaymentID (a GUID) to delete.",
+ "The Xero InvoiceID (a GUID) or invoice number.": "The Xero InvoiceID (a GUID) or invoice number.",
+ "Xero AccountID of the bank account (List Accounts).": "Xero AccountID of the bank account (List Accounts).",
+ "Transactions per page, 1 to 100.": "Transactions per page, 1 to 100.",
+ "Description of the journal.": "Description of the journal.",
+ "JSON array of lines, e.g. [{\"LineAmount\":100,\"AccountCode\":\"400\",\"Description\":\"Accrual\"},{\"LineAmount\":-100,\"AccountCode\":\"800\"}]. Positive amounts are debits, negative are credits, and the total must be 0. Allowed keys: LineAmount, AccountCode, AccountID, Description, TaxType, TaxAmount, Tracking.": "JSON array of lines, e.g. [{\"LineAmount\":100,\"AccountCode\":\"400\",\"Description\":\"Accrual\"},{\"LineAmount\":-100,\"AccountCode\":\"800\"}]. Positive amounts are debits, negative are credits, and the total must be 0. Allowed keys: LineAmount, AccountCode, AccountID, Description, TaxType, TaxAmount, Tracking.",
+ "Defaults to today in Xero.": "Defaults to today in Xero.",
+ "Keep only bank accounts and accounts with \"Enable payments to this account\" on.": "Keep only bank accounts and accounts with \"Enable payments to this account\" on.",
+ "Only the rate with this TaxType code, e.g. OUTPUT.": "Only the rate with this TaxType code, e.g. OUTPUT.",
+ "Length of each comparison period.": "Length of each comparison period.",
+ "Number of earlier periods to compare with, 1 to 11.": "Number of earlier periods to compare with, 1 to 11.",
+ "Ignore custom report layouts.": "Ignore custom report layouts.",
+ "Any date in the month to report on.": "Any date in the month to report on.",
+ "Defaults to today.": "Defaults to today.",
+ "Xero tenant ID of the organisation to use, from List Organisations. Leave empty when the connection has only one organisation.": "Xero tenant ID of the organisation to use, from List Organisations. Leave empty when the connection has only one organisation.",
+ "Xero ContactID (a GUID) of the customer or supplier.": "Xero ContactID (a GUID) of the customer or supplier.",
+ "JSON array of line items, e.g. [{\"Description\":\"Consulting\",\"Quantity\":2,\"UnitAmount\":150.5,\"AccountCode\":\"200\",\"TaxType\":\"OUTPUT\"}]. Each line needs a Description or an ItemCode. Allowed keys: Description, Quantity, UnitAmount, LineAmount, AccountCode, ItemCode, TaxType, TaxAmount, DiscountRate, Tracking (array of {\"Name\",\"Option\"}), LineItemID. Amounts keep up to 4 decimal places for UnitAmount and Quantity.": "JSON array of line items, e.g. [{\"Description\":\"Consulting\",\"Quantity\":2,\"UnitAmount\":150.5,\"AccountCode\":\"200\",\"TaxType\":\"OUTPUT\"}]. Each line needs a Description or an ItemCode. Allowed keys: Description, Quantity, UnitAmount, LineAmount, AccountCode, ItemCode, TaxType, TaxAmount, DiscountRate, Tracking (array of {\"Name\",\"Option\"}), LineItemID. Amounts keep up to 4 decimal places for UnitAmount and Quantity.",
+ "Invoice date; Xero uses today when empty.": "Invoice date; Xero uses today when empty.",
+ "Required by Xero before the invoice can be approved.": "Required by Xero before the invoice can be approved.",
+ "Leave empty to let Xero number sales invoices automatically.": "Leave empty to let Xero number sales invoices automatically.",
+ "ISO code such as USD; defaults to the organisation base currency.": "ISO code such as USD; defaults to the organisation base currency.",
+ "Xero InvoiceID (a GUID) of the invoice or bill to update.": "Xero InvoiceID (a GUID) of the invoice or bill to update.",
+ "Move the invoice to this ContactID.": "Move the invoice to this ContactID.",
+ "Keep the existing lines, update lines whose LineItemID is given and append new ones. Off replaces all lines.": "Keep the existing lines, update lines whose LineItemID is given and append new ones. Off replaces all lines.",
+ "Xero InvoiceID (a GUID) of the sales invoice to email.": "Xero InvoiceID (a GUID) of the sales invoice to email.",
+ "Xero InvoiceID (a GUID) of the AUTHORISED invoice or bill.": "Xero InvoiceID (a GUID) of the AUTHORISED invoice or bill.",
+ "AccountID of the bank account. Give this or Account Code.": "AccountID of the bank account. Give this or Account Code.",
+ "Code of the bank account, e.g. 090. Give this or Account ID.": "Code of the bank account, e.g. 090. Give this or Account ID.",
+ "Payment amount in the invoice currency, up to 2 decimal places.": "Payment amount in the invoice currency, up to 2 decimal places.",
+ "Exchange rate for foreign-currency invoices.": "Exchange rate for foreign-currency invoices.",
+ "Xero ContactID (a GUID).": "Xero ContactID (a GUID).",
+ "Xero CreditNoteID (a GUID).": "Xero CreditNoteID (a GUID).",
+ "Xero InvoiceID (a GUID) to apply the credit to.": "Xero InvoiceID (a GUID) to apply the credit to.",
+ "Amount to allocate, up to 2 decimal places.": "Amount to allocate, up to 2 decimal places.",
+ "Xero ContactID (a GUID) of the customer.": "Xero ContactID (a GUID) of the customer.",
+ "Xero ContactID (a GUID) of the supplier.": "Xero ContactID (a GUID) of the supplier.",
+ "AccountID of the bank account. Give this or Bank Account Code.": "AccountID of the bank account. Give this or Bank Account Code.",
+ "Code of the bank account, e.g. 090. Give this or Bank Account ID.": "Code of the bank account, e.g. 090. Give this or Bank Account ID.",
+ "Xero ID (a GUID) of the record, e.g. the InvoiceID.": "Xero ID (a GUID) of the record, e.g. the InvoiceID.",
+ "The file to attach, up to 10 MB.": "The file to attach, up to 10 MB.",
+ "Defaults to the file's own name.": "Defaults to the file's own name.",
+ "Show the attachment on the online invoice (sales invoices and credit notes only).": "Show the attachment on the online invoice (sales invoices and credit notes only).",
"Authorization headers are injected automatically from your connection.": "Authorization headers are injected automatically from your connection.",
+ "Appended to the URL as ?key=value.": "Appended to the URL as ?key=value.",
"Enable for files like PDFs, images, etc.": "Enable for files like PDFs, images, etc.",
+ "On a failed request, output the error instead of failing the step.": "On a failed request, output the error instead of failing the step.",
+ "Seconds to wait for a response. Empty: up to the flow limit (10 min).": "Seconds to wait for a response. Empty: up to the flow limit (10 min).",
+ "Follow 3xx redirects instead of returning them as the response.": "Follow 3xx redirects instead of returning them as the response.",
"Draft": "Draft",
"Submitted": "Submitted",
"Authorised": "Authorised",
@@ -232,7 +422,7 @@
"Bank Transfer": "Bank Transfer",
"Bank Transaction": "Bank Transaction",
"Manual Journal": "Manual Journal",
- "Receipt": "Receipt",
+ "Receipt (connections created before 0.8.0 only)": "Receipt (connections created before 0.8.0 only)",
"Repeating Invoice": "Repeating Invoice",
"Accounts Receivable Credit (ACCRECCREDIT)": "Accounts Receivable Credit (ACCRECCREDIT)",
"Accounts Payable Credit (ACCPAYCREDIT)": "Accounts Payable Credit (ACCPAYCREDIT)",
@@ -242,7 +432,6 @@
"Account Number (exact match)": "Account Number (exact match)",
"Search Term (broad search)": "Search Term (broad search)",
"Invoice Number (exact)": "Invoice Number (exact)",
- "Reference (exact)": "Reference (exact)",
"Search Term (InvoiceNumber/Reference)": "Search Term (InvoiceNumber/Reference)",
"Sales Invoice (ACCREC)": "Sales Invoice (ACCREC)",
"Bill (ACCPAY)": "Bill (ACCPAY)",
@@ -252,16 +441,71 @@
"Purchase Order ID (GUID)": "Purchase Order ID (GUID)",
"Spend Money (SPEND)": "Spend Money (SPEND)",
"Receive Money (RECEIVE)": "Receive Money (RECEIVE)",
+ "Sales invoice (ACCREC)": "Sales invoice (ACCREC)",
+ "DRAFT": "DRAFT",
+ "SUBMITTED": "SUBMITTED",
+ "AUTHORISED": "AUTHORISED",
+ "PAID": "PAID",
+ "VOIDED": "VOIDED",
+ "DELETED": "DELETED",
+ "ACCRECPAYMENT": "ACCRECPAYMENT",
+ "ACCPAYPAYMENT": "ACCPAYPAYMENT",
+ "ARCREDITPAYMENT": "ARCREDITPAYMENT",
+ "APCREDITPAYMENT": "APCREDITPAYMENT",
+ "AROVERPAYMENTPAYMENT": "AROVERPAYMENTPAYMENT",
+ "APOVERPAYMENTPAYMENT": "APOVERPAYMENTPAYMENT",
+ "ARPREPAYMENTPAYMENT": "ARPREPAYMENTPAYMENT",
+ "APPREPAYMENTPAYMENT": "APPREPAYMENTPAYMENT",
+ "RECEIVE": "RECEIVE",
+ "SPEND": "SPEND",
+ "RECEIVE-OVERPAYMENT": "RECEIVE-OVERPAYMENT",
+ "SPEND-OVERPAYMENT": "SPEND-OVERPAYMENT",
+ "RECEIVE-PREPAYMENT": "RECEIVE-PREPAYMENT",
+ "SPEND-PREPAYMENT": "SPEND-PREPAYMENT",
+ "RECEIVE-TRANSFER": "RECEIVE-TRANSFER",
+ "SPEND-TRANSFER": "SPEND-TRANSFER",
+ "Reconciled only": "Reconciled only",
+ "Unreconciled only": "Unreconciled only",
+ "Posted": "Posted",
+ "Tax exclusive": "Tax exclusive",
+ "Tax inclusive": "Tax inclusive",
+ "No tax": "No tax",
+ "BANK": "BANK",
+ "CURRENT": "CURRENT",
+ "CURRLIAB": "CURRLIAB",
+ "DEPRECIATN": "DEPRECIATN",
+ "DIRECTCOSTS": "DIRECTCOSTS",
+ "EQUITY": "EQUITY",
+ "EXPENSE": "EXPENSE",
+ "FIXED": "FIXED",
+ "INVENTORY": "INVENTORY",
+ "LIABILITY": "LIABILITY",
+ "NONCURRENT": "NONCURRENT",
+ "OTHERINCOME": "OTHERINCOME",
+ "OVERHEADS": "OVERHEADS",
+ "PREPAYMENT": "PREPAYMENT",
+ "REVENUE": "REVENUE",
+ "SALES": "SALES",
+ "TERMLIAB": "TERMLIAB",
+ "ASSET": "ASSET",
+ "Active": "Active",
+ "Archived": "Archived",
+ "Month": "Month",
+ "Quarter": "Quarter",
+ "Year": "Year",
+ "Submitted for approval": "Submitted for approval",
+ "Customer credit note (ACCRECCREDIT)": "Customer credit note (ACCRECCREDIT)",
+ "Supplier credit note (ACCPAYCREDIT)": "Supplier credit note (ACCPAYCREDIT)",
+ "Sent": "Sent",
+ "Spend money (SPEND)": "Spend money (SPEND)",
+ "Receive money (RECEIVE)": "Receive money (RECEIVE)",
+ "Invoice or bill": "Invoice or bill",
"GET": "GET",
"POST": "POST",
"PATCH": "PATCH",
"PUT": "PUT",
"DELETE": "DELETE",
"HEAD": "HEAD",
- "None": "None",
- "JSON": "JSON",
- "Form Data": "Form Data",
- "Raw": "Raw",
"New Contact": "New Contact",
"New or Updated Contact": "New or Updated Contact",
"New Sales Invoice": "New Sales Invoice",
@@ -279,21 +523,20 @@
"Fires when a contact is created or updated (via Xero webhooks).": "Fires when a contact is created or updated (via Xero webhooks).",
"Fires when a new sales invoice (Accounts Receivable) is created.": "Fires when a new sales invoice (Accounts Receivable) is created.",
"Fires when an existing sales invoice (Accounts Receivable) is updated.": "Fires when an existing sales invoice (Accounts Receivable) is updated.",
- "Fires when a new bank transaction is created.": "Fires when a new bank transaction is created.",
- "Fires when a payment is received.": "Fires when a payment is received.",
- "Fires when a new purchase order is created or enters a specific status for the first time.": "Fires when a new purchase order is created or enters a specific status for the first time.",
+ "Fires the first time a bank transaction is created or changed after the trigger is turned on.": "Fires the first time a bank transaction is created or changed after the trigger is turned on.",
+ "Fires the first time a payment is recorded or changed after the trigger is turned on.": "Fires the first time a payment is recorded or changed after the trigger is turned on.",
+ "Fires the first time a purchase order is created or changed after the trigger is turned on, or enters a chosen status for the first time.": "Fires the first time a purchase order is created or changed after the trigger is turned on, or enters a chosen status for the first time.",
"Fires when a payment is reconciled for the first time.": "Fires when a payment is reconciled for the first time.",
"Fires when a quote is created or updated.": "Fires when a quote is created or updated.",
- "Fires when a new bill (Accounts Payable) is added.": "Fires when a new bill (Accounts Payable) is added.",
- "Fires when a new credit note is created.": "Fires when a new credit note is created.",
+ "Fires the first time a bill (Accounts Payable) is created or changed after the trigger is turned on.": "Fires the first time a bill (Accounts Payable) is created or changed after the trigger is turned on.",
+ "Fires the first time a credit note is created or changed after the trigger is turned on.": "Fires the first time a credit note is created or changed after the trigger is turned on.",
"Fires when a new project is created.": "Fires when a new project is created.",
- "Fires when a new quote is created.": "Fires when a new quote is created.",
+ "Fires the first time a quote is created or changed after the trigger is turned on.": "Fires the first time a quote is created or changed after the trigger is turned on.",
"Markdown": "Markdown",
"Webhook Key": "Webhook Key",
"Fetch Full Contact": "Fetch Full Contact",
"Fetch Full Invoice": "Fetch Full Invoice",
"Types": "Types",
- "Bank Account Code": "Bank Account Code",
"Payment Types": "Payment Types",
"Filter by Status (optional)": "Filter by Status (optional)",
"First-time Status (optional)": "First-time Status (optional)",
@@ -304,33 +547,20 @@
"Summary Only (lighter, faster)": "Summary Only (lighter, faster)",
"States (optional)": "States (optional)",
"Page Size (1-500)": "Page Size (1-500)",
- "\nTo use this trigger, manually configure a Xero webhook for your app:\n\n1. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n2. Select the Contact category.\n3. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n4. Click Save, then click Validate \"Intent to receive\".\n5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.\n6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.\n\nNotes:\n- Keep this trigger enabled so the URL remains": "\nTo use this trigger, manually configure a Xero webhook for your app:\n\n1. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n2. Select the Contact category.\n3. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n4. Click Save, then click Validate \"Intent to receive\".\n5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.\n6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.\n\nNotes:\n- Keep this trigger enabled so the URL remains active.\n- We verify Xero's x-xero-signature header using your Webhook Key.\n ",
+ "\nThis trigger needs a webhook on **your own Xero app** (the app whose Client ID and Secret this connection uses). Xero allows one delivery URL per app, so one app can feed only one flow, and connections made through a shared app (such as Activepieces Cloud's built-in Xero app) cannot set up webhooks.\n\n1. Publish this flow first, so the URL below is live.\n2. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n3. Select the Contact category.\n4. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n5. Copy": "\nThis trigger needs a webhook on **your own Xero app** (the app whose Client ID and Secret this connection uses). Xero allows one delivery URL per app, so one app can feed only one flow, and connections made through a shared app (such as Activepieces Cloud's built-in Xero app) cannot set up webhooks.\n\n1. Publish this flow first, so the URL below is live.\n2. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n3. Select the Contact category.\n4. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n5. Copy the Webhook Key from the Webhooks page into the Webhook Key field below and publish again.\n6. Click Save, then \"Send Intent to receive\". This trigger answers Xero's check: 200 for a correctly signed request and 401 otherwise.\n\nNotes:\n- Only events for the selected organisation are used.\n- Every delivery's x-xero-signature header is checked with your Webhook Key; repeated deliveries of the same event are ignored.\n ",
"From Xero Developer portal > Your App > Webhooks. Used to verify x-xero-signature.": "From Xero Developer portal > Your App > Webhooks. Used to verify x-xero-signature.",
- "If enabled, fetches the full contact from Xero using the Resource URL.": "If enabled, fetches the full contact from Xero using the Resource URL.",
- "\nTo use this trigger, manually configure a Xero webhook for your app:\n\n1. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n2. Select the Invoice category.\n3. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n4. Click Save, then click Validate \"Intent to receive\".\n5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.\n6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.\n\nNotes:\n- Keep this trigger enabled so the URL remains": "\nTo use this trigger, manually configure a Xero webhook for your app:\n\n1. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n2. Select the Invoice category.\n3. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n4. Click Save, then click Validate \"Intent to receive\".\n5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.\n6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.\n\nNotes:\n- Keep this trigger enabled so the URL remains active.\n- We verify Xero's x-xero-signature header using your Webhook Key.\n ",
- "Fetch the full invoice and ensure Type is ACCREC (recommended).": "Fetch the full invoice and ensure Type is ACCREC (recommended).",
+ "If enabled, fetches the full contact from Xero. If disabled, the output is the raw webhook event (resourceId, eventType, eventDateUtc).": "If enabled, fetches the full contact from Xero. If disabled, the output is the raw webhook event (resourceId, eventType, eventDateUtc).",
+ "\nThis trigger needs a webhook on **your own Xero app** (the app whose Client ID and Secret this connection uses). Xero allows one delivery URL per app, so one app can feed only one flow, and connections made through a shared app (such as Activepieces Cloud's built-in Xero app) cannot set up webhooks.\n\n1. Publish this flow first, so the URL below is live.\n2. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n3. Select the Invoice category.\n4. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n5. Copy": "\nThis trigger needs a webhook on **your own Xero app** (the app whose Client ID and Secret this connection uses). Xero allows one delivery URL per app, so one app can feed only one flow, and connections made through a shared app (such as Activepieces Cloud's built-in Xero app) cannot set up webhooks.\n\n1. Publish this flow first, so the URL below is live.\n2. Go to Xero Developer > My Apps > [Your App] > Webhooks.\n3. Select the Invoice category.\n4. Set the Delivery URL to:\n\n\n```text\n{{webhookUrl}}\n```\n5. Copy the Webhook Key from the Webhooks page into the Webhook Key field below and publish again.\n6. Click Save, then \"Send Intent to receive\". This trigger answers Xero's check: 200 for a correctly signed request and 401 otherwise.\n\nNotes:\n- Only events for the selected organisation are used.\n- Every delivery's x-xero-signature header is checked with your Webhook Key; repeated deliveries of the same event are ignored.\n ",
+ "Fetch the full invoice and ensure Type is ACCREC (recommended). If disabled, the output is the raw webhook event and bills are not filtered out.": "Fetch the full invoice and ensure Type is ACCREC (recommended). If disabled, the output is the raw webhook event and bills are not filtered out.",
"Also fire when a purchase order enters this status for the first time (since enabling).": "Also fire when a purchase order enters this status for the first time (since enabling).",
- "RECEIVE": "RECEIVE",
- "SPEND": "SPEND",
- "RECEIVE-OVERPAYMENT": "RECEIVE-OVERPAYMENT",
- "SPEND-OVERPAYMENT": "SPEND-OVERPAYMENT",
- "RECEIVE-PREPAYMENT": "RECEIVE-PREPAYMENT",
- "SPEND-PREPAYMENT": "SPEND-PREPAYMENT",
- "RECEIVE-TRANSFER": "RECEIVE-TRANSFER",
- "SPEND-TRANSFER": "SPEND-TRANSFER",
- "AUTHORISED": "AUTHORISED",
- "DELETED": "DELETED",
+ "No longer used: the trigger reads projects 500 at a time.": "No longer used: the trigger reads projects 500 at a time.",
"ACCRECPAYMENT (Received on Sales Invoice)": "ACCRECPAYMENT (Received on Sales Invoice)",
"ACCPAYPAYMENT (Paid on Bill)": "ACCPAYPAYMENT (Paid on Bill)",
- "DRAFT": "DRAFT",
- "SUBMITTED": "SUBMITTED",
"BILLED": "BILLED",
"SENT": "SENT",
"ACCEPTED": "ACCEPTED",
"DECLINED": "DECLINED",
"INVOICED": "INVOICED",
- "PAID": "PAID",
- "VOIDED": "VOIDED",
"ACCRECCREDIT (Sales Credit)": "ACCRECCREDIT (Sales Credit)",
"ACCPAYCREDIT (Supplier Credit)": "ACCPAYCREDIT (Supplier Credit)",
"INPROGRESS": "INPROGRESS",
diff --git a/packages/pieces/community/xero/src/index.ts b/packages/pieces/community/xero/src/index.ts
index d73791ad970..81c85d452be 100644
--- a/packages/pieces/community/xero/src/index.ts
+++ b/packages/pieces/community/xero/src/index.ts
@@ -29,6 +29,39 @@ import { xeroFindPurchaseOrder } from './lib/actions/find-purchase-order';
import { xeroGetInvoiceHistory } from './lib/actions/get-invoice-history';
import { xeroCreateBankTransaction } from './lib/actions/create-bank-transaction';
import { xeroFindOrCreateContact } from './lib/actions/find-or-create-contact';
+import { xeroListOrganisations } from './lib/actions/list-organisations';
+import { xeroGetOrganisation } from './lib/actions/get-organisation';
+import { xeroGetInvoice } from './lib/actions/get-invoice';
+import { xeroSearchInvoices } from './lib/actions/search-invoices';
+import { xeroDownloadInvoicePdf } from './lib/actions/download-invoice-pdf';
+import { xeroGetContact } from './lib/actions/get-contact';
+import { xeroArchiveContact } from './lib/actions/archive-contact';
+import { xeroUpsertItem } from './lib/actions/upsert-item';
+import { xeroSearchPayments } from './lib/actions/search-payments';
+import { xeroDeletePayment } from './lib/actions/delete-payment';
+import { xeroVoidInvoice } from './lib/actions/void-invoice';
+import { xeroSearchBankTransactions } from './lib/actions/search-bank-transactions';
+import { xeroCreateManualJournal } from './lib/actions/create-manual-journal';
+import { xeroListAccounts } from './lib/actions/list-accounts';
+import { xeroListTaxRates } from './lib/actions/list-tax-rates';
+import { xeroListTrackingCategories } from './lib/actions/list-tracking-categories';
+import { xeroGetProfitAndLoss } from './lib/actions/get-profit-and-loss';
+import { xeroGetBalanceSheet } from './lib/actions/get-balance-sheet';
+import { xeroGetBankSummary } from './lib/actions/get-bank-summary';
+import { xeroGetTrialBalance } from './lib/actions/get-trial-balance';
+import { xeroGetExecutiveSummary } from './lib/actions/get-executive-summary';
+import { xeroGetAgedReceivables } from './lib/actions/get-aged-receivables';
+import { xeroGetAgedPayables } from './lib/actions/get-aged-payables';
+import { xeroCreateInvoiceAi } from './lib/actions/ai/create-invoice';
+import { xeroUpdateInvoiceAi } from './lib/actions/ai/update-invoice';
+import { xeroEmailInvoiceAi } from './lib/actions/ai/email-invoice';
+import { xeroCreatePaymentAi } from './lib/actions/ai/create-payment';
+import { xeroCreateCreditNoteAi } from './lib/actions/ai/create-credit-note';
+import { xeroAllocateCreditNoteAi } from './lib/actions/ai/allocate-credit-note';
+import { xeroCreateQuoteAi } from './lib/actions/ai/create-quote';
+import { xeroCreatePurchaseOrderAi } from './lib/actions/ai/create-purchase-order';
+import { xeroCreateBankTransactionAi } from './lib/actions/ai/create-bank-transaction';
+import { xeroUploadAttachmentAi } from './lib/actions/ai/upload-attachment';
import { xeroNewContact } from './lib/triggers/new-contact';
import { xeroNewOrUpdatedContact } from './lib/triggers/new-or-updated-contact';
import { xeroNewSalesInvoice } from './lib/triggers/new-sales-invoice';
@@ -43,6 +76,29 @@ import { xeroNewCreditNote } from './lib/triggers/new-credit-note';
import { xeroNewProject } from './lib/triggers/new-project';
import { xeroNewQuote } from './lib/triggers/new-quote';
+export const xeroScopes = [
+ 'openid',
+ 'profile',
+ 'email',
+ 'offline_access',
+ 'accounting.contacts',
+ 'accounting.invoices',
+ 'accounting.payments',
+ 'accounting.banktransactions',
+ 'accounting.manualjournals',
+ 'accounting.reports.aged.read',
+ 'accounting.reports.balancesheet.read',
+ 'accounting.reports.banksummary.read',
+ 'accounting.reports.executivesummary.read',
+ 'accounting.reports.profitandloss.read',
+ 'accounting.reports.taxreports.read',
+ 'accounting.reports.trialbalance.read',
+ 'accounting.budgets.read',
+ 'accounting.attachments',
+ 'accounting.settings',
+ 'projects',
+];
+
export const xeroAuth = PieceAuth.OAuth2({
description: `
1. Log in to Xero.
@@ -51,31 +107,20 @@ export const xeroAuth = PieceAuth.OAuth2({
4. On the left, click on \`Configuration\`.
5. Enter your \`redirect url\`.
6. Copy the \`Client Id\` and \`Client Secret\`.
+
+ The connection requests Xero's granular scopes (for example \`accounting.invoices\` and \`accounting.payments\` instead of \`accounting.transactions\`), which apps created on or after 2 March 2026 require. Receipts, Expense Claims and Journals are not available on connections created with this version.
`,
authUrl: 'https://login.xero.com/identity/connect/authorize',
tokenUrl: 'https://identity.xero.com/connect/token',
required: true,
- scope: [
- 'openid',
- 'profile',
- 'email',
- 'offline_access',
- 'accounting.contacts',
- 'accounting.transactions',
- 'accounting.reports.read',
- 'accounting.journals.read',
- 'accounting.budgets.read',
- 'accounting.attachments',
- 'accounting.settings',
- 'projects',
- ],
+ scope: xeroScopes,
});
export const xero = createPiece({
displayName: 'Xero',
description: 'Beautiful accounting software',
- minimumSupportedRelease: '0.30.0',
+ minimumSupportedRelease: '0.88.2',
logoUrl: 'https://cdn.activepieces.com/pieces/xero.png',
authors: ['kanarelo', 'kishanprmr', 'MoShizzle', 'khaledmashaly', 'abuaboud', 'thejaachi'],
categories: [PieceCategory.ACCOUNTING],
@@ -105,6 +150,39 @@ export const xero = createPiece({
xeroGetInvoiceHistory,
xeroCreateBankTransaction,
xeroFindOrCreateContact,
+ xeroListOrganisations,
+ xeroGetOrganisation,
+ xeroGetInvoice,
+ xeroSearchInvoices,
+ xeroDownloadInvoicePdf,
+ xeroGetContact,
+ xeroArchiveContact,
+ xeroUpsertItem,
+ xeroSearchPayments,
+ xeroDeletePayment,
+ xeroVoidInvoice,
+ xeroSearchBankTransactions,
+ xeroCreateManualJournal,
+ xeroListAccounts,
+ xeroListTaxRates,
+ xeroListTrackingCategories,
+ xeroGetProfitAndLoss,
+ xeroGetBalanceSheet,
+ xeroGetBankSummary,
+ xeroGetTrialBalance,
+ xeroGetExecutiveSummary,
+ xeroGetAgedReceivables,
+ xeroGetAgedPayables,
+ xeroCreateInvoiceAi,
+ xeroUpdateInvoiceAi,
+ xeroEmailInvoiceAi,
+ xeroCreatePaymentAi,
+ xeroCreateCreditNoteAi,
+ xeroAllocateCreditNoteAi,
+ xeroCreateQuoteAi,
+ xeroCreatePurchaseOrderAi,
+ xeroCreateBankTransactionAi,
+ xeroUploadAttachmentAi,
createCustomApiCallAction({
baseUrl: () => 'https://api.xero.com/api.xro/2.0',
auth: xeroAuth,
diff --git a/packages/pieces/community/xero/src/lib/actions/add-items-to-sales-invoice.ts b/packages/pieces/community/xero/src/lib/actions/add-items-to-sales-invoice.ts
index fa742ab5831..2623336eb5e 100644
--- a/packages/pieces/community/xero/src/lib/actions/add-items-to-sales-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/add-items-to-sales-invoice.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroAddItemsToSalesInvoice = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroAddItemsToSalesInvoice = createAction({
classification: 'WRITE',
displayName: 'Add Items to Existing Sales Invoice',
description: 'Adds line items to an existing sales invoice (ACCREC).',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Append new line items to an existing ACCREC sales invoice, preserving its current lines (the action fetches the invoice and merges). Pick this to add charges to an invoice without touching existing lines; to edit or replace existing lines use Update Sales Invoice instead. Not idempotent: re-running appends the same items again. AUTHORISED invoices require the allow-authorised flag.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.invoiceEnvelope,
props: {
tenant_id: props.tenant_id,
invoice_id: props.invoice_id(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/allocate-credit-note.ts b/packages/pieces/community/xero/src/lib/actions/ai/allocate-credit-note.ts
new file mode 100644
index 00000000000..f8833ae47c3
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/allocate-credit-note.ts
@@ -0,0 +1,45 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroAllocateCreditNoteAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_allocate_credit_note_ai',
+ classification: 'WRITE',
+ displayName: 'Allocate Credit Note to Invoice',
+ description: 'Applies part or all of a credit note to an invoice or bill.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Applies an amount from an AUTHORISED credit note (CreditNoteID) to an AUTHORISED invoice or bill of the same contact (InvoiceID), reducing what is due. The amount cannot exceed the remaining credit or the amount due. Not idempotent: each call allocates again, and allocations cannot be removed through the API.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.allocation,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ credit_note_id: aiProps.id({ displayName: 'Credit Note ID', description: 'Xero CreditNoteID (a GUID).' }),
+ invoice_id: aiProps.id({ displayName: 'Invoice ID', description: 'Xero InvoiceID (a GUID) to apply the credit to.' }),
+ amount: Property.Number({ displayName: 'Amount', description: 'Amount to allocate, up to 2 decimal places.', required: true }),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', description: 'Defaults to today in Xero.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const creditNoteId = xeroInput.requiredText({ value: values.credit_note_id, field: 'Credit Note ID' });
+ const invoiceId = xeroInput.requiredText({ value: values.invoice_id, field: 'Invoice ID' });
+ const amount = xeroInput.parseDecimal({ value: values.amount, field: 'Amount', maxDecimals: 2, positive: true });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/CreditNotes/${encodeURIComponent(creditNoteId)}/Allocations`,
+ body: { Allocations: [{ Invoice: { InvoiceID: invoiceId }, Amount: amount, ...(date ? { Date: date } : {}) }] },
+ operation: 'allocate credit note',
+ });
+ return xeroApi.firstRecord({ body, key: 'Allocations', operation: 'allocate credit note' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-bank-transaction.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-bank-transaction.ts
new file mode 100644
index 00000000000..22831ec80e7
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-bank-transaction.ts
@@ -0,0 +1,79 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreateBankTransactionAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_bank_transaction_ai',
+ classification: 'WRITE',
+ displayName: 'Create Bank Transaction',
+ description: 'Records a spend money or receive money transaction on a bank account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Records a spend money (SPEND) or receive money (RECEIVE) transaction for a ContactID on a bank account given by AccountID or account code, with JSON line items; use it for money that is not paying an invoice (use Record Payment for invoices). Not idempotent: each call records another transaction.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.bankTransaction,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ options: { options: [{ label: 'Spend money (SPEND)', value: 'SPEND' }, { label: 'Receive money (RECEIVE)', value: 'RECEIVE' }] },
+ }),
+ contact_id: aiProps.id({ displayName: 'Contact ID', description: 'Xero ContactID (a GUID).' }),
+ bank_account_id: Property.ShortText({ displayName: 'Bank Account ID', description: 'AccountID of the bank account. Give this or Bank Account Code.', required: false }),
+ bank_account_code: Property.ShortText({ displayName: 'Bank Account Code', description: 'Code of the bank account, e.g. 090. Give this or Bank Account ID.', required: false }),
+ line_items: aiProps.lineItems(),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', required: false }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ is_reconciled: Property.Checkbox({ displayName: 'Mark as Reconciled', required: false, defaultValue: false }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: { options: [{ label: 'Tax exclusive', value: 'Exclusive' }, { label: 'Tax inclusive', value: 'Inclusive' }, { label: 'No tax', value: 'NoTax' }] },
+ }),
+ currency_code: Property.ShortText({ displayName: 'Currency Code', description: 'ISO code such as USD; defaults to the organisation base currency.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const contactId = xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' });
+ const bankAccountId = xeroInput.trimmedOrUndefined({ value: values.bank_account_id });
+ const bankAccountCode = xeroInput.trimmedOrUndefined({ value: values.bank_account_code });
+ if ((bankAccountId === undefined) === (bankAccountCode === undefined)) {
+ throw new Error('Give exactly one of Bank Account ID or Bank Account Code.');
+ }
+ const lineItems = aiInput.parseLineItems({ value: values.line_items });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/BankTransactions`,
+ queryParams: { unitdp: '4' },
+ body: {
+ BankTransactions: [
+ {
+ Type: values.type,
+ Contact: { ContactID: contactId },
+ BankAccount: bankAccountId ? { AccountID: bankAccountId } : { Code: bankAccountCode },
+ LineItems: lineItems,
+ ...(date ? { Date: date } : {}),
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(values.is_reconciled ? { IsReconciled: true } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(text(values.currency_code) ? { CurrencyCode: text(values.currency_code) } : {}),
+ },
+ ],
+ },
+ operation: 'create bank transaction',
+ });
+ return xeroApi.firstRecord({ body, key: 'BankTransactions', operation: 'create bank transaction' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-credit-note.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-credit-note.ts
new file mode 100644
index 00000000000..967cd12fcb9
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-credit-note.ts
@@ -0,0 +1,78 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreateCreditNoteAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_credit_note_ai',
+ classification: 'WRITE',
+ displayName: 'Create Credit Note',
+ description: 'Creates a customer or supplier credit note for a contact ID with line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a credit note for an existing ContactID: ACCRECCREDIT for a customer (reduces what they owe) or ACCPAYCREDIT for a supplier, with JSON line items; saved as DRAFT unless Status is SUBMITTED or AUTHORISED. Use Allocate Credit Note to Invoice afterwards to apply it. Not idempotent: each call creates another credit note.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.creditNote,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ options: { options: [{ label: 'Customer credit note (ACCRECCREDIT)', value: 'ACCRECCREDIT' }, { label: 'Supplier credit note (ACCPAYCREDIT)', value: 'ACCPAYCREDIT' }] },
+ }),
+ contact_id: aiProps.id({ displayName: 'Contact ID', description: 'Xero ContactID (a GUID).' }),
+ line_items: aiProps.lineItems(),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', required: false }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ credit_note_number: Property.ShortText({ displayName: 'Credit Note Number', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'DRAFT',
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Submitted for approval', value: 'SUBMITTED' }, { label: 'Authorised', value: 'AUTHORISED' }] },
+ }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: { options: [{ label: 'Tax exclusive', value: 'Exclusive' }, { label: 'Tax inclusive', value: 'Inclusive' }, { label: 'No tax', value: 'NoTax' }] },
+ }),
+ currency_code: Property.ShortText({ displayName: 'Currency Code', description: 'ISO code such as USD; defaults to the organisation base currency.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const contactId = xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' });
+ const lineItems = aiInput.parseLineItems({ value: values.line_items });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/CreditNotes`,
+ queryParams: { unitdp: '4' },
+ body: {
+ CreditNotes: [
+ {
+ Type: values.type,
+ Contact: { ContactID: contactId },
+ LineItems: lineItems,
+ Status: values.status ?? 'DRAFT',
+ ...(date ? { Date: date } : {}),
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(text(values.credit_note_number) ? { CreditNoteNumber: text(values.credit_note_number) } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(text(values.currency_code) ? { CurrencyCode: text(values.currency_code) } : {}),
+ },
+ ],
+ },
+ operation: 'create credit note',
+ });
+ return xeroApi.firstRecord({ body, key: 'CreditNotes', operation: 'create credit note' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-invoice.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-invoice.ts
new file mode 100644
index 00000000000..900078effc7
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-invoice.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreateInvoiceAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_invoice_ai',
+ classification: 'WRITE',
+ displayName: 'Create Invoice or Bill',
+ description: 'Creates a sales invoice or a supplier bill for a contact ID with line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates one sales invoice (Type ACCREC) or supplier bill (Type ACCPAY) for an existing ContactID with JSON line items, saved as DRAFT unless Status says SUBMITTED or AUTHORISED. Resolve the contact with Find Contact and account codes with List Accounts first; use Update Invoice to change an existing one. Not idempotent: each call creates another invoice, so pass a unique Reference and check Search Invoices before retrying.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.invoice,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: true,
+ options: { options: [{ label: 'Sales invoice (ACCREC)', value: 'ACCREC' }, { label: 'Bill (ACCPAY)', value: 'ACCPAY' }] },
+ }),
+ contact_id: aiProps.id({ displayName: 'Contact ID', description: 'Xero ContactID (a GUID) of the customer or supplier.' }),
+ line_items: aiProps.lineItems(),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', description: 'Invoice date; Xero uses today when empty.', required: false }),
+ due_date: Property.ShortText({ displayName: 'Due Date (YYYY-MM-DD)', description: 'Required by Xero before the invoice can be approved.', required: false }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ invoice_number: Property.ShortText({ displayName: 'Invoice Number', description: 'Leave empty to let Xero number sales invoices automatically.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'DRAFT',
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Submitted for approval', value: 'SUBMITTED' }, { label: 'Authorised', value: 'AUTHORISED' }] },
+ }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: { options: [{ label: 'Tax exclusive', value: 'Exclusive' }, { label: 'Tax inclusive', value: 'Inclusive' }, { label: 'No tax', value: 'NoTax' }] },
+ }),
+ currency_code: Property.ShortText({ displayName: 'Currency Code', description: 'ISO code such as USD; defaults to the organisation base currency.', required: false }),
+ branding_theme_id: Property.ShortText({ displayName: 'Branding Theme ID', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const contactId = xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' });
+ const lineItems = aiInput.parseLineItems({ value: values.line_items });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const dueDate = xeroInput.parseDateInput({ value: values.due_date, field: 'Due Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/Invoices`,
+ queryParams: { unitdp: '4' },
+ body: {
+ Invoices: [
+ {
+ Type: values.type,
+ Contact: { ContactID: contactId },
+ LineItems: lineItems,
+ Status: values.status ?? 'DRAFT',
+ ...(date ? { Date: date } : {}),
+ ...(dueDate ? { DueDate: dueDate } : {}),
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(text(values.invoice_number) ? { InvoiceNumber: text(values.invoice_number) } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(text(values.currency_code) ? { CurrencyCode: text(values.currency_code) } : {}),
+ ...(text(values.branding_theme_id) ? { BrandingThemeID: text(values.branding_theme_id) } : {}),
+ },
+ ],
+ },
+ operation: 'create invoice',
+ });
+ return xeroApi.firstRecord({ body, key: 'Invoices', operation: 'create invoice' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-payment.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-payment.ts
new file mode 100644
index 00000000000..34aa8dda951
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-payment.ts
@@ -0,0 +1,66 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreatePaymentAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_payment_ai',
+ classification: 'WRITE',
+ displayName: 'Record Payment',
+ description: 'Records a payment against an approved invoice or bill from a bank account.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Records a payment of an amount against an AUTHORISED invoice or bill by InvoiceID, paid into or out of a bank account given by AccountID or account code; the amount must not exceed the amount due. Use List Accounts (Only Accounts That Accept Payments) to find the account. Not idempotent: a re-run pays twice; Delete Payment reverses it.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.payment,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ invoice_id: aiProps.id({ displayName: 'Invoice ID', description: 'Xero InvoiceID (a GUID) of the AUTHORISED invoice or bill.' }),
+ account_id: Property.ShortText({ displayName: 'Account ID', description: 'AccountID of the bank account. Give this or Account Code.', required: false }),
+ account_code: Property.ShortText({ displayName: 'Account Code', description: 'Code of the bank account, e.g. 090. Give this or Account ID.', required: false }),
+ amount: Property.Number({ displayName: 'Amount', description: 'Payment amount in the invoice currency, up to 2 decimal places.', required: true }),
+ date: Property.ShortText({ displayName: 'Payment Date (YYYY-MM-DD)', required: true }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ currency_rate: Property.Number({ displayName: 'Currency Rate', description: 'Exchange rate for foreign-currency invoices.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const invoiceId = xeroInput.requiredText({ value: values.invoice_id, field: 'Invoice ID' });
+ const accountId = xeroInput.trimmedOrUndefined({ value: values.account_id });
+ const accountCode = xeroInput.trimmedOrUndefined({ value: values.account_code });
+ if ((accountId === undefined) === (accountCode === undefined)) {
+ throw new Error('Give exactly one of Account ID or Account Code.');
+ }
+ const amount = xeroInput.parseDecimal({ value: values.amount, field: 'Amount', maxDecimals: 2, positive: true });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Payment Date' });
+ if (!date) throw new Error('Payment Date is required.');
+ const currencyRate = xeroInput.optionalDecimal({ value: values.currency_rate, field: 'Currency Rate', maxDecimals: 10, positive: true });
+ const reference = xeroInput.trimmedOrUndefined({ value: values.reference });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/Payments`,
+ body: {
+ Payments: [
+ {
+ Invoice: { InvoiceID: invoiceId },
+ Account: accountId ? { AccountID: accountId } : { Code: accountCode },
+ Amount: amount,
+ Date: date,
+ ...(reference ? { Reference: reference } : {}),
+ ...(currencyRate !== undefined ? { CurrencyRate: currencyRate } : {}),
+ },
+ ],
+ },
+ operation: 'record payment',
+ });
+ return xeroApi.firstRecord({ body, key: 'Payments', operation: 'record payment' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-purchase-order.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-purchase-order.ts
new file mode 100644
index 00000000000..a8531da6fd1
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-purchase-order.ts
@@ -0,0 +1,83 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreatePurchaseOrderAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_purchase_order_ai',
+ classification: 'WRITE',
+ displayName: 'Create Purchase Order',
+ description: 'Creates a purchase order to a supplier contact ID with line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a purchase order to an existing supplier ContactID with JSON line items and optional delivery details; saved as DRAFT unless Status is SUBMITTED or AUTHORISED. Use Update Purchase Order to change it later. Not idempotent: each call creates another purchase order.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.purchaseOrder,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ contact_id: aiProps.id({ displayName: 'Contact ID', description: 'Xero ContactID (a GUID) of the supplier.' }),
+ line_items: aiProps.lineItems(),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', required: false }),
+ delivery_date: Property.ShortText({ displayName: 'Delivery Date (YYYY-MM-DD)', required: false }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ purchase_order_number: Property.ShortText({ displayName: 'Purchase Order Number', required: false }),
+ delivery_address: Property.LongText({ displayName: 'Delivery Address', required: false }),
+ attention_to: Property.ShortText({ displayName: 'Attention To', required: false }),
+ telephone: Property.ShortText({ displayName: 'Telephone', required: false }),
+ delivery_instructions: Property.LongText({ displayName: 'Delivery Instructions', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'DRAFT',
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Submitted for approval', value: 'SUBMITTED' }, { label: 'Authorised', value: 'AUTHORISED' }] },
+ }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: { options: [{ label: 'Tax exclusive', value: 'Exclusive' }, { label: 'Tax inclusive', value: 'Inclusive' }, { label: 'No tax', value: 'NoTax' }] },
+ }),
+ currency_code: Property.ShortText({ displayName: 'Currency Code', description: 'ISO code such as USD; defaults to the organisation base currency.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const contactId = xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' });
+ const lineItems = aiInput.parseLineItems({ value: values.line_items });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const deliveryDate = xeroInput.parseDateInput({ value: values.delivery_date, field: 'Delivery Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/PurchaseOrders`,
+ queryParams: { unitdp: '4' },
+ body: {
+ PurchaseOrders: [
+ {
+ Contact: { ContactID: contactId },
+ LineItems: lineItems,
+ Status: values.status ?? 'DRAFT',
+ ...(date ? { Date: date } : {}),
+ ...(deliveryDate ? { DeliveryDate: deliveryDate } : {}),
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(text(values.purchase_order_number) ? { PurchaseOrderNumber: text(values.purchase_order_number) } : {}),
+ ...(text(values.delivery_address) ? { DeliveryAddress: text(values.delivery_address) } : {}),
+ ...(text(values.attention_to) ? { AttentionTo: text(values.attention_to) } : {}),
+ ...(text(values.telephone) ? { Telephone: text(values.telephone) } : {}),
+ ...(text(values.delivery_instructions) ? { DeliveryInstructions: text(values.delivery_instructions) } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(text(values.currency_code) ? { CurrencyCode: text(values.currency_code) } : {}),
+ },
+ ],
+ },
+ operation: 'create purchase order',
+ });
+ return xeroApi.firstRecord({ body, key: 'PurchaseOrders', operation: 'create purchase order' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/create-quote.ts b/packages/pieces/community/xero/src/lib/actions/ai/create-quote.ts
new file mode 100644
index 00000000000..b40d118dd30
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/create-quote.ts
@@ -0,0 +1,82 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroCreateQuoteAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_quote_ai',
+ classification: 'WRITE',
+ displayName: 'Create Quote',
+ description: 'Creates a quote for a contact ID with line items.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Creates a sales quote for an existing customer ContactID with a quote date and JSON line items, plus optional title, summary, terms and expiry date; saved as DRAFT unless Status is SENT. Not idempotent: each call creates another quote, so check before retrying.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.quote,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ contact_id: aiProps.id({ displayName: 'Contact ID', description: 'Xero ContactID (a GUID) of the customer.' }),
+ date: Property.ShortText({ displayName: 'Quote Date (YYYY-MM-DD)', required: true }),
+ line_items: aiProps.lineItems(),
+ expiry_date: Property.ShortText({ displayName: 'Expiry Date (YYYY-MM-DD)', required: false }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ quote_number: Property.ShortText({ displayName: 'Quote Number', required: false }),
+ title: Property.ShortText({ displayName: 'Title', required: false }),
+ summary: Property.LongText({ displayName: 'Summary', required: false }),
+ terms: Property.LongText({ displayName: 'Terms', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'DRAFT',
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Sent', value: 'SENT' }] },
+ }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: { options: [{ label: 'Tax exclusive', value: 'Exclusive' }, { label: 'Tax inclusive', value: 'Inclusive' }, { label: 'No tax', value: 'NoTax' }] },
+ }),
+ currency_code: Property.ShortText({ displayName: 'Currency Code', description: 'ISO code such as USD; defaults to the organisation base currency.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const contactId = xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Quote Date' });
+ if (!date) throw new Error('Quote Date is required.');
+ const lineItems = aiInput.parseLineItems({ value: values.line_items });
+ const expiryDate = xeroInput.parseDateInput({ value: values.expiry_date, field: 'Expiry Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/Quotes`,
+ queryParams: { unitdp: '4' },
+ body: {
+ Quotes: [
+ {
+ Contact: { ContactID: contactId },
+ Date: date,
+ LineItems: lineItems,
+ Status: values.status ?? 'DRAFT',
+ ...(expiryDate ? { ExpiryDate: expiryDate } : {}),
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(text(values.quote_number) ? { QuoteNumber: text(values.quote_number) } : {}),
+ ...(text(values.title) ? { Title: text(values.title) } : {}),
+ ...(text(values.summary) ? { Summary: text(values.summary) } : {}),
+ ...(text(values.terms) ? { Terms: text(values.terms) } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(text(values.currency_code) ? { CurrencyCode: text(values.currency_code) } : {}),
+ },
+ ],
+ },
+ operation: 'create quote',
+ });
+ return xeroApi.firstRecord({ body, key: 'Quotes', operation: 'create quote' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/email-invoice.ts b/packages/pieces/community/xero/src/lib/actions/ai/email-invoice.ts
new file mode 100644
index 00000000000..65999c7f7ed
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/email-invoice.ts
@@ -0,0 +1,38 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroEmailInvoiceAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_email_invoice_ai',
+ classification: 'WRITE',
+ displayName: 'Email Invoice',
+ description: 'Emails a sales invoice to its contact through Xero.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Emails a SUBMITTED, AUTHORISED or PAID sales invoice (ACCREC) to its contact\'s email address through Xero, using the organisation\'s email template; the contact must have an email address. Not idempotent: each call sends another email.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.invoiceEmail,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ invoice_id: aiProps.id({ displayName: 'Invoice ID', description: 'Xero InvoiceID (a GUID) of the sales invoice to email.' }),
+ },
+ async run(context) {
+ const invoiceId = xeroInput.requiredText({ value: context.propsValue.invoice_id, field: 'Invoice ID' });
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: context.propsValue.tenant_id });
+ await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.POST,
+ url: `${XERO_URLS.api}/Invoices/${encodeURIComponent(invoiceId)}/Email`,
+ body: {},
+ operation: 'email invoice',
+ });
+ return { success: true, invoiceId };
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/update-invoice.ts b/packages/pieces/community/xero/src/lib/actions/ai/update-invoice.ts
new file mode 100644
index 00000000000..b36a4306e9a
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/update-invoice.ts
@@ -0,0 +1,123 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, xeroApi, xeroInput, xeroValue } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroUpdateInvoiceAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_update_invoice_ai',
+ classification: 'WRITE',
+ displayName: 'Update Invoice or Bill',
+ description: 'Updates fields or line items of an existing invoice or bill by ID.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Updates an existing invoice or bill by InvoiceID: reference, dates, invoice number, contact, status (DRAFT, SUBMITTED or AUTHORISED) and line items. Line items replace the whole set unless Merge Line Items is on, which keeps existing lines, updates those whose LineItemID you pass and appends the rest. DRAFT and SUBMITTED invoices are fully editable; AUTHORISED ones only partly. Use Void or Delete Invoice to cancel one. Not idempotent when lines are appended; field-only changes converge.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.invoice,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ invoice_id: aiProps.id({ displayName: 'Invoice ID', description: 'Xero InvoiceID (a GUID) of the invoice or bill to update.' }),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', required: false }),
+ due_date: Property.ShortText({ displayName: 'Due Date (YYYY-MM-DD)', required: false }),
+ invoice_number: Property.ShortText({ displayName: 'Invoice Number', required: false }),
+ contact_id: Property.ShortText({ displayName: 'Contact ID', description: 'Move the invoice to this ContactID.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Submitted for approval', value: 'SUBMITTED' }, { label: 'Authorised', value: 'AUTHORISED' }] },
+ }),
+ line_items: aiProps.lineItems({ required: false }),
+ merge_line_items: Property.Checkbox({
+ displayName: 'Merge Line Items',
+ description: 'Keep the existing lines, update lines whose LineItemID is given and append new ones. Off replaces all lines.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const invoiceId = xeroInput.requiredText({ value: values.invoice_id, field: 'Invoice ID' });
+ const lineItems = aiInput.parseLineItems({ value: values.line_items, required: false });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const dueDate = xeroInput.parseDateInput({ value: values.due_date, field: 'Due Date' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const changes = {
+ ...(text(values.reference) ? { Reference: text(values.reference) } : {}),
+ ...(date ? { Date: date } : {}),
+ ...(dueDate ? { DueDate: dueDate } : {}),
+ ...(text(values.invoice_number) ? { InvoiceNumber: text(values.invoice_number) } : {}),
+ ...(text(values.contact_id) ? { Contact: { ContactID: text(values.contact_id) } } : {}),
+ ...(values.status ? { Status: values.status } : {}),
+ };
+ if (Object.keys(changes).length === 0 && lineItems === undefined) {
+ throw new Error('Nothing to update: pass at least one field or Line Items.');
+ }
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ const url = `${XERO_URLS.api}/Invoices/${encodeURIComponent(invoiceId)}`;
+ const finalLines =
+ lineItems && values.merge_line_items
+ ? mergeLines({
+ existing: xeroValue.readRecords(
+ xeroApi.firstRecord({
+ body: await xeroApi.request<unknown>({ accessToken, tenantId, method: HttpMethod.GET, url, queryParams: { unitdp: '4' }, operation: 'get invoice' }),
+ key: 'Invoices',
+ operation: 'get invoice',
+ })['LineItems'],
+ ),
+ updates: lineItems,
+ })
+ : lineItems;
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.POST,
+ url,
+ queryParams: { unitdp: '4' },
+ body: { Invoices: [{ ...changes, ...(finalLines ? { LineItems: finalLines } : {}) }] },
+ operation: 'update invoice',
+ });
+ return xeroApi.firstRecord({ body, key: 'Invoices', operation: 'update invoice' });
+ },
+});
+
+function mergeLines({ existing, updates }: { existing: Record<string, unknown>[]; updates: Record<string, unknown>[] }) {
+ const updatesById = new Map(
+ updates.flatMap((line): [string, Record<string, unknown>][] => {
+ const id = xeroValue.readString(line['LineItemID']);
+ return id ? [[id, line]] : [];
+ }),
+ );
+ const kept = existing.map((line) => {
+ const id = xeroValue.readString(line['LineItemID']);
+ const update = id ? updatesById.get(id) : undefined;
+ return update ? { ...withoutStaleTotals({ line: pickLine({ line }), update }), ...update } : pickLine({ line });
+ });
+ const existingIds = new Set(existing.map((line) => xeroValue.readString(line['LineItemID'])).filter((id) => id !== undefined));
+ const appended = updates.filter((line) => {
+ const id = xeroValue.readString(line['LineItemID']);
+ return id === undefined || !existingIds.has(id);
+ });
+ return [...kept, ...appended];
+}
+
+function withoutStaleTotals({ line, update }: { line: Record<string, unknown>; update: Record<string, unknown> }) {
+ const touches = (keys: string[]) => keys.some((key) => update[key] !== undefined);
+ const dropLineAmount = touches(LINE_AMOUNT_INPUTS);
+ const dropTaxAmount = dropLineAmount || touches(TAX_AMOUNT_INPUTS);
+ return Object.fromEntries(
+ Object.entries(line).filter(([key]) => !(dropLineAmount && key === 'LineAmount') && !(dropTaxAmount && key === 'TaxAmount')),
+ );
+}
+
+function pickLine({ line }: { line: Record<string, unknown> }) {
+ return Object.fromEntries(Object.entries(line).filter(([key]) => LINE_KEYS.includes(key)));
+}
+
+const LINE_KEYS = ['LineItemID', 'Description', 'Quantity', 'UnitAmount', 'AccountCode', 'ItemCode', 'TaxType', 'TaxAmount', 'LineAmount', 'DiscountRate', 'Tracking'];
+const LINE_AMOUNT_INPUTS = ['Quantity', 'UnitAmount', 'DiscountRate'];
+const TAX_AMOUNT_INPUTS = ['LineAmount', 'TaxType'];
diff --git a/packages/pieces/community/xero/src/lib/actions/ai/upload-attachment.ts b/packages/pieces/community/xero/src/lib/actions/ai/upload-attachment.ts
new file mode 100644
index 00000000000..f87935724f6
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/ai/upload-attachment.ts
@@ -0,0 +1,77 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../../..';
+import { XERO_URLS, XeroApiError, xeroApi, xeroInput } from '../../common/client';
+import { aiInput, aiProps } from '../../common/ai-props';
+import { MAX_ATTACHMENT_BYTES, xeroAttachments } from '../../common/attachments';
+import { xeroOutputSchemas } from '../../output-schemas';
+
+export const xeroUploadAttachmentAi = createAction({
+ auth: xeroAuth,
+ name: 'xero_upload_attachment_ai',
+ classification: 'WRITE',
+ displayName: 'Upload Attachment',
+ description: 'Attaches a file to an existing invoice, bill, credit note, quote, purchase order, contact or other record.',
+ audience: 'ai',
+ aiMetadata: {
+ description:
+ 'Attaches a file (max 10 MB) to an existing Xero record given by resource type and record ID, such as an invoice, bill, credit note, purchase order, quote, contact, bank transaction or manual journal. Include Online only applies to sales invoices and credit notes. Attachments cannot be deleted through the API. Not idempotent: each call adds another attachment.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.attachment,
+ props: {
+ tenant_id: aiProps.tenantId(),
+ resource_type: Property.StaticDropdown({
+ displayName: 'Resource Type',
+ required: true,
+ options: {
+ options: [
+ { label: 'Invoice or bill', value: 'Invoices' },
+ { label: 'Credit Note', value: 'CreditNotes' },
+ { label: 'Purchase Order', value: 'PurchaseOrders' },
+ { label: 'Quote', value: 'Quotes' },
+ { label: 'Bank Transaction', value: 'BankTransactions' },
+ { label: 'Bank Transfer', value: 'BankTransfers' },
+ { label: 'Contact', value: 'Contacts' },
+ { label: 'Account', value: 'Accounts' },
+ { label: 'Manual Journal', value: 'ManualJournals' },
+ { label: 'Repeating Invoice', value: 'RepeatingInvoices' },
+ ],
+ },
+ }),
+ resource_id: aiProps.id({ displayName: 'Record ID', description: 'Xero ID (a GUID) of the record, e.g. the InvoiceID.' }),
+ file: Property.File({ displayName: 'File', description: 'The file to attach, up to 10 MB.', required: true }),
+ file_name: Property.ShortText({ displayName: 'File Name', description: 'Defaults to the file\'s own name.', required: false }),
+ include_online: Property.Checkbox({ displayName: 'Include Online', description: 'Show the attachment on the online invoice (sales invoices and credit notes only).', required: false, defaultValue: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const resourceId = xeroInput.requiredText({ value: values.resource_id, field: 'Record ID' });
+ const file = values.file;
+ if (!Buffer.isBuffer(file.data)) throw new Error('File could not be read.');
+ if (file.data.length > MAX_ATTACHMENT_BYTES) throw new Error('Xero accepts attachments up to 10 MB.');
+ const fileName = xeroAttachments.sanitizeFileName({
+ value: xeroInput.trimmedOrUndefined({ value: values.file_name }) ?? file.filename ?? `attachment${file.extension ? `.${file.extension}` : ''}`,
+ });
+ const includeOnline = values.include_online === true && (values.resource_type === 'Invoices' || values.resource_type === 'CreditNotes');
+ const { accessToken, tenantId } = await aiInput.target({ accessToken: context.auth.access_token, tenantId: values.tenant_id });
+ try {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/${values.resource_type}/${encodeURIComponent(resourceId)}/Attachments/${encodeURIComponent(fileName)}`,
+ queryParams: includeOnline ? { IncludeOnline: 'true' } : {},
+ headers: { 'Content-Type': xeroAttachments.mimeTypeFor({ fileName, extension: file.extension }) },
+ body: file.data,
+ operation: 'upload attachment',
+ });
+ return xeroApi.firstRecord({ body, key: 'Attachments', operation: 'upload attachment' });
+ } catch (error) {
+ if (error instanceof XeroApiError && error.status === 404) {
+ throw new Error(`No ${values.resource_type} record with ID ${resourceId} was found in this organisation.`);
+ }
+ throw error;
+ }
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/allocate-credit-note-to-invoice.ts b/packages/pieces/community/xero/src/lib/actions/allocate-credit-note-to-invoice.ts
index 1797b48c8b6..9798fda3b15 100644
--- a/packages/pieces/community/xero/src/lib/actions/allocate-credit-note-to-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/allocate-credit-note-to-invoice.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroAllocateCreditNoteToInvoice = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroAllocateCreditNoteToInvoice = createAction({
classification: 'WRITE',
displayName: 'Allocate Credit Note to Invoice',
description: 'Allocates a credit note to a specific invoice.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Apply a specified amount of an existing credit note against a specific invoice in Xero, both referenced by ID. Pick this to offset an outstanding invoice with available credit. Not idempotent: each call records another allocation, so re-running over-allocates; resolve the credit-note and invoice IDs and the remaining credit first.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.allocationEnvelope,
props: {
tenant_id: props.tenant_id,
credit_note_id: props.credit_note_id(true),
@@ -54,7 +56,7 @@ export const xeroAllocateCreditNoteToInvoice = createAction({
};
const request: HttpRequest = {
- method: HttpMethod.POST,
+ method: HttpMethod.PUT,
url,
body,
authentication: {
diff --git a/packages/pieces/community/xero/src/lib/actions/archive-contact.ts b/packages/pieces/community/xero/src/lib/actions/archive-contact.ts
new file mode 100644
index 00000000000..e8117864ba5
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/archive-contact.ts
@@ -0,0 +1,48 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroArchiveContact = createAction({
+ auth: xeroAuth,
+ name: 'xero_archive_contact',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Archive Contact',
+ description: 'Archives a contact so it no longer appears in contact lists.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Archives a Xero contact by ContactID, hiding it from contact lists and new transactions; Xero does not allow deleting contacts. Xero refuses to archive a contact with outstanding balances or linked repeating invoices (even deleted ones). Idempotent: archiving an already archived contact leaves it archived.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.contact,
+ props: {
+ tenant_id: props.tenant_id,
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Xero ContactID (a GUID) of the contact to archive.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ return archiveContact({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ contactId: xeroInput.requiredText({ value: context.propsValue.contact_id, field: 'Contact ID' }),
+ });
+ },
+});
+
+async function archiveContact({ accessToken, tenantId, contactId }: { accessToken: string; tenantId: string; contactId: string }) {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.POST,
+ url: `${XERO_URLS.api}/Contacts/${encodeURIComponent(contactId)}`,
+ body: { Contacts: [{ ContactID: contactId, ContactStatus: 'ARCHIVED' }] },
+ operation: 'archive contact',
+ });
+ return xeroApi.firstRecord({ body, key: 'Contacts', operation: 'archive contact' });
+}
diff --git a/packages/pieces/community/xero/src/lib/actions/create-bank-transaction.ts b/packages/pieces/community/xero/src/lib/actions/create-bank-transaction.ts
index d2c34364b6e..50d5e0118a6 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-bank-transaction.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-bank-transaction.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateBankTransaction = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreateBankTransaction = createAction({
classification: 'WRITE',
displayName: 'Create Bank Transaction',
description: 'Creates a new Spend/Receive Money bank transaction.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Record a Spend Money (SPEND) or Receive Money (RECEIVE) bank transaction against one of the organization\'s bank accounts, attributed to a contact with at least one line item (Description, UnitAmount, AccountCode). Pick this for direct money in/out of a bank account, not for paying an invoice (use Create Payment) or moving money between own accounts (use Create Bank Transfer). Not idempotent: each call records another transaction.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.bankTransactionEnvelope,
props: {
tenant_id: props.tenant_id,
type: Property.StaticDropdown({
diff --git a/packages/pieces/community/xero/src/lib/actions/create-bank-transfer.ts b/packages/pieces/community/xero/src/lib/actions/create-bank-transfer.ts
index 87c6ce903f0..9893d693b89 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-bank-transfer.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-bank-transfer.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateBankTransfer = createAction({
auth: xeroAuth,
@@ -20,10 +21,11 @@ export const xeroCreateBankTransfer = createAction({
'Record a transfer of money between two of the organization\'s own Xero bank accounts (the two account currencies must match). Pick this for internal account-to-account movements, not for paying invoices (use Create Payment). Not idempotent: each call records another transfer, so re-running duplicates it.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.bankTransferEnvelope,
props: {
tenant_id: props.tenant_id,
- from_bank_account_id: props.bank_account_id(true),
- to_bank_account_id: props.bank_account_id(true),
+ from_bank_account_id: props.bank_account_id(true, { displayName: 'From Bank Account', description: 'The bank account the money leaves.' }),
+ to_bank_account_id: props.bank_account_id(true, { displayName: 'To Bank Account', description: 'The bank account the money arrives in.' }),
amount: Property.Number({
displayName: 'Amount',
description: 'Amount to transfer. Currencies must match between accounts.',
diff --git a/packages/pieces/community/xero/src/lib/actions/create-bill.ts b/packages/pieces/community/xero/src/lib/actions/create-bill.ts
index 3371724ca0e..b1a317d96b1 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-bill.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-bill.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateBill = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreateBill = createAction({
classification: 'WRITE',
displayName: 'Create Bill',
description: 'Creates a new bill (Accounts Payable).',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Create a new accounts-payable (ACCPAY) bill from a supplier contact, with at least one line item (Description required) and optional dates, reference, and status. Pick this for money the organization owes a supplier; for customer-facing sales invoices use Create or Update Invoice instead. Not idempotent: each call creates another bill.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.invoiceEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-contact.ts b/packages/pieces/community/xero/src/lib/actions/create-contact.ts
index 1e286a07dde..cbe638fa059 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-contact.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-contact.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { props } from '../common/props';
import { xeroAuth } from '../..';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateContact = createAction({
auth: xeroAuth,
@@ -20,6 +21,7 @@ export const xeroCreateContact = createAction({
'Create a new Xero contact (customer or supplier) or update an existing one when a contact ID is supplied. Pick this to maintain the contact record that invoices, bills, and payments attach to. Supplying an existing contact ID updates that record in place (idempotent on a fixed ID); omitting it creates a new contact each call, so de-duplicate by looking the contact up first.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.contactEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_id(false),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-credit-note.ts b/packages/pieces/community/xero/src/lib/actions/create-credit-note.ts
index b77f1f24c58..5ce56f11497 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-credit-note.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-credit-note.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateCreditNote = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreateCreditNote = createAction({
classification: 'WRITE',
displayName: 'Create Credit Note',
description: 'Creates a new credit note for a contact.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Create a new Xero credit note for a contact, either accounts-receivable (ACCRECCREDIT, customer refunds) or accounts-payable (ACCPAYCREDIT, supplier credits), with optional line items and status. Pick this to issue credit; to apply it against an invoice afterward use Allocate Credit Note to Invoice. Not idempotent: each call creates another credit note. Reference is honored only for ACCRECCREDIT.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.creditNoteEnvelope,
props: {
tenant_id: props.tenant_id,
type: Property.StaticDropdown({
diff --git a/packages/pieces/community/xero/src/lib/actions/create-inventory-item.ts b/packages/pieces/community/xero/src/lib/actions/create-inventory-item.ts
index db255434573..20edc06a3d2 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-inventory-item.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-inventory-item.ts
@@ -1,12 +1,9 @@
import { Property, createAction } from '@activepieces/pieces-framework';
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
+import { HttpMethod } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroValue } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateInventoryItem = createAction({
auth: xeroAuth,
@@ -17,9 +14,10 @@ export const xeroCreateInventoryItem = createAction({
audience: 'both',
aiMetadata: {
description:
- 'Create a new Xero item (product/service) keyed by a unique item code, optionally tracked as inventory via sales, purchase, COGS, and inventory-asset accounts. Pick this to register a catalog item that line items can later reference by ItemCode. Not idempotent: each call creates an item, and Xero rejects a duplicate code; look the code up first if it may already exist.',
- idempotent: false,
+ 'Creates a Xero item (product or service) keyed by its item code, optionally tracked as inventory via sales, purchase, COGS and inventory-asset accounts picked by account. Pick this to register a catalog item that line items can later reference by ItemCode; use Create or Update Item to work with account codes directly. Idempotent on the code: if an item with this code already exists, Xero updates it instead of creating a duplicate.',
+ idempotent: true,
},
+ outputSchema: xeroOutputSchemas.itemEnvelope,
props: {
tenant_id: props.tenant_id,
code: Property.ShortText({
@@ -83,8 +81,16 @@ export const xeroCreateInventoryItem = createAction({
cogs_account_id,
inventory_asset_account_id,
} = context.propsValue;
-
- const url = 'https://api.xero.com/api.xro/2.0/Items';
+ const accessToken = context.auth.access_token;
+ const selected = [sales_account_id, purchase_account_id, cogs_account_id, inventory_asset_account_id].filter(
+ (value): value is string => typeof value === 'string' && value.trim().length > 0,
+ );
+ const codes = selected.length > 0 ? await accountCodes({ accessToken, tenantId: tenant_id }) : new Map<string, string>();
+ const codeOf = (value: unknown) => resolveAccountCode({ value, codes });
+ const salesAccountCode = codeOf(sales_account_id);
+ const purchaseAccountCode = codeOf(purchase_account_id);
+ const cogsAccountCode = codeOf(cogs_account_id);
+ const inventoryAccountCode = codeOf(inventory_asset_account_id);
const item: Record<string, unknown> = {
Code: code,
@@ -93,44 +99,54 @@ export const xeroCreateInventoryItem = createAction({
...(typeof is_purchased === 'boolean' ? { IsPurchased: is_purchased } : {}),
...(description ? { Description: description } : {}),
...(purchase_description ? { PurchaseDescription: purchase_description } : {}),
- ...(sales_details || sales_account_id
- ? { SalesDetails: { ...(sales_details ?? {}), ...(sales_account_id ? { AccountID: sales_account_id } : {}) } }
+ ...(sales_details || salesAccountCode
+ ? { SalesDetails: { ...(sales_details ?? {}), ...(salesAccountCode ? { AccountCode: salesAccountCode } : {}) } }
: {}),
- ...(purchase_details || purchase_account_id || cogs_account_id
+ ...(purchase_details || purchaseAccountCode || cogsAccountCode
? {
PurchaseDetails: {
...(purchase_details ?? {}),
- ...(purchase_account_id ? { AccountID: purchase_account_id } : {}),
- ...(cogs_account_id ? { COGSAccountID: cogs_account_id } : {}),
+ ...(purchaseAccountCode ? { AccountCode: purchaseAccountCode } : {}),
+ ...(cogsAccountCode ? { COGSAccountCode: cogsAccountCode } : {}),
},
}
: {}),
- ...(inventory_asset_account_id
- ? { InventoryAssetAccountCode: undefined, InventoryAssetAccountID: inventory_asset_account_id }
- : {}),
+ ...(inventoryAccountCode ? { InventoryAssetAccountCode: inventoryAccountCode, IsTrackedAsInventory: true } : {}),
};
- const payload = item;
-
- const request: HttpRequest = {
+ return xeroApi.request<unknown>({
+ accessToken,
+ tenantId: tenant_id,
method: HttpMethod.POST,
- url,
- body: payload,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (context.auth as any).access_token,
- },
- headers: {
- 'Xero-Tenant-Id': tenant_id,
- },
- };
-
- const result = await httpClient.sendRequest(request);
- if (result.status === 200) {
- return result.body;
- }
- return result;
+ url: `${XERO_URLS.api}/Items`,
+ body: item,
+ operation: 'create inventory item',
+ });
},
});
+async function accountCodes({ accessToken, tenantId }: { accessToken: string; tenantId: string }): Promise<Map<string, string>> {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Accounts`,
+ operation: 'list accounts for item account codes',
+ });
+ return new Map(
+ xeroApi.recordsOf({ body, key: 'Accounts' }).flatMap((account): [string, string][] => {
+ const id = xeroValue.readString(account['AccountID']);
+ const accountCode = xeroValue.readString(account['Code']);
+ return id && accountCode ? [[id, accountCode]] : [];
+ }),
+ );
+}
+function resolveAccountCode({ value, codes }: { value: unknown; codes: Map<string, string> }): string | undefined {
+ if (typeof value !== 'string' || value.trim().length === 0) return undefined;
+ const key = value.trim();
+ const fromId = codes.get(key);
+ if (fromId) return fromId;
+ if ([...codes.values()].includes(key)) return key;
+ throw new Error(`Xero account ${key} was not found or has no account code; items can only use accounts that have a code.`);
+}
diff --git a/packages/pieces/community/xero/src/lib/actions/create-invoice.ts b/packages/pieces/community/xero/src/lib/actions/create-invoice.ts
index 3e0502e88c7..32f2be85dc9 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-invoice.ts
@@ -7,8 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { props } from '../common/props';
-import dayjs from 'dayjs';
import { xeroAuth } from '../..';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateInvoice = createAction({
auth: xeroAuth,
@@ -16,12 +16,13 @@ export const xeroCreateInvoice = createAction({
classification: 'DESTRUCTIVE',
description: 'Create Xero Invoice',
displayName: 'Create or Update Invoice',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Create a new ACCREC sales invoice for a customer (resolving or creating the contact from name/email) or update an existing invoice when an invoice ID is supplied. Use this for a single sales invoice; for recurring billing use Create Repeating Sales Invoice. Supplying an invoice ID updates that record (idempotent on a fixed ID); omitting it creates a new invoice each call.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.invoiceEnvelope,
props: {
tenant_id: props.tenant_id,
invoice_id: props.invoice_id(false),
@@ -30,16 +31,9 @@ export const xeroCreateInvoice = createAction({
email: props.contact_email(false),
line_item: Property.Object({
displayName: 'Line Item',
- description: 'Invoice line items',
+ description:
+ 'One invoice line as key/value pairs, e.g. Description, Quantity, UnitAmount, AccountCode (such as 200 for Sales) and TaxType. Use List Accounts and List Tax Rates to find valid codes.',
required: true,
- defaultValue: {
- AccountCode: 200,
- Quantity: 0,
- UnitAmount: 0,
- LineAmount: 0,
- TaxType: 'NONE',
- Description: 'description',
- },
}),
date: Property.ShortText({
displayName: 'Date Prepared',
@@ -49,7 +43,6 @@ export const xeroCreateInvoice = createAction({
due_date: Property.ShortText({
displayName: 'Due Date',
description: 'Due date of the invoice. Format example: 2019-03-11',
- defaultValue: dayjs().format('YYYY-MM-DD'),
required: true,
}),
reference: Property.ShortText({
diff --git a/packages/pieces/community/xero/src/lib/actions/create-manual-journal.ts b/packages/pieces/community/xero/src/lib/actions/create-manual-journal.ts
new file mode 100644
index 00000000000..9bf3af267ff
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/create-manual-journal.ts
@@ -0,0 +1,77 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { aiInput } from '../common/ai-props';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroCreateManualJournal = createAction({
+ auth: xeroAuth,
+ name: 'xero_create_manual_journal',
+ classification: 'WRITE',
+ displayName: 'Create Manual Journal',
+ description: 'Creates a manual journal with balanced debit and credit lines.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates a manual journal from journal lines where positive LineAmount values are debits and negative values are credits; the lines must add up to exactly zero and are checked before anything is sent. Saved as DRAFT unless Status is POSTED. Not idempotent: each call creates another journal.',
+ idempotent: false,
+ },
+ outputSchema: xeroOutputSchemas.manualJournal,
+ props: {
+ tenant_id: props.tenant_id,
+ narration: Property.ShortText({ displayName: 'Narration', description: 'Description of the journal.', required: true }),
+ journal_lines: Property.Json({
+ displayName: 'Journal Lines',
+ description:
+ 'JSON array of lines, e.g. [{"LineAmount":100,"AccountCode":"400","Description":"Accrual"},{"LineAmount":-100,"AccountCode":"800"}]. Positive amounts are debits, negative are credits, and the total must be 0. Allowed keys: LineAmount, AccountCode, AccountID, Description, TaxType, TaxAmount, Tracking.',
+ required: true,
+ }),
+ date: Property.ShortText({ displayName: 'Date (YYYY-MM-DD)', description: 'Defaults to today in Xero.', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'DRAFT',
+ options: { options: [{ label: 'Draft', value: 'DRAFT' }, { label: 'Posted', value: 'POSTED' }] },
+ }),
+ line_amount_types: Property.StaticDropdown({
+ displayName: 'Line Amount Types',
+ required: false,
+ options: {
+ options: [
+ { label: 'Tax exclusive', value: 'Exclusive' },
+ { label: 'Tax inclusive', value: 'Inclusive' },
+ { label: 'No tax', value: 'NoTax' },
+ ],
+ },
+ }),
+ show_on_cash_basis_reports: Property.Checkbox({ displayName: 'Show on Cash Basis Reports', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const narration = xeroInput.requiredText({ value: values.narration, field: 'Narration' });
+ const journalLines = aiInput.parseJournalLines({ value: values.journal_lines });
+ const date = xeroInput.parseDateInput({ value: values.date, field: 'Date' });
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ method: HttpMethod.PUT,
+ url: `${XERO_URLS.api}/ManualJournals`,
+ body: {
+ ManualJournals: [
+ {
+ Narration: narration,
+ JournalLines: journalLines,
+ ...(date ? { Date: date } : {}),
+ ...(values.status ? { Status: values.status } : {}),
+ ...(values.line_amount_types ? { LineAmountTypes: values.line_amount_types } : {}),
+ ...(typeof values.show_on_cash_basis_reports === 'boolean' ? { ShowOnCashBasisReports: values.show_on_cash_basis_reports } : {}),
+ },
+ ],
+ },
+ operation: 'create manual journal',
+ });
+ return xeroApi.firstRecord({ body, key: 'ManualJournals', operation: 'create manual journal' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/create-payment.ts b/packages/pieces/community/xero/src/lib/actions/create-payment.ts
index d304c6c5063..99f4631a12b 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-payment.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-payment.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreatePayment = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreatePayment = createAction({
classification: 'WRITE',
displayName: 'Create Payment',
description: 'Applies a payment to an invoice.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Record a payment against an existing Xero invoice (or bill), paid from a specific bank account. Pick this once an invoice exists and you need to settle it for an amount up to the amount due. Not idempotent: each call records another payment, so re-running double-pays; resolve the target invoice and bank account IDs first (separate find/lookup actions).',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.paymentEnvelope,
props: {
tenant_id: props.tenant_id,
invoice_id: props.payable_invoice_id(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-project.ts b/packages/pieces/community/xero/src/lib/actions/create-project.ts
index 37faa653d23..2cc1f0db315 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-project.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-project.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateProject = createAction({
auth: xeroAuth,
@@ -20,6 +21,7 @@ export const xeroCreateProject = createAction({
'Create a new Xero Projects project for a contact, with a name and optional deadline (UTC ISO-8601) and estimate amount. Pick this for time/cost tracking on the Xero Projects product, distinct from accounting invoices. Not idempotent: each call creates another project.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.project,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-purchase-order.ts b/packages/pieces/community/xero/src/lib/actions/create-purchase-order.ts
index 11f3c877d9d..d3776e5efa5 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-purchase-order.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-purchase-order.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreatePurchaseOrder = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreatePurchaseOrder = createAction({
classification: 'WRITE',
displayName: 'Create Purchase Order',
description: 'Creates a new purchase order for a contact.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Create a new Xero purchase order for a supplier contact, with at least one line item (Description required) and optional delivery, reference, and status details. Pick this to raise a new order to a supplier; to change an existing one use Update Purchase Order. Not idempotent: each call creates another purchase order.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.purchaseOrderEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-quote-draft.ts b/packages/pieces/community/xero/src/lib/actions/create-quote-draft.ts
index 26f50101d44..fc1351ffdaf 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-quote-draft.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-quote-draft.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateQuoteDraft = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroCreateQuoteDraft = createAction({
classification: 'WRITE',
displayName: 'Create New Quote Draft',
description: 'Creates a new draft quote.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Create a new draft sales quote in Xero for a contact, with at least one line item (Description required) plus optional title, summary, terms, and expiry. Pick this to draft a customer-facing quote before it becomes an invoice. Not idempotent: each call creates another quote.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.quoteEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/create-repeating-sales-invoice.ts b/packages/pieces/community/xero/src/lib/actions/create-repeating-sales-invoice.ts
index d04417c9fd4..0be274a8fff 100644
--- a/packages/pieces/community/xero/src/lib/actions/create-repeating-sales-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/create-repeating-sales-invoice.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroCreateRepeatingSalesInvoice = createAction({
auth: xeroAuth,
@@ -20,6 +21,7 @@ export const xeroCreateRepeatingSalesInvoice = createAction({
'Set up a recurring accounts-receivable (ACCREC) sales invoice template in Xero that auto-generates invoices on a weekly or monthly schedule. Pick this for subscriptions or retainers that bill a contact on a repeating cadence, not for a single invoice (use Create Invoice for that). Not idempotent: each call creates another recurring template; the schedule unit constrains which due-date types are valid.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.repeatingInvoiceEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/delete-payment.ts b/packages/pieces/community/xero/src/lib/actions/delete-payment.ts
new file mode 100644
index 00000000000..9b22a348b4b
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/delete-payment.ts
@@ -0,0 +1,51 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroDeletePayment = createAction({
+ auth: xeroAuth,
+ name: 'xero_delete_payment',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Delete Payment',
+ description: 'Deletes (reverses) a payment so the invoice or bill is unpaid again.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Deletes a payment by PaymentID by setting its status to DELETED, which puts the amount back on the invoice or bill; Xero refuses reconciled payments and batch payments. Use Search Payments to find the PaymentID. Idempotent: deleting an already deleted payment leaves it deleted.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.payment,
+ props: {
+ tenant_id: props.tenant_id,
+ payment_id: Property.ShortText({ displayName: 'Payment ID', description: 'The Xero PaymentID (a GUID) to delete.', required: true }),
+ },
+ async run(context) {
+ return deletePayment({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ paymentId: xeroInput.requiredText({ value: context.propsValue.payment_id, field: 'Payment ID' }),
+ });
+ },
+});
+
+async function deletePayment({ accessToken, tenantId, paymentId }: { accessToken: string; tenantId: string; paymentId: string }) {
+ const url = `${XERO_URLS.api}/Payments/${encodeURIComponent(paymentId)}`;
+ const current = xeroApi.firstRecord({
+ body: await xeroApi.request<unknown>({ accessToken, tenantId, method: HttpMethod.GET, url, operation: 'get payment before deleting' }),
+ key: 'Payments',
+ operation: 'get payment before deleting',
+ });
+ if (current['Status'] === 'DELETED') return current;
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.POST,
+ url,
+ body: { Payments: [{ Status: 'DELETED' }] },
+ operation: 'delete payment',
+ });
+ return xeroApi.firstRecord({ body, key: 'Payments', operation: 'delete payment' });
+}
diff --git a/packages/pieces/community/xero/src/lib/actions/download-invoice-pdf.ts b/packages/pieces/community/xero/src/lib/actions/download-invoice-pdf.ts
new file mode 100644
index 00000000000..c1b5494b893
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/download-invoice-pdf.ts
@@ -0,0 +1,83 @@
+import { Readable } from 'stream';
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroDownloadInvoicePdf = createAction({
+ auth: xeroAuth,
+ name: 'xero_download_invoice_pdf',
+ classification: 'READ',
+ displayName: 'Download Invoice PDF',
+ description: 'Downloads the PDF of an invoice or bill so you can attach or send it in later steps.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Downloads the Xero-rendered PDF of one invoice or bill by InvoiceID and stores it as a file for later steps (email attachment, cloud storage). Use Get Invoice for the invoice data itself. Read-only and idempotent: repeating the call returns the same document.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.invoicePdf,
+ props: {
+ tenant_id: props.tenant_id,
+ invoice_id: Property.ShortText({
+ displayName: 'Invoice ID',
+ description: 'The Xero InvoiceID (a GUID). Use Search Invoices or Get Invoice to find it.',
+ required: true,
+ }),
+ file_name: Property.ShortText({
+ displayName: 'File Name',
+ description: 'Defaults to invoice-<InvoiceID>.pdf.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const invoiceId = xeroInput.requiredText({ value: context.propsValue.invoice_id, field: 'Invoice ID' });
+ const stream = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Invoices/${encodeURIComponent(invoiceId)}`,
+ headers: { Accept: 'application/pdf' },
+ responseType: 'stream',
+ timeout: DOWNLOAD_TIMEOUT_MS,
+ operation: 'download invoice PDF',
+ });
+ const data = await readCapped({ stream, maxBytes: MAX_PDF_BYTES, timeoutMs: DOWNLOAD_TIMEOUT_MS });
+ const requestedName = xeroInput.trimmedOrUndefined({ value: context.propsValue.file_name });
+ const baseName = requestedName ?? `invoice-${invoiceId}`;
+ const fileName = baseName.toLowerCase().endsWith('.pdf') ? baseName : `${baseName}.pdf`;
+ const file = await context.files.write({ fileName, data });
+ return { file, fileName, size: data.length, invoiceId: invoiceId };
+ },
+});
+
+async function readCapped({ stream, maxBytes, timeoutMs }: { stream: unknown; maxBytes: number; timeoutMs: number }): Promise<Buffer> {
+ if (!(stream instanceof Readable)) throw new Error('Xero did not return a PDF stream.');
+ return new Promise<Buffer>((resolve, reject) => {
+ const chunks: Buffer[] = [];
+ let size = 0;
+ const timer = setTimeout(() => stream.destroy(new Error(`Downloading the invoice PDF took longer than ${timeoutMs / 1000} seconds.`)), timeoutMs);
+ stream.on('data', (chunk: Buffer | string) => {
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
+ size += buffer.length;
+ if (size > maxBytes) {
+ stream.destroy(new Error(`The invoice PDF is larger than ${maxBytes / (1024 * 1024)} MB.`));
+ return;
+ }
+ chunks.push(buffer);
+ });
+ stream.on('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ stream.on('end', () => {
+ clearTimeout(timer);
+ resolve(Buffer.concat(chunks));
+ });
+ });
+}
+
+const MAX_PDF_BYTES = 25 * 1024 * 1024;
+const DOWNLOAD_TIMEOUT_MS = 120000;
diff --git a/packages/pieces/community/xero/src/lib/actions/find-contact.ts b/packages/pieces/community/xero/src/lib/actions/find-contact.ts
index a81ed4c37f5..98d0f79d8c5 100644
--- a/packages/pieces/community/xero/src/lib/actions/find-contact.ts
+++ b/packages/pieces/community/xero/src/lib/actions/find-contact.ts
@@ -7,6 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroFindContact = createAction({
auth: xeroAuth,
@@ -20,6 +22,7 @@ export const xeroFindContact = createAction({
'Read-only lookup of Xero contacts in a tenant; pick when you need to locate a contact or its ID before invoicing or other operations. Choose the search mode via Search By: exact Name or Account Number, or a broad Search Term for fuzzy matching across fields. Returns matching contacts without modifying anything; supply the tenant ID and use Summary Only / Page for large result sets.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.contactEnvelope,
props: {
tenant_id: props.tenant_id,
search_by: Property.StaticDropdown({
@@ -76,10 +79,10 @@ export const xeroFindContact = createAction({
if (search_by === 'SEARCH_TERM') {
params.push(`SearchTerm=${encodeURIComponent(value)}`);
} else if (search_by === 'NAME') {
- const where = `Name="${value.replace(/"/g, '\\"')}"`;
+ const where = `Name=${xeroInput.whereString({ value })}`;
params.push(`where=${encodeURIComponent(where)}`);
} else if (search_by === 'ACCOUNT_NUMBER') {
- const where = `AccountNumber="${value.replace(/"/g, '\\"')}"`;
+ const where = `AccountNumber=${xeroInput.whereString({ value })}`;
params.push(`where=${encodeURIComponent(where)}`);
}
diff --git a/packages/pieces/community/xero/src/lib/actions/find-invoice.ts b/packages/pieces/community/xero/src/lib/actions/find-invoice.ts
index 95690b09118..d369d82af65 100644
--- a/packages/pieces/community/xero/src/lib/actions/find-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/find-invoice.ts
@@ -7,6 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroFindInvoice = createAction({
auth: xeroAuth,
@@ -20,6 +22,7 @@ export const xeroFindInvoice = createAction({
'Look up Xero invoices by exact invoice number, exact reference, or a fuzzy search term, optionally filtered to sales invoices (ACCREC) or bills (ACCPAY). Read-only and idempotent; use it to resolve an invoice ID before recording a payment, sending, or allocating a credit note. The search-term mode matches invoice number or reference more loosely than the exact modes.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.invoiceEnvelope,
props: {
tenant_id: props.tenant_id,
search_by: Property.StaticDropdown({
@@ -73,9 +76,9 @@ export const xeroFindInvoice = createAction({
}
if (search_by === 'INVOICE_NUMBER') {
- whereClauses.push(`InvoiceNumber="${value.replace(/"/g, '\\"')}"`);
+ whereClauses.push(`InvoiceNumber=${xeroInput.whereString({ value })}`);
} else if (search_by === 'REFERENCE') {
- whereClauses.push(`Reference="${value.replace(/"/g, '\\"')}"`);
+ whereClauses.push(`Reference=${xeroInput.whereString({ value })}`);
} else if (search_by === 'SEARCH_TERM') {
params.push(`SearchTerm=${encodeURIComponent(value)}`);
}
diff --git a/packages/pieces/community/xero/src/lib/actions/find-item.ts b/packages/pieces/community/xero/src/lib/actions/find-item.ts
index 28a3de927a0..6f35ded0150 100644
--- a/packages/pieces/community/xero/src/lib/actions/find-item.ts
+++ b/packages/pieces/community/xero/src/lib/actions/find-item.ts
@@ -7,6 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroFindItem = createAction({
auth: xeroAuth,
@@ -20,6 +22,7 @@ export const xeroFindItem = createAction({
'Look up a Xero item by exact code or exact name, with optional ordering. Read-only and idempotent; use it to confirm an item exists or resolve its details before referencing it on a line item or creating a duplicate. Both search modes require an exact match.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.itemEnvelope,
props: {
tenant_id: props.tenant_id,
search_by: Property.StaticDropdown({
@@ -49,7 +52,7 @@ export const xeroFindItem = createAction({
const baseUrl = 'https://api.xero.com/api.xro/2.0/Items';
const whereField = search_by === 'CODE' ? 'Code' : 'Name';
- const where = `${whereField}="${String(value).replace(/"/g, '\\"')}"`;
+ const where = `${whereField}=${xeroInput.whereString({ value: String(value) })}`;
const params: string[] = [`where=${encodeURIComponent(where)}`];
if (order) params.push(`order=${encodeURIComponent(order)}`);
diff --git a/packages/pieces/community/xero/src/lib/actions/find-or-create-contact.ts b/packages/pieces/community/xero/src/lib/actions/find-or-create-contact.ts
index 3648cb3f521..e3016ce4d76 100644
--- a/packages/pieces/community/xero/src/lib/actions/find-or-create-contact.ts
+++ b/packages/pieces/community/xero/src/lib/actions/find-or-create-contact.ts
@@ -7,6 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroFindOrCreateContact = createAction({
auth: xeroAuth,
@@ -20,6 +22,7 @@ export const xeroFindOrCreateContact = createAction({
'Look up a Xero contact by exact name and return it if it exists, otherwise create it. Pick this to de-duplicate contacts before invoicing so re-runs reuse the same record instead of creating duplicates. Idempotent on the contact name: the same name always resolves to the same contact.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.contactEnvelope,
props: {
tenant_id: props.tenant_id,
name: props.contact_name(true),
@@ -29,7 +32,7 @@ export const xeroFindOrCreateContact = createAction({
const { tenant_id, name, email } = context.propsValue;
const baseUrl = 'https://api.xero.com/api.xro/2.0/Contacts';
- const where = `Name="${name?.replace(/"/g, '\\"')}"`;
+ const where = `Name=${xeroInput.whereString({ value: name ?? '' })}`;
const findRequest: HttpRequest = {
method: HttpMethod.GET,
diff --git a/packages/pieces/community/xero/src/lib/actions/find-purchase-order.ts b/packages/pieces/community/xero/src/lib/actions/find-purchase-order.ts
index 6d0a210fe37..bb47bf87ed6 100644
--- a/packages/pieces/community/xero/src/lib/actions/find-purchase-order.ts
+++ b/packages/pieces/community/xero/src/lib/actions/find-purchase-order.ts
@@ -7,6 +7,8 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroFindPurchaseOrder = createAction({
auth: xeroAuth,
@@ -20,6 +22,7 @@ export const xeroFindPurchaseOrder = createAction({
'Look up Xero purchase orders by exact number, exact reference, or GUID ID, with optional filters for contact, status, date range, and paging. Read-only and idempotent; use it to resolve a purchase-order ID or inspect orders before updating one. Searching by ID fetches that single record directly; the other modes run a filtered list query.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.purchaseOrderEnvelope,
props: {
tenant_id: props.tenant_id,
contact_id: props.contact_dropdown(false),
@@ -111,9 +114,9 @@ export const xeroFindPurchaseOrder = createAction({
// Equality filter using where for non-ID searches
const whereClauses: string[] = [];
if (search_by === 'NUMBER') {
- whereClauses.push(`PurchaseOrderNumber=="${String(value).replace(/"/g, '\\"')}"`);
+ whereClauses.push(`PurchaseOrderNumber==${xeroInput.whereString({ value: String(value) })}`);
} else if (search_by === 'REFERENCE') {
- whereClauses.push(`Reference=="${String(value).replace(/"/g, '\\"')}"`);
+ whereClauses.push(`Reference==${xeroInput.whereString({ value: String(value) })}`);
}
if (contact_id) {
whereClauses.push(`Contact.ContactID==guid("${contact_id}")`);
diff --git a/packages/pieces/community/xero/src/lib/actions/get-aged-payables.ts b/packages/pieces/community/xero/src/lib/actions/get-aged-payables.ts
new file mode 100644
index 00000000000..919b6e75124
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-aged-payables.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetAgedPayables = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_aged_payables',
+ classification: 'READ',
+ displayName: 'Get Aged Payables for Contact',
+ description: 'Runs the Aged Payables report for one supplier: what you owe them, by bill and age.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Aged Payables by Contact report for one supplier ContactID: each outstanding bill with its amount due and how overdue it is. Needs a connection created with Xero piece 0.8.0 or later. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ contact_id: Property.ShortText({ displayName: 'Contact ID', description: 'The Xero ContactID (a GUID). Use Find Contact to get it.', required: true }),
+ date: Property.ShortText({ displayName: 'Aged As At (YYYY-MM-DD)', description: 'Defaults to today.', required: false }),
+ from_date: Property.ShortText({ displayName: 'Show Invoices From (YYYY-MM-DD)', required: false }),
+ to_date: Property.ShortText({ displayName: 'Show Invoices To (YYYY-MM-DD)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ contactId: xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' }),
+ date: xeroInput.parseDateInput({ value: values.date, field: 'Aged As At' }),
+ fromDate: xeroInput.parseDateInput({ value: values.from_date, field: 'Show Invoices From' }),
+ toDate: xeroInput.parseDateInput({ value: values.to_date, field: 'Show Invoices To' }),
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'AgedPayablesByContact',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-aged-receivables.ts b/packages/pieces/community/xero/src/lib/actions/get-aged-receivables.ts
new file mode 100644
index 00000000000..f9ae2324be1
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-aged-receivables.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetAgedReceivables = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_aged_receivables',
+ classification: 'READ',
+ displayName: 'Get Aged Receivables for Contact',
+ description: 'Runs the Aged Receivables report for one customer: what they owe, by invoice and age.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Aged Receivables by Contact report for one customer ContactID: each outstanding sales invoice with its amount due and how overdue it is. Use it to chase a customer; use Get Contact for the totals only. Needs a connection created with Xero piece 0.8.0 or later. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ contact_id: Property.ShortText({ displayName: 'Contact ID', description: 'The Xero ContactID (a GUID). Use Find Contact to get it.', required: true }),
+ date: Property.ShortText({ displayName: 'Aged As At (YYYY-MM-DD)', description: 'Defaults to today.', required: false }),
+ from_date: Property.ShortText({ displayName: 'Show Invoices From (YYYY-MM-DD)', required: false }),
+ to_date: Property.ShortText({ displayName: 'Show Invoices To (YYYY-MM-DD)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ contactId: xeroInput.requiredText({ value: values.contact_id, field: 'Contact ID' }),
+ date: xeroInput.parseDateInput({ value: values.date, field: 'Aged As At' }),
+ fromDate: xeroInput.parseDateInput({ value: values.from_date, field: 'Show Invoices From' }),
+ toDate: xeroInput.parseDateInput({ value: values.to_date, field: 'Show Invoices To' }),
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'AgedReceivablesByContact',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-balance-sheet.ts b/packages/pieces/community/xero/src/lib/actions/get-balance-sheet.ts
new file mode 100644
index 00000000000..cd160111b7b
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-balance-sheet.ts
@@ -0,0 +1,50 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetBalanceSheet = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_balance_sheet',
+ classification: 'READ',
+ displayName: 'Get Balance Sheet',
+ description: 'Runs the Balance Sheet report as at a date, with optional comparison periods.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Balance Sheet report as at a date (defaults to the end of the current month) and returns flat rows with a section, a label and one value per column, optionally compared with earlier periods. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ date: Property.ShortText({ displayName: 'As At Date (YYYY-MM-DD)', required: false }),
+ timeframe: Property.StaticDropdown({
+ displayName: 'Period Length',
+ description: 'Length of each comparison period.',
+ required: false,
+ options: { options: [{ label: 'Month', value: 'MONTH' }, { label: 'Quarter', value: 'QUARTER' }, { label: 'Year', value: 'YEAR' }] },
+ }),
+ periods: Property.Number({ displayName: 'Comparison Periods', description: 'Number of earlier periods to compare with, 1 to 11.', required: false }),
+ standard_layout: Property.Checkbox({ displayName: 'Standard Layout', description: 'Ignore custom report layouts.', required: false }),
+ payments_only: Property.Checkbox({ displayName: 'Cash Basis (Payments Only)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ date: xeroInput.parseDateInput({ value: values.date, field: 'As At Date' }),
+ periods: xeroReports.periodsParam({ value: values.periods }),
+ timeframe: values.timeframe,
+ standardLayout: values.standard_layout,
+ paymentsOnly: values.payments_only,
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'BalanceSheet',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-bank-summary.ts b/packages/pieces/community/xero/src/lib/actions/get-bank-summary.ts
new file mode 100644
index 00000000000..4055af24598
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-bank-summary.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetBankSummary = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_bank_summary',
+ classification: 'READ',
+ displayName: 'Get Bank Summary',
+ description: 'Runs the Bank Summary report: opening balance, cash in, cash out and closing balance per bank account.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Bank Summary report for a date range (defaults to the current month): one row per bank account with opening balance, cash received, cash spent and closing balance. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ from_date: Property.ShortText({ displayName: 'From Date (YYYY-MM-DD)', required: false }),
+ to_date: Property.ShortText({ displayName: 'To Date (YYYY-MM-DD)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ fromDate: xeroInput.parseDateInput({ value: values.from_date, field: 'From Date' }),
+ toDate: xeroInput.parseDateInput({ value: values.to_date, field: 'To Date' }),
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'BankSummary',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-contact.ts b/packages/pieces/community/xero/src/lib/actions/get-contact.ts
new file mode 100644
index 00000000000..68adcbdef4b
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-contact.ts
@@ -0,0 +1,40 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetContact = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_contact',
+ classification: 'READ',
+ displayName: 'Get Contact',
+ description: 'Gets one contact by ID, with addresses and phone numbers.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Fetches a single Xero contact by ContactID with its email, addresses, phones, status and whether it is a customer or supplier. Use Find Contact to look a contact up by name or email first. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.contact,
+ props: {
+ tenant_id: props.tenant_id,
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'The Xero ContactID (a GUID). Use Find Contact to get it.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const contactId = xeroInput.pathSegment({ value: context.propsValue.contact_id, field: 'Contact ID' });
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Contacts/${contactId}`,
+ operation: 'get contact',
+ });
+ return xeroApi.firstRecord({ body, key: 'Contacts', operation: 'get contact' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-executive-summary.ts b/packages/pieces/community/xero/src/lib/actions/get-executive-summary.ts
new file mode 100644
index 00000000000..8eb6ffad21d
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-executive-summary.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetExecutiveSummary = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_executive_summary',
+ classification: 'READ',
+ displayName: 'Get Executive Summary',
+ description: 'Runs the Executive Summary report: cash, profitability, balance sheet and performance ratios for a month.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Executive Summary report for the month containing a date (defaults to the current month), comparing it with the previous month: cash, income, expenses, receivables, payables and ratios. Needs a connection created with Xero piece 0.8.0 or later. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ date: Property.ShortText({ displayName: 'Month Date (YYYY-MM-DD)', description: 'Any date in the month to report on.', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ date: xeroInput.parseDateInput({ value: values.date, field: 'Month Date' }),
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'ExecutiveSummary',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-invoice-history.ts b/packages/pieces/community/xero/src/lib/actions/get-invoice-history.ts
index 9496aaf0e74..15e5772ad47 100644
--- a/packages/pieces/community/xero/src/lib/actions/get-invoice-history.ts
+++ b/packages/pieces/community/xero/src/lib/actions/get-invoice-history.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroGetInvoiceHistory = createAction({
auth: xeroAuth,
@@ -20,6 +21,7 @@ export const xeroGetInvoiceHistory = createAction({
'Retrieve the history and notes for a Xero invoice by its InvoiceID. Read-only and idempotent; returns HistoryRecords describing changes, the acting user, timestamps, and details.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.historyEnvelope,
props: {
tenant_id: props.tenant_id,
invoice_id: props.invoice_id(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/get-invoice.ts b/packages/pieces/community/xero/src/lib/actions/get-invoice.ts
new file mode 100644
index 00000000000..4db5d411e47
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-invoice.ts
@@ -0,0 +1,41 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetInvoice = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_invoice',
+ classification: 'READ',
+ displayName: 'Get Invoice',
+ description: 'Gets one invoice or bill by its ID or invoice number, including line items.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Fetches a single sales invoice or supplier bill by its Xero InvoiceID or its invoice number, with line items, totals, amounts due and paid. Use it when you already know which invoice you need; use Search Invoices to find invoices by contact, status or date. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.invoice,
+ props: {
+ tenant_id: props.tenant_id,
+ invoice_id: Property.ShortText({
+ displayName: 'Invoice ID or Number',
+ description: 'The Xero InvoiceID (a GUID) or the invoice number, for example INV-0042.',
+ required: true,
+ }),
+ },
+ async run(context) {
+ const invoiceId = xeroInput.pathSegment({ value: context.propsValue.invoice_id, field: 'Invoice ID or Number' });
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Invoices/${invoiceId}`,
+ queryParams: { unitdp: '4' },
+ operation: 'get invoice',
+ });
+ return xeroApi.firstRecord({ body, key: 'Invoices', operation: 'get invoice' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-organisation.ts b/packages/pieces/community/xero/src/lib/actions/get-organisation.ts
new file mode 100644
index 00000000000..634d2edb46d
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-organisation.ts
@@ -0,0 +1,35 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetOrganisation = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_organisation',
+ classification: 'READ',
+ displayName: 'Get Organisation Details',
+ description: 'Gets the settings of a Xero organisation, such as base currency, tax settings and financial year end.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Returns the selected Xero organisation\'s settings: name, base currency, country, timezone, tax defaults and financial year end. Use it before creating documents to pick the right currency or report period. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.organisation,
+ props: {
+ tenant_id: props.tenant_id,
+ },
+ async run(context) {
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Organisation`,
+ operation: 'get organisation',
+ });
+ const organisation = xeroApi.firstRecord({ body, key: 'Organisations', operation: 'get organisation' });
+ return Object.fromEntries(Object.entries(organisation).filter(([key]) => key !== 'APIKey'));
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-profit-and-loss.ts b/packages/pieces/community/xero/src/lib/actions/get-profit-and-loss.ts
new file mode 100644
index 00000000000..bc2b7403693
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-profit-and-loss.ts
@@ -0,0 +1,52 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetProfitAndLoss = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_profit_and_loss',
+ classification: 'READ',
+ displayName: 'Get Profit and Loss',
+ description: 'Runs the Profit and Loss report for a date range, with optional comparison periods.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Profit and Loss report for a date range (defaults to the current month) and returns it as flat rows with a section, a label and one value per column, optionally compared with earlier months, quarters or years. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ from_date: Property.ShortText({ displayName: 'From Date (YYYY-MM-DD)', required: false }),
+ to_date: Property.ShortText({ displayName: 'To Date (YYYY-MM-DD)', required: false }),
+ timeframe: Property.StaticDropdown({
+ displayName: 'Period Length',
+ description: 'Length of each comparison period.',
+ required: false,
+ options: { options: [{ label: 'Month', value: 'MONTH' }, { label: 'Quarter', value: 'QUARTER' }, { label: 'Year', value: 'YEAR' }] },
+ }),
+ periods: Property.Number({ displayName: 'Comparison Periods', description: 'Number of earlier periods to compare with, 1 to 11.', required: false }),
+ standard_layout: Property.Checkbox({ displayName: 'Standard Layout', description: 'Ignore custom report layouts.', required: false }),
+ payments_only: Property.Checkbox({ displayName: 'Cash Basis (Payments Only)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ fromDate: xeroInput.parseDateInput({ value: values.from_date, field: 'From Date' }),
+ toDate: xeroInput.parseDateInput({ value: values.to_date, field: 'To Date' }),
+ periods: xeroReports.periodsParam({ value: values.periods }),
+ timeframe: values.timeframe,
+ standardLayout: values.standard_layout,
+ paymentsOnly: values.payments_only,
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'ProfitAndLoss',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/get-trial-balance.ts b/packages/pieces/community/xero/src/lib/actions/get-trial-balance.ts
new file mode 100644
index 00000000000..003d0961af1
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/get-trial-balance.ts
@@ -0,0 +1,39 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { xeroInput } from '../common/client';
+import { xeroReports } from '../common/reports';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroGetTrialBalance = createAction({
+ auth: xeroAuth,
+ name: 'xero_get_trial_balance',
+ classification: 'READ',
+ displayName: 'Get Trial Balance',
+ description: 'Runs the Trial Balance report as at a date.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Runs the Trial Balance report as at a date (defaults to today): one row per account with debit, credit and year-to-date columns. Needs a connection created with Xero piece 0.8.0 or later (trial balance permission). Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.report,
+ props: {
+ tenant_id: props.tenant_id,
+ date: Property.ShortText({ displayName: 'As At Date (YYYY-MM-DD)', required: false }),
+ payments_only: Property.Checkbox({ displayName: 'Cash Basis (Payments Only)', required: false }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const params = {
+ date: xeroInput.parseDateInput({ value: values.date, field: 'As At Date' }),
+ paymentsOnly: values.payments_only,
+ };
+ return xeroReports.fetchReport({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ report: 'TrialBalance',
+ queryParams: xeroReports.definedParams({ params }),
+ });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/list-accounts.ts b/packages/pieces/community/xero/src/lib/actions/list-accounts.ts
new file mode 100644
index 00000000000..5ab0aad443a
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/list-accounts.ts
@@ -0,0 +1,72 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroListAccounts = createAction({
+ auth: xeroAuth,
+ name: 'xero_list_accounts',
+ classification: 'SEARCH',
+ displayName: 'List Accounts',
+ description: 'Lists the chart of accounts, optionally filtered by type, class or status.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists accounts from the chart of accounts with their code, name, type, class, tax type and whether payments are enabled, optionally filtered by type (e.g. BANK, REVENUE, EXPENSE), class or status. Use it to find the AccountCode for line items or the bank account for payments. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.accounts,
+ props: {
+ tenant_id: props.tenant_id,
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: false,
+ options: {
+ options: [
+ 'BANK', 'CURRENT', 'CURRLIAB', 'DEPRECIATN', 'DIRECTCOSTS', 'EQUITY', 'EXPENSE', 'FIXED', 'INVENTORY', 'LIABILITY',
+ 'NONCURRENT', 'OTHERINCOME', 'OVERHEADS', 'PREPAYMENT', 'REVENUE', 'SALES', 'TERMLIAB',
+ ].map((type) => ({ label: type, value: type })),
+ },
+ }),
+ account_class: Property.StaticDropdown({
+ displayName: 'Class',
+ required: false,
+ options: { options: ['ASSET', 'EQUITY', 'EXPENSE', 'LIABILITY', 'REVENUE'].map((value) => ({ label: value, value })) },
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ defaultValue: 'ACTIVE',
+ options: { options: [{ label: 'Active', value: 'ACTIVE' }, { label: 'Archived', value: 'ARCHIVED' }] },
+ }),
+ payments_enabled_only: Property.Checkbox({
+ displayName: 'Only Accounts That Accept Payments',
+ description: 'Keep only bank accounts and accounts with "Enable payments to this account" on.',
+ required: false,
+ defaultValue: false,
+ }),
+ },
+ async run(context) {
+ const { tenant_id, type, account_class, status, payments_enabled_only } = context.propsValue;
+ const where = [
+ ...(type ? [`Type==${xeroInput.whereString({ value: type })}`] : []),
+ ...(account_class ? [`Class==${xeroInput.whereString({ value: account_class })}`] : []),
+ ...(status ? [`Status==${xeroInput.whereString({ value: status })}`] : []),
+ ];
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Accounts`,
+ queryParams: { order: 'Code ASC', ...(where.length > 0 ? { where: where.join(' AND ') } : {}) },
+ operation: 'list accounts',
+ });
+ const accounts = xeroApi.recordsOf({ body, key: 'Accounts' });
+ const items = payments_enabled_only
+ ? accounts.filter((account) => account['Type'] === 'BANK' || account['EnablePaymentsToAccount'] === true)
+ : accounts;
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/list-organisations.ts b/packages/pieces/community/xero/src/lib/actions/list-organisations.ts
new file mode 100644
index 00000000000..98633bbcabb
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/list-organisations.ts
@@ -0,0 +1,24 @@
+import { createAction } from '@activepieces/pieces-framework';
+import { xeroAuth } from '../..';
+import { xeroApi } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroListOrganisations = createAction({
+ auth: xeroAuth,
+ name: 'xero_list_organisations',
+ classification: 'SEARCH',
+ displayName: 'List Organisations',
+ description: 'Lists the Xero organisations this connection can access.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists every Xero organisation (tenant) the connection was authorised for, with its tenant ID, name and type. Call this first when an action needs an Organisation ID and the connection may cover more than one organisation. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.organisations,
+ props: {},
+ async run(context) {
+ const items = await xeroApi.listTenants({ accessToken: context.auth.access_token });
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/list-tax-rates.ts b/packages/pieces/community/xero/src/lib/actions/list-tax-rates.ts
new file mode 100644
index 00000000000..0675af55c9f
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/list-tax-rates.ts
@@ -0,0 +1,43 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroListTaxRates = createAction({
+ auth: xeroAuth,
+ name: 'xero_list_tax_rates',
+ classification: 'SEARCH',
+ displayName: 'List Tax Rates',
+ description: 'Lists the tax rates of the organisation and the TaxType codes to use on line items.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the organisation\'s tax rates with the TaxType code to put on invoice, bill and transaction lines, the effective rate and which account types each applies to. Use it before creating documents with tax. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.taxRates,
+ props: {
+ tenant_id: props.tenant_id,
+ tax_type: Property.ShortText({ displayName: 'Tax Type', description: 'Only the rate with this TaxType code, e.g. OUTPUT.', required: false }),
+ active_only: Property.Checkbox({ displayName: 'Active Only', required: false, defaultValue: true }),
+ },
+ async run(context) {
+ const taxType = xeroInput.trimmedOrUndefined({ value: context.propsValue.tax_type });
+ const where = [
+ ...(taxType ? [`TaxType==${xeroInput.whereString({ value: taxType })}`] : []),
+ ...(context.propsValue.active_only === false ? [] : ['Status=="ACTIVE"']),
+ ];
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/TaxRates`,
+ queryParams: where.length > 0 ? { where: where.join(' AND ') } : {},
+ operation: 'list tax rates',
+ });
+ const items = xeroApi.recordsOf({ body, key: 'TaxRates' });
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/list-tracking-categories.ts b/packages/pieces/community/xero/src/lib/actions/list-tracking-categories.ts
new file mode 100644
index 00000000000..df1ef5bdd00
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/list-tracking-categories.ts
@@ -0,0 +1,37 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroListTrackingCategories = createAction({
+ auth: xeroAuth,
+ name: 'xero_list_tracking_categories',
+ classification: 'SEARCH',
+ displayName: 'List Tracking Categories',
+ description: 'Lists tracking categories (such as Region or Department) and their options.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Lists the organisation\'s tracking categories (for example Region or Department) with their options, which line items reference as Tracking {Name, Option}. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.trackingCategories,
+ props: {
+ tenant_id: props.tenant_id,
+ include_archived: Property.Checkbox({ displayName: 'Include Archived', required: false, defaultValue: false }),
+ },
+ async run(context) {
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/TrackingCategories`,
+ queryParams: context.propsValue.include_archived ? { includeArchived: 'true' } : {},
+ operation: 'list tracking categories',
+ });
+ const items = xeroApi.recordsOf({ body, key: 'TrackingCategories' });
+ return { items, count: items.length };
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/search-bank-transactions.ts b/packages/pieces/community/xero/src/lib/actions/search-bank-transactions.ts
new file mode 100644
index 00000000000..36b0a76deef
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/search-bank-transactions.ts
@@ -0,0 +1,81 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroSearchBankTransactions = createAction({
+ auth: xeroAuth,
+ name: 'xero_search_bank_transactions',
+ classification: 'SEARCH',
+ displayName: 'Search Bank Transactions',
+ description: 'Searches spend and receive money transactions by type, status, bank account, contact or date range.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches bank transactions (spend money, receive money, overpayments, prepayments, transfers) filtered by type, status, bank account ID, contact ID, reconciled flag or date range, newest first; returns one page with a hasMore flag. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.bankTransactionsPage,
+ props: {
+ tenant_id: props.tenant_id,
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ required: false,
+ options: {
+ options: ['RECEIVE', 'SPEND', 'RECEIVE-OVERPAYMENT', 'SPEND-OVERPAYMENT', 'RECEIVE-PREPAYMENT', 'SPEND-PREPAYMENT', 'RECEIVE-TRANSFER', 'SPEND-TRANSFER'].map(
+ (type) => ({ label: type, value: type }),
+ ),
+ },
+ }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: { options: [{ label: 'AUTHORISED', value: 'AUTHORISED' }, { label: 'DELETED', value: 'DELETED' }] },
+ }),
+ bank_account_id: Property.ShortText({ displayName: 'Bank Account ID', description: 'Xero AccountID of the bank account (List Accounts).', required: false }),
+ contact_id: Property.ShortText({ displayName: 'Contact ID', required: false }),
+ is_reconciled: Property.StaticDropdown({
+ displayName: 'Reconciled',
+ required: false,
+ options: { options: [{ label: 'Reconciled only', value: 'true' }, { label: 'Unreconciled only', value: 'false' }] },
+ }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),
+ page_size: Property.Number({ displayName: 'Page Size', description: 'Transactions per page, 1 to 100.', required: false, defaultValue: 100 }),
+ },
+ async run(context) {
+ const { tenant_id, type, status, bank_account_id, contact_id, is_reconciled, date_from, date_to, page, page_size } = context.propsValue;
+ const paging = xeroInput.pageParams({ page, pageSize: page_size, maxPageSize: 100 });
+ const from = xeroInput.parseDateInput({ value: date_from, field: 'Date From' });
+ const to = xeroInput.parseDateInput({ value: date_to, field: 'Date To' });
+ const bankAccountId = xeroInput.trimmedOrUndefined({ value: bank_account_id });
+ const contactId = xeroInput.trimmedOrUndefined({ value: contact_id });
+ const where = [
+ ...(type ? [`Type==${xeroInput.whereString({ value: type })}`] : []),
+ ...(status ? [`Status==${xeroInput.whereString({ value: status })}`] : []),
+ ...(bankAccountId ? [`BankAccount.AccountID==${xeroInput.whereGuid({ value: bankAccountId, field: 'Bank Account ID' })}`] : []),
+ ...(contactId ? [`Contact.ContactID==${xeroInput.whereGuid({ value: contactId, field: 'Contact ID' })}`] : []),
+ ...(is_reconciled === 'true' || is_reconciled === 'false' ? [`IsReconciled==${is_reconciled}`] : []),
+ ...(from ? [`Date>=${xeroInput.whereDate({ value: from })}`] : []),
+ ...(to ? [`Date<=${xeroInput.whereDate({ value: to })}`] : []),
+ ];
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/BankTransactions`,
+ queryParams: {
+ page: String(paging.page),
+ pageSize: String(paging.pageSize),
+ order: 'Date DESC',
+ unitdp: '4',
+ ...(where.length > 0 ? { where: where.join(' AND ') } : {}),
+ },
+ operation: 'search bank transactions',
+ });
+ return xeroApi.pageResult({ body, key: 'BankTransactions', ...paging });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/search-invoices.ts b/packages/pieces/community/xero/src/lib/actions/search-invoices.ts
new file mode 100644
index 00000000000..373fb64dff2
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/search-invoices.ts
@@ -0,0 +1,94 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroSearchInvoices = createAction({
+ auth: xeroAuth,
+ name: 'xero_search_invoices',
+ classification: 'SEARCH',
+ displayName: 'Search Invoices',
+ description: 'Searches sales invoices and bills by type, status, contact, date range or text, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches sales invoices (ACCREC) and supplier bills (ACCPAY) by type, statuses, contact ID, invoice date range or a free-text term, newest first, and returns one page with a hasMore flag; request the next page to continue. Use Get Invoice when you already have the ID or number. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.invoicesPage,
+ props: {
+ tenant_id: props.tenant_id,
+ type: Property.StaticDropdown({
+ displayName: 'Type',
+ description: 'Leave empty to include both sales invoices and bills.',
+ required: false,
+ options: {
+ options: [
+ { label: 'Sales invoice (ACCREC)', value: 'ACCREC' },
+ { label: 'Bill (ACCPAY)', value: 'ACCPAY' },
+ ],
+ },
+ }),
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses',
+ required: false,
+ options: {
+ options: ['DRAFT', 'SUBMITTED', 'AUTHORISED', 'PAID', 'VOIDED', 'DELETED'].map((status) => ({ label: status, value: status })),
+ },
+ }),
+ contact_id: Property.ShortText({
+ displayName: 'Contact ID',
+ description: 'Only invoices for this Xero ContactID. Use Find Contact to get it.',
+ required: false,
+ }),
+ date_from: Property.ShortText({ displayName: 'Invoice Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Invoice Date To (YYYY-MM-DD)', required: false }),
+ search_term: Property.ShortText({
+ displayName: 'Search Term',
+ description: 'Matches invoice number and reference (case-insensitive, partial).',
+ required: false,
+ }),
+ summary_only: Property.Checkbox({
+ displayName: 'Summary Only',
+ description: 'Leave on for faster results without line items; use Get Invoice for the full invoice.',
+ required: false,
+ defaultValue: true,
+ }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),
+ page_size: Property.Number({ displayName: 'Page Size', description: 'Invoices per page, 1 to 100.', required: false, defaultValue: 100 }),
+ },
+ async run(context) {
+ const { tenant_id, type, statuses, contact_id, date_from, date_to, search_term, summary_only, page, page_size } = context.propsValue;
+ const paging = xeroInput.pageParams({ page, pageSize: page_size, maxPageSize: 100 });
+ const from = xeroInput.parseDateInput({ value: date_from, field: 'Invoice Date From' });
+ const to = xeroInput.parseDateInput({ value: date_to, field: 'Invoice Date To' });
+ const contactId = xeroInput.trimmedOrUndefined({ value: contact_id });
+ const term = xeroInput.trimmedOrUndefined({ value: search_term });
+ const where = [
+ ...(type ? [`Type==${xeroInput.whereString({ value: type })}`] : []),
+ ...(from ? [`Date>=${xeroInput.whereDate({ value: from })}`] : []),
+ ...(to ? [`Date<=${xeroInput.whereDate({ value: to })}`] : []),
+ ];
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Invoices`,
+ queryParams: {
+ page: String(paging.page),
+ pageSize: String(paging.pageSize),
+ order: 'Date DESC',
+ unitdp: '4',
+ ...(summary_only === false ? {} : { summaryOnly: 'true' }),
+ ...(where.length > 0 ? { where: where.join(' AND ') } : {}),
+ ...(statuses && statuses.length > 0 ? { Statuses: statuses.join(',') } : {}),
+ ...(contactId ? { ContactIDs: contactId } : {}),
+ ...(term ? { searchTerm: term } : {}),
+ },
+ operation: 'search invoices',
+ });
+ return xeroApi.pageResult({ body, key: 'Invoices', ...paging });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/search-payments.ts b/packages/pieces/community/xero/src/lib/actions/search-payments.ts
new file mode 100644
index 00000000000..aedcd9391e0
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/search-payments.ts
@@ -0,0 +1,74 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroSearchPayments = createAction({
+ auth: xeroAuth,
+ name: 'xero_search_payments',
+ classification: 'SEARCH',
+ displayName: 'Search Payments',
+ description: 'Searches payments by invoice, status, payment type or date range, one page at a time.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Searches payments recorded against invoices, bills and credit notes, filtered by invoice ID, status, payment type, reference or payment date range, newest first; returns one page with a hasMore flag. Use it to check whether an invoice was paid or to find a PaymentID before Delete Payment. Read-only and idempotent.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.paymentsPage,
+ props: {
+ tenant_id: props.tenant_id,
+ invoice_id: Property.ShortText({ displayName: 'Invoice ID', description: 'Only payments on this Xero InvoiceID (a GUID).', required: false }),
+ status: Property.StaticDropdown({
+ displayName: 'Status',
+ required: false,
+ options: { options: [{ label: 'AUTHORISED', value: 'AUTHORISED' }, { label: 'DELETED', value: 'DELETED' }] },
+ }),
+ payment_type: Property.StaticDropdown({
+ displayName: 'Payment Type',
+ required: false,
+ options: {
+ options: ['ACCRECPAYMENT', 'ACCPAYPAYMENT', 'ARCREDITPAYMENT', 'APCREDITPAYMENT', 'AROVERPAYMENTPAYMENT', 'APOVERPAYMENTPAYMENT', 'ARPREPAYMENTPAYMENT', 'APPREPAYMENTPAYMENT'].map(
+ (type) => ({ label: type, value: type }),
+ ),
+ },
+ }),
+ reference: Property.ShortText({ displayName: 'Reference (exact)', required: false }),
+ date_from: Property.ShortText({ displayName: 'Payment Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Payment Date To (YYYY-MM-DD)', required: false }),
+ page: Property.Number({ displayName: 'Page', description: 'Page number, starting at 1.', required: false, defaultValue: 1 }),
+ page_size: Property.Number({ displayName: 'Page Size', description: 'Payments per page, 1 to 100.', required: false, defaultValue: 100 }),
+ },
+ async run(context) {
+ const { tenant_id, invoice_id, status, payment_type, reference, date_from, date_to, page, page_size } = context.propsValue;
+ const paging = xeroInput.pageParams({ page, pageSize: page_size, maxPageSize: 100 });
+ const from = xeroInput.parseDateInput({ value: date_from, field: 'Payment Date From' });
+ const to = xeroInput.parseDateInput({ value: date_to, field: 'Payment Date To' });
+ const invoiceId = xeroInput.trimmedOrUndefined({ value: invoice_id });
+ const ref = xeroInput.trimmedOrUndefined({ value: reference });
+ const where = [
+ ...(invoiceId ? [`Invoice.InvoiceID==${xeroInput.whereGuid({ value: invoiceId, field: 'Invoice ID' })}`] : []),
+ ...(status ? [`Status==${xeroInput.whereString({ value: status })}`] : []),
+ ...(payment_type ? [`PaymentType==${xeroInput.whereString({ value: payment_type })}`] : []),
+ ...(ref ? [`Reference==${xeroInput.whereString({ value: ref })}`] : []),
+ ...(from ? [`Date>=${xeroInput.whereDate({ value: from })}`] : []),
+ ...(to ? [`Date<=${xeroInput.whereDate({ value: to })}`] : []),
+ ];
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Payments`,
+ queryParams: {
+ page: String(paging.page),
+ pageSize: String(paging.pageSize),
+ order: 'Date DESC',
+ ...(where.length > 0 ? { where: where.join(' AND ') } : {}),
+ },
+ operation: 'search payments',
+ });
+ return xeroApi.pageResult({ body, key: 'Payments', ...paging });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/update-purchase-order.ts b/packages/pieces/community/xero/src/lib/actions/update-purchase-order.ts
index 49f3e62f64d..f4ce28f7b19 100644
--- a/packages/pieces/community/xero/src/lib/actions/update-purchase-order.ts
+++ b/packages/pieces/community/xero/src/lib/actions/update-purchase-order.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroUpdatePurchaseOrder = createAction({
auth: xeroAuth,
@@ -20,6 +21,7 @@ export const xeroUpdatePurchaseOrder = createAction({
'Update an existing Xero purchase order identified by its ID, changing fields such as status, delivery address/instructions, attention-to, telephone, or expected arrival date. Idempotent on a fixed purchase-order ID. To raise a new order use Create Purchase Order instead.',
idempotent: true,
},
+ outputSchema: xeroOutputSchemas.purchaseOrderEnvelope,
props: {
tenant_id: props.tenant_id,
purchase_order_id: props.purchase_order_id(true),
diff --git a/packages/pieces/community/xero/src/lib/actions/update-sales-invoice.ts b/packages/pieces/community/xero/src/lib/actions/update-sales-invoice.ts
index 39ffeb87446..69576913a8b 100644
--- a/packages/pieces/community/xero/src/lib/actions/update-sales-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/actions/update-sales-invoice.ts
@@ -7,6 +7,7 @@ import {
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroUpdateSalesInvoice = createAction({
auth: xeroAuth,
@@ -14,12 +15,13 @@ export const xeroUpdateSalesInvoice = createAction({
classification: 'WRITE',
displayName: 'Update Sales Invoice',
description: 'Updates details of an existing sales invoice (ACCREC).',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
- 'Update an existing ACCREC sales invoice identified by its ID, changing fields like reference, due date, status, contact, or line items. Idempotent on a fixed invoice ID. By default line-item changes merge into the existing lines (matching by LineItemID, appending new ones); enable Replace All Line Items to overwrite the full set instead. AUTHORISED invoices can only be edited when the allow-authorised flag is set.',
- idempotent: true,
+ 'Update an existing ACCREC sales invoice identified by its ID, changing fields like reference, due date, status, contact, or line items. By default line-item changes merge into the existing lines (matching by LineItemID, appending new ones); enable Replace All Line Items to overwrite the full set instead. AUTHORISED invoices can only be edited when the allow-authorised flag is set. Not idempotent when line items without a LineItemID are passed in merge mode, because each run appends them again; field-only changes converge.',
+ idempotent: false,
},
+ outputSchema: xeroOutputSchemas.invoiceEnvelope,
props: {
tenant_id: props.tenant_id,
allow_authorised: Property.Checkbox({
diff --git a/packages/pieces/community/xero/src/lib/actions/upload-attachment.ts b/packages/pieces/community/xero/src/lib/actions/upload-attachment.ts
index 23ab61904fd..2c5e346f10c 100644
--- a/packages/pieces/community/xero/src/lib/actions/upload-attachment.ts
+++ b/packages/pieces/community/xero/src/lib/actions/upload-attachment.ts
@@ -1,12 +1,15 @@
import { Property, createAction } from '@activepieces/pieces-framework';
import {
AuthenticationType,
+ HttpError,
HttpMethod,
HttpRequest,
httpClient,
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
import { props } from '../common/props';
+import { xeroAttachments } from '../common/attachments';
+import { xeroOutputSchemas } from '../output-schemas';
type ResourceType =
| 'Invoices'
@@ -27,17 +30,19 @@ export const xeroUploadAttachment = createAction({
classification: 'WRITE',
displayName: 'Upload Attachment',
description: 'Uploads an attachment to a specific Xero resource.',
- audience: 'both',
+ audience: 'human',
aiMetadata: {
description:
'Attach a file (max 10MB) to an existing Xero record such as an invoice, bill, credit note, purchase order, quote, contact, or bank transaction, selected by resource type and ID. Pick this to add supporting documents (receipts, PDFs) to an already-created record, not to create the record itself. Not idempotent: it appends a new attachment per call; IncludeOnline only applies to ACCREC invoices and credit notes.',
idempotent: false,
},
+ outputSchema: xeroOutputSchemas.attachmentEnvelope,
props: {
tenant_id: props.tenant_id,
resource_type: Property.StaticDropdown({
displayName: 'Resource Type',
- description: 'The Xero resource to attach the file to.',
+ description:
+ 'The Xero resource to attach the file to. Receipt works only on connections created before version 0.8.0.',
required: true,
options: {
options: [
@@ -50,7 +55,7 @@ export const xeroUploadAttachment = createAction({
{ label: 'Contact', value: 'Contacts' },
{ label: 'Account', value: 'Accounts' },
{ label: 'Manual Journal', value: 'ManualJournals' },
- { label: 'Receipt', value: 'Receipts' },
+ { label: 'Receipt (connections created before 0.8.0 only)', value: 'Receipts' },
{ label: 'Repeating Invoice', value: 'RepeatingInvoices' },
],
},
@@ -171,7 +176,19 @@ export const xeroUploadAttachment = createAction({
},
};
- const result = await httpClient.sendRequest<Record<string, any>>(request);
+ let result;
+ try {
+ result = await httpClient.sendRequest<Record<string, unknown[] | undefined>>(request);
+ } catch (error) {
+ if (resourceType === 'Receipts' && isMissingPermissionError({ error })) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: RECEIPTS_SCOPE_MESSAGE,
+ };
+ }
+ throw error;
+ }
if (result.status === 200) {
const items: any[] = result.body?.[cfg.arrayKey] ?? [];
const options = items.slice(0, 100).map((item) => ({
@@ -224,7 +241,7 @@ export const xeroUploadAttachment = createAction({
const endpoint = resource_type as string;
const chosenFileName = file_name || file.filename || `attachment${file.extension ? '.' + file.extension : ''}`;
- const inferredContentType = content_type || (file.extension ? `application/${file.extension}` : 'application/octet-stream');
+ const inferredContentType = content_type || xeroAttachments.mimeTypeFor({ fileName: chosenFileName, extension: file.extension });
const includeOnlineAllowed = resource_type === 'Invoices' || resource_type === 'CreditNotes';
const query = include_online && includeOnlineAllowed ? '?IncludeOnline=true' : '';
@@ -246,7 +263,15 @@ export const xeroUploadAttachment = createAction({
},
};
- const result = await httpClient.sendRequest(request);
+ let result;
+ try {
+ result = await httpClient.sendRequest(request);
+ } catch (error) {
+ if (resource_type === 'Receipts' && isMissingPermissionError({ error })) {
+ throw new Error(RECEIPTS_SCOPE_MESSAGE);
+ }
+ throw error;
+ }
if (result.status === 200) {
return result.body;
}
@@ -254,4 +279,11 @@ export const xeroUploadAttachment = createAction({
},
});
+const RECEIPTS_SCOPE_MESSAGE =
+ 'Xero refused access to Receipts (HTTP 401/403). Receipts need the accounting.classicexpenses permission, which Xero no longer grants to new connections. Only Xero connections created before Xero piece version 0.8.0 can attach files to Receipts; choose another resource type.';
+
+function isMissingPermissionError({ error }: { error: unknown }) {
+ return error instanceof HttpError && (error.response.status === 401 || error.response.status === 403);
+}
+
diff --git a/packages/pieces/community/xero/src/lib/actions/upsert-item.ts b/packages/pieces/community/xero/src/lib/actions/upsert-item.ts
new file mode 100644
index 00000000000..550fe1b2bd7
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/upsert-item.ts
@@ -0,0 +1,86 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroUpsertItem = createAction({
+ auth: xeroAuth,
+ name: 'xero_upsert_item',
+ classification: 'WRITE',
+ displayName: 'Create or Update Item',
+ description: 'Creates a product or service item, or updates the item that already has this code.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Creates or updates a Xero item (product or service) keyed by its Item Code, with sales and purchase prices, account codes and tax types; set an Inventory Asset Account Code and a COGS Account Code to make it a tracked inventory item. When updating, pass every sales or purchase price, account and tax field you want to keep, because Xero replaces each details block as a whole. Use Find Item to read an item. Idempotent on the code: Xero updates the item that already has this code instead of creating a duplicate.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.item,
+ props: {
+ tenant_id: props.tenant_id,
+ code: Property.ShortText({ displayName: 'Item Code', description: 'Unique code of the item (max 30 characters).', required: true }),
+ name: Property.ShortText({ displayName: 'Name', description: 'Item name (max 50 characters).', required: false }),
+ description: Property.LongText({ displayName: 'Sales Description', required: false }),
+ purchase_description: Property.LongText({ displayName: 'Purchase Description', required: false }),
+ is_sold: Property.Checkbox({ displayName: 'Is Sold', required: false }),
+ is_purchased: Property.Checkbox({ displayName: 'Is Purchased', required: false }),
+ sales_unit_price: Property.Number({ displayName: 'Sales Unit Price', description: 'Up to 4 decimal places.', required: false }),
+ sales_account_code: Property.ShortText({ displayName: 'Sales Account Code', description: 'Revenue account code, e.g. 200. Use List Accounts to find codes.', required: false }),
+ sales_tax_type: Property.ShortText({ displayName: 'Sales Tax Type', description: 'Tax type from List Tax Rates, e.g. OUTPUT.', required: false }),
+ purchase_unit_price: Property.Number({ displayName: 'Purchase Unit Price', description: 'Up to 4 decimal places.', required: false }),
+ purchase_account_code: Property.ShortText({ displayName: 'Purchase Account Code', description: 'Expense account code, e.g. 400. Not used for tracked inventory items.', required: false }),
+ purchase_tax_type: Property.ShortText({ displayName: 'Purchase Tax Type', description: 'Tax type from List Tax Rates, e.g. INPUT.', required: false }),
+ cogs_account_code: Property.ShortText({ displayName: 'COGS Account Code', description: 'Cost of goods sold account code; required for tracked inventory items.', required: false }),
+ inventory_asset_account_code: Property.ShortText({
+ displayName: 'Inventory Asset Account Code',
+ description: 'Inventory asset account code. Setting it makes the item a tracked inventory item.',
+ required: false,
+ }),
+ },
+ async run(context) {
+ const values = context.propsValue;
+ const code = xeroInput.requiredText({ value: values.code, field: 'Item Code' });
+ const text = (value: unknown) => xeroInput.trimmedOrUndefined({ value });
+ const salesPrice = xeroInput.optionalDecimal({ value: values.sales_unit_price, field: 'Sales Unit Price', maxDecimals: 4 });
+ const purchasePrice = xeroInput.optionalDecimal({ value: values.purchase_unit_price, field: 'Purchase Unit Price', maxDecimals: 4 });
+ const inventoryAccount = text(values.inventory_asset_account_code);
+ const cogsAccount = text(values.cogs_account_code);
+ if (inventoryAccount && !cogsAccount) {
+ throw new Error('A tracked inventory item needs a COGS Account Code as well as the Inventory Asset Account Code.');
+ }
+ const salesDetails = {
+ ...(salesPrice !== undefined ? { UnitPrice: salesPrice } : {}),
+ ...(text(values.sales_account_code) ? { AccountCode: text(values.sales_account_code) } : {}),
+ ...(text(values.sales_tax_type) ? { TaxType: text(values.sales_tax_type) } : {}),
+ };
+ const purchaseDetails = {
+ ...(purchasePrice !== undefined ? { UnitPrice: purchasePrice } : {}),
+ ...(text(values.purchase_account_code) ? { AccountCode: text(values.purchase_account_code) } : {}),
+ ...(cogsAccount ? { COGSAccountCode: cogsAccount } : {}),
+ ...(text(values.purchase_tax_type) ? { TaxType: text(values.purchase_tax_type) } : {}),
+ };
+ const item = {
+ Code: code,
+ ...(text(values.name) ? { Name: text(values.name) } : {}),
+ ...(text(values.description) ? { Description: text(values.description) } : {}),
+ ...(text(values.purchase_description) ? { PurchaseDescription: text(values.purchase_description) } : {}),
+ ...(typeof values.is_sold === 'boolean' ? { IsSold: values.is_sold } : {}),
+ ...(typeof values.is_purchased === 'boolean' ? { IsPurchased: values.is_purchased } : {}),
+ ...(Object.keys(salesDetails).length > 0 ? { SalesDetails: salesDetails } : {}),
+ ...(Object.keys(purchaseDetails).length > 0 ? { PurchaseDetails: purchaseDetails } : {}),
+ ...(inventoryAccount ? { InventoryAssetAccountCode: inventoryAccount, IsTrackedAsInventory: true } : {}),
+ };
+ const body = await xeroApi.request<unknown>({
+ accessToken: context.auth.access_token,
+ tenantId: values.tenant_id,
+ method: HttpMethod.POST,
+ url: `${XERO_URLS.api}/Items`,
+ queryParams: { unitdp: '4' },
+ body: { Items: [item] },
+ operation: 'create or update item',
+ });
+ return xeroApi.firstRecord({ body, key: 'Items', operation: 'create or update item' });
+ },
+});
diff --git a/packages/pieces/community/xero/src/lib/actions/void-invoice.ts b/packages/pieces/community/xero/src/lib/actions/void-invoice.ts
new file mode 100644
index 00000000000..9f1592af0c7
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/actions/void-invoice.ts
@@ -0,0 +1,64 @@
+import { createAction, Property } from '@activepieces/pieces-framework';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { xeroAuth } from '../..';
+import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput, xeroValue } from '../common/client';
+import { xeroOutputSchemas } from '../output-schemas';
+
+export const xeroVoidInvoice = createAction({
+ auth: xeroAuth,
+ name: 'xero_void_invoice',
+ classification: 'DESTRUCTIVE',
+ displayName: 'Void or Delete Invoice',
+ description: 'Voids an approved invoice or bill, or deletes it while it is still a draft or awaiting approval.',
+ audience: 'both',
+ aiMetadata: {
+ description:
+ 'Cancels an invoice or bill by InvoiceID: DRAFT and SUBMITTED invoices are deleted, AUTHORISED invoices are voided. Paid or part-paid invoices are refused; delete their payments first with Delete Payment. Idempotent: an invoice that is already voided or deleted is returned unchanged.',
+ idempotent: true,
+ },
+ outputSchema: xeroOutputSchemas.invoice,
+ props: {
+ tenant_id: props.tenant_id,
+ invoice_id: Property.ShortText({ displayName: 'Invoice ID', description: 'The Xero InvoiceID (a GUID) or invoice number.', required: true }),
+ },
+ async run(context) {
+ return voidInvoice({
+ accessToken: context.auth.access_token,
+ tenantId: context.propsValue.tenant_id,
+ invoiceId: xeroInput.requiredText({ value: context.propsValue.invoice_id, field: 'Invoice ID' }),
+ });
+ },
+});
+
+async function voidInvoice({ accessToken, tenantId, invoiceId }: { accessToken: string; tenantId: string; invoiceId: string }) {
+ const url = `${XERO_URLS.api}/Invoices/${encodeURIComponent(invoiceId)}`;
+ const current = xeroApi.firstRecord({
+ body: await xeroApi.request<unknown>({ accessToken, tenantId, method: HttpMethod.GET, url, queryParams: { unitdp: '4' }, operation: 'get invoice before voiding' }),
+ key: 'Invoices',
+ operation: 'get invoice before voiding',
+ });
+ const status = xeroValue.readString(current['Status']);
+ const target = targetStatus({ status, amountPaid: current['AmountPaid'], amountCredited: current['AmountCredited'] });
+ if (target === null) return current;
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.POST,
+ url,
+ queryParams: { unitdp: '4' },
+ body: { Invoices: [{ InvoiceID: current['InvoiceID'], Status: target }] },
+ operation: target === 'VOIDED' ? 'void invoice' : 'delete invoice',
+ });
+ return xeroApi.firstRecord({ body, key: 'Invoices', operation: 'void invoice' });
+}
+
+function targetStatus({ status, amountPaid, amountCredited }: { status: string | undefined; amountPaid: unknown; amountCredited: unknown }): 'VOIDED' | 'DELETED' | null {
+ if (status === 'VOIDED' || status === 'DELETED') return null;
+ if (status === 'DRAFT' || status === 'SUBMITTED') return 'DELETED';
+ if (status === 'PAID' || (typeof amountPaid === 'number' && amountPaid > 0) || (typeof amountCredited === 'number' && amountCredited > 0)) {
+ throw new Error('This invoice has payments or credit applied. Delete the payments (Delete Payment) or remove the allocations before voiding it.');
+ }
+ if (status === 'AUTHORISED') return 'VOIDED';
+ throw new Error(`Invoices with status ${status ?? 'unknown'} cannot be voided or deleted.`);
+}
diff --git a/packages/pieces/community/xero/src/lib/common/ai-props.ts b/packages/pieces/community/xero/src/lib/common/ai-props.ts
new file mode 100644
index 00000000000..832ddcedbd5
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/ai-props.ts
@@ -0,0 +1,180 @@
+import { Property } from '@activepieces/pieces-framework';
+import { xeroApi, xeroInput, xeroValue } from './client';
+
+function tenantIdProp() {
+ return Property.ShortText({
+ displayName: 'Organisation ID',
+ description:
+ 'Xero tenant ID of the organisation to use, from List Organisations. Leave empty when the connection has only one organisation.',
+ required: false,
+ });
+}
+
+function idProp({ displayName, description, required = true }: { displayName: string; description: string; required?: boolean }) {
+ return Property.ShortText({ displayName, description, required });
+}
+
+function lineItemsProp({ required = true }: { required?: boolean } = {}) {
+ return Property.Json({
+ displayName: 'Line Items',
+ description:
+ 'JSON array of line items, e.g. [{"Description":"Consulting","Quantity":2,"UnitAmount":150.5,"AccountCode":"200","TaxType":"OUTPUT"}]. Each line needs a Description or an ItemCode. Allowed keys: Description, Quantity, UnitAmount, LineAmount, AccountCode, ItemCode, TaxType, TaxAmount, DiscountRate, Tracking (array of {"Name","Option"}), LineItemID. Amounts keep up to 4 decimal places for UnitAmount and Quantity.',
+ required,
+ });
+}
+
+async function target({ accessToken, tenantId }: { accessToken: string; tenantId: unknown }) {
+ return { accessToken, tenantId: await xeroApi.resolveTenantId({ accessToken, tenantId }) };
+}
+
+function parseJsonArray({ value, field }: { value: unknown; field: string }): unknown[] {
+ const parsed = typeof value === 'string' ? safeJsonParse({ text: value, field }) : value;
+ if (!Array.isArray(parsed)) throw new Error(`${field} must be a JSON array.`);
+ return parsed;
+}
+
+function safeJsonParse({ text, field }: { text: string; field: string }): unknown {
+ try {
+ return JSON.parse(text);
+ } catch {
+ throw new Error(`${field} is not valid JSON.`);
+ }
+}
+
+function parseTracking({ value, field }: { value: unknown; field: string }) {
+ if (value === undefined || value === null) return undefined;
+ if (!Array.isArray(value)) throw new Error(`${field} must be an array of {"Name","Option"} objects.`);
+ return value.map((entry, index) => {
+ if (!xeroValue.isRecord(entry)) throw new Error(`${field}[${index}] must be an object.`);
+ const name = xeroValue.readString(entry['Name']);
+ const option = xeroValue.readString(entry['Option']);
+ const categoryId = xeroValue.readString(entry['TrackingCategoryID']);
+ const optionId = xeroValue.readString(entry['TrackingOptionID']);
+ if (!(name && option) && !(categoryId && optionId)) {
+ throw new Error(`${field}[${index}] needs Name and Option (or TrackingCategoryID and TrackingOptionID).`);
+ }
+ return {
+ ...(name ? { Name: name } : {}),
+ ...(option ? { Option: option } : {}),
+ ...(categoryId ? { TrackingCategoryID: categoryId } : {}),
+ ...(optionId ? { TrackingOptionID: optionId } : {}),
+ };
+ });
+}
+
+function rejectUnknownKeys({ entry, allowed, field }: { entry: Record<string, unknown>; allowed: string[]; field: string }) {
+ const unknown = Object.keys(entry).filter((key) => !allowed.includes(key));
+ if (unknown.length > 0) {
+ throw new Error(`${field} has unknown keys: ${unknown.join(', ')}. Allowed keys: ${allowed.join(', ')}.`);
+ }
+}
+
+function optionalText({ entry, key }: { entry: Record<string, unknown>; key: string }) {
+ const value = entry[key];
+ if (value === undefined || value === null || value === '') return {};
+ if (typeof value !== 'string' && typeof value !== 'number') throw new Error(`${key} must be text.`);
+ const text = String(value).trim();
+ return text.length > 0 ? { [key]: text } : {};
+}
+
+function optionalNumber({ entry, key, field, maxDecimals }: { entry: Record<string, unknown>; key: string; field: string; maxDecimals: number }) {
+ const parsed = xeroInput.optionalDecimal({ value: entry[key], field: `${field}.${key}`, maxDecimals });
+ return parsed === undefined ? {} : { [key]: parsed };
+}
+
+function parseLineItems({ value, field = 'Line Items', required = true }: { value: unknown; field?: string; required?: boolean }) {
+ if (!required && (value === undefined || value === null || value === '')) return undefined;
+ const entries = parseJsonArray({ value, field });
+ if (entries.length === 0) throw new Error(`${field} must contain at least one line.`);
+ if (entries.length > MAX_LINES) throw new Error(`${field} can contain at most ${MAX_LINES} lines.`);
+ return entries.map((entry, index) => {
+ const lineField = `${field}[${index}]`;
+ if (!xeroValue.isRecord(entry)) throw new Error(`${lineField} must be an object.`);
+ rejectUnknownKeys({ entry, allowed: LINE_ITEM_KEYS, field: lineField });
+ const line: Record<string, unknown> = {
+ ...optionalText({ entry, key: 'LineItemID' }),
+ ...optionalText({ entry, key: 'Description' }),
+ ...optionalNumber({ entry, key: 'Quantity', field: lineField, maxDecimals: 4 }),
+ ...optionalNumber({ entry, key: 'UnitAmount', field: lineField, maxDecimals: 4 }),
+ ...optionalNumber({ entry, key: 'LineAmount', field: lineField, maxDecimals: 2 }),
+ ...optionalText({ entry, key: 'AccountCode' }),
+ ...optionalText({ entry, key: 'ItemCode' }),
+ ...optionalText({ entry, key: 'TaxType' }),
+ ...optionalNumber({ entry, key: 'TaxAmount', field: lineField, maxDecimals: 2 }),
+ ...optionalNumber({ entry, key: 'DiscountRate', field: lineField, maxDecimals: 2 }),
+ };
+ const tracking = parseTracking({ value: entry['Tracking'], field: `${lineField}.Tracking` });
+ if (tracking) line['Tracking'] = tracking;
+ if (line['Description'] === undefined && line['ItemCode'] === undefined && line['LineItemID'] === undefined) {
+ throw new Error(`${lineField} needs a Description or an ItemCode.`);
+ }
+ return line;
+ });
+}
+
+function parseJournalLines({ value, field = 'Journal Lines' }: { value: unknown; field?: string }) {
+ const entries = parseJsonArray({ value, field });
+ if (entries.length < 2) throw new Error(`${field} needs at least two lines (a debit and a credit).`);
+ if (entries.length > MAX_LINES) throw new Error(`${field} can contain at most ${MAX_LINES} lines.`);
+ const lines = entries.map((entry, index) => {
+ const lineField = `${field}[${index}]`;
+ if (!xeroValue.isRecord(entry)) throw new Error(`${lineField} must be an object.`);
+ rejectUnknownKeys({ entry, allowed: JOURNAL_LINE_KEYS, field: lineField });
+ const amount = xeroInput.parseDecimal({ value: entry['LineAmount'], field: `${lineField}.LineAmount`, maxDecimals: 2 });
+ if (amount === 0) throw new Error(`${lineField}.LineAmount cannot be zero.`);
+ const line: Record<string, unknown> = {
+ LineAmount: amount,
+ ...optionalText({ entry, key: 'AccountCode' }),
+ ...optionalText({ entry, key: 'AccountID' }),
+ ...optionalText({ entry, key: 'Description' }),
+ ...optionalText({ entry, key: 'TaxType' }),
+ ...optionalNumber({ entry, key: 'TaxAmount', field: lineField, maxDecimals: 2 }),
+ };
+ if (line['AccountCode'] === undefined && line['AccountID'] === undefined) {
+ throw new Error(`${lineField} needs an AccountCode or an AccountID.`);
+ }
+ const tracking = parseTracking({ value: entry['Tracking'], field: `${lineField}.Tracking` });
+ if (tracking) line['Tracking'] = tracking;
+ return { line, amount };
+ });
+ const total = lines.reduce((sum, { amount }) => sum + xeroInput.toScaledInteger({ value: amount, decimals: 2 }), BigInt(0));
+ if (total !== BigInt(0)) {
+ const sign = total < BigInt(0) ? '-' : '';
+ const absolute = total < BigInt(0) ? -total : total;
+ const whole = absolute / BigInt(100);
+ const cents = (absolute % BigInt(100)).toString().padStart(2, '0');
+ throw new Error(
+ `${field} must balance: debits (positive LineAmount) and credits (negative LineAmount) must add up to 0, but they add up to ${sign}${whole}.${cents}.`,
+ );
+ }
+ return lines.map(({ line }) => line);
+}
+
+const MAX_LINES = 500;
+const LINE_ITEM_KEYS = [
+ 'LineItemID',
+ 'Description',
+ 'Quantity',
+ 'UnitAmount',
+ 'LineAmount',
+ 'AccountCode',
+ 'ItemCode',
+ 'TaxType',
+ 'TaxAmount',
+ 'DiscountRate',
+ 'Tracking',
+];
+const JOURNAL_LINE_KEYS = ['LineAmount', 'AccountCode', 'AccountID', 'Description', 'TaxType', 'TaxAmount', 'Tracking'];
+
+export const aiProps = {
+ tenantId: tenantIdProp,
+ id: idProp,
+ lineItems: lineItemsProp,
+};
+
+export const aiInput = {
+ target,
+ parseLineItems,
+ parseJournalLines,
+ parseJsonArray,
+};
diff --git a/packages/pieces/community/xero/src/lib/common/attachments.ts b/packages/pieces/community/xero/src/lib/common/attachments.ts
new file mode 100644
index 00000000000..97cc8aeb4f5
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/attachments.ts
@@ -0,0 +1,46 @@
+function mimeTypeFor({ fileName, extension }: { fileName: string; extension?: string }): string {
+ const fromName = fileName.includes('.') ? fileName.split('.').pop() : undefined;
+ const ext = (extension ?? fromName ?? '').replace(/^\./, '').toLowerCase();
+ return MIME_TYPES[ext] ?? 'application/octet-stream';
+}
+
+function sanitizeFileName({ value }: { value: string }): string {
+ const cleaned = value.replace(/[<>:"/\\|?*]/g, '_').trim();
+ if (cleaned.length === 0) throw new Error('File Name is empty after removing characters Xero does not allow.');
+ return cleaned;
+}
+
+const MIME_TYPES: Record<string, string> = {
+ pdf: 'application/pdf',
+ png: 'image/png',
+ jpg: 'image/jpeg',
+ jpeg: 'image/jpeg',
+ gif: 'image/gif',
+ bmp: 'image/bmp',
+ tif: 'image/tiff',
+ tiff: 'image/tiff',
+ webp: 'image/webp',
+ csv: 'text/csv',
+ txt: 'text/plain',
+ rtf: 'application/rtf',
+ xml: 'application/xml',
+ json: 'application/json',
+ doc: 'application/msword',
+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ xls: 'application/vnd.ms-excel',
+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ ppt: 'application/vnd.ms-powerpoint',
+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ odt: 'application/vnd.oasis.opendocument.text',
+ ods: 'application/vnd.oasis.opendocument.spreadsheet',
+ zip: 'application/zip',
+ eml: 'message/rfc822',
+ msg: 'application/vnd.ms-outlook',
+};
+
+export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
+
+export const xeroAttachments = {
+ mimeTypeFor,
+ sanitizeFileName,
+};
diff --git a/packages/pieces/community/xero/src/lib/common/client.ts b/packages/pieces/community/xero/src/lib/common/client.ts
new file mode 100644
index 00000000000..e42c0a0349b
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/client.ts
@@ -0,0 +1,364 @@
+import {
+ AuthenticationType,
+ HttpError,
+ HttpMethod,
+ HttpRequest,
+ QueryParams,
+ httpClient,
+} from '@activepieces/pieces-common';
+
+export class XeroApiError extends Error {
+ readonly status: number;
+ readonly responseBody: unknown;
+
+ constructor({ message, status, responseBody }: { message: string; status: number; responseBody: unknown }) {
+ super(message);
+ this.name = 'XeroApiError';
+ this.status = status;
+ this.responseBody = responseBody;
+ }
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
+}
+
+function readString(value: unknown): string | undefined {
+ return typeof value === 'string' && value.trim().length > 0 ? value : undefined;
+}
+
+function readRecords(value: unknown): Record<string, unknown>[] {
+ return Array.isArray(value) ? value.filter(isRecord) : [];
+}
+
+function wait({ ms }: { ms: number }) {
+ return new Promise<void>((resolve) => setTimeout(resolve, ms));
+}
+
+function validationMessages({ body }: { body: unknown }): string[] {
+ if (!isRecord(body)) return [];
+ const messages: string[] = [];
+ for (const element of readRecords(body['Elements'])) {
+ for (const error of readRecords(element['ValidationErrors'])) {
+ const message = readString(error['Message']);
+ if (message && !messages.includes(message)) messages.push(message);
+ }
+ }
+ return messages;
+}
+
+function describeXeroError({ status, body }: { status: number; body: unknown }): string {
+ const validation = validationMessages({ body });
+ if (validation.length > 0) return truncate({ text: validation.join('; '), max: MAX_ERROR_DETAIL_CHARS });
+ if (isRecord(body)) {
+ const parts = [readString(body['Message']), readString(body['Detail']), readString(body['Title']), readString(body['detail'])];
+ const found = parts.find((part) => part !== undefined);
+ if (found) return truncate({ text: found, max: MAX_ERROR_DETAIL_CHARS });
+ }
+ if (typeof body === 'string' && body.trim().length > 0) return truncate({ text: body.trim(), max: 300 });
+ return `HTTP ${status}`;
+}
+
+function truncate({ text, max }: { text: string; max: number }): string {
+ return text.length > max ? `${text.slice(0, max)}…` : text;
+}
+
+function boundedBody({ body }: { body: unknown }): unknown {
+ const serialized = typeof body === 'string' ? body : JSON.stringify(body ?? null);
+ return serialized.length > MAX_ERROR_BODY_CHARS ? truncate({ text: serialized, max: MAX_ERROR_BODY_CHARS }) : body;
+}
+
+function errorHint({ status }: { status: number }): string {
+ if (status === 401) {
+ return ' The Xero connection was rejected; reconnect it, and check that it was granted the permission this step needs.';
+ }
+ if (status === 403) {
+ return ' The connected Xero user or app is not allowed to do this for this organisation.';
+ }
+ if (status === 404) {
+ return ' Check the ID and the selected organisation.';
+ }
+ return '';
+}
+
+function toXeroError({ error, operation }: { error: HttpError; operation: string }): XeroApiError {
+ const status = error.response.status;
+ const body = error.response.body;
+ if (status === 429) {
+ return new XeroApiError({
+ message: `Xero rate limit reached during ${operation}: Xero allows 60 calls per minute and 5 concurrent calls per organisation (5,000 per day). Wait a minute and retry, or space out the steps.`,
+ status,
+ responseBody: boundedBody({ body }),
+ });
+ }
+ return new XeroApiError({
+ message: `Xero ${operation} failed (HTTP ${status}): ${describeXeroError({ status, body }).replace(/\.+$/, '')}.${errorHint({ status })}`,
+ status,
+ responseBody: boundedBody({ body }),
+ });
+}
+
+async function xeroRequest<T>({
+ accessToken,
+ tenantId,
+ method,
+ url,
+ body,
+ queryParams,
+ headers,
+ responseType,
+ timeout,
+ operation,
+}: XeroRequestParams): Promise<T> {
+ const request: HttpRequest = {
+ method,
+ url,
+ body,
+ queryParams,
+ responseType,
+ timeout,
+ authentication: { type: AuthenticationType.BEARER_TOKEN, token: accessToken },
+ headers: {
+ Accept: 'application/json',
+ ...(tenantId ? { 'Xero-Tenant-Id': tenantId } : {}),
+ ...(headers ?? {}),
+ },
+ };
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const response = await httpClient.sendRequest<T>(request);
+ return response.body;
+ } catch (error) {
+ if (!(error instanceof HttpError)) throw error;
+ if (error.response.status === 429 && attempt === 0) {
+ await wait({ ms: RATE_LIMIT_RETRY_MS });
+ continue;
+ }
+ throw toXeroError({ error, operation });
+ }
+ }
+}
+
+function requiredText({ value, field }: { value: unknown; field: string }): string {
+ const text = typeof value === 'number' ? String(value) : typeof value === 'string' ? value.trim() : '';
+ if (text.length === 0) throw new Error(`${field} is required.`);
+ return text;
+}
+
+function pathSegment({ value, field }: { value: unknown; field: string }): string {
+ return encodeURIComponent(requiredText({ value, field }));
+}
+
+function whereString({ value }: { value: string }): string {
+ return `"${value.replace(/"/g, '""')}"`;
+}
+
+function isGuid(value: unknown): boolean {
+ return typeof value === 'string' && GUID_PATTERN.test(value);
+}
+
+function whereGuid({ value, field }: { value: string; field: string }): string {
+ const trimmed = value.trim();
+ if (!GUID_PATTERN.test(trimmed)) throw new Error(`${field} must be a Xero ID (a GUID such as 00000000-0000-0000-0000-000000000000).`);
+ return `guid("${trimmed}")`;
+}
+
+function parseDateInput({ value, field }: { value: unknown; field: string }): string | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const text = typeof value === 'string' ? value.trim() : '';
+ const match = DATE_PATTERN.exec(text);
+ if (!match) throw new Error(`${field} must be a date in YYYY-MM-DD format.`);
+ const date = new Date(`${text}T00:00:00Z`);
+ if (Number.isNaN(date.getTime()) || date.toISOString().slice(0, 10) !== text) {
+ throw new Error(`${field} is not a valid calendar date.`);
+ }
+ return text;
+}
+
+function whereDate({ value }: { value: string }): string {
+ const [year, month, day] = value.split('-').map((part) => Number(part));
+ return `DateTime(${year}, ${month}, ${day})`;
+}
+
+function xeroDateToEpoch({ value }: { value: unknown }): number | undefined {
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
+ if (typeof value !== 'string') return undefined;
+ const match = /\/Date\((-?\d+)/.exec(value);
+ if (match) return Number(match[1]);
+ const parsed = Date.parse(value);
+ return Number.isNaN(parsed) ? undefined : parsed;
+}
+
+function parseDecimal({
+ value,
+ field,
+ maxDecimals,
+ positive,
+}: {
+ value: unknown;
+ field: string;
+ maxDecimals: number;
+ positive?: boolean;
+}): number {
+ const text = typeof value === 'number' ? (Number.isFinite(value) ? String(value) : '') : typeof value === 'string' ? value.trim() : '';
+ if (!DECIMAL_PATTERN.test(text)) throw new Error(`${field} must be a plain number such as 12.5.`);
+ const [whole, fraction = ''] = text.replace('-', '').split('.');
+ if (fraction.length > maxDecimals) throw new Error(`${field} can have at most ${maxDecimals} decimal places (got ${text}).`);
+ const significant = `${whole.replace(/^0+/, '')}${fraction}`.replace(/0+$/, '');
+ if (significant.length > 15) throw new Error(`${field} has more than 15 significant digits and cannot be sent exactly.`);
+ const parsed = Number(text);
+ if (positive && parsed <= 0) throw new Error(`${field} must be greater than zero.`);
+ return parsed;
+}
+
+function optionalDecimal(params: { value: unknown; field: string; maxDecimals: number; positive?: boolean }): number | undefined {
+ if (params.value === undefined || params.value === null || params.value === '') return undefined;
+ return parseDecimal(params);
+}
+
+function toScaledInteger({ value, decimals }: { value: number; decimals: number }): bigint {
+ const text = String(value);
+ if (!DECIMAL_PATTERN.test(text)) throw new Error(`Cannot represent ${text} exactly.`);
+ const negative = text.startsWith('-');
+ const [whole, fraction = ''] = text.replace('-', '').split('.');
+ if (fraction.length > decimals) throw new Error(`${text} has more than ${decimals} decimal places.`);
+ const scaled = BigInt(`${whole}${fraction.padEnd(decimals, '0')}`);
+ return negative ? -scaled : scaled;
+}
+
+async function listTenants({ accessToken }: { accessToken: string }): Promise<XeroTenant[]> {
+ const body = await xeroRequest<unknown>({
+ accessToken,
+ method: HttpMethod.GET,
+ url: XERO_URLS.connections,
+ operation: 'list connected organisations',
+ });
+ return readRecords(body).flatMap((entry) => {
+ const tenantId = readString(entry['tenantId']);
+ if (!tenantId) return [];
+ return [
+ {
+ tenantId,
+ tenantName: readString(entry['tenantName']) ?? null,
+ tenantType: readString(entry['tenantType']) ?? 'ORGANISATION',
+ connectionId: readString(entry['id']) ?? null,
+ createdDateUtc: readString(entry['createdDateUtc']) ?? null,
+ updatedDateUtc: readString(entry['updatedDateUtc']) ?? null,
+ },
+ ];
+ });
+}
+
+async function resolveTenantId({ accessToken, tenantId }: { accessToken: string; tenantId: unknown }): Promise<string> {
+ const given = typeof tenantId === 'string' ? tenantId.trim() : '';
+ if (given.length > 0) return given;
+ const tenants = await listTenants({ accessToken });
+ if (tenants.length === 1) return tenants[0].tenantId;
+ if (tenants.length === 0) {
+ throw new Error('No Xero organisation is connected. Reconnect the Xero connection and select an organisation.');
+ }
+ const list = tenants.map((tenant) => `${tenant.tenantName ?? 'Unnamed'} (${tenant.tenantId})`).join(', ');
+ throw new Error(`This connection has ${tenants.length} Xero organisations; set Organisation ID to one of: ${list}. List Organisations returns the same IDs.`);
+}
+
+function firstRecord({ body, key, operation }: { body: unknown; key: string; operation: string }): Record<string, unknown> {
+ const record = isRecord(body) ? readRecords(body[key])[0] : undefined;
+ if (!record) throw new Error(`Xero ${operation} returned no ${key} record.`);
+ return record;
+}
+
+function recordsOf({ body, key }: { body: unknown; key: string }): Record<string, unknown>[] {
+ return isRecord(body) ? readRecords(body[key]) : [];
+}
+
+function pageParams({ page, pageSize, maxPageSize }: { page: unknown; pageSize: unknown; maxPageSize: number }) {
+ const pageNumber = page === undefined || page === null || page === '' ? 1 : Number(page);
+ if (!Number.isInteger(pageNumber) || pageNumber < 1) throw new Error('Page must be a whole number of 1 or more.');
+ const size = pageSize === undefined || pageSize === null || pageSize === '' ? maxPageSize : Number(pageSize);
+ if (!Number.isInteger(size) || size < 1 || size > maxPageSize) {
+ throw new Error(`Page Size must be a whole number from 1 to ${maxPageSize}.`);
+ }
+ return { page: pageNumber, pageSize: size };
+}
+
+function pageResult({ body, key, page, pageSize }: { body: unknown; key: string; page: number; pageSize: number }) {
+ const items = recordsOf({ body, key });
+ const pagination = isRecord(body) && isRecord(body['pagination']) ? body['pagination'] : undefined;
+ const pageCount = pagination && typeof pagination['pageCount'] === 'number' ? pagination['pageCount'] : undefined;
+ const hasMore = pageCount !== undefined ? page < pageCount : items.length === pageSize;
+ return { items, page, pageSize, hasMore };
+}
+
+function trimmedOrUndefined({ value }: { value: unknown }): string | undefined {
+ if (typeof value !== 'string') return undefined;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+const GUID_PATTERN = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
+const DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/;
+const DECIMAL_PATTERN = /^-?\d+(\.\d+)?$/;
+
+export const xeroApi = {
+ request: xeroRequest,
+ listTenants,
+ resolveTenantId,
+ firstRecord,
+ recordsOf,
+ pageResult,
+ describeError: describeXeroError,
+};
+
+export const xeroInput = {
+ requiredText,
+ pathSegment,
+ whereString,
+ whereGuid,
+ whereDate,
+ parseDateInput,
+ parseDecimal,
+ optionalDecimal,
+ toScaledInteger,
+ pageParams,
+ trimmedOrUndefined,
+};
+
+export const xeroValue = {
+ isRecord,
+ isGuid,
+ readString,
+ readRecords,
+ xeroDateToEpoch,
+};
+
+const RATE_LIMIT_RETRY_MS = 30000;
+const MAX_ERROR_DETAIL_CHARS = 1000;
+const MAX_ERROR_BODY_CHARS = 4000;
+
+export const XERO_URLS = {
+ api: 'https://api.xero.com/api.xro/2.0',
+ projects: 'https://api.xero.com/projects.xro/2.0',
+ connections: 'https://api.xero.com/connections',
+};
+
+export type XeroTenant = {
+ tenantId: string;
+ tenantName: string | null;
+ tenantType: string;
+ connectionId: string | null;
+ createdDateUtc: string | null;
+ updatedDateUtc: string | null;
+};
+
+type XeroRequestParams = {
+ accessToken: string;
+ tenantId?: string;
+ method: HttpMethod;
+ url: string;
+ body?: unknown;
+ queryParams?: QueryParams;
+ headers?: Record<string, string>;
+ responseType?: HttpRequest['responseType'];
+ timeout?: number;
+ operation: string;
+};
diff --git a/packages/pieces/community/xero/src/lib/common/polling.ts b/packages/pieces/community/xero/src/lib/common/polling.ts
new file mode 100644
index 00000000000..48ffc1e5750
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/polling.ts
@@ -0,0 +1,251 @@
+import { createHash } from 'crypto';
+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';
+import { Store } from '@activepieces/pieces-framework';
+import { XERO_URLS, xeroApi, xeroInput, xeroValue } from './client';
+
+async function fetchUpdated({
+ accessToken,
+ tenantId,
+ url,
+ key,
+ queryParams,
+ lastFetchEpochMS,
+ pageSize,
+ paged = true,
+}: FetchParams & { lastFetchEpochMS: number; pageSize: number; paged?: boolean }): Promise<Record<string, unknown>[]> {
+ const records: Record<string, unknown>[] = [];
+ for (let page = 1; ; page++) {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.GET,
+ url,
+ queryParams: {
+ ...queryParams,
+ ...(paged ? { page: String(page), pageSize: String(pageSize) } : {}),
+ order: 'UpdatedDateUTC ASC',
+ },
+ headers: lastFetchEpochMS > 0 ? { 'If-Modified-Since': new Date(lastFetchEpochMS).toISOString().slice(0, 19) } : {},
+ operation: `poll ${key}`,
+ });
+ const pageRecords = xeroApi.recordsOf({ body, key });
+ records.push(...pageRecords);
+ if (!paged || pageRecords.length < pageSize) return records;
+ if (page < MAX_PAGES) continue;
+ const older = withoutNewestInstant({ records });
+ if (older.length > 0) return older;
+ if (page >= MAX_SAME_INSTANT_PAGES) {
+ throw new Error(
+ `More than ${records.length} ${key} records share the same UpdatedDateUTC, so this poll cannot advance without skipping some. Raise Page Size (up to 1000) and publish again: the cursor is kept, so the next poll reads past them.`,
+ );
+ }
+ }
+}
+
+function withoutNewestInstant({ records }: { records: Record<string, unknown>[] }): Record<string, unknown>[] {
+ const newest = records.reduce((max, record) => Math.max(max, epochOf({ record })), Number.NEGATIVE_INFINITY);
+ return records.filter((record) => epochOf({ record }) < newest);
+}
+
+function toItems({
+ records,
+ matches,
+}: {
+ records: Record<string, unknown>[];
+ matches?: (record: Record<string, unknown>) => boolean;
+}): { epochMilliSeconds: number; data: Record<string, unknown> | null }[] {
+ return records.map((record) => ({ epochMilliSeconds: epochOf({ record }), data: matches === undefined || matches(record) ? record : null }));
+}
+
+function fingerprint({ propsValue }: { propsValue: Record<string, unknown> }): string {
+ const sorted = Object.keys(propsValue)
+ .filter((key) => !CURSOR_NEUTRAL_PROPS.includes(key))
+ .sort()
+ .map((key) => [key, propsValue[key]]);
+ return createHash('sha256').update(JSON.stringify(sorted)).digest('hex').slice(0, 32);
+}
+
+async function keepStateOnRepublish({
+ store,
+ isRepublish,
+ propsValue,
+}: {
+ store: Store;
+ isRepublish: boolean | undefined;
+ propsValue: Record<string, unknown>;
+}): Promise<boolean> {
+ const current = fingerprint({ propsValue });
+ const previous = await store.get<unknown>(INPUTS_FINGERPRINT_KEY);
+ await store.put(INPUTS_FINGERPRINT_KEY, current);
+ const keep = isRepublish === true && (previous === null || previous === undefined || previous === current);
+ if (!keep) await store.delete(LAST_POLL_KEY);
+ return keep;
+}
+
+async function fetchRecent({ accessToken, tenantId, url, key, queryParams, paged = true }: FetchParams & { paged?: boolean }): Promise<Record<string, unknown>[]> {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.GET,
+ url,
+ queryParams: {
+ ...queryParams,
+ ...(paged ? { page: '1', pageSize: String(TEST_ITEM_LIMIT) } : {}),
+ order: 'UpdatedDateUTC DESC',
+ },
+ operation: `load recent ${key}`,
+ });
+ return xeroApi.recordsOf({ body, key }).slice(0, TEST_ITEM_LIMIT);
+}
+
+function epochOf({ record }: { record: Record<string, unknown> }): number {
+ return xeroValue.xeroDateToEpoch({ value: record['UpdatedDateUTC'] }) ?? xeroValue.xeroDateToEpoch({ value: record['Date'] }) ?? Date.now();
+}
+
+function pageSizeOf({ value, fallback, max }: { value: unknown; fallback: number; max: number }): number {
+ if (value === undefined || value === null || value === '') return fallback;
+ const size = Number(value);
+ if (!Number.isInteger(size) || size < 1 || size > max) throw new Error(`Page Size must be a whole number from 1 to ${max}.`);
+ return size;
+}
+
+function stringList({ value }: { value: unknown }): string[] {
+ return Array.isArray(value) ? value.filter((entry): entry is string => typeof entry === 'string' && entry.length > 0) : [];
+}
+
+function records({ items }: { items: unknown[] }): Record<string, unknown>[] {
+ return items.filter(xeroValue.isRecord);
+}
+
+function idOf({ record, key }: { record: Record<string, unknown>; key: string }): string | undefined {
+ return xeroValue.readString(record[key]);
+}
+
+function paymentRequest({
+ accessToken,
+ tenantId,
+ paymentTypes,
+ statuses,
+ invoiceId,
+ reference,
+ dateFrom,
+ dateTo,
+}: {
+ accessToken: string;
+ tenantId: string;
+ paymentTypes: unknown;
+ statuses: unknown;
+ invoiceId: unknown;
+ reference: unknown;
+ dateFrom: unknown;
+ dateTo: unknown;
+}) {
+ const types = paymentTypes === undefined || paymentTypes === null ? ['ACCRECPAYMENT'] : stringList({ value: paymentTypes });
+ const statusList = statuses === undefined || statuses === null ? ['AUTHORISED'] : stringList({ value: statuses });
+ const invoice = xeroInput.trimmedOrUndefined({ value: invoiceId });
+ const ref = xeroInput.trimmedOrUndefined({ value: reference });
+ const from = xeroInput.parseDateInput({ value: dateFrom, field: 'Date From' });
+ const to = xeroInput.parseDateInput({ value: dateTo, field: 'Date To' });
+ const where = [
+ ...anyOf({ field: 'PaymentType', values: types }),
+ ...anyOf({ field: 'Status', values: statusList }),
+ ...(invoice ? [`Invoice.InvoiceID==${xeroInput.whereGuid({ value: invoice, field: 'Invoice' })}`] : []),
+ ...(ref ? [`Reference==${xeroInput.whereString({ value: ref })}`] : []),
+ ...(from ? [`Date>=${xeroInput.whereDate({ value: from })}`] : []),
+ ...(to ? [`Date<${xeroInput.whereDate({ value: to })}`] : []),
+ ];
+ return {
+ accessToken,
+ tenantId,
+ url: `${XERO_URLS.api}/Payments`,
+ key: 'Payments',
+ queryParams: whereParams({ where }),
+ };
+}
+
+function anyOf({ field, values }: { field: string; values: string[] }): string[] {
+ if (values.length === 0) return [];
+ if (values.length === 1) return [`${field}==${xeroInput.whereString({ value: values[0] })}`];
+ return [`(${values.map((value) => `${field}==${xeroInput.whereString({ value })}`).join(' OR ')})`];
+}
+
+function quoteRequest({
+ accessToken,
+ tenantId,
+ statuses,
+ contactId,
+ quoteNumber,
+ dateFrom,
+ dateTo,
+ expiryDateFrom,
+ expiryDateTo,
+}: {
+ accessToken: string;
+ tenantId: string;
+ statuses: unknown;
+ contactId: unknown;
+ quoteNumber: unknown;
+ dateFrom: unknown;
+ dateTo: unknown;
+ expiryDateFrom: unknown;
+ expiryDateTo: unknown;
+}) {
+ const statusList = stringList({ value: statuses });
+ const contact = xeroInput.trimmedOrUndefined({ value: contactId });
+ const number = xeroInput.trimmedOrUndefined({ value: quoteNumber });
+ const params = {
+ ...(statusList.length === 1 ? { Status: statusList[0] } : {}),
+ ...(contact ? { ContactID: contact } : {}),
+ ...(number ? { QuoteNumber: number } : {}),
+ ...dateParam({ key: 'DateFrom', value: dateFrom, field: 'Date From' }),
+ ...dateParam({ key: 'DateTo', value: dateTo, field: 'Date To' }),
+ ...dateParam({ key: 'ExpiryDateFrom', value: expiryDateFrom, field: 'Expiry Date From' }),
+ ...dateParam({ key: 'ExpiryDateTo', value: expiryDateTo, field: 'Expiry Date To' }),
+ };
+ return {
+ request: { accessToken, tenantId, url: `${XERO_URLS.api}/Quotes`, key: 'Quotes', queryParams: params },
+ matches: (record: Record<string, unknown>) => statusList.length <= 1 || statusList.includes(String(record['Status'])),
+ };
+}
+
+function dateParam({ key, value, field }: { key: string; value: unknown; field: string }): Record<string, string> {
+ const date = xeroInput.parseDateInput({ value, field });
+ return date ? { [key]: date } : {};
+}
+
+function whereParams({ where }: { where: string[] }): QueryParams {
+ return where.length > 0 ? { where: where.join(' AND ') } : {};
+}
+
+const MAX_PAGES = 5;
+const MAX_SAME_INSTANT_PAGES = 50;
+const CURSOR_NEUTRAL_PROPS = ['page_size'];
+const INPUTS_FINGERPRINT_KEY = 'xero_trigger_inputs_fingerprint';
+const LAST_POLL_KEY = 'lastPoll';
+
+export const TEST_ITEM_LIMIT = 5;
+
+export const xeroPolling = {
+ whereParams,
+ fetchUpdated,
+ fetchRecent,
+ toItems,
+ fingerprint,
+ keepStateOnRepublish,
+ epochOf,
+ pageSizeOf,
+ stringList,
+ records,
+ idOf,
+ anyOf,
+ paymentRequest,
+ quoteRequest,
+};
+
+type FetchParams = {
+ accessToken: string;
+ tenantId: string;
+ url: string;
+ key: string;
+ queryParams: QueryParams;
+};
diff --git a/packages/pieces/community/xero/src/lib/common/props.ts b/packages/pieces/community/xero/src/lib/common/props.ts
index 7c6310767a1..873d6f82fd3 100644
--- a/packages/pieces/community/xero/src/lib/common/props.ts
+++ b/packages/pieces/community/xero/src/lib/common/props.ts
@@ -2,15 +2,43 @@ import { OAuth2PropertyValue, Property } from '@activepieces/pieces-framework';
import {
AuthenticationType,
HttpMethod,
+ HttpError,
HttpRequest,
httpClient,
} from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-export const props = {
- tenant_id: Property.Dropdown({
- auth: xeroAuth,
+export function buildTenantOptions({
+ connections,
+}: {
+ connections: XeroTenantConnection[] | null | undefined;
+}) {
+ const tenants = Array.isArray(connections)
+ ? connections.filter((connection) => typeof connection?.tenantId === 'string' && connection.tenantId.length > 0)
+ : [];
+ if (tenants.length === 0) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: 'No Xero organizations are connected. Reconnect and select at least one organization.',
+ };
+ }
+ const organisationsFirst = [
+ ...tenants.filter((tenant) => tenant.tenantType === 'ORGANISATION'),
+ ...tenants.filter((tenant) => tenant.tenantType !== 'ORGANISATION'),
+ ];
+ return {
+ disabled: false,
+ options: organisationsFirst.map((tenant) => ({
+ label: tenantLabel({ tenant }),
+ value: tenant.tenantId,
+ })),
+ };
+}
+export const props = {
+ tenant_id: Property.Dropdown({
+ auth: xeroAuth,
displayName: 'Organization',
refreshers: [],
required: true,
@@ -22,44 +50,26 @@ export const props = {
placeholder: 'Please authenticate first',
};
- const request: HttpRequest = {
- method: HttpMethod.GET,
- url: 'https://api.xero.com/connections',
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (auth as OAuth2PropertyValue).access_token,
- },
- };
-
- const result = await httpClient.sendRequest<
- {
- id: string;
- authEventId: string;
- tenantId: string;
- tenantType: string;
- tenantName: string;
- createdDateUtc: string;
- updatedDateUtc: string;
- }[]
- >(request);
-
- if (result.status === 200) {
- return {
- disabled: false,
- options: [
- {
- label: result.body?.[0].tenantName,
- value: result.body?.[0].tenantId,
- },
- ],
- };
+ try {
+ const result = await httpClient.sendRequest<XeroTenantConnection[]>({
+ method: HttpMethod.GET,
+ url: 'https://api.xero.com/connections',
+ authentication: {
+ type: AuthenticationType.BEARER_TOKEN,
+ token: auth.access_token,
+ },
+ });
+ return buildTenantOptions({ connections: result.body });
+ } catch (error) {
+ if (error instanceof HttpError) {
+ return {
+ disabled: true,
+ options: [],
+ placeholder: `Could not load Xero organizations (HTTP ${error.response.status}). Reconnect the Xero connection and try again.`,
+ };
+ }
+ throw error;
}
-
- return {
- disabled: true,
- options: [],
- placeholder: 'Error processing tenant_id',
- };
},
}),
invoice_id: (required = false) =>
@@ -70,7 +80,8 @@ export const props = {
description: 'Select an invoice',
required,
refreshers: ['tenant_id'],
- options: async ({ auth, propsValue, tenant_id }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, propsValue, tenant_id }, { searchValue }) => {
if (!auth)
return {
disabled: true,
@@ -92,7 +103,7 @@ export const props = {
const request: HttpRequest = {
method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1',
+ url: `https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1${searchParam({ searchValue })}`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: (auth as OAuth2PropertyValue).access_token,
@@ -105,7 +116,7 @@ export const props = {
const result = await httpClient.sendRequest<Record<string, any>>(request);
if (result.status === 200) {
const invoices: any[] = result.body?.Invoices ?? [];
- const options = invoices.slice(0, 50).map((inv) => {
+ const options = invoices.slice(0, 100).map((inv) => {
const labelParts = [inv.InvoiceNumber || inv.InvoiceID];
if (inv.Contact?.Name) labelParts.push(inv.Contact.Name);
if (inv.Status) labelParts.push(inv.Status);
@@ -132,7 +143,8 @@ export const props = {
description: 'Select an authorised invoice (sales or bill) to apply payment to.',
required,
refreshers: ['tenant_id'],
- options: async ({ auth, propsValue, tenant_id }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, propsValue, tenant_id }, { searchValue }) => {
if (!auth)
return {
disabled: true,
@@ -153,7 +165,7 @@ export const props = {
};
const url =
- 'https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=AUTHORISED';
+ `https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=AUTHORISED${searchParam({ searchValue })}`;
const request: HttpRequest = {
method: HttpMethod.GET,
@@ -170,7 +182,7 @@ export const props = {
const result = await httpClient.sendRequest<Record<string, any>>(request);
if (result.status === 200) {
const invoices: any[] = result.body?.Invoices ?? [];
- const options = invoices.slice(0, 50).map((inv) => {
+ const options = invoices.slice(0, 100).map((inv) => {
const labelParts = [
inv.Type,
inv.InvoiceNumber || inv.InvoiceID,
@@ -200,7 +212,8 @@ export const props = {
description: 'Select a sales invoice with a valid status for sending email (SUBMITTED, AUTHORISED, or PAID).',
required,
refreshers: ['tenant_id'],
- options: async ({ auth, propsValue, tenant_id }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, propsValue, tenant_id }, { searchValue }) => {
if (!auth)
return {
disabled: true,
@@ -221,7 +234,7 @@ export const props = {
};
const url =
- 'https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=SUBMITTED,AUTHORISED,PAID&where=Type%3d%3d%22ACCREC%22';
+ `https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=SUBMITTED,AUTHORISED,PAID&where=Type%3d%3d%22ACCREC%22${searchParam({ searchValue })}`;
const request: HttpRequest = {
method: HttpMethod.GET,
@@ -238,7 +251,7 @@ export const props = {
const result = await httpClient.sendRequest<Record<string, any>>(request);
if (result.status === 200) {
const invoices: any[] = result.body?.Invoices ?? [];
- const options = invoices.slice(0, 50).map((inv) => {
+ const options = invoices.slice(0, 100).map((inv) => {
const labelParts = [inv.InvoiceNumber || inv.InvoiceID];
if (inv.Contact?.Name) labelParts.push(inv.Contact.Name);
if (inv.Status) labelParts.push(inv.Status);
@@ -265,7 +278,8 @@ export const props = {
description: 'Select a sales invoice (ACCREC) with DRAFT or SUBMITTED status.',
required,
refreshers: ['tenant_id', 'allow_authorised'],
- options: async ({ auth, propsValue, tenant_id, allow_authorised }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, propsValue, tenant_id, allow_authorised }, { searchValue }) => {
if (!auth)
return {
disabled: true,
@@ -294,7 +308,7 @@ export const props = {
? 'DRAFT,SUBMITTED,AUTHORISED'
: 'DRAFT,SUBMITTED';
const url =
- `https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=${encodeURIComponent(statuses)}&where=Type%3d%3d%22ACCREC%22`;
+ `https://api.xero.com/api.xro/2.0/Invoices?summaryOnly=true&page=1&Statuses=${encodeURIComponent(statuses)}&where=Type%3d%3d%22ACCREC%22${searchParam({ searchValue })}`;
const request: HttpRequest = {
method: HttpMethod.GET,
@@ -311,7 +325,7 @@ export const props = {
const result = await httpClient.sendRequest<Record<string, any>>(request);
if (result.status === 200) {
const invoices: any[] = result.body?.Invoices ?? [];
- const options = invoices.slice(0, 50).map((inv) => {
+ const options = invoices.slice(0, 100).map((inv) => {
const labelParts = [inv.InvoiceNumber || inv.InvoiceID];
if (inv.Contact?.Name) labelParts.push(inv.Contact.Name);
if (inv.Status) labelParts.push(inv.Status);
@@ -407,7 +421,8 @@ export const props = {
description: 'Select a contact',
required,
refreshers: ['tenant_id'],
- options: async ({ auth, propsValue, tenant_id }) => {
+ refreshOnSearch: true,
+ options: async ({ auth, propsValue, tenant_id }, { searchValue }) => {
if (!auth)
return {
disabled: true,
@@ -429,7 +444,7 @@ export const props = {
const request: HttpRequest = {
method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Contacts?summaryOnly=true&page=1',
+ url: `https://api.xero.com/api.xro/2.0/Contacts?summaryOnly=true&page=1${searchParam({ searchValue })}`,
authentication: {
type: AuthenticationType.BEARER_TOKEN,
token: (auth as OAuth2PropertyValue).access_token,
@@ -472,12 +487,12 @@ export const props = {
description: 'Email address of the contact.',
required: required,
}),
- bank_account_id: (required = false) =>
+ bank_account_id: (required = false, labels: { displayName: string; description: string } = { displayName: 'Bank Account', description: 'Select a bank account' }) =>
Property.Dropdown({
auth: xeroAuth,
- displayName: 'Bank Account',
- description: 'Select a bank account',
+ displayName: labels.displayName,
+ description: labels.description,
required,
refreshers: ['tenant_id'],
options: async ({ auth, propsValue, tenant_id }) => {
@@ -843,3 +858,20 @@ export const props = {
},
}),
};
+
+function searchParam({ searchValue }: { searchValue?: string }): string {
+ const term = typeof searchValue === 'string' ? searchValue.trim() : '';
+ return term.length > 0 ? `&searchTerm=${encodeURIComponent(term)}` : '';
+}
+
+function tenantLabel({ tenant }: { tenant: XeroTenantConnection }) {
+ const name = tenant.tenantName && tenant.tenantName.trim().length > 0 ? tenant.tenantName : tenant.tenantId;
+ return tenant.tenantType === 'ORGANISATION' ? name : `${name} (${tenant.tenantType})`;
+}
+
+export type XeroTenantConnection = {
+ id: string;
+ tenantId: string;
+ tenantType: string;
+ tenantName: string | null;
+};
diff --git a/packages/pieces/community/xero/src/lib/common/reports.ts b/packages/pieces/community/xero/src/lib/common/reports.ts
new file mode 100644
index 00000000000..ab206175c64
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/reports.ts
@@ -0,0 +1,116 @@
+import { HttpMethod, QueryParams } from '@activepieces/pieces-common';
+import { XERO_URLS, xeroApi, xeroValue } from './client';
+
+function cellValue({ cell }: { cell: Record<string, unknown> }): string {
+ const value = cell['Value'];
+ return typeof value === 'string' ? value : value === undefined || value === null ? '' : String(value);
+}
+
+function attributeOf({ cells, id }: { cells: Record<string, unknown>[]; id: string }): string | null {
+ for (const cell of cells) {
+ const attribute = xeroValue.readRecords(cell['Attributes']).find((entry) => typeof entry['Id'] === 'string' && entry['Id'].toLowerCase() === id);
+ const value = attribute ? xeroValue.readString(attribute['Value']) : undefined;
+ if (value) return value;
+ }
+ return null;
+}
+
+function flattenRows({ rows, section }: { rows: Record<string, unknown>[]; section: string }): FlatReportRow[] {
+ return rows.flatMap((row) => {
+ const rowType = xeroValue.readString(row['RowType']) ?? 'Row';
+ if (rowType === 'Header') return [];
+ if (rowType === 'Section') {
+ const title = typeof row['Title'] === 'string' ? row['Title'] : '';
+ return flattenRows({ rows: xeroValue.readRecords(row['Rows']), section: title });
+ }
+ const cells = xeroValue.readRecords(row['Cells']);
+ const [first, ...rest] = cells;
+ return [
+ {
+ section,
+ rowType,
+ label: first ? cellValue({ cell: first }) : '',
+ values: rest.map((cell) => cellValue({ cell })),
+ accountId: attributeOf({ cells: first ? [first] : [], id: 'account' }),
+ invoiceId: attributeOf({ cells, id: 'invoiceid' }),
+ },
+ ];
+ });
+}
+
+function flattenReport({ body }: { body: unknown }): FlatReport {
+ const report = xeroApi.firstRecord({ body, key: 'Reports', operation: 'report' });
+ const rows = xeroValue.readRecords(report['Rows']);
+ const header = rows.find((row) => row['RowType'] === 'Header');
+ const titles = Array.isArray(report['ReportTitles']) ? report['ReportTitles'].filter((title): title is string => typeof title === 'string') : [];
+ return {
+ reportId: xeroValue.readString(report['ReportID']) ?? null,
+ reportName: xeroValue.readString(report['ReportName']) ?? null,
+ reportType: xeroValue.readString(report['ReportType']) ?? null,
+ reportDate: xeroValue.readString(report['ReportDate']) ?? null,
+ reportTitles: titles,
+ columns: header ? xeroValue.readRecords(header['Cells']).map((cell) => cellValue({ cell })) : [],
+ rows: flattenRows({ rows, section: '' }),
+ };
+}
+
+async function fetchReport({
+ accessToken,
+ tenantId,
+ report,
+ queryParams,
+}: {
+ accessToken: string;
+ tenantId: string;
+ report: string;
+ queryParams: QueryParams;
+}): Promise<FlatReport> {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/Reports/${report}`,
+ queryParams,
+ operation: `${report} report`,
+ });
+ return flattenReport({ body });
+}
+
+function definedParams({ params }: { params: Record<string, string | number | boolean | undefined | null> }): QueryParams {
+ return Object.fromEntries(
+ Object.entries(params).flatMap(([key, value]) => (value === undefined || value === null || value === '' ? [] : [[key, String(value)]])),
+ );
+}
+
+function periodsParam({ value }: { value: unknown }): number | undefined {
+ if (value === undefined || value === null || value === '') return undefined;
+ const periods = Number(value);
+ if (!Number.isInteger(periods) || periods < 1 || periods > 11) throw new Error('Comparison Periods must be a whole number from 1 to 11.');
+ return periods;
+}
+
+export const xeroReports = {
+ periodsParam,
+ fetchReport,
+ flattenReport,
+ definedParams,
+};
+
+export type FlatReportRow = {
+ section: string;
+ rowType: string;
+ label: string;
+ values: string[];
+ accountId: string | null;
+ invoiceId: string | null;
+};
+
+export type FlatReport = {
+ reportId: string | null;
+ reportName: string | null;
+ reportType: string | null;
+ reportDate: string | null;
+ reportTitles: string[];
+ columns: string[];
+ rows: FlatReportRow[];
+};
diff --git a/packages/pieces/community/xero/src/lib/common/samples.ts b/packages/pieces/community/xero/src/lib/common/samples.ts
new file mode 100644
index 00000000000..653071c2aaa
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/samples.ts
@@ -0,0 +1,131 @@
+const contact = { ContactID: '6d42f03b-181f-43e3-93fb-2025c012de92', Name: 'Acme Ltd', EmailAddress: '[email protected]' };
+
+const lineItem = {
+ LineItemID: '52208ff9-528a-4985-a9ad-b2b1d4210e38',
+ Description: 'Consulting services',
+ Quantity: 2,
+ UnitAmount: 250,
+ AccountCode: '200',
+ TaxType: 'OUTPUT',
+ TaxAmount: 75,
+ LineAmount: 500,
+ DiscountRate: 0,
+ Tracking: [],
+};
+
+const totals = { LineAmountTypes: 'Exclusive', SubTotal: 500, TotalTax: 75, Total: 575, CurrencyCode: 'USD', CurrencyRate: 1 };
+
+const invoice = {
+ InvoiceID: '4f7a5f8e-8e3c-4c4d-9b8a-0a1f2b3c4d5e',
+ InvoiceNumber: 'INV-0042',
+ Type: 'ACCREC',
+ Status: 'AUTHORISED',
+ Reference: 'PO-1001',
+ Contact: contact,
+ DateString: '2026-10-05T00:00:00',
+ DueDateString: '2026-10-19T00:00:00',
+ ...totals,
+ AmountDue: 575,
+ AmountPaid: 0,
+ AmountCredited: 0,
+ SentToContact: false,
+ HasAttachments: false,
+ LineItems: [lineItem],
+};
+
+export const xeroSamples = {
+ contact: {
+ ...contact,
+ FirstName: 'Jane',
+ LastName: 'Doe',
+ ContactStatus: 'ACTIVE',
+ IsCustomer: true,
+ IsSupplier: false,
+ DefaultCurrency: 'USD',
+ Phones: [{ PhoneType: 'DEFAULT', PhoneNumber: '5550100', PhoneAreaCode: '', PhoneCountryCode: '1' }],
+ Addresses: [{ AddressType: 'POBOX', AddressLine1: '1 Main Street', City: 'Springfield', Region: '', PostalCode: '12345', Country: 'US' }],
+ HasAttachments: false,
+ },
+ invoice,
+ bill: { ...invoice, InvoiceID: '8a7d3f0c-2b1e-4d5f-9c8b-7a6e5d4c3b2a', InvoiceNumber: 'SUP-77', Type: 'ACCPAY', Contact: { ...contact, Name: 'Office Mart' } },
+ payment: {
+ PaymentID: '0d666415-cf77-43fa-80c7-56775591d426',
+ Amount: 575,
+ BankAmount: 575,
+ CurrencyRate: 1,
+ Reference: 'INV-0042 payment',
+ Status: 'AUTHORISED',
+ PaymentType: 'ACCRECPAYMENT',
+ IsReconciled: false,
+ Invoice: { InvoiceID: invoice.InvoiceID, InvoiceNumber: invoice.InvoiceNumber, Type: 'ACCREC', Contact: contact },
+ Account: { AccountID: 'bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4', Code: '090', Name: 'Business Bank Account' },
+ },
+ bankTransaction: {
+ BankTransactionID: 'd20b6c54-7f5d-4ce6-ab83-55f609719126',
+ Type: 'RECEIVE',
+ Status: 'AUTHORISED',
+ Reference: 'Cash sale',
+ Contact: contact,
+ BankAccount: { AccountID: 'bd9e85e0-0478-433d-ae9f-0b3c4f04bfe4', Code: '090', Name: 'Business Bank Account' },
+ DateString: '2026-10-05T00:00:00',
+ IsReconciled: false,
+ ...totals,
+ LineItems: [lineItem],
+ },
+ creditNote: {
+ CreditNoteID: 'c1d2e3f4-a5b6-4c7d-8e9f-0a1b2c3d4e5f',
+ CreditNoteNumber: 'CN-0007',
+ Type: 'ACCRECCREDIT',
+ Status: 'AUTHORISED',
+ Reference: 'Refund for INV-0042',
+ Contact: contact,
+ DateString: '2026-10-05T00:00:00',
+ ...totals,
+ RemainingCredit: 575,
+ Allocations: [],
+ LineItems: [lineItem],
+ },
+ quote: {
+ QuoteID: 'a9b8c7d6-e5f4-4a3b-9c2d-1e0f9a8b7c6d',
+ QuoteNumber: 'QU-0012',
+ Reference: 'Website redesign',
+ Status: 'DRAFT',
+ Title: 'Website redesign',
+ Summary: 'Design and build of the new website',
+ Terms: 'Valid for 30 days',
+ Contact: contact,
+ DateString: '2026-10-05T00:00:00',
+ ExpiryDateString: '2026-11-04T00:00:00',
+ ...totals,
+ LineItems: [lineItem],
+ },
+ purchaseOrder: {
+ PurchaseOrderID: 'f0e1d2c3-b4a5-4968-8776-655443322110',
+ PurchaseOrderNumber: 'PO-0005',
+ Reference: 'Stock reorder',
+ Status: 'AUTHORISED',
+ Contact: { ...contact, Name: 'Office Mart' },
+ DateString: '2026-10-05T00:00:00',
+ DeliveryDateString: '2026-10-12T00:00:00',
+ DeliveryAddress: '1 Main Street, Springfield',
+ AttentionTo: 'Warehouse',
+ Telephone: '5550100',
+ DeliveryInstructions: 'Rear entrance',
+ SentToContact: false,
+ ...totals,
+ LineItems: [lineItem],
+ },
+ project: {
+ projectId: 'b7c8d9e0-f1a2-4b3c-8d4e-5f6a7b8c9d0e',
+ name: 'Website redesign',
+ contactId: contact.ContactID,
+ status: 'INPROGRESS',
+ currencyCode: 'USD',
+ deadlineUtc: '2026-12-31T00:00:00Z',
+ minutesLogged: 0,
+ estimate: { currency: 'USD', value: 5000 },
+ totalTaskAmount: { currency: 'USD', value: 0 },
+ totalInvoiced: { currency: 'USD', value: 0 },
+ totalToBeInvoiced: { currency: 'USD', value: 0 },
+ },
+};
diff --git a/packages/pieces/community/xero/src/lib/common/trigger-state.ts b/packages/pieces/community/xero/src/lib/common/trigger-state.ts
new file mode 100644
index 00000000000..7b0e629ce88
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/common/trigger-state.ts
@@ -0,0 +1,309 @@
+import { createHash, createHmac, randomUUID, timingSafeEqual } from 'crypto';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { Store, WebhookResponse } from '@activepieces/pieces-framework';
+import { XERO_URLS, XeroApiError, xeroApi, xeroValue } from './client';
+
+function mergeIds({ previous, ids, limit }: { previous: unknown; ids: string[]; limit: number }) {
+ const known = new Set(Array.isArray(previous) ? previous.filter((value): value is string => typeof value === 'string') : []);
+ const touched = [...new Set(ids)];
+ const newIds = touched.filter((id) => !known.has(id));
+ const touchedSet = new Set(touched);
+ const merged = [...[...known].filter((id) => !touchedSet.has(id)), ...touched];
+ return { newIds, stored: merged.slice(Math.max(merged.length - limit, 0)) };
+}
+
+async function emitFirstSeen<T>({
+ store,
+ key,
+ items,
+ idOf,
+ limit = SEEN_ID_LIMIT,
+}: {
+ store: Store;
+ key: string;
+ items: T[];
+ idOf: (item: T) => string | undefined;
+ limit?: number;
+}): Promise<T[]> {
+ const previous = await store.get<unknown>(key);
+ const known = new Set(Array.isArray(previous) ? previous.filter((value): value is string => typeof value === 'string') : []);
+ const emitted: T[] = [];
+ const batchIds = new Set<string>();
+ for (const item of items) {
+ const id = idOf(item);
+ if (!id || batchIds.has(id)) continue;
+ batchIds.add(id);
+ if (!known.has(id)) emitted.push(item);
+ }
+ const { stored } = mergeIds({ previous, ids: [...batchIds], limit });
+ await store.put(key, stored);
+ return emitted;
+}
+
+async function seedSeenIds({ store, key, ids, limit = SEEN_ID_LIMIT }: { store: Store; key: string; ids: string[]; limit?: number }) {
+ const { stored } = mergeIds({ previous: await store.get<unknown>(key), ids, limit });
+ await store.put(key, stored);
+}
+
+function boundMap<V>({ map, limit = SEEN_ID_LIMIT }: { map: Record<string, V>; limit?: number }): Record<string, V> {
+ const entries = Object.entries(map);
+ if (entries.length <= limit) return map;
+ return Object.fromEntries(entries.slice(entries.length - limit));
+}
+
+function readMap<V>({ value, isValue }: { value: unknown; isValue: (entry: unknown) => entry is V }): Record<string, V> {
+ if (!xeroValue.isRecord(value)) return {};
+ return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, V] => isValue(entry[1])));
+}
+
+function verifySignature({ webhookKey, rawBody, signature }: { webhookKey: unknown; rawBody: unknown; signature: unknown }): boolean {
+ if (typeof webhookKey !== 'string' || webhookKey.length === 0) return false;
+ if (typeof signature !== 'string' || signature.length === 0) return false;
+ const body = typeof rawBody === 'string' ? rawBody : Buffer.isBuffer(rawBody) ? rawBody : undefined;
+ if (body === undefined) return false;
+ const expected = createHmac('sha256', webhookKey).update(body).digest();
+ const received = Buffer.from(signature, 'base64');
+ return received.length === expected.length && timingSafeEqual(received, expected);
+}
+
+function continueToRun(): WebhookResponse;
+function continueToRun(): WebhookResponse | undefined {
+ return undefined;
+}
+
+async function handshake({ payload, webhookKey }: { payload: XeroWebhookPayload; webhookKey: unknown }): Promise<WebhookResponse> {
+ const valid = verifySignature({
+ webhookKey,
+ rawBody: payload.rawBody,
+ signature: headerValue({ headers: payload.headers, name: SIGNATURE_HEADER }),
+ });
+ if (!valid) return { status: 401 };
+ return continueToRun();
+}
+
+function headerValue({ headers, name }: { headers: Record<string, string>; name: string }): string | undefined {
+ const match = Object.keys(headers).find((key) => key.toLowerCase() === name);
+ return match ? headers[match] : undefined;
+}
+
+function readEvents({ body }: { body: unknown }): XeroWebhookEvent[] {
+ if (!xeroValue.isRecord(body)) return [];
+ return xeroValue.readRecords(body['events']).flatMap((event) => {
+ const resourceId = xeroValue.readString(event['resourceId']);
+ const tenantId = xeroValue.readString(event['tenantId']);
+ const eventCategory = xeroValue.readString(event['eventCategory']);
+ const eventType = xeroValue.readString(event['eventType']);
+ if (!resourceId || !xeroValue.isGuid(resourceId) || !tenantId || !eventCategory || !eventType) return [];
+ return [
+ {
+ resourceUrl: xeroValue.readString(event['resourceUrl']) ?? null,
+ resourceId,
+ eventDateUtc: xeroValue.readString(event['eventDateUtc']) ?? null,
+ eventType,
+ eventCategory,
+ tenantId,
+ tenantType: xeroValue.readString(event['tenantType']) ?? null,
+ },
+ ];
+ });
+}
+
+async function fetchResource({
+ accessToken,
+ event,
+ resource,
+}: {
+ accessToken: string;
+ event: XeroWebhookEvent;
+ resource: XeroWebhookResource;
+}): Promise<Record<string, unknown> | null> {
+ for (let attempt = 0; ; attempt++) {
+ try {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId: event.tenantId,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.api}/${resource.path}/${encodeURIComponent(event.resourceId)}`,
+ operation: `fetch ${resource.path} ${event.resourceId} for a webhook event`,
+ });
+ return xeroApi.recordsOf({ body, key: resource.path })[0] ?? null;
+ } catch (error) {
+ if (error instanceof XeroApiError && error.status === 404) return null;
+ const delay = webhookTiming.fetchRetryDelaysMs[attempt];
+ if (delay === undefined || !isTransient({ error })) throw error;
+ await pause({ ms: delay });
+ }
+ }
+}
+
+function isTransient({ error }: { error: unknown }): boolean {
+ if (!(error instanceof XeroApiError)) return true;
+ return error.status >= 500 || error.status === 408;
+}
+
+function pause({ ms }: { ms: number }): Promise<void> {
+ return ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) : Promise.resolve();
+}
+
+async function claimDelivery({ store, keys }: { store: Store; keys: string[] }): Promise<string | null> {
+ const claimKey = `${WEBHOOK_CLAIM_PREFIX}${createHash('sha256').update([...keys].sort().join('|')).digest('base64url').slice(0, 22)}`;
+ const token = randomUUID();
+ await store.put(claimKey, token);
+ await pause({ ms: webhookTiming.claimSettleMs });
+ return (await store.get<unknown>(claimKey)) === token ? claimKey : null;
+}
+
+async function processDelivery({
+ payload,
+ webhookKey,
+ tenantId,
+ accessToken,
+ store,
+ resource,
+ fetchFull,
+ accept,
+}: {
+ payload: XeroWebhookPayload;
+ webhookKey: unknown;
+ tenantId: unknown;
+ accessToken: string;
+ store: Store;
+ resource: XeroWebhookResource;
+ fetchFull: boolean;
+ accept?: (record: Record<string, unknown>) => boolean;
+}): Promise<unknown[]> {
+ const valid = verifySignature({
+ webhookKey,
+ rawBody: payload.rawBody,
+ signature: headerValue({ headers: payload.headers, name: SIGNATURE_HEADER }),
+ });
+ if (!valid) return [];
+ const events = readEvents({ body: payload.body }).filter(
+ (event) =>
+ event.eventCategory === resource.category &&
+ resource.eventTypes.includes(event.eventType) &&
+ (typeof tenantId !== 'string' || tenantId.length === 0 || event.tenantId === tenantId),
+ );
+ if (events.length === 0) return [];
+ const candidates = unseen({ events, seen: await readSeenEvents({ store, now: Date.now() }) });
+ if (candidates.size === 0) return [];
+ const claimKey = await claimDelivery({ store, keys: [...candidates.keys()] });
+ if (claimKey === null) return [];
+ const now = Date.now();
+ const fresh = unseen({ events: [...candidates.values()], seen: await readSeenEvents({ store, now }) });
+ try {
+ if (fresh.size === 0) return [];
+ await writeSeenEvents({ store, now, add: [...fresh.keys()] });
+ } finally {
+ await store.delete(claimKey);
+ }
+ try {
+ const results: unknown[] = [];
+ for (const event of fresh.values()) {
+ if (!fetchFull) {
+ results.push(event);
+ continue;
+ }
+ const record = await fetchResource({ accessToken, event, resource });
+ if (record && (accept === undefined || accept(record))) results.push(record);
+ }
+ return results;
+ } catch (error) {
+ await writeSeenEvents({ store, now, remove: [...fresh.keys()] });
+ throw error;
+ }
+}
+
+function unseen({ events, seen }: { events: XeroWebhookEvent[]; seen: Record<string, number> }): Map<string, XeroWebhookEvent> {
+ const fresh = new Map<string, XeroWebhookEvent>();
+ for (const event of events) {
+ const key = eventKey({ event });
+ if (seen[key] === undefined && !fresh.has(key)) fresh.set(key, event);
+ }
+ return fresh;
+}
+
+function eventKey({ event }: { event: XeroWebhookEvent }): string {
+ return createHash('sha256').update(`${event.tenantId}|${event.resourceId}|${event.eventType}|${event.eventDateUtc ?? ''}`).digest('base64url').slice(0, 22);
+}
+
+async function readSeenEvents({ store, now }: { store: Store; now: number }): Promise<Record<string, number>> {
+ const stored = readMap({ value: await store.get<unknown>(WEBHOOK_SEEN_KEY), isValue: (entry): entry is number => typeof entry === 'number' });
+ return Object.fromEntries(Object.entries(stored).filter(([, seenAt]) => now - seenAt < WEBHOOK_DEDUPE_WINDOW_MS));
+}
+
+async function writeSeenEvents({ store, now, add = [], remove = [] }: { store: Store; now: number; add?: string[]; remove?: string[] }) {
+ const current = await readSeenEvents({ store, now });
+ for (const key of remove) delete current[key];
+ for (const key of add) current[key] = now;
+ await store.put(WEBHOOK_SEEN_KEY, boundMap({ map: current, limit: WEBHOOK_SEEN_LIMIT }));
+}
+
+function instructions({ category }: { category: 'Contact' | 'Invoice' }): string {
+ return `
+This trigger needs a webhook on **your own Xero app** (the app whose Client ID and Secret this connection uses). Xero allows one delivery URL per app, so one app can feed only one flow, and connections made through a shared app (such as Activepieces Cloud's built-in Xero app) cannot set up webhooks.
+
+1. Publish this flow first, so the URL below is live.
+2. Go to Xero Developer > My Apps > [Your App] > Webhooks.
+3. Select the ${category} category.
+4. Set the Delivery URL to:
+\n\n\`\`\`text
+{{webhookUrl}}
+\`\`\`
+5. Copy the Webhook Key from the Webhooks page into the Webhook Key field below and publish again.
+6. Click Save, then "Send Intent to receive". This trigger answers Xero's check: 200 for a correctly signed request and 401 otherwise.
+
+Notes:
+- Only events for the selected organisation are used.
+- Every delivery's x-xero-signature header is checked with your Webhook Key; repeated deliveries of the same event are ignored.
+ `;
+}
+
+const SIGNATURE_HEADER = 'x-xero-signature';
+const WEBHOOK_SEEN_KEY = 'xero_webhook_seen_events';
+const WEBHOOK_DEDUPE_WINDOW_MS = 48 * 60 * 60 * 1000;
+const WEBHOOK_SEEN_LIMIT = 10000;
+const WEBHOOK_CLAIM_PREFIX = 'xero_webhook_claim_';
+
+export const webhookTiming = { claimSettleMs: 1500, fetchRetryDelaysMs: [2000, 5000] };
+
+export const SEEN_ID_LIMIT = 5000;
+
+export const xeroTriggerState = {
+ mergeIds,
+ emitFirstSeen,
+ seedSeenIds,
+ boundMap,
+ readMap,
+};
+
+export const xeroWebhook = {
+ verifySignature,
+ handshake,
+ processDelivery,
+ readEvents,
+ instructions,
+ handshakeConfiguration: { paramName: SIGNATURE_HEADER },
+};
+
+export type XeroWebhookPayload = {
+ body: unknown;
+ rawBody?: unknown;
+ headers: Record<string, string>;
+};
+
+export type XeroWebhookEvent = {
+ resourceUrl: string | null;
+ resourceId: string;
+ eventDateUtc: string | null;
+ eventType: string;
+ eventCategory: string;
+ tenantId: string;
+ tenantType: string | null;
+};
+
+export type XeroWebhookResource = {
+ category: 'CONTACT' | 'INVOICE';
+ path: 'Contacts' | 'Invoices';
+ eventTypes: string[];
+};
diff --git a/packages/pieces/community/xero/src/lib/output-schemas.ts b/packages/pieces/community/xero/src/lib/output-schemas.ts
new file mode 100644
index 00000000000..ad9e9e141d9
--- /dev/null
+++ b/packages/pieces/community/xero/src/lib/output-schemas.ts
@@ -0,0 +1,490 @@
+import { FieldFormat, OutputSchema, OutputSchemaField } from '@activepieces/pieces-framework';
+
+function field({ key, label, format, value }: { key: string; label: string; format?: FieldFormat; value?: string }): OutputSchemaField {
+ return { key, label, ...(format ? { format } : {}), ...(value !== undefined ? { value } : {}) };
+}
+
+function envelope({ key, label, fields, labelKey }: { key: string; label: string; fields: OutputSchemaField[]; labelKey: string }): OutputSchema {
+ return {
+ fields: [field({ key: 'Status', label: 'Response Status' }), { key, label, labelKey, listItems: fields }],
+ };
+}
+
+function itemsPage({ label, fields, labelKey, paged }: { label: string; fields: OutputSchemaField[]; labelKey: string; paged: boolean }): OutputSchema {
+ return {
+ fields: [
+ { key: 'items', label, labelKey, listItems: fields },
+ ...(paged
+ ? [
+ field({ key: 'page', label: 'Page', format: 'number' }),
+ field({ key: 'pageSize', label: 'Page Size', format: 'number' }),
+ field({ key: 'hasMore', label: 'Has More Pages', format: 'boolean' }),
+ ]
+ : [field({ key: 'count', label: 'Count', format: 'number' })]),
+ ],
+ };
+}
+
+const contactRefFields: OutputSchemaField[] = [
+ field({ key: 'ContactID', label: 'Contact ID' }),
+ field({ key: 'Name', label: 'Contact Name' }),
+ field({ key: 'EmailAddress', label: 'Contact Email', format: 'email' }),
+];
+
+const accountRefFields: OutputSchemaField[] = [
+ field({ key: 'AccountID', label: 'Account ID' }),
+ field({ key: 'Code', label: 'Account Code' }),
+ field({ key: 'Name', label: 'Account Name' }),
+];
+
+const trackingFields: OutputSchemaField[] = [
+ field({ key: 'Name', label: 'Tracking Category' }),
+ field({ key: 'Option', label: 'Tracking Option' }),
+];
+
+const lineItemFields: OutputSchemaField[] = [
+ field({ key: 'LineItemID', label: 'Line Item ID' }),
+ field({ key: 'Description', label: 'Description' }),
+ field({ key: 'Quantity', label: 'Quantity', format: 'number' }),
+ field({ key: 'UnitAmount', label: 'Unit Amount', format: 'number' }),
+ field({ key: 'ItemCode', label: 'Item Code' }),
+ field({ key: 'AccountCode', label: 'Account Code' }),
+ field({ key: 'TaxType', label: 'Tax Type' }),
+ field({ key: 'TaxAmount', label: 'Tax Amount', format: 'number' }),
+ field({ key: 'LineAmount', label: 'Line Amount', format: 'number' }),
+ field({ key: 'DiscountRate', label: 'Discount Rate (%)', format: 'number' }),
+ { key: 'Tracking', label: 'Tracking', labelKey: 'Name', listItems: trackingFields },
+];
+
+const totalsFields: OutputSchemaField[] = [
+ field({ key: 'LineAmountTypes', label: 'Line Amount Types' }),
+ field({ key: 'SubTotal', label: 'Subtotal', format: 'number' }),
+ field({ key: 'TotalTax', label: 'Total Tax', format: 'number' }),
+ field({ key: 'Total', label: 'Total', format: 'number' }),
+ field({ key: 'CurrencyCode', label: 'Currency' }),
+ field({ key: 'CurrencyRate', label: 'Currency Rate', format: 'number' }),
+];
+
+const invoiceFields: OutputSchemaField[] = [
+ field({ key: 'InvoiceID', label: 'Invoice ID' }),
+ field({ key: 'InvoiceNumber', label: 'Invoice Number' }),
+ field({ key: 'Type', label: 'Type (ACCREC sales / ACCPAY bill)' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ field({ key: 'DueDateString', label: 'Due Date', format: 'date' }),
+ ...totalsFields,
+ field({ key: 'AmountDue', label: 'Amount Due', format: 'number' }),
+ field({ key: 'AmountPaid', label: 'Amount Paid', format: 'number' }),
+ field({ key: 'AmountCredited', label: 'Amount Credited', format: 'number' }),
+ field({ key: 'SentToContact', label: 'Sent to Contact', format: 'boolean' }),
+ field({ key: 'BrandingThemeID', label: 'Branding Theme ID' }),
+ field({ key: 'Url', label: 'Source URL', format: 'url' }),
+ field({ key: 'HasAttachments', label: 'Has Attachments', format: 'boolean' }),
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const contactFields: OutputSchemaField[] = [
+ field({ key: 'ContactID', label: 'Contact ID' }),
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'FirstName', label: 'First Name' }),
+ field({ key: 'LastName', label: 'Last Name' }),
+ field({ key: 'EmailAddress', label: 'Email', format: 'email' }),
+ field({ key: 'ContactStatus', label: 'Status' }),
+ field({ key: 'IsCustomer', label: 'Is Customer', format: 'boolean' }),
+ field({ key: 'IsSupplier', label: 'Is Supplier', format: 'boolean' }),
+ field({ key: 'TaxNumber', label: 'Tax Number' }),
+ field({ key: 'DefaultCurrency', label: 'Default Currency' }),
+ {
+ key: 'Phones',
+ label: 'Phones',
+ labelKey: 'PhoneType',
+ listItems: [
+ field({ key: 'PhoneType', label: 'Type' }),
+ field({ key: 'PhoneNumber', label: 'Number' }),
+ field({ key: 'PhoneAreaCode', label: 'Area Code' }),
+ field({ key: 'PhoneCountryCode', label: 'Country Code' }),
+ ],
+ },
+ {
+ key: 'Addresses',
+ label: 'Addresses',
+ labelKey: 'AddressType',
+ listItems: [
+ field({ key: 'AddressType', label: 'Type' }),
+ field({ key: 'AddressLine1', label: 'Line 1' }),
+ field({ key: 'AddressLine2', label: 'Line 2' }),
+ field({ key: 'City', label: 'City' }),
+ field({ key: 'Region', label: 'Region' }),
+ field({ key: 'PostalCode', label: 'Postal Code' }),
+ field({ key: 'Country', label: 'Country' }),
+ ],
+ },
+ field({ key: 'HasAttachments', label: 'Has Attachments', format: 'boolean' }),
+];
+
+const paymentFields: OutputSchemaField[] = [
+ field({ key: 'PaymentID', label: 'Payment ID' }),
+ field({ key: 'Amount', label: 'Amount', format: 'number' }),
+ field({ key: 'BankAmount', label: 'Bank Amount', format: 'number' }),
+ field({ key: 'CurrencyRate', label: 'Currency Rate', format: 'number' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'PaymentType', label: 'Payment Type' }),
+ field({ key: 'IsReconciled', label: 'Is Reconciled', format: 'boolean' }),
+ {
+ key: 'Invoice',
+ label: 'Invoice',
+ children: [
+ field({ key: 'InvoiceID', label: 'Invoice ID' }),
+ field({ key: 'InvoiceNumber', label: 'Invoice Number' }),
+ field({ key: 'Type', label: 'Invoice Type' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ ],
+ },
+ { key: 'Account', label: 'Bank Account', children: accountRefFields },
+];
+
+const creditNoteFields: OutputSchemaField[] = [
+ field({ key: 'CreditNoteID', label: 'Credit Note ID' }),
+ field({ key: 'CreditNoteNumber', label: 'Credit Note Number' }),
+ field({ key: 'Type', label: 'Type' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ ...totalsFields,
+ field({ key: 'RemainingCredit', label: 'Remaining Credit', format: 'number' }),
+ {
+ key: 'Allocations',
+ label: 'Allocations',
+ listItems: [
+ field({ key: 'AllocationID', label: 'Allocation ID' }),
+ field({ key: 'Amount', label: 'Amount', format: 'number' }),
+ { key: 'Invoice', label: 'Invoice', children: [field({ key: 'InvoiceID', label: 'Invoice ID' }), field({ key: 'InvoiceNumber', label: 'Invoice Number' })] },
+ ],
+ },
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const allocationFields: OutputSchemaField[] = [
+ field({ key: 'AllocationID', label: 'Allocation ID' }),
+ field({ key: 'Amount', label: 'Amount', format: 'number' }),
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ { key: 'Invoice', label: 'Invoice', children: [field({ key: 'InvoiceID', label: 'Invoice ID' }), field({ key: 'InvoiceNumber', label: 'Invoice Number' })] },
+ { key: 'CreditNote', label: 'Credit Note', children: [field({ key: 'CreditNoteID', label: 'Credit Note ID' }), field({ key: 'CreditNoteNumber', label: 'Credit Note Number' })] },
+];
+
+const quoteFields: OutputSchemaField[] = [
+ field({ key: 'QuoteID', label: 'Quote ID' }),
+ field({ key: 'QuoteNumber', label: 'Quote Number' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Title', label: 'Title' }),
+ field({ key: 'Terms', label: 'Terms' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ field({ key: 'ExpiryDateString', label: 'Expiry Date', format: 'date' }),
+ ...totalsFields,
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const purchaseOrderFields: OutputSchemaField[] = [
+ field({ key: 'PurchaseOrderID', label: 'Purchase Order ID' }),
+ field({ key: 'PurchaseOrderNumber', label: 'Purchase Order Number' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ field({ key: 'Status', label: 'Status' }),
+ { key: 'Contact', label: 'Supplier', children: contactRefFields },
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ field({ key: 'DeliveryDateString', label: 'Delivery Date', format: 'date' }),
+ field({ key: 'DeliveryAddress', label: 'Delivery Address' }),
+ field({ key: 'AttentionTo', label: 'Attention To' }),
+ field({ key: 'Telephone', label: 'Telephone' }),
+ field({ key: 'DeliveryInstructions', label: 'Delivery Instructions' }),
+ field({ key: 'SentToContact', label: 'Sent to Contact', format: 'boolean' }),
+ ...totalsFields,
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const bankTransactionFields: OutputSchemaField[] = [
+ field({ key: 'BankTransactionID', label: 'Bank Transaction ID' }),
+ field({ key: 'Type', label: 'Type' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ { key: 'BankAccount', label: 'Bank Account', children: accountRefFields },
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ field({ key: 'IsReconciled', label: 'Is Reconciled', format: 'boolean' }),
+ field({ key: 'Url', label: 'Source URL', format: 'url' }),
+ ...totalsFields,
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const bankTransferFields: OutputSchemaField[] = [
+ field({ key: 'BankTransferID', label: 'Bank Transfer ID' }),
+ field({ key: 'Amount', label: 'Amount', format: 'number' }),
+ field({ key: 'DateString', label: 'Date', format: 'date' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ field({ key: 'CurrencyRate', label: 'Currency Rate', format: 'number' }),
+ { key: 'FromBankAccount', label: 'From Bank Account', children: accountRefFields },
+ { key: 'ToBankAccount', label: 'To Bank Account', children: accountRefFields },
+ field({ key: 'FromBankTransactionID', label: 'From Bank Transaction ID' }),
+ field({ key: 'ToBankTransactionID', label: 'To Bank Transaction ID' }),
+];
+
+const itemDetailsFields: OutputSchemaField[] = [
+ field({ key: 'UnitPrice', label: 'Unit Price', format: 'number' }),
+ field({ key: 'AccountCode', label: 'Account Code' }),
+ field({ key: 'COGSAccountCode', label: 'COGS Account Code' }),
+ field({ key: 'TaxType', label: 'Tax Type' }),
+];
+
+const itemFields: OutputSchemaField[] = [
+ field({ key: 'ItemID', label: 'Item ID' }),
+ field({ key: 'Code', label: 'Item Code' }),
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'Description', label: 'Sales Description' }),
+ field({ key: 'IsSold', label: 'Is Sold', format: 'boolean' }),
+ field({ key: 'IsPurchased', label: 'Is Purchased', format: 'boolean' }),
+ field({ key: 'IsTrackedAsInventory', label: 'Is Tracked as Inventory', format: 'boolean' }),
+ field({ key: 'InventoryAssetAccountCode', label: 'Inventory Asset Account Code' }),
+ field({ key: 'QuantityOnHand', label: 'Quantity on Hand', format: 'number' }),
+ field({ key: 'TotalCostPool', label: 'Total Cost Pool', format: 'number' }),
+ { key: 'SalesDetails', label: 'Sales Details', children: itemDetailsFields },
+ { key: 'PurchaseDetails', label: 'Purchase Details', children: itemDetailsFields },
+];
+
+const moneyFields: OutputSchemaField[] = [field({ key: 'currency', label: 'Currency' }), field({ key: 'value', label: 'Amount', format: 'number' })];
+
+const projectFields: OutputSchemaField[] = [
+ field({ key: 'projectId', label: 'Project ID' }),
+ field({ key: 'name', label: 'Name' }),
+ field({ key: 'contactId', label: 'Contact ID' }),
+ field({ key: 'status', label: 'Status' }),
+ field({ key: 'currencyCode', label: 'Currency' }),
+ field({ key: 'deadlineUtc', label: 'Deadline', format: 'datetime' }),
+ field({ key: 'minutesLogged', label: 'Minutes Logged', format: 'number' }),
+ { key: 'estimate', label: 'Estimate', children: moneyFields },
+ { key: 'totalTaskAmount', label: 'Total Task Amount', children: moneyFields },
+ { key: 'totalInvoiced', label: 'Total Invoiced', children: moneyFields },
+ { key: 'totalToBeInvoiced', label: 'Total To Be Invoiced', children: moneyFields },
+];
+
+const accountFields: OutputSchemaField[] = [
+ field({ key: 'AccountID', label: 'Account ID' }),
+ field({ key: 'Code', label: 'Code' }),
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Type', label: 'Type' }),
+ field({ key: 'Class', label: 'Class' }),
+ field({ key: 'TaxType', label: 'Tax Type' }),
+ field({ key: 'Description', label: 'Description' }),
+ field({ key: 'BankAccountType', label: 'Bank Account Type' }),
+ field({ key: 'BankAccountNumber', label: 'Bank Account Number' }),
+ field({ key: 'CurrencyCode', label: 'Currency' }),
+ field({ key: 'EnablePaymentsToAccount', label: 'Payments Enabled', format: 'boolean' }),
+ field({ key: 'ShowInExpenseClaims', label: 'Shown in Expense Claims', format: 'boolean' }),
+ field({ key: 'SystemAccount', label: 'System Account' }),
+ field({ key: 'ReportingCode', label: 'Reporting Code' }),
+ field({ key: 'ReportingCodeName', label: 'Reporting Code Name' }),
+];
+
+const taxRateFields: OutputSchemaField[] = [
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'TaxType', label: 'Tax Type' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'ReportTaxType', label: 'Report Tax Type' }),
+ field({ key: 'DisplayTaxRate', label: 'Display Rate (%)', format: 'number' }),
+ field({ key: 'EffectiveRate', label: 'Effective Rate (%)', format: 'number' }),
+ field({ key: 'CanApplyToRevenue', label: 'Applies to Revenue', format: 'boolean' }),
+ field({ key: 'CanApplyToExpenses', label: 'Applies to Expenses', format: 'boolean' }),
+ field({ key: 'CanApplyToAssets', label: 'Applies to Assets', format: 'boolean' }),
+ field({ key: 'CanApplyToLiabilities', label: 'Applies to Liabilities', format: 'boolean' }),
+ field({ key: 'CanApplyToEquity', label: 'Applies to Equity', format: 'boolean' }),
+ {
+ key: 'TaxComponents',
+ label: 'Tax Components',
+ labelKey: 'Name',
+ listItems: [
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'Rate', label: 'Rate (%)', format: 'number' }),
+ field({ key: 'IsCompound', label: 'Is Compound', format: 'boolean' }),
+ field({ key: 'IsNonRecoverable', label: 'Is Non-Recoverable', format: 'boolean' }),
+ ],
+ },
+];
+
+const trackingCategoryFields: OutputSchemaField[] = [
+ field({ key: 'TrackingCategoryID', label: 'Tracking Category ID' }),
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'Status', label: 'Status' }),
+ {
+ key: 'Options',
+ label: 'Options',
+ labelKey: 'Name',
+ listItems: [field({ key: 'TrackingOptionID', label: 'Option ID' }), field({ key: 'Name', label: 'Name' }), field({ key: 'Status', label: 'Status' })],
+ },
+];
+
+const organisationFields: OutputSchemaField[] = [
+ field({ key: 'OrganisationID', label: 'Organisation ID' }),
+ field({ key: 'Name', label: 'Name' }),
+ field({ key: 'LegalName', label: 'Legal Name' }),
+ field({ key: 'ShortCode', label: 'Short Code' }),
+ field({ key: 'BaseCurrency', label: 'Base Currency' }),
+ field({ key: 'CountryCode', label: 'Country Code' }),
+ field({ key: 'Timezone', label: 'Timezone' }),
+ field({ key: 'OrganisationType', label: 'Organisation Type' }),
+ field({ key: 'OrganisationStatus', label: 'Status' }),
+ field({ key: 'Class', label: 'Subscription Class' }),
+ field({ key: 'Edition', label: 'Edition' }),
+ field({ key: 'IsDemoCompany', label: 'Is Demo Company', format: 'boolean' }),
+ field({ key: 'PaysTax', label: 'Pays Tax', format: 'boolean' }),
+ field({ key: 'DefaultSalesTax', label: 'Default Sales Tax' }),
+ field({ key: 'DefaultPurchasesTax', label: 'Default Purchases Tax' }),
+ field({ key: 'FinancialYearEndDay', label: 'Financial Year End Day', format: 'number' }),
+ field({ key: 'FinancialYearEndMonth', label: 'Financial Year End Month', format: 'number' }),
+ field({ key: 'LineOfBusiness', label: 'Line of Business' }),
+];
+
+const tenantFields: OutputSchemaField[] = [
+ field({ key: 'tenantId', label: 'Organisation ID (Tenant ID)' }),
+ field({ key: 'tenantName', label: 'Name' }),
+ field({ key: 'tenantType', label: 'Type' }),
+ field({ key: 'connectionId', label: 'Connection ID' }),
+ field({ key: 'createdDateUtc', label: 'Connected At', format: 'datetime' }),
+ field({ key: 'updatedDateUtc', label: 'Updated At', format: 'datetime' }),
+];
+
+const manualJournalFields: OutputSchemaField[] = [
+ field({ key: 'ManualJournalID', label: 'Manual Journal ID' }),
+ field({ key: 'Narration', label: 'Narration' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'LineAmountTypes', label: 'Line Amount Types' }),
+ field({ key: 'ShowOnCashBasisReports', label: 'Show on Cash Basis Reports', format: 'boolean' }),
+ field({ key: 'Url', label: 'Source URL', format: 'url' }),
+ {
+ key: 'JournalLines',
+ label: 'Journal Lines',
+ labelKey: 'Description',
+ listItems: [
+ field({ key: 'LineAmount', label: 'Line Amount', format: 'number' }),
+ field({ key: 'AccountCode', label: 'Account Code' }),
+ field({ key: 'AccountID', label: 'Account ID' }),
+ field({ key: 'Description', label: 'Description' }),
+ field({ key: 'TaxType', label: 'Tax Type' }),
+ field({ key: 'TaxAmount', label: 'Tax Amount', format: 'number' }),
+ ],
+ },
+];
+
+const attachmentFields: OutputSchemaField[] = [
+ field({ key: 'AttachmentID', label: 'Attachment ID' }),
+ field({ key: 'FileName', label: 'File Name' }),
+ field({ key: 'Url', label: 'URL', format: 'url' }),
+ field({ key: 'MimeType', label: 'MIME Type' }),
+ field({ key: 'ContentLength', label: 'Size', format: 'filesize' }),
+ field({ key: 'IncludeOnline', label: 'Included Online', format: 'boolean' }),
+];
+
+const historyFields: OutputSchemaField[] = [
+ field({ key: 'Changes', label: 'Change' }),
+ field({ key: 'DateUTCString', label: 'Date', format: 'datetime' }),
+ field({ key: 'User', label: 'User' }),
+ field({ key: 'Details', label: 'Details' }),
+];
+
+const repeatingInvoiceFields: OutputSchemaField[] = [
+ field({ key: 'RepeatingInvoiceID', label: 'Repeating Invoice ID' }),
+ field({ key: 'Type', label: 'Type' }),
+ field({ key: 'Status', label: 'Status' }),
+ field({ key: 'Reference', label: 'Reference' }),
+ { key: 'Contact', label: 'Contact', children: contactRefFields },
+ {
+ key: 'Schedule',
+ label: 'Schedule',
+ children: [
+ field({ key: 'Period', label: 'Every (Period)', format: 'number' }),
+ field({ key: 'Unit', label: 'Unit' }),
+ field({ key: 'DueDate', label: 'Due Day', format: 'number' }),
+ field({ key: 'DueDateType', label: 'Due Date Type' }),
+ field({ key: 'NextScheduledDateString', label: 'Next Scheduled Date', format: 'date' }),
+ ],
+ },
+ field({ key: 'ApprovedForSending', label: 'Approved for Sending', format: 'boolean' }),
+ ...totalsFields,
+ { key: 'LineItems', label: 'Line Items', labelKey: 'Description', listItems: lineItemFields },
+];
+
+const reportSchema: OutputSchema = {
+ fields: [
+ field({ key: 'reportId', label: 'Report ID' }),
+ field({ key: 'reportName', label: 'Report Name' }),
+ field({ key: 'reportType', label: 'Report Type' }),
+ field({ key: 'reportDate', label: 'Report Date' }),
+ { key: 'reportTitles', label: 'Report Titles' },
+ { key: 'columns', label: 'Columns' },
+ {
+ key: 'rows',
+ label: 'Rows',
+ labelKey: 'label',
+ listItems: [
+ field({ key: 'section', label: 'Section' }),
+ field({ key: 'rowType', label: 'Row Type' }),
+ field({ key: 'label', label: 'Label' }),
+ { key: 'values', label: 'Values' },
+ field({ key: 'accountId', label: 'Account ID' }),
+ field({ key: 'invoiceId', label: 'Invoice ID' }),
+ ],
+ },
+ ],
+};
+
+export const xeroOutputSchemas = {
+ invoiceEnvelope: envelope({ key: 'Invoices', label: 'Invoices', fields: invoiceFields, labelKey: 'InvoiceNumber' }),
+ contactEnvelope: envelope({ key: 'Contacts', label: 'Contacts', fields: contactFields, labelKey: 'Name' }),
+ paymentEnvelope: envelope({ key: 'Payments', label: 'Payments', fields: paymentFields, labelKey: 'Reference' }),
+ creditNoteEnvelope: envelope({ key: 'CreditNotes', label: 'Credit Notes', fields: creditNoteFields, labelKey: 'CreditNoteNumber' }),
+ allocationEnvelope: envelope({ key: 'Allocations', label: 'Allocations', fields: allocationFields, labelKey: 'Amount' }),
+ quoteEnvelope: envelope({ key: 'Quotes', label: 'Quotes', fields: quoteFields, labelKey: 'QuoteNumber' }),
+ purchaseOrderEnvelope: envelope({ key: 'PurchaseOrders', label: 'Purchase Orders', fields: purchaseOrderFields, labelKey: 'PurchaseOrderNumber' }),
+ bankTransactionEnvelope: envelope({ key: 'BankTransactions', label: 'Bank Transactions', fields: bankTransactionFields, labelKey: 'Reference' }),
+ bankTransferEnvelope: envelope({ key: 'BankTransfers', label: 'Bank Transfers', fields: bankTransferFields, labelKey: 'Reference' }),
+ itemEnvelope: envelope({ key: 'Items', label: 'Items', fields: itemFields, labelKey: 'Code' }),
+ attachmentEnvelope: envelope({ key: 'Attachments', label: 'Attachments', fields: attachmentFields, labelKey: 'FileName' }),
+ repeatingInvoiceEnvelope: envelope({ key: 'RepeatingInvoices', label: 'Repeating Invoices', fields: repeatingInvoiceFields, labelKey: 'Reference' }),
+ historyEnvelope: envelope({ key: 'HistoryRecords', label: 'History Records', fields: historyFields, labelKey: 'Changes' }),
+ invoice: { fields: invoiceFields },
+ contact: { fields: contactFields },
+ payment: { fields: paymentFields },
+ creditNote: { fields: creditNoteFields },
+ allocation: { fields: allocationFields },
+ quote: { fields: quoteFields },
+ purchaseOrder: { fields: purchaseOrderFields },
+ bankTransaction: { fields: bankTransactionFields },
+ item: { fields: itemFields },
+ project: { fields: projectFields },
+ organisation: { fields: organisationFields },
+ manualJournal: { fields: manualJournalFields },
+ attachment: { fields: attachmentFields },
+ report: reportSchema,
+ organisations: itemsPage({ label: 'Organisations', fields: tenantFields, labelKey: 'tenantName', paged: false }),
+ accounts: itemsPage({ label: 'Accounts', fields: accountFields, labelKey: 'Name', paged: false }),
+ taxRates: itemsPage({ label: 'Tax Rates', fields: taxRateFields, labelKey: 'Name', paged: false }),
+ trackingCategories: itemsPage({ label: 'Tracking Categories', fields: trackingCategoryFields, labelKey: 'Name', paged: false }),
+ invoicesPage: itemsPage({ label: 'Invoices', fields: invoiceFields, labelKey: 'InvoiceNumber', paged: true }),
+ paymentsPage: itemsPage({ label: 'Payments', fields: paymentFields, labelKey: 'Reference', paged: true }),
+ bankTransactionsPage: itemsPage({ label: 'Bank Transactions', fields: bankTransactionFields, labelKey: 'Reference', paged: true }),
+ invoiceEmail: {
+ fields: [field({ key: 'success', label: 'Sent', format: 'boolean' }), field({ key: 'invoiceId', label: 'Invoice ID' })],
+ },
+ invoicePdf: {
+ fields: [
+ field({ key: 'file', label: 'PDF File', format: 'url' }),
+ field({ key: 'fileName', label: 'File Name' }),
+ field({ key: 'size', label: 'Size', format: 'filesize' }),
+ field({ key: 'invoiceId', label: 'Invoice ID' }),
+ ],
+ },
+};
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-bank-transaction.ts b/packages/pieces/community/xero/src/lib/triggers/new-bank-transaction.ts
index 309cd94e591..e6c7d7a5e23 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-bank-transaction.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-bank-transaction.ts
@@ -1,119 +1,67 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { XERO_URLS, xeroInput, xeroValue } from '../common/client';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
- AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const types = (propsValue?.['types'] as string[]) || [];
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const bankAccountId = propsValue?.['bank_account_id'] as string | undefined;
- const bankAccountCode = propsValue?.['bank_account_code'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
-
- const whereClauses: string[] = [];
- if (types.length === 1) whereClauses.push(`Type=="${types[0]}"`);
- if (contactId) whereClauses.push(`Contact.ContactID==guid("${contactId}")`);
- if (statuses.length === 1) whereClauses.push(`Status=="${statuses[0]}"`);
- if (statuses.length > 1) whereClauses.push(`(${statuses.map((s) => `Status=="${s}"`).join(' OR ')})`);
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
-
- if (bankAccountCode) {
- whereClauses.push(`BankAccount.Code=="${bankAccountCode.replace(/"/g, '\\"')}"`);
- }
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
-
- const requestHeaders: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- requestHeaders['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/BankTransactions',
- headers: requestHeaders,
- queryParams,
- });
-
- if (resp.status !== 200) {
- break;
- }
-
- const bankTxns: any[] = resp.body?.BankTransactions ?? [];
- let filtered = bankTxns;
- if (bankAccountId) {
- filtered = filtered.filter((t) => t?.BankAccount?.AccountID === bankAccountId);
- }
- if (bankAccountCode) {
- filtered = filtered.filter((t) => t?.BankAccount?.Code === bankAccountCode);
- }
-
- for (const t of filtered) {
- const epoch = parseXeroDateToEpoch(t.UpdatedDateUTC || t.Date);
- results.push({ epochMilliSeconds: epoch, data: t });
- }
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ types: Property.StaticMultiSelectDropdown({
+ displayName: 'Types',
+ required: false,
+ options: {
+ options: [
+ { label: 'RECEIVE', value: 'RECEIVE' },
+ { label: 'SPEND', value: 'SPEND' },
+ { label: 'RECEIVE-OVERPAYMENT', value: 'RECEIVE-OVERPAYMENT' },
+ { label: 'SPEND-OVERPAYMENT', value: 'SPEND-OVERPAYMENT' },
+ { label: 'RECEIVE-PREPAYMENT', value: 'RECEIVE-PREPAYMENT' },
+ { label: 'SPEND-PREPAYMENT', value: 'SPEND-PREPAYMENT' },
+ { label: 'RECEIVE-TRANSFER', value: 'RECEIVE-TRANSFER' },
+ { label: 'SPEND-TRANSFER', value: 'SPEND-TRANSFER' },
+ ],
+ },
+ }),
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses',
+ required: false,
+ options: {
+ options: [
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ }),
+ contact_id: props.contact_dropdown(false),
+ bank_account_id: props.bank_account_id(false),
+ bank_account_code: Property.ShortText({ displayName: 'Bank Account Code', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- if (bankTxns.length < pageSize) break;
- }
+type BankTransactionProps = StaticPropsValue<typeof triggerProps>;
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, BankTransactionProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...request({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ const kept = new Set(matching({ records, propsValue }));
+ return xeroPolling.toItems({ records, matches: (record) => kept.has(record) });
},
};
@@ -122,81 +70,78 @@ export const xeroNewBankTransaction = createTrigger({
name: 'xero_new_bank_transaction',
classification: 'READ',
displayName: 'New Bank Transaction',
- description: 'Fires when a new bank transaction is created.',
+ description: 'Fires the first time a bank transaction is created or changed after the trigger is turned on.',
aiMetadata: {
- description: 'Fires when a new bank transaction is created in the connected Xero organisation. Polls the Xero BankTransactions endpoint and emits each transaction the first time its BankTransactionID is seen, optionally filtered by type (RECEIVE/SPEND and their overpayment, prepayment, and transfer variants), status (AUTHORISED, DELETED), contact, bank account, or date range. Each item is a full bank transaction record (amount, type, date, line items, bank account). Represents a newly created transaction, not an update to one.',
+ description:
+ 'Fires once per bank transaction (spend or receive money, overpayment, prepayment or transfer) the first time it is seen after the trigger is enabled, optionally filtered by type, status, contact, bank account or date range. Xero records have no creation time, so a transaction created before enabling but edited afterwards also fires once. Each item is one full bank transaction.',
},
props: {
- tenant_id: props.tenant_id,
- types: Property.StaticMultiSelectDropdown({
- displayName: 'Types',
- required: false,
- options: {
- options: [
- { label: 'RECEIVE', value: 'RECEIVE' },
- { label: 'SPEND', value: 'SPEND' },
- { label: 'RECEIVE-OVERPAYMENT', value: 'RECEIVE-OVERPAYMENT' },
- { label: 'SPEND-OVERPAYMENT', value: 'SPEND-OVERPAYMENT' },
- { label: 'RECEIVE-PREPAYMENT', value: 'RECEIVE-PREPAYMENT' },
- { label: 'SPEND-PREPAYMENT', value: 'SPEND-PREPAYMENT' },
- { label: 'RECEIVE-TRANSFER', value: 'RECEIVE-TRANSFER' },
- { label: 'SPEND-TRANSFER', value: 'SPEND-TRANSFER' },
- ],
- },
- }),
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Statuses',
- required: false,
- options: {
- options: [
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- bank_account_id: props.bank_account_id(false),
- bank_account_code: Property.ShortText({ displayName: 'Bank Account Code', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ types: triggerProps.types,
+ statuses: triggerProps.statuses,
+ contact_id: triggerProps.contact_id,
+ bank_account_id: triggerProps.bank_account_id,
+ bank_account_code: triggerProps.bank_account_code,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.bankTransaction,
+ sampleData: xeroSamples.bankTransaction,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const records = await xeroPolling.fetchRecent(request({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
+ return matching({ records, propsValue: context.propsValue });
},
- async run(context: any) {
- const items = await pollingHelper.poll(polling, context);
- // Emit only first-time seen BankTransactionID to approximate "new" semantics
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_bank_txn_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
- const results: any[] = [];
- for (const it of items as any[]) {
- const id = it?.BankTransactionID;
- if (id && !seen.includes(id)) {
- results.push(it);
- seen.push(id);
- }
- }
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_bank_txn_seen_ids_${context.propsValue.tenant_id}`,
+ items,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'BankTransactionID' }),
+ });
},
- sampleData: undefined,
});
+function request({ accessToken, propsValue }: { accessToken: string; propsValue: BankTransactionProps }) {
+ const types = xeroPolling.stringList({ value: propsValue.types });
+ const statuses = xeroPolling.stringList({ value: propsValue.statuses });
+ const contactId = xeroInput.trimmedOrUndefined({ value: propsValue.contact_id });
+ const bankAccountCode = xeroInput.trimmedOrUndefined({ value: propsValue.bank_account_code });
+ const dateFrom = xeroInput.parseDateInput({ value: propsValue.date_from, field: 'Date From' });
+ const dateTo = xeroInput.parseDateInput({ value: propsValue.date_to, field: 'Date To' });
+ const where = [
+ ...(types.length === 1 ? [`Type==${xeroInput.whereString({ value: types[0] })}`] : []),
+ ...(contactId ? [`Contact.ContactID==${xeroInput.whereGuid({ value: contactId, field: 'Contact' })}`] : []),
+ ...(statuses.length > 0 ? [`(${statuses.map((status) => `Status==${xeroInput.whereString({ value: status })}`).join(' OR ')})`] : []),
+ ...(dateFrom ? [`Date>=${xeroInput.whereDate({ value: dateFrom })}`] : []),
+ ...(dateTo ? [`Date<${xeroInput.whereDate({ value: dateTo })}`] : []),
+ ...(bankAccountCode ? [`BankAccount.Code==${xeroInput.whereString({ value: bankAccountCode })}`] : []),
+ ];
+ return {
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ url: `${XERO_URLS.api}/BankTransactions`,
+ key: 'BankTransactions',
+ queryParams: xeroPolling.whereParams({ where }),
+ };
+}
+function matching({ records, propsValue }: { records: Record<string, unknown>[]; propsValue: BankTransactionProps }) {
+ const types = xeroPolling.stringList({ value: propsValue.types });
+ const bankAccountId = xeroInput.trimmedOrUndefined({ value: propsValue.bank_account_id });
+ return records.filter((record) => {
+ const bankAccount = record['BankAccount'];
+ const accountId = xeroValue.isRecord(bankAccount) ? bankAccount['AccountID'] : undefined;
+ const typeOk = types.length <= 1 || types.includes(String(record['Type']));
+ return typeOk && (bankAccountId === undefined || accountId === bankAccountId);
+ });
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-bill.ts b/packages/pieces/community/xero/src/lib/triggers/new-bill.ts
index a86993ebe28..f42d995277c 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-bill.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-bill.ts
@@ -1,109 +1,53 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { XERO_URLS, xeroInput } from '../common/client';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
- AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
- const summaryOnly = Boolean(propsValue?.['summary_only']);
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
-
- if (Array.isArray(statuses) && statuses.length > 0) {
- queryParams['Statuses'] = statuses.join(',');
- }
- if (contactId) {
- queryParams['ContactIDs'] = contactId;
- }
- if (summaryOnly) {
- queryParams['summaryOnly'] = 'true';
- }
-
- const whereClauses: string[] = ['Type=="ACCPAY"'];
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- headers['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Invoices',
- headers,
- queryParams,
- });
-
- if (resp.status !== 200) break;
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses (optional)',
+ required: false,
+ options: {
+ options: [
+ { label: 'DRAFT', value: 'DRAFT' },
+ { label: 'SUBMITTED', value: 'SUBMITTED' },
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'PAID', value: 'PAID' },
+ { label: 'VOIDED', value: 'VOIDED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ }),
+ contact_id: props.contact_dropdown(false),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ summary_only: Property.Checkbox({ displayName: 'Summary Only (lighter, faster)', required: false, defaultValue: true }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- const invoices: any[] = resp.body?.Invoices ?? [];
- for (const inv of invoices) {
- if (inv?.Type !== 'ACCPAY') continue;
- const epoch = parseXeroDateToEpoch(inv.UpdatedDateUTC || inv.Date);
- results.push({ epochMilliSeconds: epoch, data: inv });
- }
+type BillProps = StaticPropsValue<typeof triggerProps>;
- if (invoices.length < pageSize) break;
- }
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, BillProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...billRequest({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records, matches: (record) => record['Type'] === 'ACCPAY' });
},
};
@@ -112,69 +56,65 @@ export const xeroNewBill = createTrigger({
name: 'xero_new_bill',
classification: 'READ',
displayName: 'New Bill',
- description: 'Fires when a new bill (Accounts Payable) is added.',
+ description: 'Fires the first time a bill (Accounts Payable) is created or changed after the trigger is turned on.',
aiMetadata: {
- description: 'Fires when a new bill (Accounts Payable, Type ACCPAY) is added in the connected Xero organisation. Polls the Xero Invoices endpoint restricted to ACCPAY and emits each bill the first time its InvoiceID is seen, optionally filtered by status (DRAFT, SUBMITTED, AUTHORISED, PAID, VOIDED, DELETED), contact, or date range. Each item is a bill record (number, status, supplier contact, totals; line items unless summary-only). Excludes sales invoices and represents a newly added bill, not an update.',
+ description:
+ 'Fires once per supplier bill (Accounts Payable, Type ACCPAY) the first time it is seen after the trigger is enabled, optionally filtered by status, contact or date range; sales invoices are excluded. Xero records have no creation time, so a bill created before enabling but edited afterwards also fires once. Each item is one bill, without line items when Summary Only is on.',
},
props: {
- tenant_id: props.tenant_id,
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Statuses (optional)',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'SUBMITTED', value: 'SUBMITTED' },
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'PAID', value: 'PAID' },
- { label: 'VOIDED', value: 'VOIDED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- summary_only: Property.Checkbox({ displayName: 'Summary Only (lighter, faster)', required: false, defaultValue: true }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ statuses: triggerProps.statuses,
+ contact_id: triggerProps.contact_id,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ summary_only: triggerProps.summary_only,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.invoice,
+ sampleData: xeroSamples.bill,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const records = await xeroPolling.fetchRecent(billRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
+ return records.filter((record) => record['Type'] === 'ACCPAY');
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_bill_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
-
- const results: any[] = [];
- for (const inv of items) {
- const id = inv?.InvoiceID as string | undefined;
- if (!id) continue;
- if (!seen.includes(id)) {
- results.push(inv);
- seen.push(id);
- }
- }
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_bill_seen_ids_${context.propsValue.tenant_id}`,
+ items,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'InvoiceID' }),
+ });
},
- sampleData: undefined,
});
-
+function billRequest({ accessToken, propsValue }: { accessToken: string; propsValue: BillProps }) {
+ const statuses = xeroPolling.stringList({ value: propsValue.statuses });
+ const contactId = xeroInput.trimmedOrUndefined({ value: propsValue.contact_id });
+ const dateFrom = xeroInput.parseDateInput({ value: propsValue.date_from, field: 'Date From' });
+ const dateTo = xeroInput.parseDateInput({ value: propsValue.date_to, field: 'Date To' });
+ const where = [
+ 'Type=="ACCPAY"',
+ ...(dateFrom ? [`Date>=${xeroInput.whereDate({ value: dateFrom })}`] : []),
+ ...(dateTo ? [`Date<${xeroInput.whereDate({ value: dateTo })}`] : []),
+ ];
+ return {
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ url: `${XERO_URLS.api}/Invoices`,
+ key: 'Invoices',
+ queryParams: {
+ where: where.join(' AND '),
+ ...(statuses.length > 0 ? { Statuses: statuses.join(',') } : {}),
+ ...(contactId ? { ContactIDs: contactId } : {}),
+ ...(propsValue.summary_only ? { summaryOnly: 'true' } : {}),
+ },
+ };
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-contact.ts b/packages/pieces/community/xero/src/lib/triggers/new-contact.ts
index 40430c30921..68e55a43e64 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-contact.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-contact.ts
@@ -1,13 +1,9 @@
-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';
+import { Property, TriggerStrategy, WebhookHandshakeStrategy, createTrigger } from '@activepieces/pieces-framework';
import { xeroAuth } from '../..';
-import { createHmac } from 'crypto';
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroSamples } from '../common/samples';
+import { xeroWebhook } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroNewContact = createTrigger({
auth: xeroAuth,
@@ -16,29 +12,12 @@ export const xeroNewContact = createTrigger({
displayName: 'New Contact',
description: 'Fires when a new contact is added to Xero (via Xero webhooks). Configure the webhook in Xero Developer portal to point to this URL.',
aiMetadata: {
- description: 'Fires when a new contact (customer or supplier) is created in the connected Xero organisation. Delivered through a Xero webhook on the CONTACT category filtered to CREATE events; the verified payload event optionally enriched with the full contact record (name, email, addresses, contact ID) fetched from Xero. Represents a brand-new contact, not an update to an existing one.',
+ description:
+ 'Fires once per contact (customer or supplier) created in the connected Xero organisation, delivered by a Xero webhook (CONTACT category, CREATE events) that you set up on your own Xero app; deliveries are signature-checked and duplicates are dropped. Each item is the full contact, or the raw webhook event when Fetch Full Contact is off. Use New or Updated Contact to also fire on edits.',
},
type: TriggerStrategy.WEBHOOK,
props: {
- webhookInstructions: Property.MarkDown({
- value: `
-To use this trigger, manually configure a Xero webhook for your app:
-
-1. Go to Xero Developer > My Apps > [Your App] > Webhooks.
-2. Select the Contact category.
-3. Set the Delivery URL to:
-\n\n\`\`\`text
-{{webhookUrl}}
-\`\`\`
-4. Click Save, then click Validate "Intent to receive".
-5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.
-6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.
-
-Notes:
-- Keep this trigger enabled so the URL remains active.
-- We verify Xero's x-xero-signature header using your Webhook Key.
- `,
- }),
+ webhookInstructions: Property.MarkDown({ value: xeroWebhook.instructions({ category: 'Contact' }) }),
tenant_id: props.tenant_id,
webhook_key: Property.ShortText({
displayName: 'Webhook Key',
@@ -47,91 +26,35 @@ Notes:
}),
fetch_full_contact: Property.Checkbox({
displayName: 'Fetch Full Contact',
- description: 'If enabled, fetches the full contact from Xero using the Resource URL.',
+ description: 'If enabled, fetches the full contact from Xero. If disabled, the output is the raw webhook event (resourceId, eventType, eventDateUtc).',
required: false,
defaultValue: true,
}),
},
- sampleData: {
- ContactID: '717f2bfc-c6d4-41fd-b238-3f2f0c0cf777',
- Name: 'Sample Contact',
- EmailAddress: '[email protected]',
+ outputSchema: xeroOutputSchemas.contact,
+ sampleData: xeroSamples.contact,
+ handshakeConfiguration: {
+ strategy: WebhookHandshakeStrategy.HEADER_PRESENT,
+ paramName: xeroWebhook.handshakeConfiguration.paramName,
},
- async onEnable(context: any) {
- // Nothing to register programmatically. User must configure webhook in Xero Developer portal.
+ async onHandshake(context) {
+ return xeroWebhook.handshake({ payload: context.payload, webhookKey: context.propsValue.webhook_key });
},
- async onDisable(context: any) {
- // Nothing to clean up programmatically.
+ async onEnable() {
+ return;
},
- async run(context: any) {
- const { webhook_key, tenant_id, fetch_full_contact } = context.propsValue as any;
-
- const signatureHeader = context.payload.headers['x-xero-signature'] as string | undefined;
- const rawBody = context.payload.rawBody as string | undefined;
-
- if (!signatureHeader || !rawBody) {
- return [];
- }
-
- // Verify HMAC-SHA256 signature (base64)
- const computed = createHmac('sha256', webhook_key).update(rawBody).digest('base64');
- if (computed !== signatureHeader) {
- return [];
- }
-
- const body = context.payload.body as any;
- const events: any[] = body?.events ?? [];
- if (!Array.isArray(events) || events.length === 0) {
- // Intent to receive or empty payload
- return [];
- }
-
- // Filter to CONTACT CREATE events, optionally by tenant
- const filtered = events.filter((e) => {
- const isContact = e.eventCategory === 'CONTACT';
- const isCreate = e.eventType === 'CREATE';
- const tenantOk = tenant_id ? e.tenantId === tenant_id : true;
- return isContact && isCreate && tenantOk;
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ return xeroWebhook.processDelivery({
+ payload: context.payload,
+ webhookKey: context.propsValue.webhook_key,
+ tenantId: context.propsValue.tenant_id,
+ accessToken: context.auth.access_token,
+ store: context.store,
+ resource: { category: 'CONTACT', path: 'Contacts', eventTypes: ['CREATE'] },
+ fetchFull: context.propsValue.fetch_full_contact !== false,
});
-
- if (filtered.length === 0) {
- return [];
- }
-
- if (!fetch_full_contact) {
- return filtered;
- }
-
- // Fetch full contact for each event (best-effort)
- const results: any[] = [];
- for (const ev of filtered) {
- try {
- const req: HttpRequest = {
- method: HttpMethod.GET,
- url: ev.resourceUrl,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (context.auth as any).access_token,
- },
- headers: {
- 'Xero-Tenant-Id': ev.tenantId,
- Accept: 'application/json',
- },
- };
- const resp = await httpClient.sendRequest<any>(req);
- if (resp.status === 200) {
- const contact = resp.body?.Contacts?.[0] ?? resp.body;
- results.push(contact);
- } else {
- results.push(ev);
- }
- } catch {
- results.push(ev);
- }
- }
-
- return results;
},
});
-
-
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-credit-note.ts b/packages/pieces/community/xero/src/lib/triggers/new-credit-note.ts
index fbc70ffa8dc..1e202abc056 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-credit-note.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-credit-note.ts
@@ -1,105 +1,61 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { XERO_URLS, xeroInput } from '../common/client';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const types = (propsValue?.['types'] as string[]) || [];
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const reference = propsValue?.['reference'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
-
- const whereClauses: string[] = [];
- if (types.length === 1) whereClauses.push(`Type=="${types[0]}"`);
- if (statuses.length === 1) whereClauses.push(`Status=="${statuses[0]}"`);
- if (statuses.length > 1) whereClauses.push(`(${statuses.map((s) => `Status=="${s}"`).join(' OR ')})`);
- if (contactId) whereClauses.push(`Contact.ContactID==guid("${contactId}")`);
- if (reference) whereClauses.push(`Reference=="${reference.replace(/"/g, '\\"')}"`);
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- headers['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/CreditNotes',
- headers,
- queryParams,
- });
-
- if (resp.status !== 200) break;
-
- const notes: any[] = resp.body?.CreditNotes ?? [];
- for (const cn of notes) {
- const epoch = parseXeroDateToEpoch(cn.UpdatedDateUTC || cn.Date);
- results.push({ epochMilliSeconds: epoch, data: cn });
- }
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ types: Property.StaticMultiSelectDropdown({
+ displayName: 'Types',
+ required: false,
+ options: {
+ options: [
+ { label: 'ACCRECCREDIT (Sales Credit)', value: 'ACCRECCREDIT' },
+ { label: 'ACCPAYCREDIT (Supplier Credit)', value: 'ACCPAYCREDIT' },
+ ],
+ },
+ }),
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses (optional)',
+ required: false,
+ options: {
+ options: [
+ { label: 'DRAFT', value: 'DRAFT' },
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'PAID', value: 'PAID' },
+ { label: 'VOIDED', value: 'VOIDED' },
+ ],
+ },
+ }),
+ contact_id: props.contact_dropdown(false),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- if (notes.length < pageSize) break;
- }
+type CreditNoteProps = StaticPropsValue<typeof triggerProps>;
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, CreditNoteProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...creditNoteRequest({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records });
},
};
@@ -108,77 +64,65 @@ export const xeroNewCreditNote = createTrigger({
name: 'xero_new_credit_note',
classification: 'READ',
displayName: 'New Credit Note',
- description: 'Fires when a new credit note is created.',
+ description: 'Fires the first time a credit note is created or changed after the trigger is turned on.',
aiMetadata: {
- description: 'Fires when a new credit note is created in the connected Xero organisation. Polls the Xero CreditNotes endpoint and emits each credit note the first time its CreditNoteID is seen, optionally filtered by type (ACCRECCREDIT sales credit / ACCPAYCREDIT supplier credit), status (DRAFT, AUTHORISED, PAID, VOIDED), contact, reference, or date range. Each item is a full credit note record. Represents a newly added credit note, not subsequent edits.',
+ description:
+ 'Fires once per credit note (customer ACCRECCREDIT or supplier ACCPAYCREDIT) the first time it is seen after the trigger is enabled, optionally filtered by type, status, contact, reference or date range. Xero records have no creation time, so a credit note created before enabling but edited afterwards also fires once. Each item is one full credit note.',
},
props: {
- tenant_id: props.tenant_id,
- types: Property.StaticMultiSelectDropdown({
- displayName: 'Types',
- required: false,
- options: {
- options: [
- { label: 'ACCRECCREDIT (Sales Credit)', value: 'ACCRECCREDIT' },
- { label: 'ACCPAYCREDIT (Supplier Credit)', value: 'ACCPAYCREDIT' },
- ],
- },
- }),
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Statuses (optional)',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'PAID', value: 'PAID' },
- { label: 'VOIDED', value: 'VOIDED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- reference: Property.ShortText({ displayName: 'Reference', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ types: triggerProps.types,
+ statuses: triggerProps.statuses,
+ contact_id: triggerProps.contact_id,
+ reference: triggerProps.reference,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.creditNote,
+ sampleData: xeroSamples.creditNote,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ return xeroPolling.fetchRecent(creditNoteRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_credit_note_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
-
- const results: any[] = [];
- for (const cn of items) {
- const id = cn?.CreditNoteID as string | undefined;
- if (!id) continue;
- if (!seen.includes(id)) {
- results.push(cn);
- seen.push(id);
- }
- }
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_credit_note_seen_ids_${context.propsValue.tenant_id}`,
+ items,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'CreditNoteID' }),
+ });
},
- sampleData: undefined,
});
-
+function creditNoteRequest({ accessToken, propsValue }: { accessToken: string; propsValue: CreditNoteProps }) {
+ const types = xeroPolling.stringList({ value: propsValue.types });
+ const statuses = xeroPolling.stringList({ value: propsValue.statuses });
+ const contactId = xeroInput.trimmedOrUndefined({ value: propsValue.contact_id });
+ const reference = xeroInput.trimmedOrUndefined({ value: propsValue.reference });
+ const dateFrom = xeroInput.parseDateInput({ value: propsValue.date_from, field: 'Date From' });
+ const dateTo = xeroInput.parseDateInput({ value: propsValue.date_to, field: 'Date To' });
+ const where = [
+ ...xeroPolling.anyOf({ field: 'Type', values: types }),
+ ...xeroPolling.anyOf({ field: 'Status', values: statuses }),
+ ...(contactId ? [`Contact.ContactID==${xeroInput.whereGuid({ value: contactId, field: 'Contact' })}`] : []),
+ ...(reference ? [`Reference==${xeroInput.whereString({ value: reference })}`] : []),
+ ...(dateFrom ? [`Date>=${xeroInput.whereDate({ value: dateFrom })}`] : []),
+ ...(dateTo ? [`Date<${xeroInput.whereDate({ value: dateTo })}`] : []),
+ ];
+ return {
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ url: `${XERO_URLS.api}/CreditNotes`,
+ key: 'CreditNotes',
+ queryParams: xeroPolling.whereParams({ where }),
+ };
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-or-updated-contact.ts b/packages/pieces/community/xero/src/lib/triggers/new-or-updated-contact.ts
index dc31d73886f..8daf6f03bf0 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-or-updated-contact.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-or-updated-contact.ts
@@ -1,13 +1,9 @@
-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';
+import { Property, TriggerStrategy, WebhookHandshakeStrategy, createTrigger } from '@activepieces/pieces-framework';
import { xeroAuth } from '../..';
-import { createHmac } from 'crypto';
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroSamples } from '../common/samples';
+import { xeroWebhook } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroNewOrUpdatedContact = createTrigger({
auth: xeroAuth,
@@ -16,29 +12,12 @@ export const xeroNewOrUpdatedContact = createTrigger({
displayName: 'New or Updated Contact',
description: 'Fires when a contact is created or updated (via Xero webhooks).',
aiMetadata: {
- description: 'Fires when a contact is created or updated in the connected Xero organisation. Delivered through a Xero webhook on the CONTACT category filtered to CREATE and UPDATE events; the verified payload event optionally enriched with the full contact record (name, email, addresses, contact ID) fetched from Xero. Fires on both new contacts and edits to existing ones; use the New Contact trigger if only creations are wanted.',
+ description:
+ 'Fires once per contact creation or edit in the connected Xero organisation, delivered by a Xero webhook (CONTACT category, CREATE and UPDATE events) that you set up on your own Xero app; deliveries are signature-checked and duplicates are dropped. Each item is the full contact, or the raw webhook event when Fetch Full Contact is off. Use New Contact if only creations are wanted.',
},
type: TriggerStrategy.WEBHOOK,
props: {
- webhookInstructions: Property.MarkDown({
- value: `
-To use this trigger, manually configure a Xero webhook for your app:
-
-1. Go to Xero Developer > My Apps > [Your App] > Webhooks.
-2. Select the Contact category.
-3. Set the Delivery URL to:
-\n\n\`\`\`text
-{{webhookUrl}}
-\`\`\`
-4. Click Save, then click Validate "Intent to receive".
-5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.
-6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.
-
-Notes:
-- Keep this trigger enabled so the URL remains active.
-- We verify Xero's x-xero-signature header using your Webhook Key.
- `,
- }),
+ webhookInstructions: Property.MarkDown({ value: xeroWebhook.instructions({ category: 'Contact' }) }),
tenant_id: props.tenant_id,
webhook_key: Property.ShortText({
displayName: 'Webhook Key',
@@ -47,86 +26,35 @@ Notes:
}),
fetch_full_contact: Property.Checkbox({
displayName: 'Fetch Full Contact',
- description: 'If enabled, fetches the full contact from Xero using the Resource URL.',
+ description: 'If enabled, fetches the full contact from Xero. If disabled, the output is the raw webhook event (resourceId, eventType, eventDateUtc).',
required: false,
defaultValue: true,
}),
},
- sampleData: {
- ContactID: '717f2bfc-c6d4-41fd-b238-3f2f0c0cf777',
- Name: 'Sample Contact',
- EmailAddress: '[email protected]',
+ outputSchema: xeroOutputSchemas.contact,
+ sampleData: xeroSamples.contact,
+ handshakeConfiguration: {
+ strategy: WebhookHandshakeStrategy.HEADER_PRESENT,
+ paramName: xeroWebhook.handshakeConfiguration.paramName,
+ },
+ async onHandshake(context) {
+ return xeroWebhook.handshake({ payload: context.payload, webhookKey: context.propsValue.webhook_key });
},
async onEnable() {
- // Manual webhook setup by user
+ return;
},
async onDisable() {
- // Manual webhook lifecycle
+ return;
},
- async run(context: any) {
- const { webhook_key, tenant_id, fetch_full_contact } = context.propsValue as any;
-
- const signatureHeader = context.payload.headers['x-xero-signature'] as string | undefined;
- const rawBody = context.payload.rawBody as string | undefined;
- if (!signatureHeader || !rawBody) {
- return [];
- }
-
- const computed = createHmac('sha256', webhook_key).update(rawBody).digest('base64');
- if (computed !== signatureHeader) {
- return [];
- }
-
- const body = context.payload.body as any;
- const events: any[] = body?.events ?? [];
- if (!Array.isArray(events) || events.length === 0) {
- return [];
- }
-
- const filtered = events.filter((e) => {
- const isContact = e.eventCategory === 'CONTACT';
- const isCreateOrUpdate = e.eventType === 'CREATE' || e.eventType === 'UPDATE';
- const tenantOk = tenant_id ? e.tenantId === tenant_id : true;
- return isContact && isCreateOrUpdate && tenantOk;
+ async run(context) {
+ return xeroWebhook.processDelivery({
+ payload: context.payload,
+ webhookKey: context.propsValue.webhook_key,
+ tenantId: context.propsValue.tenant_id,
+ accessToken: context.auth.access_token,
+ store: context.store,
+ resource: { category: 'CONTACT', path: 'Contacts', eventTypes: ['CREATE', 'UPDATE'] },
+ fetchFull: context.propsValue.fetch_full_contact !== false,
});
-
- if (filtered.length === 0) {
- return [];
- }
-
- if (!fetch_full_contact) {
- return filtered;
- }
-
- const results: any[] = [];
- for (const ev of filtered) {
- try {
- const req: HttpRequest = {
- method: HttpMethod.GET,
- url: ev.resourceUrl,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (context.auth as any).access_token,
- },
- headers: {
- 'Xero-Tenant-Id': ev.tenantId,
- Accept: 'application/json',
- },
- };
- const resp = await httpClient.sendRequest<any>(req);
- if (resp.status === 200) {
- const contact = resp.body?.Contacts?.[0] ?? resp.body;
- results.push(contact);
- } else {
- results.push(ev);
- }
- } catch {
- results.push(ev);
- }
- }
-
- return results;
},
});
-
-
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-payment.ts b/packages/pieces/community/xero/src/lib/triggers/new-payment.ts
index 922d96478d6..18e282a9d12 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-payment.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-payment.ts
@@ -1,107 +1,60 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const paymentTypes = (propsValue?.['payment_types'] as string[]) || ['ACCRECPAYMENT'];
- const statuses = (propsValue?.['statuses'] as string[]) || ['AUTHORISED'];
- const invoiceId = propsValue?.['invoice_id'] as string | undefined;
- const reference = propsValue?.['reference'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
-
- const whereClauses: string[] = [];
- if (paymentTypes.length === 1) whereClauses.push(`PaymentType=="${paymentTypes[0]}"`);
- if (paymentTypes.length > 1)
- whereClauses.push(`(${paymentTypes.map((t) => `PaymentType=="${t}"`).join(' OR ')})`);
- if (statuses.length === 1) whereClauses.push(`Status=="${statuses[0]}"`);
- if (statuses.length > 1) whereClauses.push(`(${statuses.map((s) => `Status=="${s}"`).join(' OR ')})`);
- if (invoiceId) whereClauses.push(`Invoice.InvoiceID==guid("${invoiceId}")`);
- if (reference) whereClauses.push(`Reference=="${reference.replace(/"/g, '\\"')}"`);
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
-
- const requestHeaders: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- requestHeaders['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Payments',
- headers: requestHeaders,
- queryParams,
- });
-
- if (resp.status !== 200) break;
-
- const items: any[] = resp.body?.Payments ?? [];
- for (const p of items) {
- const epoch = parseXeroDateToEpoch(p.UpdatedDateUTC || p.Date);
- results.push({ epochMilliSeconds: epoch, data: p });
- }
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ payment_types: Property.StaticMultiSelectDropdown({
+ displayName: 'Payment Types',
+ required: false,
+ options: {
+ options: [
+ { label: 'ACCRECPAYMENT (Received on Sales Invoice)', value: 'ACCRECPAYMENT' },
+ { label: 'ACCPAYPAYMENT (Paid on Bill)', value: 'ACCPAYPAYMENT' },
+ ],
+ },
+ defaultValue: ['ACCRECPAYMENT'],
+ }),
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses',
+ required: false,
+ options: {
+ options: [
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ defaultValue: ['AUTHORISED'],
+ }),
+ invoice_id: props.invoice_id(false),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- if (items.length < pageSize) break;
- }
+type PaymentProps = StaticPropsValue<typeof triggerProps>;
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, PaymentProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...paymentRequest({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records });
},
};
@@ -110,74 +63,54 @@ export const xeroNewPayment = createTrigger({
name: 'xero_new_payment',
classification: 'READ',
displayName: 'New Payment',
- description: 'Fires when a payment is received.',
+ description: 'Fires the first time a payment is recorded or changed after the trigger is turned on.',
aiMetadata: {
- description: 'Fires when a new payment is recorded in the connected Xero organisation. Polls the Xero Payments endpoint and emits each payment the first time its PaymentID is seen, optionally filtered by payment type (ACCRECPAYMENT received on a sales invoice / ACCPAYPAYMENT paid on a bill), status, invoice, reference, or date range. Each item is a full payment record (amount, date, linked invoice, account). Represents a newly recorded payment, not an update to one.',
+ description:
+ 'Fires once per payment the first time it is seen after the trigger is enabled, optionally filtered by payment type (received on sales invoices or paid on bills), status, invoice, reference or date range. Xero records have no creation time, so a payment recorded before enabling but edited afterwards also fires once. Each item is one full payment with its invoice and bank account.',
},
props: {
- tenant_id: props.tenant_id,
- payment_types: Property.StaticMultiSelectDropdown({
- displayName: 'Payment Types',
- required: false,
- options: {
- options: [
- { label: 'ACCRECPAYMENT (Received on Sales Invoice)', value: 'ACCRECPAYMENT' },
- { label: 'ACCPAYPAYMENT (Paid on Bill)', value: 'ACCPAYPAYMENT' },
- ],
- },
- defaultValue: ['ACCRECPAYMENT'],
- }),
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Statuses',
- required: false,
- options: { options: [
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'DELETED', value: 'DELETED' },
- ]},
- defaultValue: ['AUTHORISED'],
- }),
- invoice_id: props.invoice_id(false),
- reference: Property.ShortText({ displayName: 'Reference', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ payment_types: triggerProps.payment_types,
+ statuses: triggerProps.statuses,
+ invoice_id: triggerProps.invoice_id,
+ reference: triggerProps.reference,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.payment,
+ sampleData: xeroSamples.payment,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ return xeroPolling.fetchRecent(paymentRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
},
- async run(context: any) {
- const items = await pollingHelper.poll(polling, context);
- // Emit only first-time seen PaymentID to represent new payments
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_payment_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
- const results: any[] = [];
- for (const it of items as any[]) {
- const id = it?.PaymentID;
- if (id && !seen.includes(id)) {
- results.push(it);
- seen.push(id);
- }
- }
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_payment_seen_ids_${context.propsValue.tenant_id}`,
+ items,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'PaymentID' }),
+ });
},
- sampleData: undefined,
});
-
+function paymentRequest({ accessToken, propsValue }: { accessToken: string; propsValue: PaymentProps }) {
+ return xeroPolling.paymentRequest({
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ paymentTypes: propsValue.payment_types,
+ statuses: propsValue.statuses,
+ invoiceId: propsValue.invoice_id,
+ reference: propsValue.reference,
+ dateFrom: propsValue.date_from,
+ dateTo: propsValue.date_to,
+ });
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-project.ts b/packages/pieces/community/xero/src/lib/triggers/new-project.ts
index 6a886ea13f4..7f20e333251 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-project.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-project.ts
@@ -1,66 +1,47 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, HttpMethod, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { XERO_URLS, xeroApi, xeroInput } from '../common/client';
+import { TEST_ITEM_LIMIT, xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { SEEN_ID_LIMIT, xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, propsValue }) {
- const { access_token } = auth as any;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 50;
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const states = (propsValue?.['states'] as string[]) || [];
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- };
- if (contactId) queryParams['contactId'] = contactId;
- if (Array.isArray(states) && states.length > 0) {
- queryParams['states'] = states.join(',');
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/projects.xro/2.0/Projects',
- headers: {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- },
- queryParams,
- });
-
- if (resp.status !== 200) break;
-
- const items: any[] = resp.body?.items ?? [];
- for (const it of items) {
- results.push({ epochMilliSeconds: Date.now(), data: it });
- }
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ contact_id: props.contact_dropdown(false),
+ states: Property.StaticMultiSelectDropdown({
+ displayName: 'States (optional)',
+ required: false,
+ options: {
+ options: [
+ { label: 'INPROGRESS', value: 'INPROGRESS' },
+ { label: 'CLOSED', value: 'CLOSED' },
+ ],
+ },
+ }),
+ page_size: Property.Number({
+ displayName: 'Page Size (1-500)',
+ description: 'No longer used: the trigger reads projects 500 at a time.',
+ required: false,
+ }),
+};
- if (items.length < pageSize) break;
- }
+type ProjectProps = StaticPropsValue<typeof triggerProps>;
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, ProjectProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue }) {
+ const projects = await listProjects({ accessToken: auth.access_token, propsValue, maxPages: MAX_PAGES, pageSize: SCAN_PAGE_SIZE });
+ const now = Date.now();
+ return projects.map((project) => ({ epochMilliSeconds: now, data: project }));
},
};
@@ -71,62 +52,96 @@ export const xeroNewProject = createTrigger({
displayName: 'New Project',
description: 'Fires when a new project is created.',
aiMetadata: {
- description: 'Fires when a new project is created in Xero Projects for the connected organisation. Polls the Xero Projects endpoint and emits each project the first time its projectId is seen, optionally filtered by contact or state (INPROGRESS, CLOSED). Each item is a full project record (name, contact, status, estimate). Represents a newly created project, not an update to an existing one.',
+ description:
+ 'Fires once per Xero Projects project created after the trigger is enabled (projects that already existed when it was enabled are skipped), optionally filtered by contact or state (INPROGRESS, CLOSED). Each item is one project with its name, contact, status, deadline and estimate.',
},
props: {
- tenant_id: props.tenant_id,
- contact_id: props.contact_dropdown(false),
- states: Property.StaticMultiSelectDropdown({
- displayName: 'States (optional)',
- required: false,
- options: {
- options: [
- { label: 'INPROGRESS', value: 'INPROGRESS' },
- { label: 'CLOSED', value: 'CLOSED' },
- ],
- },
- }),
- page_size: Property.Number({ displayName: 'Page Size (1-500)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ contact_id: triggerProps.contact_id,
+ states: triggerProps.states,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.project,
+ sampleData: xeroSamples.project,
+ async onEnable(context) {
+ const seenKey = seenKeyOf({ tenantId: context.propsValue.tenant_id });
+ const keep = await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ const alreadySeeded = keep && (await context.store.get<unknown>(seenKey)) !== null;
+ if (!alreadySeeded) {
+ const existing = await listProjects({ accessToken: context.auth.access_token, propsValue: context.propsValue, maxPages: MAX_PAGES, pageSize: SCAN_PAGE_SIZE });
+ await xeroTriggerState.seedSeenIds({
+ store: context.store,
+ key: seenKey,
+ ids: existing.flatMap((project) => {
+ const id = projectIdOf({ record: project });
+ return id ? [id] : [];
+ }),
+ });
+ }
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const projects = await listProjects({ accessToken: context.auth.access_token, propsValue: context.propsValue, maxPages: 1, pageSize: TEST_ITEM_LIMIT });
+ return projects.slice(0, TEST_ITEM_LIMIT);
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_project_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
-
- const results: any[] = [];
- for (const it of items) {
- const id = it?.projectId ?? it?.ProjectID ?? it?.data?.projectId;
- const data = it?.data ?? it;
- const projectId = id as string | undefined;
- if (!projectId) continue;
- if (!seen.includes(projectId)) {
- results.push(data);
- seen.push(projectId);
- }
- }
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: seenKeyOf({ tenantId: context.propsValue.tenant_id }),
+ items,
+ idOf: (record) => projectIdOf({ record }),
+ });
},
- sampleData: undefined,
});
+async function listProjects({
+ accessToken,
+ propsValue,
+ maxPages,
+ pageSize,
+}: {
+ accessToken: string;
+ propsValue: ProjectProps;
+ maxPages: number;
+ pageSize?: number;
+}): Promise<Record<string, unknown>[]> {
+ const size = pageSize ?? xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 50, max: 500 });
+ const contactId = xeroInput.trimmedOrUndefined({ value: propsValue.contact_id });
+ const states = xeroPolling.stringList({ value: propsValue.states });
+ const projects: Record<string, unknown>[] = [];
+ for (let page = 1; page <= maxPages; page++) {
+ const body = await xeroApi.request<unknown>({
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ method: HttpMethod.GET,
+ url: `${XERO_URLS.projects}/Projects`,
+ queryParams: {
+ page: String(page),
+ pageSize: String(size),
+ ...(contactId ? { contactID: contactId } : {}),
+ ...(states.length > 0 ? { states: states.join(',') } : {}),
+ },
+ operation: 'list projects',
+ });
+ const pageItems = xeroApi.recordsOf({ body, key: 'items' });
+ projects.push(...pageItems);
+ if (pageItems.length < size) break;
+ }
+ return projects;
+}
+
+function projectIdOf({ record }: { record: Record<string, unknown> }): string | undefined {
+ return xeroPolling.idOf({ record, key: 'projectId' }) ?? xeroPolling.idOf({ record, key: 'ProjectID' });
+}
+
+function seenKeyOf({ tenantId }: { tenantId: string }): string {
+ return `xero_project_seen_ids_${tenantId}`;
+}
+const SCAN_PAGE_SIZE = 500;
+const MAX_PAGES = SEEN_ID_LIMIT / SCAN_PAGE_SIZE;
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-purchase-order.ts b/packages/pieces/community/xero/src/lib/triggers/new-purchase-order.ts
index dc62c4ffb3e..43ca8a53b00 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-purchase-order.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-purchase-order.ts
@@ -1,105 +1,57 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { XERO_URLS, xeroInput } from '../common/client';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
+
+const statusOptions = [
+ { label: 'DRAFT', value: 'DRAFT' },
+ { label: 'SUBMITTED', value: 'SUBMITTED' },
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'BILLED', value: 'BILLED' },
+ { label: 'DELETED', value: 'DELETED' },
+];
+
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Filter by Status (optional)',
+ required: false,
+ options: { options: statusOptions },
+ }),
+ first_time_status: Property.StaticDropdown({
+ displayName: 'First-time Status (optional)',
+ description: 'Also fire when a purchase order enters this status for the first time (since enabling).',
+ required: false,
+ options: { options: statusOptions },
+ }),
+ contact_id: props.contact_dropdown(false),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
+type PurchaseOrderProps = StaticPropsValue<typeof triggerProps>;
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, PurchaseOrderProps> = {
strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
-
- const whereClauses: string[] = [];
- if (contactId) whereClauses.push(`Contact.ContactID==guid("${contactId}")`);
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
- if (Array.isArray(statuses) && statuses.length > 1) {
- whereClauses.push(`(${statuses.map((s) => `Status=="${s}"`).join(' OR ')})`);
- }
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
- // Single status can use the dedicated param for efficiency
- if (Array.isArray(statuses) && statuses.length === 1) {
- queryParams['status'] = statuses[0];
- }
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- headers['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/PurchaseOrders',
- headers,
- queryParams,
- });
-
- if (resp.status !== 200) break;
-
- const pos: any[] = resp.body?.PurchaseOrders ?? [];
- for (const po of pos) {
- const epoch = parseXeroDateToEpoch(po.UpdatedDateUTC || po.Date);
- results.push({ epochMilliSeconds: epoch, data: po });
- }
-
- if (pos.length < pageSize) break;
- }
- return results;
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...purchaseOrderRequest({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records });
},
};
@@ -108,107 +60,71 @@ export const xeroNewPurchaseOrder = createTrigger({
name: 'xero_new_purchase_order',
classification: 'READ',
displayName: 'New Purchase Order',
- description: 'Fires when a new purchase order is created or enters a specific status for the first time.',
+ description: 'Fires the first time a purchase order is created or changed after the trigger is turned on, or enters a chosen status for the first time.',
aiMetadata: {
- description: 'Fires when a new purchase order is created in the connected Xero organisation, and optionally also when a purchase order enters a chosen status (DRAFT, SUBMITTED, AUTHORISED, BILLED, DELETED) for the first time since the trigger was enabled. Polls the Xero PurchaseOrders endpoint and emits each purchase order the first time its PurchaseOrderID is seen, optionally filtered by status, contact, or date range. Each item is a full purchase order record (number, status, supplier contact, line items, totals).',
+ description:
+ 'Fires once per purchase order the first time it is seen after the trigger is enabled, and optionally again when it first enters a chosen status (for example AUTHORISED or BILLED); filters by status, contact or date range. Xero records have no creation time, so a purchase order created before enabling but edited afterwards also fires once. Each item is one full purchase order.',
},
props: {
- tenant_id: props.tenant_id,
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Filter by Status (optional)',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'SUBMITTED', value: 'SUBMITTED' },
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'BILLED', value: 'BILLED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- first_time_status: Property.StaticDropdown({
- displayName: 'First-time Status (optional)',
- description: 'Also fire when a purchase order enters this status for the first time (since enabling).',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'SUBMITTED', value: 'SUBMITTED' },
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'BILLED', value: 'BILLED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ statuses: triggerProps.statuses,
+ first_time_status: triggerProps.first_time_status,
+ contact_id: triggerProps.contact_id,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.purchaseOrder,
+ sampleData: xeroSamples.purchaseOrder,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ return xeroPolling.fetchRecent(purchaseOrderRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const firstStatus: string | undefined = context.propsValue['first_time_status'];
-
- const seenIdsKey = `xero_po_seen_ids_${tenantId}`;
- const seenIds: string[] = (await context.store.get(seenIdsKey)) || [];
-
- const statusSeenKey = firstStatus ? `xero_po_status_seen_${tenantId}_${firstStatus}` : '';
- const statusSeenIds: string[] = firstStatus ? (await context.store.get(statusSeenKey)) || [] : [];
-
- const emittedIds = new Set<string>();
- const results: any[] = [];
-
- for (const po of items) {
- const id = po?.PurchaseOrderID;
- if (!id) continue;
-
- // Emit for brand new purchase orders (first time seen)
- if (!seenIds.includes(id)) {
- if (!emittedIds.has(id)) {
- results.push(po);
- emittedIds.add(id);
- }
- seenIds.push(id);
- }
-
- // Emit when entering the specific status for the first time
- if (firstStatus && po?.Status === firstStatus && !statusSeenIds.includes(id)) {
- if (!emittedIds.has(id)) {
- results.push(po);
- emittedIds.add(id);
- }
- statusSeenIds.push(id);
- }
- }
-
- await context.store.put(seenIdsKey, seenIds);
- if (firstStatus) {
- await context.store.put(statusSeenKey, statusSeenIds);
- }
-
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ const tenantId = context.propsValue.tenant_id;
+ const firstStatus = context.propsValue.first_time_status;
+ const idOf = (record: Record<string, unknown>) => xeroPolling.idOf({ record, key: 'PurchaseOrderID' });
+ const newOnes = await xeroTriggerState.emitFirstSeen({ store: context.store, key: `xero_po_seen_ids_${tenantId}`, items, idOf });
+ const enteredStatus = firstStatus
+ ? await xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_po_status_seen_${tenantId}_${firstStatus}`,
+ items: items.filter((record) => record['Status'] === firstStatus),
+ idOf,
+ })
+ : [];
+ const emittedIds = new Set(newOnes.map(idOf));
+ return [...newOnes, ...enteredStatus.filter((record) => !emittedIds.has(idOf(record)))];
},
- sampleData: undefined,
});
-
+function purchaseOrderRequest({ accessToken, propsValue }: { accessToken: string; propsValue: PurchaseOrderProps }) {
+ const statuses = xeroPolling.stringList({ value: propsValue.statuses });
+ const contactId = xeroInput.trimmedOrUndefined({ value: propsValue.contact_id });
+ const dateFrom = xeroInput.parseDateInput({ value: propsValue.date_from, field: 'Date From' });
+ const dateTo = xeroInput.parseDateInput({ value: propsValue.date_to, field: 'Date To' });
+ const where = [
+ ...(contactId ? [`Contact.ContactID==${xeroInput.whereGuid({ value: contactId, field: 'Contact' })}`] : []),
+ ...(dateFrom ? [`Date>=${xeroInput.whereDate({ value: dateFrom })}`] : []),
+ ...(dateTo ? [`Date<${xeroInput.whereDate({ value: dateTo })}`] : []),
+ ...(statuses.length > 1 ? xeroPolling.anyOf({ field: 'Status', values: statuses }) : []),
+ ];
+ return {
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ url: `${XERO_URLS.api}/PurchaseOrders`,
+ key: 'PurchaseOrders',
+ queryParams: {
+ ...(where.length > 0 ? { where: where.join(' AND ') } : {}),
+ ...(statuses.length === 1 ? { status: statuses[0] } : {}),
+ },
+ };
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-quote.ts b/packages/pieces/community/xero/src/lib/triggers/new-quote.ts
index df2a0600b97..42782c82cc6 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-quote.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-quote.ts
@@ -1,96 +1,55 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const quoteNumber = propsValue?.['quote_number'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
- const expiryFrom = propsValue?.['expiry_date_from'] as string | undefined;
- const expiryTo = propsValue?.['expiry_date_to'] as string | undefined;
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (Array.isArray(statuses) && statuses.length === 1) {
- queryParams['status'] = statuses[0];
- }
- if (contactId) queryParams['ContactID'] = contactId;
- if (quoteNumber) queryParams['QuoteNumber'] = quoteNumber;
- if (dateFrom) queryParams['DateFrom'] = dateFrom;
- if (dateTo) queryParams['DateTo'] = dateTo;
- if (expiryFrom) queryParams['ExpiryDateFrom'] = expiryFrom;
- if (expiryTo) queryParams['ExpiryDateTo'] = expiryTo;
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- headers['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Quotes',
- headers,
- queryParams,
- });
-
- if (resp.status !== 200) break;
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Filter by Status (optional)',
+ required: false,
+ options: {
+ options: [
+ { label: 'DRAFT', value: 'DRAFT' },
+ { label: 'SENT', value: 'SENT' },
+ { label: 'ACCEPTED', value: 'ACCEPTED' },
+ { label: 'DECLINED', value: 'DECLINED' },
+ { label: 'INVOICED', value: 'INVOICED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ }),
+ contact_id: props.contact_dropdown(false),
+ quote_number: Property.ShortText({ displayName: 'Quote Number (partial match)', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ expiry_date_from: Property.ShortText({ displayName: 'Expiry Date From (YYYY-MM-DD)', required: false }),
+ expiry_date_to: Property.ShortText({ displayName: 'Expiry Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- const quotes: any[] = resp.body?.Quotes ?? [];
- for (const q of quotes) {
- const epoch = parseXeroDateToEpoch(q.UpdatedDateUTC || q.Date);
- results.push({ epochMilliSeconds: epoch, data: q });
- }
+type QuoteProps = StaticPropsValue<typeof triggerProps>;
- if (quotes.length < pageSize) break;
- }
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, QuoteProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const { request, matches } = quoteRequest({ accessToken: auth.access_token, propsValue });
+ const records = await xeroPolling.fetchUpdated({
+ ...request,
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records, matches });
},
};
@@ -99,72 +58,57 @@ export const xeroNewQuote = createTrigger({
name: 'xero_new_quote',
classification: 'READ',
displayName: 'New Quote',
- description: 'Fires when a new quote is created.',
+ description: 'Fires the first time a quote is created or changed after the trigger is turned on.',
aiMetadata: {
- description: 'Fires when a new quote is created in the connected Xero organisation. Polls the Xero Quotes endpoint and emits each quote the first time its QuoteID is seen, optionally filtered by status (DRAFT, SENT, ACCEPTED, DECLINED, INVOICED, DELETED), contact, quote number, or date/expiry range. Each item is a full quote record (number, status, contact, line items, totals). Represents a brand-new quote; use Updated Quote to also fire on edits.',
+ description:
+ 'Fires once per quote the first time it is seen after the trigger is enabled, optionally filtered by status, contact, quote number, or date and expiry ranges. Xero records have no creation time, so a quote created before enabling but edited afterwards also fires once. Each item is one full quote; use Updated Quote to fire on every edit.',
},
props: {
- tenant_id: props.tenant_id,
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Filter by Status (optional)',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'SENT', value: 'SENT' },
- { label: 'ACCEPTED', value: 'ACCEPTED' },
- { label: 'DECLINED', value: 'DECLINED' },
- { label: 'INVOICED', value: 'INVOICED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- quote_number: Property.ShortText({ displayName: 'Quote Number (partial match)', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- expiry_date_from: Property.ShortText({ displayName: 'Expiry Date From (YYYY-MM-DD)', required: false }),
- expiry_date_to: Property.ShortText({ displayName: 'Expiry Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ statuses: triggerProps.statuses,
+ contact_id: triggerProps.contact_id,
+ quote_number: triggerProps.quote_number,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ expiry_date_from: triggerProps.expiry_date_from,
+ expiry_date_to: triggerProps.expiry_date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.quote,
+ sampleData: xeroSamples.quote,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const { request, matches } = quoteRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue });
+ return (await xeroPolling.fetchRecent(request)).filter(matches);
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_quote_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
-
- const results: any[] = [];
- for (const q of items) {
- const id = q?.QuoteID as string | undefined;
- if (!id) continue;
- if (!seen.includes(id)) {
- results.push(q);
- seen.push(id);
- }
- }
-
- await context.store.put(seenKey, seen);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ return xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_quote_seen_ids_${context.propsValue.tenant_id}`,
+ items,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'QuoteID' }),
+ });
},
- sampleData: undefined,
});
-
+function quoteRequest({ accessToken, propsValue }: { accessToken: string; propsValue: QuoteProps }) {
+ return xeroPolling.quoteRequest({
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ statuses: propsValue.statuses,
+ contactId: propsValue.contact_id,
+ quoteNumber: propsValue.quote_number,
+ dateFrom: propsValue.date_from,
+ dateTo: propsValue.date_to,
+ expiryDateFrom: propsValue.expiry_date_from,
+ expiryDateTo: propsValue.expiry_date_to,
+ });
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-reconciled-payment.ts b/packages/pieces/community/xero/src/lib/triggers/new-reconciled-payment.ts
index 36e6a809857..5ea99d1b620 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-reconciled-payment.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-reconciled-payment.ts
@@ -1,107 +1,60 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
+
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ payment_types: Property.StaticMultiSelectDropdown({
+ displayName: 'Payment Types',
+ required: false,
+ options: {
+ options: [
+ { label: 'ACCRECPAYMENT (Received on Sales Invoice)', value: 'ACCRECPAYMENT' },
+ { label: 'ACCPAYPAYMENT (Paid on Bill)', value: 'ACCPAYPAYMENT' },
+ ],
+ },
+ defaultValue: ['ACCRECPAYMENT'],
+ }),
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Statuses',
+ required: false,
+ options: {
+ options: [
+ { label: 'AUTHORISED', value: 'AUTHORISED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ defaultValue: ['AUTHORISED'],
+ }),
+ invoice_id: props.invoice_id(false),
+ reference: Property.ShortText({ displayName: 'Reference', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
+type PaymentProps = StaticPropsValue<typeof triggerProps>;
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, PaymentProps> = {
strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const paymentTypes = (propsValue?.['payment_types'] as string[]) || ['ACCRECPAYMENT'];
- const statuses = (propsValue?.['statuses'] as string[]) || ['AUTHORISED'];
- const invoiceId = propsValue?.['invoice_id'] as string | undefined;
- const reference = propsValue?.['reference'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
-
- const whereClauses: string[] = [];
- if (paymentTypes.length === 1) whereClauses.push(`PaymentType=="${paymentTypes[0]}"`);
- if (paymentTypes.length > 1)
- whereClauses.push(`(${paymentTypes.map((t) => `PaymentType=="${t}"`).join(' OR ')})`);
- if (statuses.length === 1) whereClauses.push(`Status=="${statuses[0]}"`);
- if (statuses.length > 1) whereClauses.push(`(${statuses.map((s) => `Status=="${s}"`).join(' OR ')})`);
- if (invoiceId) whereClauses.push(`Invoice.InvoiceID==guid("${invoiceId}")`);
- if (reference) whereClauses.push(`Reference=="${reference.replace(/"/g, '\\"')}"`);
- if (dateFrom) {
- const [y, m, d] = dateFrom.split('-');
- whereClauses.push(`Date>=DateTime(${y}, ${m}, ${d})`);
- }
- if (dateTo) {
- const [y, m, d] = dateTo.split('-');
- whereClauses.push(`Date<DateTime(${y}, ${m}, ${d})`);
- }
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (whereClauses.length > 0) {
- queryParams['where'] = whereClauses.join(' AND ');
- }
-
- const requestHeaders: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- requestHeaders['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Payments',
- headers: requestHeaders,
- queryParams,
- });
-
- if (resp.status !== 200) break;
-
- const items: any[] = resp.body?.Payments ?? [];
- for (const p of items) {
- const epoch = parseXeroDateToEpoch(p.UpdatedDateUTC || p.Date);
- results.push({ epochMilliSeconds: epoch, data: p });
- }
-
- if (items.length < pageSize) break;
- }
-
- return results;
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const records = await xeroPolling.fetchUpdated({
+ ...paymentRequest({ accessToken: auth.access_token, propsValue }),
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records });
},
};
@@ -112,86 +65,72 @@ export const xeroNewReconciledPayment = createTrigger({
displayName: 'New Reconciled Payment',
description: 'Fires when a payment is reconciled for the first time.',
aiMetadata: {
- description: 'Fires when a payment is reconciled in the connected Xero organisation for the first time, i.e. when its IsReconciled flag transitions from false to true. Polls the Xero Payments endpoint, tracks each payment\'s prior reconciliation state, and emits a payment only on that first false-to-true transition, optionally filtered by payment type (ACCRECPAYMENT / ACCPAYPAYMENT), status, invoice, reference, or date range. Each item is a full payment record. Distinct from New Payment, which fires when a payment is first recorded regardless of reconciliation.',
+ description:
+ 'Fires once per payment when it is first seen as reconciled (IsReconciled false to true) after the trigger is enabled, optionally filtered by payment type, status, invoice, reference or date range. A payment that was already reconciled before enabling and is edited afterwards also fires once, because its earlier state is unknown. Each item is one full payment. Use New Payment to fire when a payment is recorded.',
},
props: {
- tenant_id: props.tenant_id,
- payment_types: Property.StaticMultiSelectDropdown({
- displayName: 'Payment Types',
- required: false,
- options: {
- options: [
- { label: 'ACCRECPAYMENT (Received on Sales Invoice)', value: 'ACCRECPAYMENT' },
- { label: 'ACCPAYPAYMENT (Paid on Bill)', value: 'ACCPAYPAYMENT' },
- ],
- },
- defaultValue: ['ACCRECPAYMENT'],
- }),
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Statuses',
- required: false,
- options: { options: [
- { label: 'AUTHORISED', value: 'AUTHORISED' },
- { label: 'DELETED', value: 'DELETED' },
- ]},
- defaultValue: ['AUTHORISED'],
- }),
- invoice_id: props.invoice_id(false),
- reference: Property.ShortText({ displayName: 'Reference', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ payment_types: triggerProps.payment_types,
+ statuses: triggerProps.statuses,
+ invoice_id: triggerProps.invoice_id,
+ reference: triggerProps.reference,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.payment,
+ sampleData: { ...xeroSamples.payment, IsReconciled: true },
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const records = await xeroPolling.fetchRecent(paymentRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue }));
+ return records.filter((record) => record['IsReconciled'] === true);
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
- const seenKey = `xero_payment_reconciled_seen_ids_${tenantId}`;
- const seen: string[] = (await context.store.get(seenKey)) || [];
-
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ const tenantId = context.propsValue.tenant_id;
const previousStateKey = `xero_payment_prev_reconciled_state_${tenantId}`;
- const prevState: Record<string, boolean> = (await context.store.get(previousStateKey)) || {};
-
- const results: any[] = [];
- for (const p of items) {
- const id = p?.PaymentID as string | undefined;
- if (!id) continue;
-
- const isRec = Boolean(p?.IsReconciled);
- const wasRec = Boolean(prevState[id]);
-
- // Fire only when first transitions to reconciled (false -> true)
- if (isRec && !wasRec && !seen.includes(id)) {
- results.push(p);
- seen.push(id);
- }
-
- // Track current state for next poll
- prevState[id] = isRec;
+ const previousState = xeroTriggerState.readMap({
+ value: await context.store.get<unknown>(previousStateKey),
+ isValue: (entry): entry is boolean => typeof entry === 'boolean',
+ });
+ const reconciledNow = items.filter((record) => {
+ const id = xeroPolling.idOf({ record, key: 'PaymentID' });
+ return id !== undefined && record['IsReconciled'] === true && previousState[id] !== true;
+ });
+ const nextState = new Map(Object.entries(previousState));
+ for (const record of items) {
+ const id = xeroPolling.idOf({ record, key: 'PaymentID' });
+ if (id === undefined) continue;
+ nextState.delete(id);
+ nextState.set(id, record['IsReconciled'] === true);
}
-
- await context.store.put(seenKey, seen);
- await context.store.put(previousStateKey, prevState);
- return results;
+ const emitted = await xeroTriggerState.emitFirstSeen({
+ store: context.store,
+ key: `xero_payment_reconciled_seen_ids_${tenantId}`,
+ items: reconciledNow,
+ idOf: (record) => xeroPolling.idOf({ record, key: 'PaymentID' }),
+ });
+ await context.store.put(previousStateKey, xeroTriggerState.boundMap({ map: Object.fromEntries(nextState) }));
+ return emitted;
},
- sampleData: undefined,
});
-
+function paymentRequest({ accessToken, propsValue }: { accessToken: string; propsValue: PaymentProps }) {
+ return xeroPolling.paymentRequest({
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ paymentTypes: propsValue.payment_types,
+ statuses: propsValue.statuses,
+ invoiceId: propsValue.invoice_id,
+ reference: propsValue.reference,
+ dateFrom: propsValue.date_from,
+ dateTo: propsValue.date_to,
+ });
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/new-sales-invoice.ts b/packages/pieces/community/xero/src/lib/triggers/new-sales-invoice.ts
index 7528120a1bb..20ef79a8e39 100644
--- a/packages/pieces/community/xero/src/lib/triggers/new-sales-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/new-sales-invoice.ts
@@ -1,13 +1,9 @@
-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';
+import { Property, TriggerStrategy, WebhookHandshakeStrategy, createTrigger } from '@activepieces/pieces-framework';
import { xeroAuth } from '../..';
-import { createHmac } from 'crypto';
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroSamples } from '../common/samples';
+import { xeroWebhook } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroNewSalesInvoice = createTrigger({
auth: xeroAuth,
@@ -16,29 +12,12 @@ export const xeroNewSalesInvoice = createTrigger({
displayName: 'New Sales Invoice',
description: 'Fires when a new sales invoice (Accounts Receivable) is created.',
aiMetadata: {
- description: 'Fires when a new sales invoice (Accounts Receivable, Type ACCREC) is created in the connected Xero organisation. Delivered through a Xero webhook on the INVOICE category filtered to CREATE events; the full invoice is fetched and only ACCREC (sales) invoices are emitted, so bills (ACCPAY) are excluded. Each item is the full invoice (number, status, contact, line items, totals). Represents a brand-new sales invoice, not an update to an existing one.',
+ description:
+ 'Fires once per sales invoice (Type ACCREC) created in the connected Xero organisation, delivered by a Xero webhook (INVOICE category, CREATE events) that you set up on your own Xero app; bills (ACCPAY) are skipped when Fetch Full Invoice is on, and duplicates are dropped. Each item is the full invoice, or the raw webhook event when Fetch Full Invoice is off.',
},
type: TriggerStrategy.WEBHOOK,
props: {
- webhookInstructions: Property.MarkDown({
- value: `
-To use this trigger, manually configure a Xero webhook for your app:
-
-1. Go to Xero Developer > My Apps > [Your App] > Webhooks.
-2. Select the Invoice category.
-3. Set the Delivery URL to:
-\n\n\`\`\`text
-{{webhookUrl}}
-\`\`\`
-4. Click Save, then click Validate "Intent to receive".
-5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.
-6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.
-
-Notes:
-- Keep this trigger enabled so the URL remains active.
-- We verify Xero's x-xero-signature header using your Webhook Key.
- `,
- }),
+ webhookInstructions: Property.MarkDown({ value: xeroWebhook.instructions({ category: 'Invoice' }) }),
tenant_id: props.tenant_id,
webhook_key: Property.ShortText({
displayName: 'Webhook Key',
@@ -47,89 +26,36 @@ Notes:
}),
fetch_full_invoice: Property.Checkbox({
displayName: 'Fetch Full Invoice',
- description: 'Fetch the full invoice and ensure Type is ACCREC (recommended).',
+ description: 'Fetch the full invoice and ensure Type is ACCREC (recommended). If disabled, the output is the raw webhook event and bills are not filtered out.',
required: false,
defaultValue: true,
}),
},
- sampleData: {
- InvoiceID: '243216c5-369e-4056-ac67-05388f86dc81',
- Type: 'ACCREC',
- InvoiceNumber: 'INV-0001',
- Status: 'AUTHORISED',
+ outputSchema: xeroOutputSchemas.invoice,
+ sampleData: xeroSamples.invoice,
+ handshakeConfiguration: {
+ strategy: WebhookHandshakeStrategy.HEADER_PRESENT,
+ paramName: xeroWebhook.handshakeConfiguration.paramName,
},
- async onEnable(): Promise<void> {
- // Manual webhook setup by user
+ async onHandshake(context) {
+ return xeroWebhook.handshake({ payload: context.payload, webhookKey: context.propsValue.webhook_key });
},
- async onDisable(): Promise<void> {
- // Manual webhook lifecycle
+ async onEnable() {
+ return;
},
- async run(context: any) {
- const { webhook_key, tenant_id, fetch_full_invoice } = context.propsValue as any;
-
- const signatureHeader = context.payload.headers['x-xero-signature'] as string | undefined;
- const rawBody = context.payload.rawBody as string | undefined;
- if (!signatureHeader || !rawBody) {
- return [];
- }
-
- const computed = createHmac('sha256', webhook_key).update(rawBody).digest('base64');
- if (computed !== signatureHeader) {
- return [];
- }
-
- const body = context.payload.body as any;
- const events: any[] = body?.events ?? [];
- if (!Array.isArray(events) || events.length === 0) {
- return [];
- }
-
- // Filter to INVOICE CREATE events (new invoices), optional tenant match
- const filtered = events.filter((e) => {
- const isInvoice = e.eventCategory === 'INVOICE';
- const isCreate = e.eventType === 'CREATE';
- const tenantOk = tenant_id ? e.tenantId === tenant_id : true;
- return isInvoice && isCreate && tenantOk;
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ return xeroWebhook.processDelivery({
+ payload: context.payload,
+ webhookKey: context.propsValue.webhook_key,
+ tenantId: context.propsValue.tenant_id,
+ accessToken: context.auth.access_token,
+ store: context.store,
+ resource: { category: 'INVOICE', path: 'Invoices', eventTypes: ['CREATE'] },
+ fetchFull: context.propsValue.fetch_full_invoice !== false,
+ accept: (record) => record['Type'] === 'ACCREC',
});
- if (filtered.length === 0) {
- return [];
- }
-
- // If not fetching full invoice, we cannot verify ACCREC from event alone; return events
- if (!fetch_full_invoice) {
- return filtered;
- }
-
- // Fetch each invoice and only return ACCREC (sales) invoices
- const results: any[] = [];
- for (const ev of filtered) {
- try {
- const req: HttpRequest = {
- method: HttpMethod.GET,
- url: ev.resourceUrl,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (context.auth as any).access_token,
- },
- headers: {
- 'Xero-Tenant-Id': ev.tenantId,
- Accept: 'application/json',
- },
- };
- const resp = await httpClient.sendRequest<any>(req);
- if (resp.status === 200) {
- const inv = resp.body?.Invoices?.[0] ?? resp.body;
- if (inv?.Type === 'ACCREC') {
- results.push(inv);
- }
- }
- } catch {
- // ignore errors, move on
- }
- }
-
- return results;
},
});
-
-
diff --git a/packages/pieces/community/xero/src/lib/triggers/updated-quote.ts b/packages/pieces/community/xero/src/lib/triggers/updated-quote.ts
index 2676a2b8941..a091e2776f5 100644
--- a/packages/pieces/community/xero/src/lib/triggers/updated-quote.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/updated-quote.ts
@@ -1,96 +1,55 @@
import {
+ AppConnectionValueForAuthProperty,
+ Property,
+ StaticPropsValue,
TriggerStrategy,
createTrigger,
- PiecePropValueSchema,
- Property,
- AppConnectionValueForAuthProperty,
} from '@activepieces/pieces-framework';
+import { DedupeStrategy, Polling, pollingHelper } from '@activepieces/pieces-common';
import { xeroAuth } from '../..';
-import {
- DedupeStrategy,
- httpClient,
- HttpMethod,
- Polling,
- pollingHelper,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
+import { xeroPolling } from '../common/polling';
+import { xeroSamples } from '../common/samples';
+import { xeroTriggerState } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
-function parseXeroDateToEpoch(dateVal: unknown): number {
- if (typeof dateVal === 'string') {
- if (dateVal.includes('/Date(')) {
- const match = /\/Date\((\d+)/.exec(dateVal);
- if (match && match[1]) return Number(match[1]);
- }
- const t = Date.parse(dateVal);
- if (!Number.isNaN(t)) return t;
- }
- if (typeof dateVal === 'number') return dateVal;
- return Date.now();
-}
-
-const polling: Polling<
-AppConnectionValueForAuthProperty<typeof xeroAuth>,
- Record<string, unknown>
-> = {
- strategy: DedupeStrategy.TIMEBASED,
- async items({ auth, lastFetchEpochMS, propsValue }) {
- const { access_token } = auth;
- const tenantId = propsValue?.['tenant_id'] as string;
- const pageSize = (propsValue?.['page_size'] as number) || 200;
- const statuses = (propsValue?.['statuses'] as string[]) || [];
- const contactId = propsValue?.['contact_id'] as string | undefined;
- const quoteNumber = propsValue?.['quote_number'] as string | undefined;
- const dateFrom = propsValue?.['date_from'] as string | undefined;
- const dateTo = propsValue?.['date_to'] as string | undefined;
- const expiryFrom = propsValue?.['expiry_date_from'] as string | undefined;
- const expiryTo = propsValue?.['expiry_date_to'] as string | undefined;
-
- const results: any[] = [];
- const maxPages = 5;
- for (let page = 1; page <= maxPages; page++) {
- const queryParams: Record<string, string> = {
- page: String(page),
- pageSize: String(pageSize),
- order: 'UpdatedDateUTC ASC',
- };
- if (Array.isArray(statuses) && statuses.length === 1) {
- queryParams['status'] = statuses[0];
- }
- if (contactId) queryParams['ContactID'] = contactId;
- if (quoteNumber) queryParams['QuoteNumber'] = quoteNumber;
- if (dateFrom) queryParams['DateFrom'] = dateFrom;
- if (dateTo) queryParams['DateTo'] = dateTo;
- if (expiryFrom) queryParams['ExpiryDateFrom'] = expiryFrom;
- if (expiryTo) queryParams['ExpiryDateTo'] = expiryTo;
-
- const headers: Record<string, string> = {
- Authorization: `Bearer ${access_token}`,
- Accept: 'application/json',
- 'Xero-Tenant-Id': tenantId,
- };
- if (lastFetchEpochMS > 0) {
- const ifModified = new Date(lastFetchEpochMS).toISOString().slice(0, 19);
- headers['If-Modified-Since'] = ifModified;
- }
-
- const resp = await httpClient.sendRequest<Record<string, any>>({
- method: HttpMethod.GET,
- url: 'https://api.xero.com/api.xro/2.0/Quotes',
- headers,
- queryParams,
- });
-
- if (resp.status !== 200) break;
+const triggerProps = {
+ tenant_id: props.tenant_id,
+ statuses: Property.StaticMultiSelectDropdown({
+ displayName: 'Filter by Status (optional)',
+ required: false,
+ options: {
+ options: [
+ { label: 'DRAFT', value: 'DRAFT' },
+ { label: 'SENT', value: 'SENT' },
+ { label: 'ACCEPTED', value: 'ACCEPTED' },
+ { label: 'DECLINED', value: 'DECLINED' },
+ { label: 'INVOICED', value: 'INVOICED' },
+ { label: 'DELETED', value: 'DELETED' },
+ ],
+ },
+ }),
+ contact_id: props.contact_dropdown(false),
+ quote_number: Property.ShortText({ displayName: 'Quote Number (partial match)', required: false }),
+ date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
+ date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
+ expiry_date_from: Property.ShortText({ displayName: 'Expiry Date From (YYYY-MM-DD)', required: false }),
+ expiry_date_to: Property.ShortText({ displayName: 'Expiry Date To (YYYY-MM-DD)', required: false }),
+ page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+};
- const quotes: any[] = resp.body?.Quotes ?? [];
- for (const q of quotes) {
- const epoch = parseXeroDateToEpoch(q.UpdatedDateUTC || q.Date);
- results.push({ epochMilliSeconds: epoch, data: q });
- }
+type QuoteProps = StaticPropsValue<typeof triggerProps>;
- if (quotes.length < pageSize) break;
- }
- return results;
+const polling: Polling<AppConnectionValueForAuthProperty<typeof xeroAuth>, QuoteProps> = {
+ strategy: DedupeStrategy.TIMEBASED,
+ async items({ auth, propsValue, lastFetchEpochMS }) {
+ const { request, matches } = quoteRequest({ accessToken: auth.access_token, propsValue });
+ const records = await xeroPolling.fetchUpdated({
+ ...request,
+ lastFetchEpochMS,
+ pageSize: xeroPolling.pageSizeOf({ value: propsValue.page_size, fallback: 200, max: 1000 }),
+ });
+ return xeroPolling.toItems({ records, matches });
},
};
@@ -101,73 +60,66 @@ export const xeroUpdatedQuote = createTrigger({
displayName: 'Updated Quote',
description: 'Fires when a quote is created or updated.',
aiMetadata: {
- description: 'Fires when a quote is created or updated in the connected Xero organisation. Polls the Xero Quotes endpoint and emits a quote whenever its UpdatedDateUTC advances beyond the last seen value, so it fires on both new quotes and subsequent edits, optionally filtered by status (DRAFT, SENT, ACCEPTED, DECLINED, INVOICED, DELETED), contact, quote number, or date/expiry range. Each item is a full quote record (number, status, contact, line items, totals).',
+ description:
+ 'Fires each time a quote is created or edited after the trigger is enabled (whenever its UpdatedDateUTC moves forward), optionally filtered by status, contact, quote number, or date and expiry ranges. Each item is one full quote; use New Quote to fire only once per quote.',
},
props: {
- tenant_id: props.tenant_id,
- statuses: Property.StaticMultiSelectDropdown({
- displayName: 'Filter by Status (optional)',
- required: false,
- options: {
- options: [
- { label: 'DRAFT', value: 'DRAFT' },
- { label: 'SENT', value: 'SENT' },
- { label: 'ACCEPTED', value: 'ACCEPTED' },
- { label: 'DECLINED', value: 'DECLINED' },
- { label: 'INVOICED', value: 'INVOICED' },
- { label: 'DELETED', value: 'DELETED' },
- ],
- },
- }),
- contact_id: props.contact_dropdown(false),
- quote_number: Property.ShortText({ displayName: 'Quote Number (partial match)', required: false }),
- date_from: Property.ShortText({ displayName: 'Date From (YYYY-MM-DD)', required: false }),
- date_to: Property.ShortText({ displayName: 'Date To (YYYY-MM-DD)', required: false }),
- expiry_date_from: Property.ShortText({ displayName: 'Expiry Date From (YYYY-MM-DD)', required: false }),
- expiry_date_to: Property.ShortText({ displayName: 'Expiry Date To (YYYY-MM-DD)', required: false }),
- page_size: Property.Number({ displayName: 'Page Size (1-1000)', required: false }),
+ tenant_id: triggerProps.tenant_id,
+ statuses: triggerProps.statuses,
+ contact_id: triggerProps.contact_id,
+ quote_number: triggerProps.quote_number,
+ date_from: triggerProps.date_from,
+ date_to: triggerProps.date_to,
+ expiry_date_from: triggerProps.expiry_date_from,
+ expiry_date_to: triggerProps.expiry_date_to,
+ page_size: triggerProps.page_size,
},
type: TriggerStrategy.POLLING,
- async onEnable(context: any) {
- await pollingHelper.onEnable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ outputSchema: xeroOutputSchemas.quote,
+ sampleData: xeroSamples.quote,
+ async onEnable(context) {
+ await xeroPolling.keepStateOnRepublish({ store: context.store, isRepublish: context.isRepublish, propsValue: context.propsValue });
+ await pollingHelper.onEnable(polling, context);
},
- async onDisable(context: any) {
- await pollingHelper.onDisable(polling, {
- auth: context.auth,
- store: context.store,
- propsValue: context.propsValue,
- });
+ async onDisable(context) {
+ await pollingHelper.onDisable(polling, context);
},
- async test(context: any) {
- return await pollingHelper.test(polling, context);
+ async test(context) {
+ const { request, matches } = quoteRequest({ accessToken: context.auth.access_token, propsValue: context.propsValue });
+ return (await xeroPolling.fetchRecent(request)).filter(matches);
},
- async run(context: any) {
- const items = (await pollingHelper.poll(polling, context)) as any[];
- const tenantId = context.propsValue['tenant_id'];
-
- const prevMapKey = `xero_quote_prev_updated_${tenantId}`;
- const prevMap: Record<string, number> = (await context.store.get(prevMapKey)) || {};
-
- const results: any[] = [];
- for (const q of items) {
- const id = q?.QuoteID as string | undefined;
- if (!id) continue;
- const updatedEpoch = parseXeroDateToEpoch(q?.UpdatedDateUTC || q?.Date);
- const prevEpoch = prevMap[id] || 0;
- if (updatedEpoch > prevEpoch) {
- results.push(q);
- prevMap[id] = updatedEpoch;
- }
- }
-
- await context.store.put(prevMapKey, prevMap);
- return results;
+ async run(context) {
+ const items = xeroPolling.records({ items: await pollingHelper.poll(polling, context) });
+ const key = `xero_quote_prev_updated_${context.propsValue.tenant_id}`;
+ const previous = xeroTriggerState.readMap({
+ value: await context.store.get<unknown>(key),
+ isValue: (entry): entry is number => typeof entry === 'number',
+ });
+ const next = new Map(Object.entries(previous));
+ const emitted = items.filter((record) => {
+ const id = xeroPolling.idOf({ record, key: 'QuoteID' });
+ if (id === undefined) return false;
+ const updated = xeroPolling.epochOf({ record });
+ if (updated <= (next.get(id) ?? 0)) return false;
+ next.delete(id);
+ next.set(id, updated);
+ return true;
+ });
+ await context.store.put(key, xeroTriggerState.boundMap({ map: Object.fromEntries(next) }));
+ return emitted;
},
- sampleData: undefined,
});
-
+function quoteRequest({ accessToken, propsValue }: { accessToken: string; propsValue: QuoteProps }) {
+ return xeroPolling.quoteRequest({
+ accessToken,
+ tenantId: propsValue.tenant_id,
+ statuses: propsValue.statuses,
+ contactId: propsValue.contact_id,
+ quoteNumber: propsValue.quote_number,
+ dateFrom: propsValue.date_from,
+ dateTo: propsValue.date_to,
+ expiryDateFrom: propsValue.expiry_date_from,
+ expiryDateTo: propsValue.expiry_date_to,
+ });
+}
diff --git a/packages/pieces/community/xero/src/lib/triggers/updated-sales-invoice.ts b/packages/pieces/community/xero/src/lib/triggers/updated-sales-invoice.ts
index 1af44e914bf..c989eff3d4b 100644
--- a/packages/pieces/community/xero/src/lib/triggers/updated-sales-invoice.ts
+++ b/packages/pieces/community/xero/src/lib/triggers/updated-sales-invoice.ts
@@ -1,14 +1,9 @@
-import { createTrigger, TriggerStrategy, Property } from '@activepieces/pieces-framework';
+import { Property, TriggerStrategy, WebhookHandshakeStrategy, createTrigger } from '@activepieces/pieces-framework';
import { xeroAuth } from '../..';
-import { createHmac } from 'crypto';
-import {
- AuthenticationType,
- HttpMethod,
- HttpRequest,
- httpClient,
-} from '@activepieces/pieces-common';
import { props } from '../common/props';
-
+import { xeroSamples } from '../common/samples';
+import { xeroWebhook } from '../common/trigger-state';
+import { xeroOutputSchemas } from '../output-schemas';
export const xeroUpdatedSalesInvoice = createTrigger({
auth: xeroAuth,
@@ -17,29 +12,12 @@ export const xeroUpdatedSalesInvoice = createTrigger({
displayName: 'Updated Sales Invoice',
description: 'Fires when an existing sales invoice (Accounts Receivable) is updated.',
aiMetadata: {
- description: 'Fires when an existing sales invoice (Accounts Receivable, Type ACCREC) is updated in the connected Xero organisation. Delivered through a Xero webhook on the INVOICE category filtered to UPDATE events; the full invoice is fetched and only ACCREC (sales) invoices are emitted, so bills (ACCPAY) are excluded. Each item is the full updated invoice (number, status, contact, line items, totals). Represents a change to an existing sales invoice, not a newly created one.',
+ description:
+ 'Fires once per edit of a sales invoice (Type ACCREC) in the connected Xero organisation, delivered by a Xero webhook (INVOICE category, UPDATE events) that you set up on your own Xero app; bills (ACCPAY) are skipped when Fetch Full Invoice is on, and duplicates are dropped. Each item is the full updated invoice, or the raw webhook event when Fetch Full Invoice is off.',
},
type: TriggerStrategy.WEBHOOK,
props: {
- webhookInstructions: Property.MarkDown({
- value: `
-To use this trigger, manually configure a Xero webhook for your app:
-
-1. Go to Xero Developer > My Apps > [Your App] > Webhooks.
-2. Select the Invoice category.
-3. Set the Delivery URL to:
-\n\n\`\`\`text
-{{webhookUrl}}
-\`\`\`
-4. Click Save, then click Validate "Intent to receive".
-5. Copy the Webhook Key from the Webhooks page and paste it into the Webhook Key field below.
-6. Optionally set Organization ID (Tenant ID) to only accept events from a specific org.
-
-Notes:
-- Keep this trigger enabled so the URL remains active.
-- We verify Xero's x-xero-signature header using your Webhook Key.
- `,
- }),
+ webhookInstructions: Property.MarkDown({ value: xeroWebhook.instructions({ category: 'Invoice' }) }),
tenant_id: props.tenant_id,
webhook_key: Property.ShortText({
displayName: 'Webhook Key',
@@ -48,87 +26,36 @@ Notes:
}),
fetch_full_invoice: Property.Checkbox({
displayName: 'Fetch Full Invoice',
- description: 'Fetch the full invoice and ensure Type is ACCREC (recommended).',
+ description: 'Fetch the full invoice and ensure Type is ACCREC (recommended). If disabled, the output is the raw webhook event and bills are not filtered out.',
required: false,
defaultValue: true,
}),
},
- sampleData: {
- InvoiceID: '243216c5-369e-4056-ac67-05388f86dc81',
- Type: 'ACCREC',
- InvoiceNumber: 'INV-0001',
- Status: 'AUTHORISED',
+ outputSchema: xeroOutputSchemas.invoice,
+ sampleData: xeroSamples.invoice,
+ handshakeConfiguration: {
+ strategy: WebhookHandshakeStrategy.HEADER_PRESENT,
+ paramName: xeroWebhook.handshakeConfiguration.paramName,
},
- async onEnable(): Promise<void> {
- // The user has already enabled the trigger, so we don't need to do anything
+ async onHandshake(context) {
+ return xeroWebhook.handshake({ payload: context.payload, webhookKey: context.propsValue.webhook_key });
},
- async onDisable(): Promise<void> {
- // The user has already disabled the trigger, so we don't need to do anything
+ async onEnable() {
+ return;
},
- async run(context: any) {
- const { webhook_key, tenant_id, fetch_full_invoice } = context.propsValue as any;
-
- const signatureHeader = context.payload.headers['x-xero-signature'] as string | undefined;
- const rawBody = context.payload.rawBody as string | undefined;
- if (!signatureHeader || !rawBody) {
- return [];
- }
-
- const computed = createHmac('sha256', webhook_key).update(rawBody).digest('base64');
- if (computed !== signatureHeader) {
- return [];
- }
-
- const body = context.payload.body as any;
- const events: any[] = body?.events ?? [];
- if (!Array.isArray(events) || events.length === 0) {
- return [];
- }
-
- // Filter to INVOICE UPDATE events, optional tenant match
- const filtered = events.filter((e) => {
- const isInvoice = e.eventCategory === 'INVOICE';
- const isUpdate = e.eventType === 'UPDATE';
- const tenantOk = tenant_id ? e.tenantId === tenant_id : true;
- return isInvoice && isUpdate && tenantOk;
+ async onDisable() {
+ return;
+ },
+ async run(context) {
+ return xeroWebhook.processDelivery({
+ payload: context.payload,
+ webhookKey: context.propsValue.webhook_key,
+ tenantId: context.propsValue.tenant_id,
+ accessToken: context.auth.access_token,
+ store: context.store,
+ resource: { category: 'INVOICE', path: 'Invoices', eventTypes: ['UPDATE'] },
+ fetchFull: context.propsValue.fetch_full_invoice !== false,
+ accept: (record) => record['Type'] === 'ACCREC',
});
- if (filtered.length === 0) {
- return [];
- }
-
- if (!fetch_full_invoice) {
- return filtered;
- }
-
- const results: any[] = [];
- for (const ev of filtered) {
- try {
- const req: HttpRequest = {
- method: HttpMethod.GET,
- url: ev.resourceUrl,
- authentication: {
- type: AuthenticationType.BEARER_TOKEN,
- token: (context.auth as any).access_token,
- },
- headers: {
- 'Xero-Tenant-Id': ev.tenantId,
- Accept: 'application/json',
- },
- };
- const resp = await httpClient.sendRequest<any>(req);
- if (resp.status === 200) {
- const inv = resp.body?.Invoices?.[0] ?? resp.body;
- if (inv?.Type === 'ACCREC') {
- results.push(inv);
- }
- }
- } catch {
- // ignore
- }
- }
-
- return results;
},
});
-
-
diff --git a/packages/pieces/community/xero/test/actions.test.ts b/packages/pieces/community/xero/test/actions.test.ts
new file mode 100644
index 00000000000..b28b62f9a4b
--- /dev/null
+++ b/packages/pieces/community/xero/test/actions.test.ts
@@ -0,0 +1,369 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import '../src';
+import { xeroCreateInvoiceAi } from '../src/lib/actions/ai/create-invoice';
+import { xeroCreatePaymentAi } from '../src/lib/actions/ai/create-payment';
+import { xeroUpdateInvoiceAi } from '../src/lib/actions/ai/update-invoice';
+import { xeroCreateInventoryItem } from '../src/lib/actions/create-inventory-item';
+import { xeroCreateManualJournal } from '../src/lib/actions/create-manual-journal';
+import { xeroGetProfitAndLoss } from '../src/lib/actions/get-profit-and-loss';
+import { xeroGetAgedPayables } from '../src/lib/actions/get-aged-payables';
+import { xeroSearchInvoices } from '../src/lib/actions/search-invoices';
+import { xeroVoidInvoice } from '../src/lib/actions/void-invoice';
+import { xeroDeletePayment } from '../src/lib/actions/delete-payment';
+import { xeroAllocateCreditNoteToInvoice } from '../src/lib/actions/allocate-credit-note-to-invoice';
+import { xeroAttachments } from '../src/lib/common/attachments';
+import {
+ requestedBody,
+ requestedMethod,
+ requestedRawBody,
+ requestedUrl,
+ runAction,
+ stubFetch,
+ stubFetchSequence,
+} from './helpers';
+
+const CONTACT_ID = '6d42f03b-181f-43e3-93fb-2025c012de92';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Create Invoice or Bill (AI)', () => {
+ it('resolves the only organisation, sends unitdp=4 and keeps 4-decimal amounts exactly', async () => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ { status: 200, body: [{ id: 'c1', tenantId: 'org-1', tenantType: 'ORGANISATION', tenantName: 'Demo' }] },
+ { status: 200, body: { Invoices: [{ InvoiceID: 'inv-1', Status: 'DRAFT' }] } },
+ ],
+ });
+ const result = await runAction({
+ action: xeroCreateInvoiceAi,
+ propsValue: {
+ type: 'ACCREC',
+ contact_id: CONTACT_ID,
+ line_items: [{ Description: 'Widget', Quantity: '3', UnitAmount: '10.1234', AccountCode: '200' }],
+ due_date: '2026-10-19',
+ reference: 'AP-TEST-1',
+ },
+ });
+ expect(requestedUrl({ fetchMock, call: 0 })).toBe('https://api.xero.com/connections');
+ expect(requestedUrl({ fetchMock, call: 1 })).toBe('https://api.xero.com/api.xro/2.0/Invoices?unitdp=4');
+ expect(requestedMethod({ fetchMock, call: 1 })).toBe('PUT');
+ expect(String(requestedRawBody({ fetchMock, call: 1 }))).toContain('"UnitAmount":10.1234');
+ expect(requestedBody({ fetchMock, call: 1 })).toEqual({
+ Invoices: [
+ {
+ Type: 'ACCREC',
+ Contact: { ContactID: CONTACT_ID },
+ LineItems: [{ Description: 'Widget', Quantity: 3, UnitAmount: 10.1234, AccountCode: '200' }],
+ Status: 'DRAFT',
+ DueDate: '2026-10-19',
+ Reference: 'AP-TEST-1',
+ },
+ ],
+ });
+ expect(result).toEqual({ InvoiceID: 'inv-1', Status: 'DRAFT' });
+ });
+
+ it('rejects bad line items before calling Xero', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ await expect(
+ runAction({ action: xeroCreateInvoiceAi, propsValue: { tenant_id: 'org-1', type: 'ACCREC', contact_id: CONTACT_ID, line_items: [{ Description: 'x', Price: 5 }] } }),
+ ).rejects.toThrow('unknown keys: Price');
+ await expect(
+ runAction({ action: xeroCreateInvoiceAi, propsValue: { tenant_id: 'org-1', type: 'ACCREC', contact_id: CONTACT_ID, line_items: [{ Description: 'x', UnitAmount: 1.23456 }] } }),
+ ).rejects.toThrow('at most 4 decimal places');
+ await expect(
+ runAction({ action: xeroCreateInvoiceAi, propsValue: { tenant_id: 'org-1', type: 'ACCREC', contact_id: CONTACT_ID, line_items: [{ Quantity: 1 }] } }),
+ ).rejects.toThrow('needs a Description or an ItemCode');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('Update Invoice or Bill (AI)', () => {
+ it('merges lines by LineItemID and appends new ones', async () => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ { status: 200, body: { Invoices: [{ InvoiceID: 'inv-1', LineItems: [{ LineItemID: 'l1', Description: 'Old', Quantity: 1, UnitAmount: 5, LineAmount: 5 }] }] } },
+ { status: 200, body: { Invoices: [{ InvoiceID: 'inv-1' }] } },
+ ],
+ });
+ await runAction({
+ action: xeroUpdateInvoiceAi,
+ propsValue: {
+ tenant_id: 'org-1',
+ invoice_id: 'inv-1',
+ merge_line_items: true,
+ line_items: [{ LineItemID: 'l1', Quantity: 2 }, { Description: 'New', Quantity: 1, UnitAmount: 7 }],
+ },
+ });
+ expect(requestedBody({ fetchMock, call: 1 })).toEqual({
+ Invoices: [
+ {
+ LineItems: [
+ { LineItemID: 'l1', Description: 'Old', Quantity: 2, UnitAmount: 5 },
+ { Description: 'New', Quantity: 1, UnitAmount: 7 },
+ ],
+ },
+ ],
+ });
+ });
+
+ it('drops the saved totals when a merged line changes its price, and keeps them when it does not', async () => {
+ const saved = { LineItemID: 'l1', Description: 'Old', Quantity: 1, UnitAmount: 5, LineAmount: 5, TaxType: 'OUTPUT', TaxAmount: 0.75 };
+ const run = async ({ update }: { update: Record<string, unknown> }) => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ { status: 200, body: { Invoices: [{ InvoiceID: 'inv-1', LineItems: [saved] }] } },
+ { status: 200, body: { Invoices: [{ InvoiceID: 'inv-1' }] } },
+ ],
+ });
+ await runAction({ action: xeroUpdateInvoiceAi, propsValue: { tenant_id: 'org-1', invoice_id: 'inv-1', merge_line_items: true, line_items: [{ LineItemID: 'l1', ...update }] } });
+ const body = requestedBody({ fetchMock, call: 1 });
+ return Reflect.get(Object(body), 'Invoices')[0].LineItems[0];
+ };
+ expect(await run({ update: { UnitAmount: 8 } })).toEqual({ LineItemID: 'l1', Description: 'Old', Quantity: 1, UnitAmount: 8, TaxType: 'OUTPUT' });
+ expect(await run({ update: { DiscountRate: 10 } })).toEqual({ LineItemID: 'l1', Description: 'Old', Quantity: 1, UnitAmount: 5, TaxType: 'OUTPUT', DiscountRate: 10 });
+ expect(await run({ update: { Quantity: 3, LineAmount: 15 } })).toEqual({ LineItemID: 'l1', Description: 'Old', Quantity: 3, UnitAmount: 5, LineAmount: 15, TaxType: 'OUTPUT' });
+ expect(await run({ update: { TaxType: 'NONE' } })).toEqual({ LineItemID: 'l1', Description: 'Old', Quantity: 1, UnitAmount: 5, LineAmount: 5, TaxType: 'NONE' });
+ expect(await run({ update: { Description: 'Renamed' } })).toEqual({ ...saved, Description: 'Renamed' });
+ });
+
+ it('refuses an update with nothing to change', async () => {
+ stubFetch({ status: 200, body: {} });
+ await expect(runAction({ action: xeroUpdateInvoiceAi, propsValue: { tenant_id: 'org-1', invoice_id: 'inv-1' } })).rejects.toThrow('Nothing to update');
+ });
+});
+
+describe('Record Payment (AI)', () => {
+ it('needs exactly one of account ID or code', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ await expect(
+ runAction({ action: xeroCreatePaymentAi, propsValue: { tenant_id: 'org-1', invoice_id: 'inv-1', account_id: 'a', account_code: '090', amount: 5, date: '2026-10-05' } }),
+ ).rejects.toThrow('exactly one of Account ID or Account Code');
+ await expect(
+ runAction({ action: xeroCreatePaymentAi, propsValue: { tenant_id: 'org-1', invoice_id: 'inv-1', account_code: '090', amount: 5.555, date: '2026-10-05' } }),
+ ).rejects.toThrow('at most 2 decimal places');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('Create Inventory Item account codes', () => {
+ it('turns the selected account IDs into the account codes Xero reads', async () => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ {
+ status: 200,
+ body: {
+ Accounts: [
+ { AccountID: 'acc-sales', Code: '200' },
+ { AccountID: 'acc-cogs', Code: '310' },
+ { AccountID: 'acc-inv', Code: '630' },
+ ],
+ },
+ },
+ { status: 200, body: { Items: [{ ItemID: 'i1', Code: 'AP-TEST-ITEM-1' }] } },
+ ],
+ });
+ const result = await runAction({
+ action: xeroCreateInventoryItem,
+ propsValue: {
+ tenant_id: 'org-1',
+ code: 'AP-TEST-ITEM-1',
+ sales_details: { UnitPrice: 10 },
+ purchase_details: { UnitPrice: 4 },
+ sales_account_id: 'acc-sales',
+ cogs_account_id: 'acc-cogs',
+ inventory_asset_account_id: 'acc-inv',
+ },
+ });
+ expect(requestedUrl({ fetchMock, call: 0 })).toBe('https://api.xero.com/api.xro/2.0/Accounts');
+ expect(requestedBody({ fetchMock, call: 1 })).toEqual({
+ Code: 'AP-TEST-ITEM-1',
+ SalesDetails: { UnitPrice: 10, AccountCode: '200' },
+ PurchaseDetails: { UnitPrice: 4, COGSAccountCode: '310' },
+ InventoryAssetAccountCode: '630',
+ IsTrackedAsInventory: true,
+ });
+ expect(JSON.stringify(requestedBody({ fetchMock, call: 1 }))).not.toContain('AccountID');
+ expect(result).toEqual({ Items: [{ ItemID: 'i1', Code: 'AP-TEST-ITEM-1' }] });
+ });
+
+ it('fails clearly when a selected account has no code', async () => {
+ stubFetchSequence({ responses: [{ status: 200, body: { Accounts: [{ AccountID: 'acc-x' }] } }] });
+ await expect(
+ runAction({ action: xeroCreateInventoryItem, propsValue: { tenant_id: 'org-1', code: 'X', sales_account_id: 'acc-x' } }),
+ ).rejects.toThrow('has no account code');
+ });
+
+ it('makes no extra call when no account is selected', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Items: [] } });
+ await runAction({ action: xeroCreateInventoryItem, propsValue: { tenant_id: 'org-1', code: 'X' } });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('Search Invoices', () => {
+ it('builds the query and reports another page when the page is full', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Invoices: [{ InvoiceID: 'a' }, { InvoiceID: 'b' }] } });
+ const result = await runAction({
+ action: xeroSearchInvoices,
+ propsValue: { tenant_id: 'org-1', type: 'ACCREC', statuses: ['AUTHORISED'], date_from: '2026-01-01', page: 1, page_size: 2, summary_only: true },
+ });
+ const url = new URL(requestedUrl({ fetchMock }));
+ expect(url.searchParams.get('where')).toBe('Type=="ACCREC" AND Date>=DateTime(2026, 1, 1)');
+ expect(url.searchParams.get('Statuses')).toBe('AUTHORISED');
+ expect(url.searchParams.get('pageSize')).toBe('2');
+ expect(result).toEqual({ items: [{ InvoiceID: 'a' }, { InvoiceID: 'b' }], page: 1, pageSize: 2, hasMore: true });
+ });
+
+ it('refuses page sizes above 100', async () => {
+ stubFetch({ status: 200, body: {} });
+ await expect(runAction({ action: xeroSearchInvoices, propsValue: { tenant_id: 'org-1', page_size: 500 } })).rejects.toThrow('1 to 100');
+ });
+});
+
+describe('Void or Delete Invoice', () => {
+ it('deletes drafts, voids authorised invoices and leaves voided ones alone', async () => {
+ const draft = stubFetchSequence({ responses: [{ status: 200, body: { Invoices: [{ InvoiceID: 'i1', Status: 'DRAFT' }] } }, { status: 200, body: { Invoices: [{ InvoiceID: 'i1', Status: 'DELETED' }] } }] });
+ await runAction({ action: xeroVoidInvoice, propsValue: { tenant_id: 'org-1', invoice_id: 'i1' } });
+ expect(requestedBody({ fetchMock: draft, call: 1 })).toEqual({ Invoices: [{ InvoiceID: 'i1', Status: 'DELETED' }] });
+
+ const authorised = stubFetchSequence({ responses: [{ status: 200, body: { Invoices: [{ InvoiceID: 'i2', Status: 'AUTHORISED', AmountPaid: 0 }] } }, { status: 200, body: { Invoices: [{ InvoiceID: 'i2', Status: 'VOIDED' }] } }] });
+ await runAction({ action: xeroVoidInvoice, propsValue: { tenant_id: 'org-1', invoice_id: 'i2' } });
+ expect(requestedBody({ fetchMock: authorised, call: 1 })).toEqual({ Invoices: [{ InvoiceID: 'i2', Status: 'VOIDED' }] });
+
+ const voided = stubFetch({ status: 200, body: { Invoices: [{ InvoiceID: 'i3', Status: 'VOIDED' }] } });
+ await expect(runAction({ action: xeroVoidInvoice, propsValue: { tenant_id: 'org-1', invoice_id: 'i3' } })).resolves.toEqual({ InvoiceID: 'i3', Status: 'VOIDED' });
+ expect(voided).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses paid invoices', async () => {
+ stubFetch({ status: 200, body: { Invoices: [{ InvoiceID: 'i4', Status: 'PAID', AmountPaid: 10 }] } });
+ await expect(runAction({ action: xeroVoidInvoice, propsValue: { tenant_id: 'org-1', invoice_id: 'i4' } })).rejects.toThrow('Delete the payments');
+ });
+});
+
+describe('Create Manual Journal', () => {
+ it('refuses unbalanced journals before calling Xero', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ await expect(
+ runAction({
+ action: xeroCreateManualJournal,
+ propsValue: { tenant_id: 'org-1', narration: 'AP-TEST', journal_lines: [{ LineAmount: 10, AccountCode: '400' }, { LineAmount: -9, AccountCode: '800' }] },
+ }),
+ ).rejects.toThrow('must balance');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('Reports', () => {
+ it('flattens Xero report rows into section, label and values', async () => {
+ stubFetch({
+ status: 200,
+ body: {
+ Reports: [
+ {
+ ReportID: 'ProfitAndLoss',
+ ReportName: 'Profit and Loss',
+ ReportType: 'ProfitAndLoss',
+ ReportTitles: ['Profit & Loss', 'Demo'],
+ ReportDate: '5 October 2026',
+ Rows: [
+ { RowType: 'Header', Cells: [{ Value: '' }, { Value: '31 Oct 26' }] },
+ {
+ RowType: 'Section',
+ Title: 'Income',
+ Rows: [{ RowType: 'Row', Cells: [{ Value: 'Sales', Attributes: [{ Id: 'account', Value: 'acc-1' }] }, { Value: '1200.50' }] }],
+ },
+ ],
+ },
+ ],
+ },
+ });
+ const result = await runAction({ action: xeroGetProfitAndLoss, propsValue: { tenant_id: 'org-1', from_date: '2026-10-01', to_date: '2026-10-31' } });
+ expect(result).toEqual({
+ reportId: 'ProfitAndLoss',
+ reportName: 'Profit and Loss',
+ reportType: 'ProfitAndLoss',
+ reportDate: '5 October 2026',
+ reportTitles: ['Profit & Loss', 'Demo'],
+ columns: ['', '31 Oct 26'],
+ rows: [{ section: 'Income', rowType: 'Row', label: 'Sales', values: ['1200.50'], accountId: 'acc-1', invoiceId: null }],
+ });
+ });
+
+ it('filters an aged report with Xero\'s contactId parameter and keeps each row\'s invoice ID', async () => {
+ const fetchMock = stubFetch({
+ status: 200,
+ body: {
+ Reports: [
+ {
+ ReportID: 'AgedPayablesByContact',
+ ReportName: 'Aged Payables By Contact',
+ ReportType: 'AgedPayablesByContact',
+ Rows: [
+ { RowType: 'Header', Cells: [{ Value: 'Date' }, { Value: 'Total' }] },
+ {
+ RowType: 'Section',
+ Rows: [
+ {
+ RowType: 'Row',
+ Cells: [
+ { Value: '2026-09-01T00:00:00', Attributes: [{ Id: 'invoiceID', Value: 'inv-9' }] },
+ { Value: '250.00', Attributes: [{ Id: 'invoiceID', Value: 'inv-9' }] },
+ ],
+ },
+ { RowType: 'SummaryRow', Cells: [{ Value: 'Total' }, { Value: '250.00' }] },
+ ],
+ },
+ ],
+ },
+ ],
+ },
+ });
+ const result = await runAction({ action: xeroGetAgedPayables, propsValue: { tenant_id: 'org-1', contact_id: CONTACT_ID } });
+ expect(new URL(requestedUrl({ fetchMock })).searchParams.get('contactId')).toBe(CONTACT_ID);
+ expect((result as { rows: unknown[] }).rows).toEqual([
+ { section: '', rowType: 'Row', label: '2026-09-01T00:00:00', values: ['250.00'], accountId: null, invoiceId: 'inv-9' },
+ { section: '', rowType: 'SummaryRow', label: 'Total', values: ['250.00'], accountId: null, invoiceId: null },
+ ]);
+ });
+
+ it('refuses more than 11 comparison periods', async () => {
+ stubFetch({ status: 200, body: {} });
+ await expect(runAction({ action: xeroGetProfitAndLoss, propsValue: { tenant_id: 'org-1', periods: 12 } })).rejects.toThrow('1 to 11');
+ });
+});
+
+describe('Attachment MIME types', () => {
+ it('maps common extensions instead of application/<ext>', () => {
+ expect(xeroAttachments.mimeTypeFor({ fileName: 'scan.PNG' })).toBe('image/png');
+ expect(xeroAttachments.mimeTypeFor({ fileName: 'photo', extension: 'jpg' })).toBe('image/jpeg');
+ expect(xeroAttachments.mimeTypeFor({ fileName: 'sheet.xlsx' })).toBe('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
+ expect(xeroAttachments.mimeTypeFor({ fileName: 'unknown.bin' })).toBe('application/octet-stream');
+ });
+});
+
+describe('fixes found in the live run', () => {
+ it('Void sends unitdp=4 so invoices with 4-decimal prices pass Xero validation', async () => {
+ const fetchMock = stubFetchSequence({ responses: [{ status: 200, body: { Invoices: [{ InvoiceID: 'i2', Status: 'AUTHORISED', AmountPaid: 0 }] } }, { status: 200, body: { Invoices: [{ InvoiceID: 'i2', Status: 'VOIDED' }] } }] });
+ await runAction({ action: xeroVoidInvoice, propsValue: { tenant_id: 'org-1', invoice_id: 'i2' } });
+ expect(requestedUrl({ fetchMock, call: 0 })).toBe('https://api.xero.com/api.xro/2.0/Invoices/i2?unitdp=4');
+ expect(requestedUrl({ fetchMock, call: 1 })).toBe('https://api.xero.com/api.xro/2.0/Invoices/i2?unitdp=4');
+ });
+
+ it('Delete Payment returns an already deleted payment without a second delete', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Payments: [{ PaymentID: 'p1', Status: 'DELETED' }] } });
+ await expect(runAction({ action: xeroDeletePayment, propsValue: { tenant_id: 'org-1', payment_id: 'p1' } })).resolves.toEqual({ PaymentID: 'p1', Status: 'DELETED' });
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(requestedMethod({ fetchMock })).toBe('GET');
+ });
+
+ it('Allocate Credit Note uses PUT, which Xero requires for allocations', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Allocations: [{ AllocationID: 'a1' }] } });
+ await runAction({ action: xeroAllocateCreditNoteToInvoice, propsValue: { tenant_id: 'org-1', credit_note_id: 'cn-1', invoice_id: 'inv-1', amount: 4 } });
+ expect(requestedMethod({ fetchMock })).toBe('PUT');
+ expect(requestedUrl({ fetchMock })).toBe('https://api.xero.com/api.xro/2.0/CreditNotes/cn-1/Allocations');
+ });
+});
diff --git a/packages/pieces/community/xero/test/client.test.ts b/packages/pieces/community/xero/test/client.test.ts
new file mode 100644
index 00000000000..b809f553ed6
--- /dev/null
+++ b/packages/pieces/community/xero/test/client.test.ts
@@ -0,0 +1,184 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { HttpMethod } from '@activepieces/pieces-common';
+import { XeroApiError, xeroApi, xeroInput } from '../src/lib/common/client';
+import { aiInput } from '../src/lib/common/ai-props';
+import { requestedHeaders, requestedUrl, stubFetch, stubFetchSequence } from './helpers';
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+});
+
+async function withFakeTimers<T>(run: () => Promise<T>): Promise<T> {
+ vi.useFakeTimers();
+ const pending = run();
+ await vi.advanceTimersByTimeAsync(30000);
+ return pending;
+}
+
+function get() {
+ return xeroApi.request<unknown>({
+ accessToken: 'tok_test',
+ tenantId: 'org-1',
+ method: HttpMethod.GET,
+ url: 'https://api.xero.com/api.xro/2.0/Contacts',
+ operation: 'list contacts',
+ });
+}
+
+describe('xeroApi.request rate limits and errors', () => {
+ it('sends the bearer token and tenant header', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Contacts: [] } });
+ await get();
+ expect(requestedUrl({ fetchMock })).toBe('https://api.xero.com/api.xro/2.0/Contacts');
+ expect(requestedHeaders({ fetchMock }).get('authorization')).toBe('Bearer tok_test');
+ expect(requestedHeaders({ fetchMock }).get('xero-tenant-id')).toBe('org-1');
+ });
+
+ it('retries once after a 429 and returns the second response', async () => {
+ const fetchMock = stubFetchSequence({ responses: [{ status: 429, body: {} }, { status: 200, body: { Contacts: [{ ContactID: 'c1' }] } }] });
+ await expect(withFakeTimers(() => get())).resolves.toEqual({ Contacts: [{ ContactID: 'c1' }] });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('throws a named rate-limit error after a second 429', async () => {
+ const fetchMock = stubFetchSequence({ responses: [{ status: 429, body: { Title: 'Too Many Requests' } }] });
+ const error = await withFakeTimers(() => get().catch((e: unknown) => e));
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(error).toBeInstanceOf(XeroApiError);
+ expect(String(Reflect.get(Object(error), 'message'))).toContain('60 calls per minute');
+ expect(Reflect.get(Object(error), 'status')).toBe(429);
+ expect(Object.keys(Object(error))).not.toContain('body');
+ expect(Reflect.get(Object(error), 'responseBody')).toEqual({ Title: 'Too Many Requests' });
+ });
+
+ it('waits 30 seconds before the single retry', async () => {
+ vi.useFakeTimers();
+ const fetchMock = stubFetchSequence({ responses: [{ status: 429, body: {} }, { status: 200, body: { ok: true } }] });
+ const pending = get();
+ await vi.advanceTimersByTimeAsync(29000);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1000);
+ await expect(pending).resolves.toEqual({ ok: true });
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('bounds the error message and the vendor body kept on the error', async () => {
+ const longMessage = 'x'.repeat(1500);
+ stubFetch({ status: 400, body: { Message: longMessage, Elements: Array.from({ length: 40 }, () => ({ Name: 'y'.repeat(100) })) } });
+ const error = await get().catch((e: unknown) => e);
+ expect(error).toBeInstanceOf(XeroApiError);
+ expect(String(Reflect.get(Object(error), 'message')).length).toBeLessThan(1200);
+ const kept = Reflect.get(Object(error), 'responseBody');
+ expect(typeof kept === 'string' && kept.length).toBeLessThanOrEqual(4001);
+ expect(String(Reflect.get(Object(error), 'message'))).not.toContain('tok_test');
+ });
+
+ it('puts Xero validation messages into the error message', async () => {
+ stubFetch({
+ status: 400,
+ body: {
+ ErrorNumber: 10,
+ Type: 'ValidationException',
+ Message: 'A validation exception occurred',
+ Elements: [{ ValidationErrors: [{ Message: 'Account code \'999\' is not a valid code for this document.' }] }],
+ },
+ });
+ await expect(get()).rejects.toThrow("Xero list contacts failed (HTTP 400): Account code '999' is not a valid code for this document.");
+ });
+
+ it('does not retry other errors', async () => {
+ const fetchMock = stubFetch({ status: 500, body: { Message: 'boom' } });
+ await expect(get()).rejects.toThrow('HTTP 500');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('where clauses', () => {
+ it('escapes double quotes by doubling them, as Xero requires', () => {
+ expect(xeroInput.whereString({ value: 'Bob "The Builder"' })).toBe('"Bob ""The Builder"""');
+ });
+
+ it('only accepts GUIDs inside guid()', () => {
+ expect(xeroInput.whereGuid({ value: ' 6d42f03b-181f-43e3-93fb-2025c012de92 ', field: 'Contact' })).toBe('guid("6d42f03b-181f-43e3-93fb-2025c012de92")');
+ expect(() => xeroInput.whereGuid({ value: '") OR (1==1', field: 'Contact' })).toThrow('Contact must be a Xero ID');
+ });
+
+ it('validates calendar dates', () => {
+ expect(xeroInput.parseDateInput({ value: '2026-02-28', field: 'Date' })).toBe('2026-02-28');
+ expect(() => xeroInput.parseDateInput({ value: '2026-02-30', field: 'Date' })).toThrow('not a valid calendar date');
+ expect(() => xeroInput.parseDateInput({ value: '28/02/2026', field: 'Date' })).toThrow('YYYY-MM-DD');
+ expect(xeroInput.whereDate({ value: '2026-02-08' })).toBe('DateTime(2026, 2, 8)');
+ });
+});
+
+describe('decimal precision', () => {
+ it('keeps up to the allowed decimal places exactly', () => {
+ expect(xeroInput.parseDecimal({ value: '10.1234', field: 'UnitAmount', maxDecimals: 4 })).toBe(10.1234);
+ expect(xeroInput.parseDecimal({ value: 0.1, field: 'Amount', maxDecimals: 2 })).toBe(0.1);
+ });
+
+ it('rejects values that would be rounded or lose precision', () => {
+ expect(() => xeroInput.parseDecimal({ value: '10.12345', field: 'UnitAmount', maxDecimals: 4 })).toThrow('at most 4 decimal places');
+ expect(() => xeroInput.parseDecimal({ value: '1234567890123456', field: 'Amount', maxDecimals: 2 })).toThrow('15 significant digits');
+ expect(() => xeroInput.parseDecimal({ value: '1e5', field: 'Amount', maxDecimals: 2 })).toThrow('plain number');
+ expect(() => xeroInput.parseDecimal({ value: '0', field: 'Amount', maxDecimals: 2, positive: true })).toThrow('greater than zero');
+ });
+
+ it('checks that journal lines balance with exact arithmetic', () => {
+ const lines = aiInput.parseJournalLines({
+ value: [
+ { LineAmount: 0.1, AccountCode: '400' },
+ { LineAmount: 0.2, AccountCode: '400' },
+ { LineAmount: -0.3, AccountCode: '800' },
+ ],
+ });
+ expect(lines).toHaveLength(3);
+ expect(() =>
+ aiInput.parseJournalLines({
+ value: [
+ { LineAmount: 100, AccountCode: '400' },
+ { LineAmount: -99.99, AccountCode: '800' },
+ ],
+ }),
+ ).toThrow('they add up to 0.01');
+ });
+});
+
+describe('pagination caps', () => {
+ it('defaults to page 1 with the maximum page size and refuses larger pages', () => {
+ expect(xeroInput.pageParams({ page: undefined, pageSize: undefined, maxPageSize: 100 })).toEqual({ page: 1, pageSize: 100 });
+ expect(() => xeroInput.pageParams({ page: 1, pageSize: 101, maxPageSize: 100 })).toThrow('1 to 100');
+ expect(() => xeroInput.pageParams({ page: 0, pageSize: 10, maxPageSize: 100 })).toThrow('Page must be');
+ });
+
+ it('uses Xero pagination metadata when present, otherwise a full page means more', () => {
+ expect(xeroApi.pageResult({ body: { Invoices: [{}, {}], pagination: { page: 1, pageCount: 1 } }, key: 'Invoices', page: 1, pageSize: 2 }).hasMore).toBe(false);
+ expect(xeroApi.pageResult({ body: { Invoices: [{}, {}] }, key: 'Invoices', page: 1, pageSize: 2 }).hasMore).toBe(true);
+ expect(xeroApi.pageResult({ body: { Invoices: [{}] }, key: 'Invoices', page: 1, pageSize: 2 }).hasMore).toBe(false);
+ });
+});
+
+describe('organisation resolution for AI actions', () => {
+ it('uses the given organisation without calling Xero', async () => {
+ const fetchMock = stubFetch({ status: 200, body: [] });
+ await expect(xeroApi.resolveTenantId({ accessToken: 't', tenantId: ' org-9 ' })).resolves.toBe('org-9');
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('uses the only connected organisation', async () => {
+ stubFetch({ status: 200, body: [{ id: 'c1', tenantId: 'org-1', tenantType: 'ORGANISATION', tenantName: 'Demo' }] });
+ await expect(xeroApi.resolveTenantId({ accessToken: 't', tenantId: undefined })).resolves.toBe('org-1');
+ });
+
+ it('asks for an organisation when several are connected', async () => {
+ stubFetch({
+ status: 200,
+ body: [
+ { id: 'c1', tenantId: 'org-1', tenantType: 'ORGANISATION', tenantName: 'Demo' },
+ { id: 'c2', tenantId: 'org-2', tenantType: 'ORGANISATION', tenantName: 'Second' },
+ ],
+ });
+ await expect(xeroApi.resolveTenantId({ accessToken: 't', tenantId: '' })).rejects.toThrow('Demo (org-1), Second (org-2)');
+ });
+});
diff --git a/packages/pieces/community/xero/test/helpers.ts b/packages/pieces/community/xero/test/helpers.ts
new file mode 100644
index 00000000000..6f5f43bb0ed
--- /dev/null
+++ b/packages/pieces/community/xero/test/helpers.ts
@@ -0,0 +1,117 @@
+import { AppConnectionType } from '@activepieces/pieces-framework';
+import { vi } from 'vitest';
+import { createMockActionContext } from '../../../framework/src/lib/test';
+
+export function oauthAuth() {
+ return {
+ type: AppConnectionType.OAUTH2,
+ access_token: 'tok_test',
+ client_id: 'client',
+ client_secret: 'secret',
+ redirect_url: 'https://example.com/redirect',
+ token_type: 'Bearer',
+ claimed_at: 0,
+ refresh_token: 'refresh',
+ scope: 'openid',
+ token_url: 'https://identity.xero.com/connect/token',
+ data: {},
+ };
+}
+
+export function jsonResponse({ status, body }: { status: number; body: unknown }) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+export function stubFetch({ status, body }: { status: number; body: unknown }) {
+ const fetchMock = vi.fn(async () => jsonResponse({ status, body }));
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+export function requestedUrl({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }) {
+ const input = fetchMock.mock.calls[call]?.[0];
+ return typeof input === 'string' ? input : String(input);
+}
+
+export function requestedHeaders({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }) {
+ const init = fetchMock.mock.calls[call]?.[1];
+ return new Headers(init?.headers);
+}
+
+export function runAction({
+ action,
+ propsValue,
+}: {
+ action: { run: (context: never) => Promise<unknown> };
+ propsValue: Record<string, unknown>;
+}): Promise<unknown> {
+ const context = { ...createMockActionContext({ propsValue: {} }), propsValue, auth: oauthAuth() };
+ return Reflect.apply(action.run, action, [context]);
+}
+
+export function stubFetchSequence({ responses }: { responses: { status: number; body: unknown }[] }) {
+ let call = 0;
+ const fetchMock = vi.fn(async () => {
+ const response = responses[Math.min(call, responses.length - 1)];
+ call += 1;
+ return jsonResponse(response);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+export function requestedBody({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }): unknown {
+ const init = fetchMock.mock.calls[call]?.[1];
+ const body = init?.body;
+ return typeof body === 'string' ? JSON.parse(body) : body;
+}
+
+export function requestedRawBody({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }): unknown {
+ return fetchMock.mock.calls[call]?.[1]?.body;
+}
+
+export function requestedMethod({ fetchMock, call = 0 }: { fetchMock: ReturnType<typeof vi.fn>; call?: number }): string | undefined {
+ return fetchMock.mock.calls[call]?.[1]?.method;
+}
+
+export function memoryStore({ initial = {} }: { initial?: Record<string, unknown> } = {}) {
+ const data = new Map<string, unknown>(Object.entries(initial));
+ return {
+ data,
+ store: {
+ put: async (key: string, value: unknown) => {
+ data.set(key, value);
+ return value;
+ },
+ get: async (key: string): Promise<unknown> => (data.has(key) ? data.get(key) : null),
+ delete: async (key: string) => {
+ data.delete(key);
+ },
+ },
+ };
+}
+
+export function runHook({
+ trigger,
+ hook,
+ context,
+}: {
+ trigger: object;
+ hook: 'run' | 'test' | 'onEnable' | 'onDisable' | 'onHandshake';
+ context: Record<string, unknown>;
+}): Promise<unknown> {
+ const fn: unknown = Reflect.get(trigger, hook);
+ if (typeof fn !== 'function') throw new Error(`Trigger has no ${hook}`);
+ return Reflect.apply(fn, trigger, [
+ {
+ auth: oauthAuth(),
+ server: { apiUrl: 'http://localhost:3000', publicUrl: 'http://localhost:4200', token: 'test' },
+ files: { write: async () => 'file-url' },
+ setSchedule: () => undefined,
+ ...context,
+ },
+ ]);
+}
diff --git a/packages/pieces/community/xero/test/scopes.test.ts b/packages/pieces/community/xero/test/scopes.test.ts
new file mode 100644
index 00000000000..3ad1a91b3d6
--- /dev/null
+++ b/packages/pieces/community/xero/test/scopes.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { xeroAuth, xeroScopes } from '../src';
+
+const probedScopes = [
+ 'openid',
+ 'profile',
+ 'email',
+ 'offline_access',
+ 'accounting.contacts',
+ 'accounting.invoices',
+ 'accounting.payments',
+ 'accounting.banktransactions',
+ 'accounting.manualjournals',
+ 'accounting.reports.aged.read',
+ 'accounting.reports.balancesheet.read',
+ 'accounting.reports.banksummary.read',
+ 'accounting.reports.executivesummary.read',
+ 'accounting.reports.profitandloss.read',
+ 'accounting.reports.taxreports.read',
+ 'accounting.reports.trialbalance.read',
+ 'accounting.budgets.read',
+ 'accounting.attachments',
+ 'accounting.settings',
+ 'projects',
+];
+
+const refusedScopes = [
+ 'accounting.transactions',
+ 'accounting.reports.read',
+ 'accounting.journals.read',
+ 'accounting.classicexpenses',
+];
+
+describe('xero oauth scopes', () => {
+ it('requests exactly the scopes probed as accepted for a new Xero app', () => {
+ expect(xeroAuth.scope).toEqual(probedScopes);
+ expect(xeroScopes).toEqual(probedScopes);
+ });
+
+ it('requests none of the scopes Xero refuses for new apps', () => {
+ for (const scope of refusedScopes) {
+ expect(xeroAuth.scope).not.toContain(scope);
+ }
+ });
+
+ it('has no duplicate scopes', () => {
+ expect(new Set(xeroAuth.scope).size).toBe(xeroAuth.scope.length);
+ });
+
+ it('keeps the Xero authorize and token urls', () => {
+ expect(xeroAuth.authUrl).toBe('https://login.xero.com/identity/connect/authorize');
+ expect(xeroAuth.tokenUrl).toBe('https://identity.xero.com/connect/token');
+ });
+});
diff --git a/packages/pieces/community/xero/test/tenant-dropdown.test.ts b/packages/pieces/community/xero/test/tenant-dropdown.test.ts
new file mode 100644
index 00000000000..e98da678201
--- /dev/null
+++ b/packages/pieces/community/xero/test/tenant-dropdown.test.ts
@@ -0,0 +1,82 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import '../src';
+import { buildTenantOptions, props } from '../src/lib/common/props';
+import { oauthAuth, requestedHeaders, requestedUrl, stubFetch } from './helpers';
+
+const ctx = { searchValue: undefined, server: { apiUrl: '', publicUrl: '', token: '' }, project: { id: 'p', externalId: async () => undefined } };
+
+function loadTenantOptions() {
+ return Reflect.apply(props.tenant_id.options, props.tenant_id, [{ auth: oauthAuth() }, ctx]);
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Organization dropdown', () => {
+ it('lists every connected tenant, organisations first, values are tenant IDs', async () => {
+ const fetchMock = stubFetch({
+ status: 200,
+ body: [
+ { id: 'c1', tenantId: 'practice-1', tenantType: 'PRACTICE', tenantName: 'My Practice' },
+ { id: 'c2', tenantId: 'org-1', tenantType: 'ORGANISATION', tenantName: 'Demo Company (Global)' },
+ { id: 'c3', tenantId: 'org-2', tenantType: 'ORGANISATION', tenantName: 'Second Org' },
+ ],
+ });
+
+ const result = await loadTenantOptions();
+
+ expect(requestedUrl({ fetchMock })).toBe('https://api.xero.com/connections');
+ expect(requestedHeaders({ fetchMock }).get('authorization')).toBe('Bearer tok_test');
+ expect(result).toEqual({
+ disabled: false,
+ options: [
+ { label: 'Demo Company (Global)', value: 'org-1' },
+ { label: 'Second Org', value: 'org-2' },
+ { label: 'My Practice (PRACTICE)', value: 'practice-1' },
+ ],
+ });
+ });
+
+ it('returns a disabled placeholder instead of crashing when no tenant is connected', async () => {
+ stubFetch({ status: 200, body: [] });
+
+ const result = await loadTenantOptions();
+
+ expect(result).toEqual({
+ disabled: true,
+ options: [],
+ placeholder: 'No Xero organizations are connected. Reconnect and select at least one organization.',
+ });
+ });
+
+ it('returns a disabled placeholder with the status when Xero rejects the token', async () => {
+ stubFetch({ status: 401, body: { title: 'Unauthorized' } });
+
+ const result = await loadTenantOptions();
+
+ expect(result).toMatchObject({ disabled: true, options: [] });
+ expect(JSON.stringify(result)).toContain('HTTP 401');
+ });
+
+ it('asks to authenticate when there is no connection', async () => {
+ const result = await Reflect.apply(props.tenant_id.options, props.tenant_id, [{ auth: undefined }, ctx]);
+
+ expect(result).toEqual({ disabled: true, options: [], placeholder: 'Please authenticate first' });
+ });
+
+ it('falls back to the tenant ID when the tenant has no name and skips entries without an ID', () => {
+ expect(
+ buildTenantOptions({
+ connections: [
+ { id: 'c1', tenantId: 'org-1', tenantType: 'ORGANISATION', tenantName: null },
+ { id: 'c2', tenantId: '', tenantType: 'ORGANISATION', tenantName: 'Broken' },
+ ],
+ }),
+ ).toEqual({ disabled: false, options: [{ label: 'org-1', value: 'org-1' }] });
+ });
+
+ it('treats a missing body as no tenants', () => {
+ expect(buildTenantOptions({ connections: null })).toMatchObject({ disabled: true, options: [] });
+ });
+});
diff --git a/packages/pieces/community/xero/test/triggers.test.ts b/packages/pieces/community/xero/test/triggers.test.ts
new file mode 100644
index 00000000000..87021dd5575
--- /dev/null
+++ b/packages/pieces/community/xero/test/triggers.test.ts
@@ -0,0 +1,399 @@
+import { createHmac } from 'crypto';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import '../src';
+import { xeroNewBankTransaction } from '../src/lib/triggers/new-bank-transaction';
+import { xeroNewContact } from '../src/lib/triggers/new-contact';
+import { xeroNewProject } from '../src/lib/triggers/new-project';
+import { xeroNewSalesInvoice } from '../src/lib/triggers/new-sales-invoice';
+import { xeroUpdatedQuote } from '../src/lib/triggers/updated-quote';
+import { webhookTiming, xeroTriggerState } from '../src/lib/common/trigger-state';
+import { memoryStore, requestedHeaders, requestedUrl, runHook, stubFetch, stubFetchSequence } from './helpers';
+
+const KEY = 'webhook-key';
+const ORG = 'org-1';
+const CONTACT_A = '11111111-1111-4111-8111-111111111111';
+const CONTACT_B = '22222222-2222-4222-8222-222222222222';
+
+const PRODUCTION_TIMING = { ...webhookTiming, fetchRetryDelaysMs: [...webhookTiming.fetchRetryDelaysMs] };
+
+beforeEach(() => {
+ webhookTiming.claimSettleMs = 0;
+ webhookTiming.fetchRetryDelaysMs = [0, 0];
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ Object.assign(webhookTiming, PRODUCTION_TIMING);
+});
+
+function signed({ body, key = KEY }: { body: unknown; key?: string }) {
+ const rawBody = JSON.stringify(body);
+ return { body, rawBody, headers: { 'x-xero-signature': createHmac('sha256', key).update(rawBody).digest('base64') }, queryParams: {} };
+}
+
+function event({ resourceId, eventType = 'CREATE', category = 'CONTACT', tenantId = ORG, date = '2026-10-05T10:00:00.000' }: { resourceId: string; eventType?: string; category?: string; tenantId?: string; date?: string }) {
+ return {
+ resourceUrl: `https://api.xero.com.evil.example/api.xro/2.0/Contacts/${resourceId}`,
+ resourceId,
+ eventDateUtc: date,
+ eventType,
+ eventCategory: category,
+ tenantId,
+ tenantType: 'ORGANISATION',
+ };
+}
+
+describe('Xero webhook intent to receive', () => {
+ it('declares the signature header as the handshake trigger', () => {
+ expect(xeroNewContact.handshakeConfiguration).toEqual({ strategy: 'HEADER_PRESENT', paramName: 'x-xero-signature' });
+ });
+
+ it('answers 401 to a badly signed request', async () => {
+ const payload = signed({ body: { events: [] }, key: 'wrong-key' });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'onHandshake', context: { payload, propsValue: { webhook_key: KEY } } })).resolves.toEqual({ status: 401 });
+ });
+
+ it('answers 401 when the raw body is missing', async () => {
+ const payload = { ...signed({ body: { events: [] } }), rawBody: undefined };
+ await expect(runHook({ trigger: xeroNewContact, hook: 'onHandshake', context: { payload, propsValue: { webhook_key: KEY } } })).resolves.toEqual({ status: 401 });
+ });
+
+ it('returns nothing for a correctly signed request so the delivery continues to run (and AP answers 200)', async () => {
+ const payload = signed({ body: { events: [] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'onHandshake', context: { payload, propsValue: { webhook_key: KEY } } })).resolves.toBeUndefined();
+ });
+});
+
+describe('Xero webhook deliveries', () => {
+ it('fetches each event once from api.xero.com by resource ID, never from the event URL, and skips other organisations', async () => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ { status: 200, body: { Contacts: [{ ContactID: CONTACT_A, Name: 'A' }] } },
+ { status: 200, body: { Contacts: [{ ContactID: CONTACT_B, Name: 'B' }] } },
+ ],
+ });
+ const { store } = memoryStore();
+ const payload = signed({
+ body: { events: [event({ resourceId: CONTACT_A }), event({ resourceId: CONTACT_A }), event({ resourceId: CONTACT_B }), event({ resourceId: CONTACT_B, tenantId: 'other-org' })] },
+ });
+ const result = await runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: true } } });
+ expect(result).toEqual([{ ContactID: CONTACT_A, Name: 'A' }, { ContactID: CONTACT_B, Name: 'B' }]);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(requestedUrl({ fetchMock, call: 0 })).toBe(`https://api.xero.com/api.xro/2.0/Contacts/${CONTACT_A}`);
+ expect(requestedHeaders({ fetchMock, call: 0 }).get('xero-tenant-id')).toBe(ORG);
+
+ const replay = await runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: true } } });
+ expect(replay).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores deliveries with a bad signature', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ const { store } = memoryStore();
+ const payload = { ...signed({ body: { events: [event({ resourceId: CONTACT_A })] } }), headers: { 'x-xero-signature': 'bad' } };
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).resolves.toEqual([]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('drops an event whose record was deleted (404) but fails on other errors without marking events as seen', async () => {
+ const { store, data } = memoryStore();
+ stubFetch({ status: 404, body: 'Not found' });
+ const gone = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: gone, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).resolves.toEqual([]);
+
+ const outage = stubFetch({ status: 503, body: { Message: 'Service unavailable' } });
+ const failing = signed({ body: { events: [event({ resourceId: CONTACT_B })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: failing, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).rejects.toThrow('HTTP 503');
+ expect(outage).toHaveBeenCalledTimes(3);
+ expect(Object.keys(Object(data.get('xero_webhook_seen_events')))).toHaveLength(1);
+
+ stubFetch({ status: 200, body: { Contacts: [{ ContactID: CONTACT_B }] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: failing, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).resolves.toEqual([{ ContactID: CONTACT_B }]);
+ });
+
+ it('retries a passing Xero outage inside the run, because Xero already got its 200 and will not redeliver', async () => {
+ const fetchMock = stubFetchSequence({
+ responses: [
+ { status: 503, body: { Message: 'Service unavailable' } },
+ { status: 500, body: { Message: 'Oops' } },
+ { status: 200, body: { Contacts: [{ ContactID: CONTACT_A }] } },
+ ],
+ });
+ const { store } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).resolves.toEqual([{ ContactID: CONTACT_A }]);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ it('does not retry an error that a retry cannot fix', async () => {
+ const fetchMock = stubFetch({ status: 403, body: { Detail: 'AuthorizationUnsuccessful' } });
+ const { store, data } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).rejects.toThrow('HTTP 403');
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(Object.keys(Object(data.get('xero_webhook_seen_events')))).toHaveLength(0);
+ });
+
+ it('lets only one of two copies that pass the seen check at the same moment run the flow', async () => {
+ webhookTiming.claimSettleMs = 5;
+ const fetchMock = stubFetch({ status: 200, body: { Contacts: [{ ContactID: CONTACT_A }] } });
+ const { store, data } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ const propsValue = { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: true };
+ const results = await Promise.all([
+ runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue } }),
+ runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue } }),
+ ]);
+ expect(results.filter((result) => Array.isArray(result) && result.length > 0)).toEqual([[{ ContactID: CONTACT_A }]]);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect([...data.keys()].filter((key) => key.startsWith('xero_webhook_claim_'))).toEqual([]);
+ });
+
+ it('drops a repeated event for 48 hours however many other events arrive in between', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-05T10:00:00Z'));
+ stubFetch({ status: 200, body: {} });
+ const { store } = memoryStore();
+ const propsValue = { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: false };
+ const first = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: first, store, propsValue } })).resolves.toHaveLength(1);
+
+ const others = Array.from({ length: 3000 }, (_, index) => event({ resourceId: `${index.toString(16).padStart(8, '0')}-0000-4000-8000-000000000000` }));
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: signed({ body: { events: others } }), store, propsValue } })).resolves.toHaveLength(3000);
+
+ vi.setSystemTime(new Date('2026-10-07T09:00:00Z'));
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload: first, store, propsValue } })).resolves.toEqual([]);
+ vi.useRealTimers();
+ });
+
+ it('lets only one of two concurrent duplicate deliveries emit the event', async () => {
+ let release: (() => void) | undefined;
+ const fetchMock = vi.fn(
+ () =>
+ new Promise<Response>((resolve) => {
+ release = () => resolve(new Response(JSON.stringify({ Contacts: [{ ContactID: CONTACT_A }] }), { status: 200, headers: { 'Content-Type': 'application/json' } }));
+ }),
+ );
+ vi.stubGlobal('fetch', fetchMock);
+ const { store } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ const propsValue = { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: true };
+ const firstRun = runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue } });
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue } })).resolves.toEqual([]);
+ release?.();
+ await expect(firstRun).resolves.toEqual([{ ContactID: CONTACT_A }]);
+ });
+
+ it('keeps working for a 0.7.1 webhook trigger after the upgrade (no stored state, same props)', async () => {
+ stubFetch({ status: 200, body: { Contacts: [{ ContactID: CONTACT_A }] } });
+ const { store } = memoryStore({ initial: { xero_webhook_seen_events: ['unexpected-legacy-shape'] } });
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ const legacyProps = { webhookInstructions: undefined, tenant_id: ORG, webhook_key: KEY, fetch_full_contact: true };
+ await expect(runHook({ trigger: xeroNewContact, hook: 'onHandshake', context: { payload, propsValue: legacyProps } })).resolves.toBeUndefined();
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: legacyProps } })).resolves.toEqual([{ ContactID: CONTACT_A }]);
+ });
+
+ it('ignores events whose resource ID is not a Xero GUID', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ const { store } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: '../Organisation' })] } });
+ await expect(runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG } } })).resolves.toEqual([]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('returns the raw events when fetching is off', async () => {
+ const fetchMock = stubFetch({ status: 200, body: {} });
+ const { store } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A })] } });
+ const result = await runHook({ trigger: xeroNewContact, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG, fetch_full_contact: false } } });
+ expect(result).toEqual([expect.objectContaining({ resourceId: CONTACT_A, eventType: 'CREATE' })]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('only emits sales invoices for the invoice triggers', async () => {
+ stubFetchSequence({
+ responses: [
+ { status: 200, body: { Invoices: [{ InvoiceID: CONTACT_A, Type: 'ACCREC' }] } },
+ { status: 200, body: { Invoices: [{ InvoiceID: CONTACT_B, Type: 'ACCPAY' }] } },
+ ],
+ });
+ const { store } = memoryStore();
+ const payload = signed({ body: { events: [event({ resourceId: CONTACT_A, category: 'INVOICE' }), event({ resourceId: CONTACT_B, category: 'INVOICE' })] } });
+ const result = await runHook({ trigger: xeroNewSalesInvoice, hook: 'run', context: { payload, store, propsValue: { webhook_key: KEY, tenant_id: ORG, fetch_full_invoice: true } } });
+ expect(result).toEqual([{ InvoiceID: CONTACT_A, Type: 'ACCREC' }]);
+ });
+});
+
+describe('Polling state stays bounded', () => {
+ it('keeps only the most recent 5,000 seen IDs and keeps the old store key', async () => {
+ const previous = Array.from({ length: 5000 }, (_, index) => `old-${index}`);
+ const { store, data } = memoryStore({ initial: { [`xero_bank_txn_seen_ids_${ORG}`]: previous } });
+ stubFetch({
+ status: 200,
+ body: {
+ BankTransactions: [
+ { BankTransactionID: 'old-4999', UpdatedDateUTC: '/Date(1791216517000+0000)/' },
+ { BankTransactionID: 'new-1', UpdatedDateUTC: '/Date(1791216518000+0000)/' },
+ { BankTransactionID: 'new-2', UpdatedDateUTC: '/Date(1791216519000+0000)/' },
+ ],
+ },
+ });
+ data.set('lastPoll', 1);
+ const result = await runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } });
+ expect(result).toEqual([
+ { BankTransactionID: 'new-1', UpdatedDateUTC: '/Date(1791216518000+0000)/' },
+ { BankTransactionID: 'new-2', UpdatedDateUTC: '/Date(1791216519000+0000)/' },
+ ]);
+ const stored = data.get(`xero_bank_txn_seen_ids_${ORG}`);
+ expect(Array.isArray(stored) && stored.length).toBe(5000);
+ expect(Array.isArray(stored) && stored.slice(-2)).toEqual(['new-1', 'new-2']);
+ expect(Array.isArray(stored) && stored.includes('old-0')).toBe(false);
+ });
+
+ it('bounds per-ID maps to the most recent entries', () => {
+ const map = Object.fromEntries(Array.from({ length: 5003 }, (_, index) => [`q-${index}`, index]));
+ const bounded = xeroTriggerState.boundMap({ map });
+ expect(Object.keys(bounded)).toHaveLength(5000);
+ expect(bounded['q-0']).toBeUndefined();
+ expect(bounded['q-5002']).toBe(5002);
+ });
+
+ it('Updated Quote fires again only when the quote changes', async () => {
+ const { store, data } = memoryStore({ initial: { lastPoll: 1 } });
+ const quote = { QuoteID: 'q1', UpdatedDateUTC: '/Date(1791216518000+0000)/' };
+ stubFetch({ status: 200, body: { Quotes: [quote] } });
+ await expect(runHook({ trigger: xeroUpdatedQuote, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } })).resolves.toEqual([quote]);
+ data.set('lastPoll', 1);
+ await expect(runHook({ trigger: xeroUpdatedQuote, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } })).resolves.toEqual([]);
+ });
+});
+
+describe('Polling cursor', () => {
+ const at = ({ seconds }: { seconds: number }) => `/Date(${1791216500000 + seconds * 1000}+0000)/`;
+
+ it('leaves the newest instant for the next poll when the page cap cuts the scan short', async () => {
+ const page = ({ id, seconds }: { id: string; seconds: number }) => ({ status: 200, body: { BankTransactions: [{ BankTransactionID: id, UpdatedDateUTC: at({ seconds }) }] } });
+ stubFetchSequence({ responses: [page({ id: 'r1', seconds: 1 }), page({ id: 'r2', seconds: 2 }), page({ id: 'r3', seconds: 3 }), page({ id: 'r4', seconds: 4 }), page({ id: 'r5', seconds: 4 })] });
+ const { store, data } = memoryStore({ initial: { lastPoll: 1 } });
+ const first = await runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG, page_size: 1 } } });
+ expect(first).toEqual([expect.objectContaining({ BankTransactionID: 'r1' }), expect.objectContaining({ BankTransactionID: 'r2' }), expect.objectContaining({ BankTransactionID: 'r3' })]);
+ expect(data.get('lastPoll')).toBe(1791216503000);
+
+ stubFetch({ status: 200, body: { BankTransactions: [{ BankTransactionID: 'r4', UpdatedDateUTC: at({ seconds: 4 }) }, { BankTransactionID: 'r5', UpdatedDateUTC: at({ seconds: 4 }) }, { BankTransactionID: 'r6', UpdatedDateUTC: at({ seconds: 4 }) }] } });
+ const second = await runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG, page_size: 5 } } });
+ expect(Array.isArray(second) && second.map((record) => Reflect.get(Object(record), 'BankTransactionID'))).toEqual(['r4', 'r5', 'r6']);
+ });
+
+ it('keeps reading past the page cap while every record shares one instant, so none are skipped', async () => {
+ const same = ({ id }: { id: string }) => ({ status: 200, body: { BankTransactions: [{ BankTransactionID: id, UpdatedDateUTC: at({ seconds: 4 }) }] } });
+ const fetchMock = stubFetchSequence({
+ responses: [
+ same({ id: 's1' }),
+ same({ id: 's2' }),
+ same({ id: 's3' }),
+ same({ id: 's4' }),
+ same({ id: 's5' }),
+ same({ id: 's6' }),
+ { status: 200, body: { BankTransactions: [{ BankTransactionID: 'n1', UpdatedDateUTC: at({ seconds: 5 }) }] } },
+ ],
+ });
+ const { store, data } = memoryStore({ initial: { lastPoll: 1 } });
+ const result = await runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG, page_size: 1 } } });
+ expect(Array.isArray(result) && result.map((record) => Reflect.get(Object(record), 'BankTransactionID'))).toEqual(['s1', 's2', 's3', 's4', 's5', 's6']);
+ expect(fetchMock).toHaveBeenCalledTimes(7);
+ expect(data.get('lastPoll')).toBe(1791216504000);
+ });
+
+ it('fails instead of skipping when too many records share one instant to read', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { BankTransactions: [{ BankTransactionID: 'same', UpdatedDateUTC: at({ seconds: 4 }) }] } });
+ const { store, data } = memoryStore({ initial: { lastPoll: 1 } });
+ await expect(runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG, page_size: 1 } } })).rejects.toThrow('share the same UpdatedDateUTC');
+ expect(fetchMock).toHaveBeenCalledTimes(50);
+ expect(data.get('lastPoll')).toBe(1);
+ });
+
+ it('moves past records that a filter rejects, so they cannot pin the cursor', async () => {
+ const account = '33333333-3333-4333-8333-333333333333';
+ stubFetch({ status: 200, body: { BankTransactions: [{ BankTransactionID: 'other', BankAccount: { AccountID: 'not-it' }, UpdatedDateUTC: at({ seconds: 9 }) }] } });
+ const { store, data } = memoryStore({ initial: { lastPoll: 1 } });
+ await expect(runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG, bank_account_id: account } } })).resolves.toEqual([]);
+ expect(data.get('lastPoll')).toBe(1791216509000);
+ });
+
+ it('keeps an ID that is still being seen even when the set is full', async () => {
+ const previous = ['kept', ...Array.from({ length: 4999 }, (_, index) => `old-${index}`)];
+ const { store, data } = memoryStore({ initial: { [`xero_bank_txn_seen_ids_${ORG}`]: previous, lastPoll: 1 } });
+ stubFetch({ status: 200, body: { BankTransactions: [{ BankTransactionID: 'kept', UpdatedDateUTC: at({ seconds: 1 }) }, { BankTransactionID: 'new-1', UpdatedDateUTC: at({ seconds: 2 }) }] } });
+ await expect(runHook({ trigger: xeroNewBankTransaction, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } })).resolves.toEqual([
+ { BankTransactionID: 'new-1', UpdatedDateUTC: at({ seconds: 2 }) },
+ ]);
+ const stored = data.get(`xero_bank_txn_seen_ids_${ORG}`);
+ expect(Array.isArray(stored) && stored.includes('kept')).toBe(true);
+ expect(Array.isArray(stored) && stored.includes('old-0')).toBe(false);
+ });
+});
+
+describe('Republishing a polling trigger', () => {
+ it('keeps the cursor when the inputs are unchanged and starts fresh when they change', async () => {
+ const { store, data } = memoryStore();
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG }, isRepublish: false } });
+ data.set('lastPoll', 123);
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG }, isRepublish: true } });
+ expect(data.get('lastPoll')).toBe(123);
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG, statuses: ['DELETED'] }, isRepublish: true } });
+ expect(data.get('lastPoll')).not.toBe(123);
+ });
+
+ it('keeps the cursor when only Page Size changes, so raising it can read past a crowded timestamp', async () => {
+ const { store, data } = memoryStore();
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG, page_size: 200 }, isRepublish: false } });
+ data.set('lastPoll', 123);
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG, page_size: 1000 }, isRepublish: true } });
+ expect(data.get('lastPoll')).toBe(123);
+ });
+
+ it('keeps state written by 0.7.1, which has no input fingerprint', async () => {
+ const { store, data } = memoryStore({ initial: { lastPoll: 123, [`xero_bank_txn_seen_ids_${ORG}`]: ['b1'] } });
+ await runHook({ trigger: xeroNewBankTransaction, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG }, isRepublish: true } });
+ expect(data.get('lastPoll')).toBe(123);
+ expect(data.get(`xero_bank_txn_seen_ids_${ORG}`)).toEqual(['b1']);
+ });
+
+ it('re-seeds New Project when its filters change, so existing projects do not fire', async () => {
+ const { store, data } = memoryStore();
+ stubFetch({ status: 200, body: { items: [{ projectId: 'p-open', name: 'Open' }] } });
+ await runHook({ trigger: xeroNewProject, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG, states: ['INPROGRESS'] }, isRepublish: false } });
+ stubFetch({ status: 200, body: { items: [{ projectId: 'p-open', name: 'Open' }, { projectId: 'p-closed', name: 'Closed' }] } });
+ await runHook({ trigger: xeroNewProject, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG, states: ['INPROGRESS', 'CLOSED'] }, isRepublish: true } });
+ data.set('lastPoll', 1);
+ await expect(runHook({ trigger: xeroNewProject, hook: 'run', context: { store, propsValue: { tenant_id: ORG, states: ['INPROGRESS', 'CLOSED'] } } })).resolves.toEqual([]);
+ });
+});
+
+describe('Trigger test step', () => {
+ it('loads only the 5 most recently updated records in one request', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { BankTransactions: Array.from({ length: 8 }, (_, index) => ({ BankTransactionID: `b${index}` })) } });
+ const { store } = memoryStore();
+ const result = await runHook({ trigger: xeroNewBankTransaction, hook: 'test', context: { store, propsValue: { tenant_id: ORG } } });
+ expect(Array.isArray(result) && result.length).toBe(5);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const url = new URL(requestedUrl({ fetchMock }));
+ expect(url.searchParams.get('order')).toBe('UpdatedDateUTC DESC');
+ expect(url.searchParams.get('pageSize')).toBe('5');
+ });
+});
+
+describe('New Project first poll', () => {
+ it('does not fire for projects that existed when the trigger was enabled', async () => {
+ const { store, data } = memoryStore();
+ const existing = { items: [{ projectId: 'p-old-1', name: 'Old 1' }, { projectId: 'p-old-2', name: 'Old 2' }] };
+ stubFetch({ status: 200, body: existing });
+ await runHook({ trigger: xeroNewProject, hook: 'onEnable', context: { store, propsValue: { tenant_id: ORG } } });
+ await expect(runHook({ trigger: xeroNewProject, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } })).resolves.toEqual([]);
+
+ data.set('lastPoll', 1);
+ stubFetch({ status: 200, body: { items: [...existing.items, { projectId: 'p-new', name: 'New' }] } });
+ await expect(runHook({ trigger: xeroNewProject, hook: 'run', context: { store, propsValue: { tenant_id: ORG } } })).resolves.toEqual([{ projectId: 'p-new', name: 'New' }]);
+ });
+});
diff --git a/packages/pieces/community/xero/test/upload-attachment.test.ts b/packages/pieces/community/xero/test/upload-attachment.test.ts
new file mode 100644
index 00000000000..3626724afb1
--- /dev/null
+++ b/packages/pieces/community/xero/test/upload-attachment.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import '../src';
+import { xeroUploadAttachment } from '../src/lib/actions/upload-attachment';
+import { requestedHeaders, requestedUrl, runAction, stubFetch } from './helpers';
+
+const file = { data: Buffer.from('hello'), filename: 'receipt.pdf', extension: 'pdf', base64: Buffer.from('hello').toString('base64') };
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('Upload Attachment', () => {
+ it('keeps the Receipts option value for existing steps', () => {
+ const options = xeroUploadAttachment.props.resource_type.options.options.map((option) => option.value);
+ expect(options).toContain('Receipts');
+ });
+
+ it('posts the file to the resource attachment endpoint', async () => {
+ const fetchMock = stubFetch({ status: 200, body: { Attachments: [{ AttachmentID: 'a1' }] } });
+
+ const result = await runAction({
+ action: xeroUploadAttachment,
+ propsValue: { tenant_id: 'org-1', resource_type: 'Invoices', resource_id: 'inv-1', file },
+ });
+
+ expect(requestedUrl({ fetchMock })).toBe('https://api.xero.com/api.xro/2.0/Invoices/inv-1/Attachments/receipt.pdf');
+ expect(requestedHeaders({ fetchMock }).get('xero-tenant-id')).toBe('org-1');
+ expect(result).toEqual({ Attachments: [{ AttachmentID: 'a1' }] });
+ });
+
+ it.each([401, 403])('explains the missing Receipts permission when Xero answers %i', async (status) => {
+ stubFetch({ status, body: { Title: 'Forbidden', Detail: 'AuthorizationUnsuccessful' } });
+
+ await expect(
+ runAction({
+ action: xeroUploadAttachment,
+ propsValue: { tenant_id: 'org-1', resource_type: 'Receipts', resource_id: 'r-1', file },
+ }),
+ ).rejects.toThrow(/accounting\.classicexpenses.*before Xero piece version 0\.8\.0/);
+ });
+
+ it('rethrows a 403 on other resource types unchanged', async () => {
+ stubFetch({ status: 403, body: { Title: 'Forbidden' } });
+
+ const error = await runAction({
+ action: xeroUploadAttachment,
+ propsValue: { tenant_id: 'org-1', resource_type: 'Invoices', resource_id: 'inv-1', file },
+ }).then(
+ () => undefined,
+ (reason: unknown) => reason,
+ );
+
+ expect(error).toBeInstanceOf(Error);
+ expect(String(error)).not.toMatch(/classicexpenses/);
+ expect(String(error)).toContain('403');
+ });
+});
diff --git a/packages/pieces/community/xero/vitest.config.ts b/packages/pieces/community/xero/vitest.config.ts
new file mode 100644
index 00000000000..79c97261904
--- /dev/null
+++ b/packages/pieces/community/xero/vitest.config.ts
@@ -0,0 +1,19 @@
+import path from 'path'
+import { defineConfig } from 'vitest/config'
+
+const repoRoot = path.resolve(__dirname, '../../../..')
+
+export default defineConfig({
+ root: __dirname,
+ test: {
+ globals: true,
+ environment: 'node',
+ include: ['test/**/*.test.ts'],
+ },
+ resolve: {
+ alias: {
+ '@activepieces/pieces-framework': path.resolve(repoRoot, 'packages/pieces/framework/src/index.ts'),
+ '@activepieces/pieces-common': path.resolve(repoRoot, 'packages/pieces/common/src/index.ts'),
+ },
+ },
+})