@mindstone/mcp-server-xero 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +7 -6
  2. package/dist/handlers/list-xero-accounts.handler.js +5 -5
  3. package/dist/handlers/list-xero-bank-transactions.handler.js +16 -9
  4. package/dist/handlers/list-xero-credit-notes.handler.js +14 -9
  5. package/dist/handlers/list-xero-invoices.handler.js +11 -18
  6. package/dist/handlers/list-xero-items.handler.js +6 -5
  7. package/dist/handlers/list-xero-manual-journals.handler.js +1 -1
  8. package/dist/handlers/list-xero-payments.handler.js +1 -1
  9. package/dist/handlers/list-xero-profit-and-loss.handler.js +8 -12
  10. package/dist/handlers/summarise-xero-totals.handler.js +195 -0
  11. package/dist/helpers/contact-totals-tool.js +107 -0
  12. package/dist/helpers/format-line-item.js +20 -13
  13. package/dist/helpers/format-report.js +28 -0
  14. package/dist/helpers/page-note.js +6 -0
  15. package/dist/helpers/xero-date-where.js +27 -0
  16. package/dist/tools/list/index.js +5 -1
  17. package/dist/tools/list/list-accounts.tool.js +9 -2
  18. package/dist/tools/list/list-aged-payables-by-contact.tool.js +5 -18
  19. package/dist/tools/list/list-aged-receivables-by-contact.tool.js +5 -18
  20. package/dist/tools/list/list-bank-summary.tool.js +2 -8
  21. package/dist/tools/list/list-bank-transactions.tool.js +60 -16
  22. package/dist/tools/list/list-budget-summary.tool.js +2 -8
  23. package/dist/tools/list/list-credit-notes.tool.js +47 -12
  24. package/dist/tools/list/list-executive-summary.tool.js +2 -8
  25. package/dist/tools/list/list-invoices.tool.js +20 -20
  26. package/dist/tools/list/list-items.tool.js +3 -6
  27. package/dist/tools/list/list-manual-journals.tool.js +1 -3
  28. package/dist/tools/list/list-organisation-details.tool.js +15 -15
  29. package/dist/tools/list/list-payments.tool.js +1 -2
  30. package/dist/tools/list/list-payroll-employees.tool.js +1 -1
  31. package/dist/tools/list/list-profit-and-loss.tool.js +23 -24
  32. package/dist/tools/list/list-quotes.tool.js +2 -3
  33. package/dist/tools/list/list-report-balance-sheet.tool.js +2 -8
  34. package/dist/tools/list/list-trial-balance.tool.js +2 -16
  35. package/dist/tools/list/summarise-sales-by-customer.tool.js +9 -0
  36. package/dist/tools/list/summarise-spend-by-supplier.tool.js +10 -0
  37. package/node_modules/cross-spawn/README.md +19 -3
  38. package/node_modules/cross-spawn/lib/parse.js +38 -10
  39. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  40. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  41. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  42. package/node_modules/cross-spawn/package.json +21 -24
  43. package/package.json +1 -1
package/README.md CHANGED
@@ -140,13 +140,15 @@ In Rebel, the `xero_sign_in` tool does all of this: Rebel opens Xero's sign-in p
140
140
 
141
141
  > **Tool naming:** this connector's tools use unprefixed dash-case names (e.g. `list-invoices`, `create-contact`), inherited from its fork lineage. Sibling connectors use prefixed snake_case names (e.g. `list_quickbooks_invoices`). In multi-server hosts, unprefixed generic names can collide with other servers' tools. Renaming would be a breaking change for existing configurations, so the names are kept as-is; if your host supports namespacing/aliasing, prefer enabling it for this server.
142
142
 
143
- - `list-accounts`: Retrieve a list of accounts
143
+ - `summarise-spend-by-supplier`: Total spending by supplier for a period, from bills, card and bank spend and supplier credits, in one call; optionally for chosen accounts (such as software subscriptions)
144
+ - `summarise-sales-by-customer`: Total sales by customer for a period, from sales invoices, money received and customer credits, in one call
145
+ - `list-accounts`: Retrieve a list of accounts, optionally of one class (such as expense or bank accounts)
144
146
  - `list-contacts`: Retrieve a list of contacts from Xero
145
- - `list-credit-notes`: Retrieve a list of credit notes
146
- - `list-invoices`: Retrieve a list of invoices
147
+ - `list-credit-notes`: Retrieve a list of credit notes, with line items; filter by type and dates
148
+ - `list-invoices`: Retrieve a list of invoices, with line items; filter by type, status, dates or due date (for overdue invoices)
147
149
  - `list-items`: Retrieve a list of items
148
150
  - `list-organisation-details`: Retrieve details about an organisation
149
- - `list-profit-and-loss`: Retrieve a profit and loss report
151
+ - `list-profit-and-loss`: Retrieve a profit and loss report, optionally month by month or for one tracking category
150
152
  - `list-bank-summary`: Retrieve the bank summary report (per-account balances and movements)
151
153
  - `list-budget-summary`: Retrieve the budget summary report (budget vs actuals)
152
154
  - `list-executive-summary`: Retrieve the executive summary report (key financial metrics snapshot)
@@ -154,8 +156,7 @@ In Rebel, the `xero_sign_in` tool does all of this: Rebel opens Xero's sign-in p
154
156
  - `list-tax-rates`: Retrieve a list of tax rates
155
157
  - `list-payments`: Retrieve a list of payments
156
158
  - `list-trial-balance`: Retrieve a trial balance report
157
- - `list-profit-and-loss`: Retrieve a profit and loss report
158
- - `list-bank-transactions`: Retrieve a list of bank account transactions
159
+ - `list-bank-transactions`: Retrieve a list of bank account transactions, with line items; filter by type and dates
159
160
  - `list-payroll-employees`: Retrieve a list of Payroll Employees
160
161
  - `list-report-balance-sheet`: Retrieve a balance sheet report
161
162
  - `list-payroll-employee-leave`: Retrieve a Payroll Employee's leave records
@@ -1,21 +1,21 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { formatError } from "../helpers/format-error.js";
3
3
  import { getClientHeaders } from "../helpers/get-client-headers.js";
4
- async function listAccounts() {
4
+ async function listAccounts(accountClass) {
5
5
  await xeroClient.authenticate();
6
6
  const response = await xeroClient.accountingApi.getAccounts(xeroClient.tenantId, undefined, // ifModifiedSince
7
- undefined, // where
7
+ accountClass ? `Class=="${accountClass}"` : undefined, // where
8
8
  undefined, // order
9
9
  getClientHeaders());
10
10
  const accounts = response.body.accounts ?? [];
11
11
  return accounts;
12
12
  }
13
13
  /**
14
- * List all accounts from Xero
14
+ * List the chart of accounts from Xero, or only one class of it
15
15
  */
16
- export async function listXeroAccounts() {
16
+ export async function listXeroAccounts(accountClass) {
17
17
  try {
18
- const accounts = await listAccounts();
18
+ const accounts = await listAccounts(accountClass);
19
19
  return {
20
20
  result: accounts,
21
21
  isError: false,
@@ -1,31 +1,38 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { getClientHeaders } from "../helpers/get-client-headers.js";
3
3
  import { formatError } from "../helpers/format-error.js";
4
- async function getBankTransactions(page, bankAccountId) {
4
+ import { joinWhere, xeroDateRangeWhere } from "../helpers/xero-date-where.js";
5
+ async function getBankTransactions(filters) {
5
6
  await xeroClient.authenticate();
7
+ const where = joinWhere([
8
+ filters.bankAccountId
9
+ ? `BankAccount.AccountID=guid("${filters.bankAccountId}")`
10
+ : undefined,
11
+ filters.type ? `Type=="${filters.type}"` : undefined,
12
+ ...xeroDateRangeWhere(filters.dateFrom, filters.dateTo),
13
+ ]);
6
14
  const response = await xeroClient.accountingApi.getBankTransactions(xeroClient.tenantId, undefined, // ifModifiedSince
7
- bankAccountId ? `BankAccount.AccountID=guid("${bankAccountId}")` : undefined, // where
15
+ where, // where
8
16
  "Date DESC", // order
9
- page, // page
17
+ filters.page ?? 1, // page
10
18
  undefined, // unitdp
11
- 10, // pagesize
19
+ filters.pageSize ?? 100, // pageSize
12
20
  getClientHeaders());
13
21
  return response.body.bankTransactions ?? [];
14
22
  }
15
- export async function listXeroBankTransactions(page = 1, bankAccountId) {
23
+ export async function listXeroBankTransactions(filters) {
16
24
  try {
17
- const bankTransactions = await getBankTransactions(page, bankAccountId);
18
25
  return {
19
- result: bankTransactions,
26
+ result: await getBankTransactions(filters),
20
27
  isError: false,
21
- error: null
28
+ error: null,
22
29
  };
23
30
  }
24
31
  catch (error) {
25
32
  return {
26
33
  result: null,
27
34
  isError: true,
28
- error: formatError(error)
35
+ error: formatError(error),
29
36
  };
30
37
  }
31
38
  }
@@ -1,25 +1,30 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { formatError } from "../helpers/format-error.js";
3
3
  import { getClientHeaders } from "../helpers/get-client-headers.js";
4
- async function getCreditNotes(contactId, page) {
4
+ import { joinWhere, xeroDateRangeWhere } from "../helpers/xero-date-where.js";
5
+ async function getCreditNotes(filters) {
5
6
  await xeroClient.authenticate();
7
+ const where = joinWhere([
8
+ filters.contactId ? `Contact.ContactID=guid("${filters.contactId}")` : undefined,
9
+ filters.type ? `Type=="${filters.type}"` : undefined,
10
+ ...xeroDateRangeWhere(filters.dateFrom, filters.dateTo),
11
+ ]);
6
12
  const response = await xeroClient.accountingApi.getCreditNotes(xeroClient.tenantId, undefined, // ifModifiedSince
7
- contactId ? `Contact.ContactID=guid("${contactId}")` : undefined, // where
8
- "UpdatedDateUTC DESC", // order
9
- page, // page
13
+ where, // where
14
+ "Date DESC", // order
15
+ filters.page ?? 1, // page
10
16
  undefined, // unitdp
11
- 10, // pageSize
17
+ filters.pageSize ?? 100, // pageSize
12
18
  getClientHeaders());
13
19
  return response.body.creditNotes ?? [];
14
20
  }
15
21
  /**
16
- * List all credit notes from Xero
22
+ * List credit notes from Xero
17
23
  */
18
- export async function listXeroCreditNotes(page = 1, contactId) {
24
+ export async function listXeroCreditNotes(filters) {
19
25
  try {
20
- const creditNotes = await getCreditNotes(contactId, page);
21
26
  return {
22
- result: creditNotes,
27
+ result: await getCreditNotes(filters),
23
28
  isError: false,
24
29
  error: null,
25
30
  };
@@ -1,24 +1,17 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { formatError } from "../helpers/format-error.js";
3
3
  import { getClientHeaders } from "../helpers/get-client-headers.js";
4
- function buildWhereClause(type, dateFrom, dateTo) {
5
- const clauses = [];
6
- if (type) {
7
- clauses.push(`Type=="${type}"`);
8
- }
9
- if (dateFrom) {
10
- const [year, month, day] = dateFrom.split("-").map(Number);
11
- clauses.push(`Date>=DateTime(${year},${month},${day})`);
12
- }
13
- if (dateTo) {
14
- const [year, month, day] = dateTo.split("-").map(Number);
15
- clauses.push(`Date<=DateTime(${year},${month},${day})`);
16
- }
17
- return clauses.length > 0 ? clauses.join("&&") : undefined;
4
+ import { joinWhere, xeroDateRangeWhere, xeroDateTime } from "../helpers/xero-date-where.js";
5
+ function buildWhereClause(type, dateFrom, dateTo, dueBefore) {
6
+ return joinWhere([
7
+ type ? `Type=="${type}"` : undefined,
8
+ ...xeroDateRangeWhere(dateFrom, dateTo),
9
+ dueBefore ? `DueDate<${xeroDateTime(dueBefore)}` : undefined,
10
+ ]);
18
11
  }
19
- async function getInvoices(invoiceNumbers, contactIds, page, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize) {
12
+ async function getInvoices(invoiceNumbers, contactIds, page, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize, dueBefore) {
20
13
  await xeroClient.authenticate();
21
- const where = buildWhereClause(type, dateFrom, dateTo);
14
+ const where = buildWhereClause(type, dateFrom, dateTo, dueBefore);
22
15
  const order = `${orderBy ?? "UpdatedDateUTC"} ${orderDirection ?? "DESC"}`;
23
16
  const statuses = status ? [status] : undefined;
24
17
  const invoices = await xeroClient.accountingApi.getInvoices(xeroClient.tenantId, undefined, // ifModifiedSince
@@ -40,9 +33,9 @@ async function getInvoices(invoiceNumbers, contactIds, page, orderBy, orderDirec
40
33
  /**
41
34
  * List all invoices from Xero
42
35
  */
43
- export async function listXeroInvoices(page = 1, contactIds, invoiceNumbers, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize) {
36
+ export async function listXeroInvoices(page = 1, contactIds, invoiceNumbers, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize, dueBefore) {
44
37
  try {
45
- const invoices = await getInvoices(invoiceNumbers, contactIds, page, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize);
38
+ const invoices = await getInvoices(invoiceNumbers, contactIds, page, orderBy, orderDirection, status, type, dateFrom, dateTo, pageSize, dueBefore);
46
39
  return {
47
40
  result: invoices,
48
41
  isError: false,
@@ -1,21 +1,22 @@
1
1
  import { xeroClient } from "../clients/xero-client.js";
2
2
  import { formatError } from "../helpers/format-error.js";
3
3
  import { getClientHeaders } from "../helpers/get-client-headers.js";
4
- async function getItems(page) {
4
+ async function getItems() {
5
5
  await xeroClient.authenticate();
6
6
  const items = await xeroClient.accountingApi.getItems(xeroClient.tenantId, undefined, // ifModifiedSince
7
7
  undefined, // where
8
8
  undefined, // order
9
- page, // page
9
+ undefined, // unitdp
10
10
  getClientHeaders());
11
11
  return items.body.items ?? [];
12
12
  }
13
13
  /**
14
- * List all items from Xero
14
+ * List all items from Xero. Xero returns every item in one response: the
15
+ * items endpoint has no pages.
15
16
  */
16
- export async function listXeroItems(page = 1) {
17
+ export async function listXeroItems() {
17
18
  try {
18
- const items = await getItems(page);
19
+ const items = await getItems();
19
20
  return {
20
21
  result: items,
21
22
  isError: false,
@@ -7,7 +7,7 @@ async function getManualJournals(page, manualJournalId, modifiedAfter) {
7
7
  const response = await xeroClient.accountingApi.getManualJournal(xeroClient.tenantId, manualJournalId, getClientHeaders());
8
8
  return response.body.manualJournals ?? [];
9
9
  }
10
- const response = await xeroClient.accountingApi.getManualJournals(xeroClient.tenantId, modifiedAfter ? new Date(modifiedAfter) : undefined, undefined, "UpdatedDateUTC DESC", page, 10, // pageSize
10
+ const response = await xeroClient.accountingApi.getManualJournals(xeroClient.tenantId, modifiedAfter ? new Date(modifiedAfter) : undefined, undefined, "UpdatedDateUTC DESC", page, 100, // pageSize
11
11
  getClientHeaders());
12
12
  return response.body.manualJournals ?? [];
13
13
  }
@@ -22,7 +22,7 @@ async function getPayments(page = 1, { invoiceNumber, invoiceId, paymentId, refe
22
22
  const response = await xeroClient.accountingApi.getPayments(xeroClient.tenantId, undefined, // ifModifiedSince
23
23
  where, "UpdatedDateUTC DESC", // order
24
24
  page, // page
25
- 10, // pageSize
25
+ 100, // pageSize
26
26
  getClientHeaders());
27
27
  return response.body.payments ?? [];
28
28
  }
@@ -4,12 +4,10 @@ import { getClientHeaders } from "../helpers/get-client-headers.js";
4
4
  /**
5
5
  * Internal function to fetch profit and loss data from Xero
6
6
  */
7
- async function fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly) {
7
+ async function fetchProfitAndLoss(fromDate, toDate, periods, timeframe, trackingCategoryID, trackingOptionID, standardLayout, paymentsOnly) {
8
8
  await xeroClient.authenticate();
9
- const response = await xeroClient.accountingApi.getReportProfitAndLoss(xeroClient.tenantId, fromDate, toDate, periods, timeframe, undefined, // trackingCategoryID
10
- undefined, // trackingOptionID
11
- undefined, // trackingCategoryID2
12
- undefined, // trackingOptionID2
9
+ const response = await xeroClient.accountingApi.getReportProfitAndLoss(xeroClient.tenantId, fromDate, toDate, periods, timeframe, trackingCategoryID, undefined, // trackingCategoryID2
10
+ trackingOptionID, undefined, // trackingOptionID2
13
11
  standardLayout, paymentsOnly, getClientHeaders());
14
12
  return response.body.reports?.[0] ?? null;
15
13
  }
@@ -19,16 +17,14 @@ async function fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standard
19
17
  * @param toDate Optional end date for the report (YYYY-MM-DD)
20
18
  * @param periods Optional number of periods for the report
21
19
  * @param timeframe Optional timeframe for the report (MONTH, QUARTER, YEAR)
22
- * @param trackingCategoryID Optional tracking category ID
23
- * @param trackingOptionID Optional tracking option ID
24
- * @param trackingCategoryID2 Optional second tracking category ID
25
- * @param trackingOptionID2 Optional second tracking option ID
20
+ * @param trackingCategoryID Optional tracking category to split the columns by
21
+ * @param trackingOptionID Optional tracking option to show alone
26
22
  * @param standardLayout Optional boolean to use standard layout
27
- * @param paymentsOnly Optional boolean to include only accounts with payments
23
+ * @param paymentsOnly Optional boolean for the cash basis
28
24
  */
29
- export async function listXeroProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly) {
25
+ export async function listXeroProfitAndLoss(fromDate, toDate, periods, timeframe, trackingCategoryID, trackingOptionID, standardLayout, paymentsOnly) {
30
26
  try {
31
- const profitAndLoss = await fetchProfitAndLoss(fromDate, toDate, periods, timeframe, standardLayout, paymentsOnly);
27
+ const profitAndLoss = await fetchProfitAndLoss(fromDate, toDate, periods, timeframe, trackingCategoryID, trackingOptionID, standardLayout, paymentsOnly);
32
28
  if (!profitAndLoss) {
33
29
  return {
34
30
  result: null,
@@ -0,0 +1,195 @@
1
+ import { xeroClient } from "../clients/xero-client.js";
2
+ import { formatError } from "../helpers/format-error.js";
3
+ import { getClientHeaders } from "../helpers/get-client-headers.js";
4
+ import { xeroDateRangeWhere } from "../helpers/xero-date-where.js";
5
+ /** Xero's largest page for invoices, bank transactions and credit notes. */
6
+ export const TOTALS_PAGE_SIZE = 1000;
7
+ /**
8
+ * Stop reading one kind of document after this many pages (50,000 documents),
9
+ * so a very long period cannot use up the organisation's daily Xero call
10
+ * allowance (5,000). The result says so when it stops early.
11
+ */
12
+ export const TOTALS_MAX_PAGES = 50;
13
+ const DOCUMENT_TYPES = {
14
+ spend: { invoice: "ACCPAY", bank: "SPEND", credit: "ACCPAYCREDIT" },
15
+ sales: { invoice: "ACCREC", bank: "RECEIVE", credit: "ACCRECCREDIT" },
16
+ };
17
+ async function readAllPages(kind, fetchPage, truncated) {
18
+ const all = [];
19
+ for (let page = 1; page <= TOTALS_MAX_PAGES; page++) {
20
+ const rows = await fetchPage(page);
21
+ all.push(...rows);
22
+ if (rows.length < TOTALS_PAGE_SIZE)
23
+ return all;
24
+ }
25
+ truncated.push(kind);
26
+ return all;
27
+ }
28
+ /** A line's amount without tax, in the document's own currency. */
29
+ function lineNet(line, lineAmountTypes) {
30
+ const amount = line.lineAmount ?? 0;
31
+ return String(lineAmountTypes) === "Inclusive"
32
+ ? amount - (line.taxAmount ?? 0)
33
+ : amount;
34
+ }
35
+ /**
36
+ * Xero's currency rate is units of the document's currency per one unit of
37
+ * the base currency, so a base amount is the document amount divided by it.
38
+ */
39
+ function toBase(amount, currencyRate) {
40
+ return currencyRate && currencyRate > 0 ? amount / currencyRate : amount;
41
+ }
42
+ function addTo(map, key, amount) {
43
+ map.set(key, (map.get(key) ?? 0) + amount);
44
+ }
45
+ /** No account code on a line, or no line items on a document. */
46
+ export const NO_ACCOUNT = "(no account code)";
47
+ export function totalByContact(documents, accountCodes) {
48
+ const wanted = accountCodes?.length ? new Set(accountCodes) : null;
49
+ const contacts = new Map();
50
+ const byAccount = new Map();
51
+ let total = 0;
52
+ let documentsWithoutLineItems = 0;
53
+ for (const { doc, sign } of documents) {
54
+ const lines = doc.lineItems?.length
55
+ ? doc.lineItems.map((line) => ({
56
+ account: line.accountCode || NO_ACCOUNT,
57
+ net: lineNet(line, doc.lineAmountTypes),
58
+ }))
59
+ : [{ account: NO_ACCOUNT, net: doc.subTotal ?? 0 }];
60
+ if (!doc.lineItems?.length)
61
+ documentsWithoutLineItems++;
62
+ const counted = lines.filter((line) => !wanted || wanted.has(line.account));
63
+ if (counted.length === 0)
64
+ continue;
65
+ const key = doc.contactId ?? `name:${doc.contactName ?? ""}`;
66
+ const contact = contacts.get(key) ??
67
+ {
68
+ contactId: doc.contactId,
69
+ name: doc.contactName || "(no contact named)",
70
+ total: 0,
71
+ documents: 0,
72
+ byAccount: new Map(),
73
+ };
74
+ contact.documents++;
75
+ for (const line of counted) {
76
+ const amount = sign * toBase(line.net, doc.currencyRate);
77
+ contact.total += amount;
78
+ total += amount;
79
+ addTo(contact.byAccount, line.account, amount);
80
+ addTo(byAccount, line.account, amount);
81
+ }
82
+ contacts.set(key, contact);
83
+ }
84
+ return {
85
+ contacts: [...contacts.values()].sort((a, b) => b.total - a.total),
86
+ total,
87
+ byAccount,
88
+ documentsWithoutLineItems,
89
+ };
90
+ }
91
+ function fromInvoice(invoice) {
92
+ return {
93
+ contactId: invoice.contact?.contactID ?? null,
94
+ contactName: invoice.contact?.name ?? null,
95
+ lineAmountTypes: invoice.lineAmountTypes,
96
+ currencyRate: invoice.currencyRate,
97
+ subTotal: invoice.subTotal,
98
+ lineItems: invoice.lineItems,
99
+ };
100
+ }
101
+ function fromBankTransaction(transaction) {
102
+ return {
103
+ contactId: transaction.contact?.contactID ?? null,
104
+ contactName: transaction.contact?.name ?? null,
105
+ lineAmountTypes: transaction.lineAmountTypes,
106
+ currencyRate: transaction.currencyRate,
107
+ subTotal: transaction.subTotal,
108
+ lineItems: transaction.lineItems,
109
+ };
110
+ }
111
+ function fromCreditNote(creditNote) {
112
+ return {
113
+ contactId: creditNote.contact?.contactID ?? null,
114
+ contactName: creditNote.contact?.name ?? null,
115
+ lineAmountTypes: creditNote.lineAmountTypes,
116
+ currencyRate: creditNote.currencyRate,
117
+ subTotal: creditNote.subTotal,
118
+ lineItems: creditNote.lineItems,
119
+ };
120
+ }
121
+ async function getTotals(request) {
122
+ await xeroClient.authenticate();
123
+ const tenantId = xeroClient.tenantId;
124
+ const dates = xeroDateRangeWhere(request.dateFrom, request.dateTo);
125
+ const types = DOCUMENT_TYPES[request.direction];
126
+ const truncated = [];
127
+ const [organisations, accounts, invoices, bankTransactions, creditNotes] = await Promise.all([
128
+ xeroClient.accountingApi.getOrganisations(tenantId, getClientHeaders()),
129
+ xeroClient.accountingApi.getAccounts(tenantId, undefined, // ifModifiedSince
130
+ undefined, // where
131
+ undefined, // order
132
+ getClientHeaders()),
133
+ readAllPages(request.direction === "spend" ? "bills" : "sales invoices", async (page) => (await xeroClient.accountingApi.getInvoices(tenantId, undefined, // ifModifiedSince
134
+ [`Type=="${types.invoice}"`, ...dates].join("&&"), // where
135
+ "Date ASC", // order
136
+ undefined, // iDs
137
+ undefined, // invoiceNumbers
138
+ undefined, // contactIDs
139
+ ["AUTHORISED", "PAID"], // statuses
140
+ page, false, // includeArchived
141
+ false, // createdByMyApp
142
+ undefined, // unitdp
143
+ false, // summaryOnly: line items are needed
144
+ TOTALS_PAGE_SIZE, // pageSize
145
+ undefined, // searchTerm
146
+ getClientHeaders())).body.invoices ?? [], truncated),
147
+ readAllPages(request.direction === "spend" ? "spend-money transactions" : "receive-money transactions", async (page) => (await xeroClient.accountingApi.getBankTransactions(tenantId, undefined, // ifModifiedSince
148
+ [`Type=="${types.bank}"`, `Status=="AUTHORISED"`, ...dates].join("&&"), // where
149
+ "Date ASC", // order
150
+ page, undefined, // unitdp
151
+ TOTALS_PAGE_SIZE, // pageSize
152
+ getClientHeaders())).body.bankTransactions ?? [], truncated),
153
+ readAllPages(request.direction === "spend" ? "supplier credit notes" : "customer credit notes", async (page) => (await xeroClient.accountingApi.getCreditNotes(tenantId, undefined, // ifModifiedSince
154
+ [
155
+ `Type=="${types.credit}"`,
156
+ `(Status=="AUTHORISED"||Status=="PAID")`,
157
+ ...dates,
158
+ ].join("&&"), // where
159
+ "Date ASC", // order
160
+ page, undefined, // unitdp
161
+ TOTALS_PAGE_SIZE, // pageSize
162
+ getClientHeaders())).body.creditNotes ?? [], truncated),
163
+ ]);
164
+ const summary = totalByContact([
165
+ ...invoices.map((invoice) => ({ doc: fromInvoice(invoice), sign: 1 })),
166
+ ...bankTransactions.map((t) => ({ doc: fromBankTransaction(t), sign: 1 })),
167
+ ...creditNotes.map((c) => ({ doc: fromCreditNote(c), sign: -1 })),
168
+ ], request.accountCodes);
169
+ const accountNames = new Map();
170
+ for (const account of accounts.body.accounts ?? []) {
171
+ if (account.code && account.name)
172
+ accountNames.set(account.code, account.name);
173
+ }
174
+ const baseCurrency = organisations.body.organisations?.[0]?.baseCurrency;
175
+ return {
176
+ ...summary,
177
+ baseCurrency: baseCurrency ? String(baseCurrency) : null,
178
+ accountNames,
179
+ counted: {
180
+ invoices: invoices.length,
181
+ bankTransactions: bankTransactions.length,
182
+ creditNotes: creditNotes.length,
183
+ },
184
+ truncated,
185
+ };
186
+ }
187
+ /** Total spend by supplier, or sales by customer, and by account over a date range, in one call. */
188
+ export async function summariseXeroTotals(request) {
189
+ try {
190
+ return { result: await getTotals(request), isError: false, error: null };
191
+ }
192
+ catch (error) {
193
+ return { result: null, isError: true, error: formatError(error) };
194
+ }
195
+ }
@@ -0,0 +1,107 @@
1
+ import { z } from "zod";
2
+ import { TOTALS_MAX_PAGES, TOTALS_PAGE_SIZE, summariseXeroTotals, } from "../handlers/summarise-xero-totals.handler.js";
3
+ import { xeroDateParam } from "./xero-date-where.js";
4
+ const WORDS = {
5
+ spend: {
6
+ title: "Spend by supplier",
7
+ contacts: "suppliers",
8
+ invoices: "approved or paid bills",
9
+ bank: "spend-money bank transactions",
10
+ credits: "supplier credit notes",
11
+ none: "No spend found.",
12
+ },
13
+ sales: {
14
+ title: "Sales by customer",
15
+ contacts: "customers",
16
+ invoices: "approved or paid sales invoices",
17
+ bank: "receive-money bank transactions",
18
+ credits: "customer credit notes",
19
+ none: "No sales found.",
20
+ },
21
+ };
22
+ function money(amount) {
23
+ return amount.toLocaleString("en-US", {
24
+ minimumFractionDigits: 2,
25
+ maximumFractionDigits: 2,
26
+ });
27
+ }
28
+ function accountLabel(code, names) {
29
+ const name = names.get(code);
30
+ return name ? `${code} ${name}` : code;
31
+ }
32
+ function topAccounts(byAccount, names, limit) {
33
+ return [...byAccount.entries()]
34
+ .sort((a, b) => b[1] - a[1])
35
+ .slice(0, limit)
36
+ .map(([code, amount]) => `${accountLabel(code, names)}: ${money(amount)}`)
37
+ .join("; ");
38
+ }
39
+ export function formatContactTotals(summary, request) {
40
+ const words = WORDS[request.direction];
41
+ const currency = summary.baseCurrency ?? "the organisation's base currency";
42
+ const scope = request.accountCodes?.length
43
+ ? `accounts ${request.accountCodes.map((code) => accountLabel(code, summary.accountNames)).join(", ")}`
44
+ : "all accounts";
45
+ const shown = summary.contacts.slice(0, request.top);
46
+ const header = [
47
+ `${words.title}, ${request.dateFrom} to ${request.dateTo}, ${scope}.`,
48
+ `Amounts exclude tax and are in ${currency}. Counted: ${summary.counted.invoices} ${words.invoices}, ` +
49
+ `${summary.counted.bankTransactions} ${words.bank}, minus ${summary.counted.creditNotes} ${words.credits}. ` +
50
+ "Payments against invoices are not counted again.",
51
+ `Total: ${money(summary.total)} across ${summary.contacts.length} ${words.contacts}` +
52
+ (summary.contacts.length > shown.length ? ` (top ${shown.length} shown).` : "."),
53
+ ];
54
+ if (!request.accountCodes?.length && summary.byAccount.size > 0) {
55
+ header.push(`Largest accounts: ${topAccounts(summary.byAccount, summary.accountNames, 10)}.`);
56
+ }
57
+ if (summary.documentsWithoutLineItems > 0) {
58
+ header.push(`${summary.documentsWithoutLineItems} documents came without line items; their subtotal is counted under "(no account code)".`);
59
+ }
60
+ if (summary.truncated.length > 0) {
61
+ header.push(`May be incomplete: reading ${summary.truncated.join(" and ")} stopped after ${(TOTALS_MAX_PAGES * TOTALS_PAGE_SIZE).toLocaleString("en-US")} documents each. Use a shorter date range for a complete total.`);
62
+ }
63
+ const rows = shown.map((contact, index) => `${index + 1}. ${contact.name}: ${money(contact.total)} from ${contact.documents} documents` +
64
+ (contact.contactId ? ` (contact ${contact.contactId})` : "") +
65
+ ` — ${topAccounts(contact.byAccount, summary.accountNames, 3)}`);
66
+ return [header.join("\n"), ...(rows.length ? [rows.join("\n")] : [words.none])];
67
+ }
68
+ /** The parameters both totals tools take. */
69
+ export function contactTotalsParams(direction) {
70
+ const kind = direction === "spend" ? "expense" : "revenue";
71
+ return {
72
+ dateFrom: xeroDateParam.describe("Start of the period, inclusive (YYYY-MM-DD)"),
73
+ dateTo: xeroDateParam.describe("End of the period, inclusive (YYYY-MM-DD)"),
74
+ accountCodes: z
75
+ .array(z.string().min(1))
76
+ .optional()
77
+ .describe(`Count only lines coded to these ${kind} account codes (from list-accounts). Omit for all accounts.`),
78
+ top: z
79
+ .number()
80
+ .int()
81
+ .min(1)
82
+ .max(500)
83
+ .optional()
84
+ .describe(`How many ${WORDS[direction].contacts} to list (default 25). The total always covers every one.`),
85
+ };
86
+ }
87
+ /** Runs one totals tool: reads Xero, then formats the ranking. */
88
+ export async function runContactTotals(direction, args) {
89
+ const { dateFrom, dateTo, accountCodes, top } = args;
90
+ const response = await summariseXeroTotals({ direction, dateFrom, dateTo, accountCodes });
91
+ if (response.error !== null) {
92
+ const what = direction === "spend" ? "spend" : "sales";
93
+ return {
94
+ content: [{ type: "text", text: `Error summarising ${what}: ${response.error}` }],
95
+ isError: true,
96
+ };
97
+ }
98
+ return {
99
+ content: formatContactTotals(response.result, {
100
+ direction,
101
+ dateFrom,
102
+ dateTo,
103
+ accountCodes,
104
+ top: top ?? 25,
105
+ }).map((text) => ({ type: "text", text })),
106
+ };
107
+ }
@@ -1,13 +1,20 @@
1
- export const formatLineItem = (lineItem) => {
2
- return [
3
- `Item ID: ${lineItem.item}`,
4
- `Item Code: ${lineItem.itemCode}`,
5
- `Description: ${lineItem.description}`,
6
- `Quantity: ${lineItem.quantity}`,
7
- `Unit Amount: ${lineItem.unitAmount}`,
8
- `Account Code: ${lineItem.accountCode}`,
9
- `Tax Type: ${lineItem.taxType}`,
10
- `Tracking: ${lineItem.tracking}`,
11
- `Line Amount: ${lineItem.lineAmount}`,
12
- ].join("\n");
13
- };
1
+ /** One line item on one line: what it is, how much, and where it is coded. */
2
+ export const formatLineItem = (lineItem) => [
3
+ lineItem.description ? `${lineItem.description}` : "(no description)",
4
+ lineItem.itemCode ? `item ${lineItem.itemCode}` : null,
5
+ lineItem.quantity !== undefined && lineItem.unitAmount !== undefined
6
+ ? `${lineItem.quantity} x ${lineItem.unitAmount}`
7
+ : null,
8
+ lineItem.lineAmount !== undefined ? `amount ${lineItem.lineAmount}` : null,
9
+ lineItem.taxAmount ? `tax ${lineItem.taxAmount}` : null,
10
+ lineItem.accountCode ? `account ${lineItem.accountCode}` : null,
11
+ lineItem.tracking?.length
12
+ ? `tracking ${lineItem.tracking.map((t) => `${t.name}: ${t.option}`).join(", ")}`
13
+ : null,
14
+ ]
15
+ .filter(Boolean)
16
+ .join(" | ");
17
+ /** A document's line items, one per row; null when it has none. */
18
+ export const formatLineItems = (lineItems) => lineItems?.length
19
+ ? `Line Items:\n${lineItems.map((line) => `- ${formatLineItem(line)}`).join("\n")}`
20
+ : null;
@@ -0,0 +1,28 @@
1
+ const cellsOf = (row) => (row.cells ?? []).map((cell) => cell.value ?? "").join(" | ");
2
+ /**
3
+ * A Xero report as a plain table: its titles (which name the period it
4
+ * covers), its column headings, then each section's rows and totals, one row
5
+ * per line with cells separated by " | ". Xero's own JSON repeats every
6
+ * account id on every cell, which makes a year's report several times longer
7
+ * to read without telling the AI anything more.
8
+ */
9
+ export function formatReport(report) {
10
+ const lines = [];
11
+ const titles = report.reportTitles?.filter(Boolean) ?? [];
12
+ lines.push(...(titles.length > 0 ? titles : [report.reportName ?? "Report"]));
13
+ if (report.updatedDateUTC)
14
+ lines.push(`Updated: ${report.updatedDateUTC.toISOString()}`);
15
+ for (const row of (report.rows ?? [])) {
16
+ if (String(row.rowType) === "Header") {
17
+ lines.push("", `Columns: ${cellsOf(row)}`);
18
+ continue;
19
+ }
20
+ if (row.title)
21
+ lines.push("", row.title);
22
+ if (row.cells?.length)
23
+ lines.push(cellsOf(row));
24
+ for (const inner of row.rows ?? [])
25
+ lines.push(cellsOf(inner));
26
+ }
27
+ return lines.join("\n");
28
+ }