TRES — Invoice/Bill Matching & ERP Sync
End-to-end workflow that lets the user close an open ERP invoice or bill against a blockchain transaction in
the TRES ledger, then optionally push the matched entry to the connected ERP.
The flow is the same regardless of which side the user starts from (a transaction hash or an invoice/bill ID).
The skill walks through seven conversational steps (verify ERP → identify input → fetch & suggest → user picks
→ configure payment account & fiat → confirm & apply → loop). Stay terse — show numbered options, capture the
user's pick, move on. Never run a mutation without explicit "yes" from the user.
Ground rules
- Identify the org first. Begin with
get_viewer and tell the user "You're connected to {orgName}."
This makes mistakes recoverable when someone has the wrong token.
- Read before write. Always fetch the current state of the transaction, invoice/bill, and payment account
before showing a change summary. Surprises are worse than slow.
- Mutations require explicit approval. Show a summary table (Transaction · Invoice/Bill · Payment Account ·
Fiat alignment · Sync) and ask "Apply these changes?" before any mutation. Only proceed on a clear yes.
- Use schema introspection when in doubt. Field names, enum values, and argument shapes can drift. If a
query/mutation errors with "unknown field" or "invalid enum", call
introspect(<TypeName>) or
build_query(<operationName>) and adjust — don't guess. Operations specifically called out as "verify at
runtime" below are the ones most likely to need this.
- The skill is a loop. After a successful match, ask "Match another?" and restart from Step 2. Don't
re-check the ERP — that only happens once per session.
Step 1 — Verify ERP is connected
Run:
query { integration(first: 50) { results { id integratedApp isErp connectionStatus companyName } } }
Filter the results where isErp == true and connectionStatus == "ACTIVE". The supported ERPs you should
recognize are Xero, QuickBooks Online (QBO), and NetSuite — integratedApp values are XERO,
QUICKBOOKS, and NETSUITE. (If you encounter unknown values, introspect("IntegrationsQueryNode") will
confirm the enum.) Ignore rows where integratedApp is empty — the API occasionally returns a null row.
- No connected ERP: Tell the user they need to connect one before matching can happen, point them at
https://app.tres.finance/settings/integrations, and stop.
- One connected ERP: Use it implicitly and just mention "Matching against {companyName} ({integratedApp})."
- Multiple connected ERPs: Ask which one to use — different ERPs have separate invoice/bill stores.
Cache the chosen ERP's id, integratedApp, and companyName for later steps and the loop.
Step 2 — Identify what the user has
Ask whether they have:
- a transaction hash (e.g.
0x…) — best case, pins the match immediately,
- an invoice/bill ID or number (numeric internal ID, or the human-facing
invoiceNumber/billNumber),
- or both.
If they have neither, require at least one. If they're not sure whether their identifier is an invoice or a
bill, accept it and try both lookups in Step 3.
Also accept loose forms — "INV-123", "Bill 9988", "the bill for Acme last week". The freeText filter on
erpInvoices / erpBills handles these.
Before moving on, always ask for the transaction date (or an approximate date range) if they haven't given
a tx hash. Ledger volume is high — date is the single most useful filter for narrowing candidates. Also
offer: "If you happen to have the tx hash, paste it now — it pins the match exactly." Date matters both
directions (tx→bill and bill→tx).
Step 3 — Fetch the known object and produce ranked match suggestions
There are two branches. Pick by what the user provided. If they provided both a tx hash and an invoice/bill
ID, skip ahead to Step 5 (match is already determined).
Branch A — User has a transaction hash
- Fetch the transaction with its sub-transactions:
query GetTx($hash: String!) {
transaction(identifier: $hash, currency: "usd", limit: 1) {
results {
id identifier timestamp platform
children {
id amount balanceFactor isInternalTransfer
fiatValue
sender { identifier displayName isInternal }
recipient { identifier displayName isInternal }
asset { symbol identifier }
}
}
}
}
- Pick the relevant sub-transaction. Skip gas, skip internal transfers, prefer the one with the user's
wallet on one side and an external counterparty on the other. Determine direction:
balanceFactor negative → outflow → look for a bill to close.
balanceFactor positive → inflow → look for an invoice to close.
If multiple sub-txs qualify (e.g., a swap with multiple legs), present them and let the user pick one.
- For invoices (inflow), try backend match suggestions first — they are pre-computed and ranked:
query Suggest($subTxIds: [String]!) {
subTransactionToInvoiceMatchSuggestions(
subTransactionId_In: $subTxIds, minScore: 0.3, ordering: "-score", first: 10
) {
results {
id score confidenceTier
scoreBreakdown { txHashMatch primaryMatchFactors }
invoice {
id invoiceId invoiceNumber customerName origAmount balance dueDate billingStatus
integration { integratedApp companyName }
}
}
}
}
Important: this endpoint is invoice-only. For bills (outflow), skip straight to the fallback below
— there is no backend bill-suggestion query exposed in the schema.
- Fallback (zero invoice suggestions, or always for bills): query
erpInvoices (inflow) or erpBills
(outflow), filtered by:
- amount window:
±20% of the sub-tx fiat value,
- date window:
dateCreated_Range = [tx.timestamp − 60d, tx.timestamp] — bills/invoices are issued at or
before the payment, never after. Don't bother with future-dated invoices/bills.
- contact: if the user has named a vendor/customer, pass that as
freeText. Do NOT try to match the
on-chain recipient address to an ERP contact — ERP contact identifiers (from QBO/Xero/NetSuite) are
internal IDs, never wallet addresses. Some contact labels happen to resemble the vendor name in text,
but the schema has no "resembles" filter, so rely on freeText over vendor/customer fields.
Rank the fallback set client-side by: amount proximity → date proximity (prefer the most recent
bill/invoice before the tx) → name hits in freeText output.
- Present the top ≤5 as a numbered list (never more — too many choices is worse than too few). For each row
show: confidence tier, $ amount, customer/vendor name,
invoiceNumber/billNumber, due date, and the
primaryMatchFactors (e.g. amount_exact, contact_match). Best-fit first.
Branch B — User has an invoice/bill ID or number
- Resolve the entity. Try
erpInvoices first, then erpBills if it's not an invoice (or vice versa if the
user said "bill"). For invoices, include the embedded suggestions:query GetInvoice($id: Float, $text: String) {
erpInvoices(id: $id, freeText: $text, first: 1) {
results {
id invoiceNumber customerName origAmount balance dateCreated dueDate billingStatus
integration { integratedApp companyName }
suggestedSubTransactionMatches {
id score confidenceTier
subTransaction {
id amount fiatValue
asset { symbol identifier }
tx { identifier timestamp platform }
}
}
}
}
}
For bills, query erpBills — note that bills do not expose suggestedSubTransactionMatches, so
just fetch the bill metadata (id billNumber vendorName vendorId origAmount balance dateCreated dueDate billingStatus integration { integratedApp companyName }) and go straight to the fallback step. If id
lookup returns nothing, retry with freeText: $userInput.
- For invoices, use the embedded
suggestedSubTransactionMatches as the ranked list.
- Fallback (zero invoice suggestions, or always for bills):
- First, ask the user for an approximate date of payment (and remind them: "if you have the tx hash,
that's fastest"). Payments happen on or after the bill/invoice date, usually within days — not before.
Default to a window of
[dateCreated, dateCreated + 60 days] if they can't be specific.
- Query
transaction with server-side filters so we don't pull the entire ledger. Use:
platform: <configuredNetwork or user's network> (e.g. "ethereum"),
timestamp_Gte / timestamp_Lte → the user-supplied date window,
children_Asset_Identifier_In: [<assetIdentifier>] → the bill's configuredAsset.identifier (e.g. the
USDC contract), or the invoice's expected asset,
children_FiatValue_Between: "<low>,<high>" → fiat window around origAmount (e.g. ±20%). This is
a string of two comma-separated numbers. Example: "0.4,0.6" for a $0.50 bill.
- Optionally
children_BalanceFactor: -1 (outflow, for bills) or 1 (inflow, for invoices).
- Use
children_Amount_Between as an additional filter only when the fiat price can't be trusted
(pre-priced historical assets, etc.).
- If the resulting set is still large, ask the user for a tighter date or an amount refinement before
presenting.
- Present up to 5 candidate transactions as a numbered list — show for each:
tx hash (truncated
0xabcd…1234), sender → recipient addresses (same shortened form), token amount +
symbol, fiat value, and timestamp. The tx hash is the user-facing identifier they recognize; the raw
addresses and token amounts disambiguate when fiat alone is too ambiguous (many txs cluster near the same
amount). Never show internal IDs like subTxId to the user — they're meaningless to them. Hold the
subTxId internally for the mutation; reference the tx by its hash in all user-visible output.
If no good matches, say so and ask for a tx hash — don't guess-dump a big list.
Step 4 — User picks a match (or asks for more)
Prompt: "Pick a number, or type more to widen the search (give me a contact name, date, or amount to focus
on)."
- On a number: capture the chosen
(subTxId, invoiceOrBillId, entityType) and continue to Step 5.
- On
more: re-query with looser windows or with the user's added hints (contact filter, expanded date range,
amount range), present a fresh list, repeat.
- On "none of these" or similar: stop gracefully — "OK, no match made. Tell me when you have more info."
Step 5 — Configure payment account and (optional) fiat alignment
Once a match pair is chosen:
Deposit account (for matchApAr.depositAccountId). This is an ERP integration account
(the GL account in Xero/QBO/NetSuite that the bill will post against — e.g. "Crypto Wallet – ETH",
"Cash and cash equivalents"). It is NOT a tres internal/wallet account. The schema FK is against
schema_integrationaccount; the value lives on ErpBill.depositAccount / ErpInvoice.depositAccount
as IntegrationAccountQuery { id name type value }.
Resolution order:
- Use the pre-set one on the bill/invoice. When the entity was created in the ERP, the user
typically already picked a deposit account. Read
erpBills.results[].depositAccount.id (or
erpInvoices.results[].depositAccount.id). If it's non-null, use that id as depositAccountId
and just mention it in the summary — no prompt.
- Otherwise ask. Query
integrationAccount(integration: <erpId>, first: 100) and show the
user the ASSET-type accounts (cash/wallet/crypto GL accounts) as a numbered list; capture the
chosen integrationAccount.id.
paymentToInternalAccounts maps wallet → asset on the tres side and is useful for payout
workflows — it is not the source of depositAccountId for matchApAr. Don't reach for it
here.
Fiat alignment. Compare the sub-tx fiatValue to the invoice/bill origAmount. Three cases:
fiatValue is null or 0: ask "This transaction has no fiat value set. Align it to ${origAmount}
so the {bill/invoice} closes fully? (y/n)" — no default, require an explicit yes.
fiatValue differs from origAmount: ask "Align tx fiat value from $X to $Y so the AP/AR
closes fully? (y/n)" — no default, require an explicit yes.
- Values match: skip.
Never run
setManualFiatValue without a clear yes — even if the user's original request implied
"close the invoice", the fiat alignment is a separate write and needs its own consent. If they say no,
the match still proceeds but the entity may stay partially paid.
Step 6 — Confirm and apply
Show this summary table — use human-readable values only: tx hash (truncated), deposit account name
(never its id), invoice/bill number or customer/vendor name. Internal IDs (subTxId, depositAccountId,
DB entityId) are for the mutation payload, never for the user.
|
|
| Transaction |
0xabcd…1234 · {asset.symbol} {amount} · ${fiatValue} |
| Invoice/Bill |
{invoiceNumber or billNumber} · {customer/vendor} · ${origAmount} {currency} |
| Payment account |
{depositAccount.name} |
| Align fiat |
yes → ${origAmount} / no |
| Sync to ERP after match |
yes / no |
Ask: *"Apply these changes to {orgName}? (yes/no)"* — only proceed on yes. Treat this as approval for
the match only. Fiat alignment and ERP sync each need their own explicit yes captured earlier (Step 5
for fiat, the prompt below for sync) — even if the user's opening request said "sync to QBO", still confirm
here, because the request was issued before they saw the actual match details.
Then run mutations in this order, reporting the result of each:
Match (always):
mutation Match($entityType: String!, $matches: [SubTxMatchInput]!) {
matchApAr(entityType: $entityType, matches: $matches) {
results { subTxId entityId depositAccountId }
}
}
Variables:
entityType: lowercase — "invoice" or "bill". Uppercase values are rejected with
Invalid entity_type.
matches[].subTxId: string (e.g. "4548595830").
matches[].entityId: integer — the DB id of the invoice/bill (from erpInvoices.results[].id
/ erpBills.results[].id), NOT the human-facing invoiceNumber/billNumber. Passing a string
errors with "Int cannot represent non-integer value"; passing a bill number looks up nothing
and errors with "One or more Bill IDs not found".
matches[].depositAccountId: integer — the integration account id (see Step 5).
Fiat alignment (only if user opted in):
mutation AlignFiat($id: String!, $newFiatValue: String!, $currency: String) {
setManualFiatValue(id: $id, newFiatValue: $newFiatValue, currency: $currency) { success }
}
Pass the sub-transaction ID as id, the target value as a string in newFiatValue (e.g. "123.45", the
invoice/bill origAmount), and currency: "usd". If the response returns an error about a "locked
period", the accounting period containing the tx is closed — surface that to the user; don't try to force.
ERP sync (ask first, every time): "Sync this transaction to {erpName} now? (y/n)" — never sync
without an explicit yes at this point, even if the user's original ask included "and sync to QBO". The
sync call is visible in the ERP and harder to undo than the match itself, so it gets its own gate. If yes:
mutation Sync($txIds: [String]!, $entityType: String!) {
syncSpecificTransactions(transactionIds: $txIds, entitySourceType: $entityType) { status }
}
entitySourceType mirrors entityType from the match call.
When reporting results back to the user, refer to the transaction by its tx hash (truncated) and the
deposit account by name — never by subTxId or depositAccountId. Those internal IDs are for debugging,
not user output.
If any mutation errors, surface the error message verbatim and offer to retry. The match is the one that
actually links the records — if it fails, the rest is moot.
Step 7 — Loop
Ask: "Match another transaction or invoice/bill? (y/n)"
- yes → restart from Step 2 (skip Step 1 — keep the cached ERP from this session).
- no → wrap up: "Done. Closed {n} item(s) this session."
Verified TRES MCP operations used
| Purpose |
Operation |
Type |
| Org identity |
get_viewer |
MCP tool |
| Schema discovery |
introspect, build_query |
MCP tool |
| Check ERP connections |
integration (filter isErp=true) |
query |
| Fetch tx by hash |
transaction(identifier:) |
query |
| Fetch invoices (with embedded suggestions) |
erpInvoices |
query |
| Fetch bills (with embedded suggestions) |
erpBills |
query |
| Pre-computed sub-tx → invoice match suggestions |
subTransactionToInvoiceMatchSuggestions |
query |
| COA-mapped payment accounts |
paymentToInternalAccounts |
query |
| Match sub-tx ↔ invoice/bill |
matchApAr |
mutation |
| Align fiat value |
setManualFiatValue (verify args at runtime) |
mutation |
| Sync transactions to the ERP |
syncSpecificTransactions |
mutation |
| Undo a match (on user request) |
manualUnmatchSubtransactions |
mutation |
Out of scope (politely redirect if asked)
- Bulk matching (many ↔ many) — not yet supported by this skill.
- Sending payments (
sendBillPayment, sendInvoicePayment) — separate workflow.
- Connecting or revoking the ERP itself — use the
tres-settings-management skill.
- Explaining a transaction in narrative form — use
tres-tx-story.
- Importing an explorer link into the ledger — use
tres-explorer-tx-to-ledger.
1---
2name: tres-invoice-bill-matching
3description: >
4 Match TRES ledger transactions to ERP invoices/bills (AP/AR) and optionally sync them to the connected ERP
5 (Xero, QuickBooks Online, NetSuite). Trigger this skill whenever the user wants to match, link, close,
6 reconcile, or sync an invoice or bill against a blockchain transaction — even if they don't say "skill" or
7 use those exact words. Trigger phrases include: "match this invoice to a transaction", "match a bill to tx",
8 "close invoice INV-123", "close bill 9988", "link this tx to a bill", "pay this invoice from this transaction",
9 "set up this tx as AP", "set up this tx as AR", "sync this transaction as AP/AR", "match AP/AR", "find the
10 invoice/bill for this hash", "what bill does this tx pay". Trigger ONLY for explicit AP/AR matching/closing
11 intent — do NOT trigger for general transaction explanations (use tres-tx-story), for ingesting an explorer
12 link into the ledger (use tres-explorer-tx-to-ledger), or for ERP connection setup itself (use tres-settings-management).
13metadata:
14 source: https://skillmd.com/skills/gabrielmoreira/tres-invoice-bill-matching
15---
16
17# TRES — Invoice/Bill Matching & ERP Sync
18
19End-to-end workflow that lets the user close an open ERP invoice or bill against a blockchain transaction in
20the TRES ledger, then optionally push the matched entry to the connected ERP.
21
22The flow is the same regardless of which side the user starts from (a transaction hash or an invoice/bill ID).
23The skill walks through seven conversational steps (verify ERP → identify input → fetch & suggest → user picks
24→ configure payment account & fiat → confirm & apply → loop). Stay terse — show numbered options, capture the
25user's pick, move on. Never run a mutation without explicit "yes" from the user.
26
27---
28
29## Ground rules
30
311. **Identify the org first.** Begin with `get_viewer` and tell the user "You're connected to **{orgName}**."
32 This makes mistakes recoverable when someone has the wrong token.
332. **Read before write.** Always fetch the current state of the transaction, invoice/bill, and payment account
34 before showing a change summary. Surprises are worse than slow.
353. **Mutations require explicit approval.** Show a summary table (Transaction · Invoice/Bill · Payment Account ·
36 Fiat alignment · Sync) and ask "Apply these changes?" before any mutation. Only proceed on a clear yes.
374. **Use schema introspection when in doubt.** Field names, enum values, and argument shapes can drift. If a
38 query/mutation errors with "unknown field" or "invalid enum", call `introspect(<TypeName>)` or
39 `build_query(<operationName>)` and adjust — don't guess. Operations specifically called out as "verify at
40 runtime" below are the ones most likely to need this.
415. **The skill is a loop.** After a successful match, ask "Match another?" and restart from Step 2. Don't
42 re-check the ERP — that only happens once per session.
43
44---
45
46## Step 1 — Verify ERP is connected
47
48Run:
49```graphql
50query { integration(first: 50) { results { id integratedApp isErp connectionStatus companyName } } }
51```
52
53Filter the results where `isErp == true` and `connectionStatus == "ACTIVE"`. The supported ERPs you should
54recognize are **Xero**, **QuickBooks Online (QBO)**, and **NetSuite** — `integratedApp` values are `XERO`,
55`QUICKBOOKS`, and `NETSUITE`. (If you encounter unknown values, `introspect("IntegrationsQueryNode")` will
56confirm the enum.) Ignore rows where `integratedApp` is empty — the API occasionally returns a null row.
57
58- **No connected ERP:** Tell the user they need to connect one before matching can happen, point them at
59 `https://app.tres.finance/settings/integrations`, and stop.
60- **One connected ERP:** Use it implicitly and just mention "Matching against **{companyName}** ({integratedApp})."
61- **Multiple connected ERPs:** Ask which one to use — different ERPs have separate invoice/bill stores.
62
63Cache the chosen ERP's `id`, `integratedApp`, and `companyName` for later steps and the loop.
64
65---
66
67## Step 2 — Identify what the user has
68
69Ask whether they have:
70- a **transaction hash** (e.g. `0x…`) — best case, pins the match immediately,
71- an **invoice/bill ID or number** (numeric internal ID, or the human-facing `invoiceNumber`/`billNumber`),
72- or **both**.
73
74If they have neither, require at least one. If they're not sure whether their identifier is an invoice or a
75bill, accept it and try both lookups in Step 3.
76
77Also accept loose forms — "INV-123", "Bill 9988", "the bill for Acme last week". The `freeText` filter on
78`erpInvoices` / `erpBills` handles these.
79
80**Before moving on, always ask for the transaction date (or an approximate date range) if they haven't given
81a tx hash.** Ledger volume is high — date is the single most useful filter for narrowing candidates. Also
82offer: *"If you happen to have the tx hash, paste it now — it pins the match exactly."* Date matters both
83directions (tx→bill and bill→tx).
84
85---
86
87## Step 3 — Fetch the known object and produce ranked match suggestions
88
89There are two branches. Pick by what the user provided. If they provided both a tx hash *and* an invoice/bill
90ID, skip ahead to Step 5 (match is already determined).
91
92### Branch A — User has a transaction hash
93
941. Fetch the transaction with its sub-transactions:
95 ```graphql
96 query GetTx($hash: String!) {
97 transaction(identifier: $hash, currency: "usd", limit: 1) {
98 results {
99 id identifier timestamp platform
100 children {
101 id amount balanceFactor isInternalTransfer
102 fiatValue
103 sender { identifier displayName isInternal }
104 recipient { identifier displayName isInternal }
105 asset { symbol identifier }
106 }
107 }
108 }
109 }
110 ```
1112. Pick the **relevant sub-transaction**. Skip gas, skip internal transfers, prefer the one with the user's
112 wallet on one side and an external counterparty on the other. Determine direction:
113 - `balanceFactor` negative → outflow → look for a **bill** to close.
114 - `balanceFactor` positive → inflow → look for an **invoice** to close.
115 If multiple sub-txs qualify (e.g., a swap with multiple legs), present them and let the user pick one.
1163. **For invoices (inflow), try backend match suggestions first** — they are pre-computed and ranked:
117 ```graphql
118 query Suggest($subTxIds: [String]!) {
119 subTransactionToInvoiceMatchSuggestions(
120 subTransactionId_In: $subTxIds, minScore: 0.3, ordering: "-score", first: 10
121 ) {
122 results {
123 id score confidenceTier
124 scoreBreakdown { txHashMatch primaryMatchFactors }
125 invoice {
126 id invoiceId invoiceNumber customerName origAmount balance dueDate billingStatus
127 integration { integratedApp companyName }
128 }
129 }
130 }
131 }
132 ```
133 Important: this endpoint is **invoice-only**. For **bills (outflow), skip straight to the fallback below**
134 — there is no backend bill-suggestion query exposed in the schema.
1354. **Fallback (zero invoice suggestions, or always for bills):** query `erpInvoices` (inflow) or `erpBills`
136 (outflow), filtered by:
137 - amount window: `±20%` of the sub-tx fiat value,
138 - date window: `dateCreated_Range = [tx.timestamp − 60d, tx.timestamp]` — bills/invoices are issued at or
139 *before* the payment, never after. Don't bother with future-dated invoices/bills.
140 - contact: if the user has named a vendor/customer, pass that as `freeText`. Do NOT try to match the
141 on-chain recipient address to an ERP contact — ERP contact identifiers (from QBO/Xero/NetSuite) are
142 internal IDs, never wallet addresses. Some contact labels *happen to resemble* the vendor name in text,
143 but the schema has no "resembles" filter, so rely on `freeText` over `vendor`/`customer` fields.
144 Rank the fallback set client-side by: amount proximity → date proximity (prefer the most recent
145 bill/invoice before the tx) → name hits in `freeText` output.
1465. Present the top ≤5 as a numbered list (never more — too many choices is worse than too few). For each row
147 show: confidence tier, $ amount, customer/vendor name, `invoiceNumber`/`billNumber`, due date, and the
148 `primaryMatchFactors` (e.g. `amount_exact`, `contact_match`). Best-fit first.
149
150### Branch B — User has an invoice/bill ID or number
151
1521. Resolve the entity. Try `erpInvoices` first, then `erpBills` if it's not an invoice (or vice versa if the
153 user said "bill"). For **invoices**, include the embedded suggestions:
154 ```graphql
155 query GetInvoice($id: Float, $text: String) {
156 erpInvoices(id: $id, freeText: $text, first: 1) {
157 results {
158 id invoiceNumber customerName origAmount balance dateCreated dueDate billingStatus
159 integration { integratedApp companyName }
160 suggestedSubTransactionMatches {
161 id score confidenceTier
162 subTransaction {
163 id amount fiatValue
164 asset { symbol identifier }
165 tx { identifier timestamp platform }
166 }
167 }
168 }
169 }
170 }
171 ```
172 For **bills**, query `erpBills` — note that bills do **not** expose `suggestedSubTransactionMatches`, so
173 just fetch the bill metadata (`id billNumber vendorName vendorId origAmount balance dateCreated dueDate
174 billingStatus integration { integratedApp companyName }`) and go straight to the fallback step. If `id`
175 lookup returns nothing, retry with `freeText: $userInput`.
1762. For invoices, use the embedded `suggestedSubTransactionMatches` as the ranked list.
1773. **Fallback (zero invoice suggestions, or always for bills):**
178 - First, **ask the user for an approximate date of payment** (and remind them: "if you have the tx hash,
179 that's fastest"). Payments happen on or after the bill/invoice date, usually within days — not before.
180 Default to a window of `[dateCreated, dateCreated + 60 days]` if they can't be specific.
181 - Query `transaction` with **server-side filters** so we don't pull the entire ledger. Use:
182 - `platform: <configuredNetwork or user's network>` (e.g. `"ethereum"`),
183 - `timestamp_Gte` / `timestamp_Lte` → the user-supplied date window,
184 - `children_Asset_Identifier_In: [<assetIdentifier>]` → the bill's `configuredAsset.identifier` (e.g. the
185 USDC contract), or the invoice's expected asset,
186 - `children_FiatValue_Between: "<low>,<high>"` → fiat window around `origAmount` (e.g. `±20%`). This is
187 a **string** of two comma-separated numbers. Example: `"0.4,0.6"` for a $0.50 bill.
188 - Optionally `children_BalanceFactor: -1` (outflow, for bills) or `1` (inflow, for invoices).
189 - Use `children_Amount_Between` as an additional filter only when the fiat price can't be trusted
190 (pre-priced historical assets, etc.).
191 - If the resulting set is still large, ask the user for a tighter date or an amount refinement before
192 presenting.
1934. Present **up to 5** candidate transactions as a numbered list — show for each:
194 **tx hash (truncated `0xabcd…1234`), sender → recipient addresses (same shortened form), token amount +
195 symbol, fiat value, and timestamp.** The tx hash is the user-facing identifier they recognize; the raw
196 addresses and token amounts disambiguate when fiat alone is too ambiguous (many txs cluster near the same
197 amount). **Never show internal IDs like `subTxId` to the user — they're meaningless to them.** Hold the
198 `subTxId` internally for the mutation; reference the tx by its hash in all user-visible output.
199 If no good matches, say so and ask for a tx hash — don't guess-dump a big list.
200
201---
202
203## Step 4 — User picks a match (or asks for more)
204
205Prompt: *"Pick a number, or type `more` to widen the search (give me a contact name, date, or amount to focus
206on)."*
207
208- On a number: capture the chosen `(subTxId, invoiceOrBillId, entityType)` and continue to Step 5.
209- On `more`: re-query with looser windows or with the user's added hints (contact filter, expanded date range,
210 amount range), present a fresh list, repeat.
211- On "none of these" or similar: stop gracefully — *"OK, no match made. Tell me when you have more info."*
212
213---
214
215## Step 5 — Configure payment account and (optional) fiat alignment
216
217Once a match pair is chosen:
218
2191. **Deposit account (for `matchApAr.depositAccountId`).** This is an **ERP integration account**
220 (the GL account in Xero/QBO/NetSuite that the bill will post against — e.g. "Crypto Wallet – ETH",
221 "Cash and cash equivalents"). It is NOT a tres internal/wallet account. The schema FK is against
222 `schema_integrationaccount`; the value lives on `ErpBill.depositAccount` / `ErpInvoice.depositAccount`
223 as `IntegrationAccountQuery { id name type value }`.
224
225 Resolution order:
226 1. **Use the pre-set one on the bill/invoice.** When the entity was created in the ERP, the user
227 typically already picked a deposit account. Read `erpBills.results[].depositAccount.id` (or
228 `erpInvoices.results[].depositAccount.id`). If it's non-null, use that id as `depositAccountId`
229 and just mention it in the summary — no prompt.
230 2. **Otherwise ask.** Query `integrationAccount(integration: <erpId>, first: 100)` and show the
231 user the ASSET-type accounts (cash/wallet/crypto GL accounts) as a numbered list; capture the
232 chosen `integrationAccount.id`.
233 3. `paymentToInternalAccounts` maps *wallet → asset* on the tres side and is useful for payout
234 workflows — it is **not** the source of `depositAccountId` for `matchApAr`. Don't reach for it
235 here.
236
2372. **Fiat alignment.** Compare the sub-tx `fiatValue` to the invoice/bill `origAmount`. Three cases:
238 - `fiatValue` is **null or 0**: ask *"This transaction has no fiat value set. Align it to ${origAmount}
239 so the {bill/invoice} closes fully? (y/n)"* — **no default**, require an explicit yes.
240 - `fiatValue` differs from `origAmount`: ask *"Align tx fiat value from $X to $Y so the AP/AR
241 closes fully? (y/n)"* — **no default**, require an explicit yes.
242 - Values match: skip.
243 **Never run `setManualFiatValue` without a clear yes** — even if the user's original request implied
244 "close the invoice", the fiat alignment is a separate write and needs its own consent. If they say no,
245 the match still proceeds but the entity may stay partially paid.
246
247---
248
249## Step 6 — Confirm and apply
250
251Show this summary table — use **human-readable values only**: tx hash (truncated), deposit account **name**
252(never its id), invoice/bill number or customer/vendor name. Internal IDs (`subTxId`, `depositAccountId`,
253DB `entityId`) are for the mutation payload, never for the user.
254
255| | |
256|---|---|
257| Transaction | `0xabcd…1234` · {asset.symbol} {amount} · ${fiatValue} |
258| Invoice/Bill | `{invoiceNumber or billNumber}` · {customer/vendor} · ${origAmount} {currency} |
259| Payment account | {depositAccount.name} |
260| Align fiat | yes → ${origAmount} / no |
261| Sync to ERP after match | yes / no |
262
263Ask: *"Apply these changes to **{orgName}**? (yes/no)"* — only proceed on yes. Treat this as approval for
264the **match only**. Fiat alignment and ERP sync each need their own explicit yes captured earlier (Step 5
265for fiat, the prompt below for sync) — even if the user's opening request said "sync to QBO", still confirm
266here, because the request was issued before they saw the actual match details.
267
268Then run mutations in this order, reporting the result of each:
269
2701. **Match (always):**
271 ```graphql
272 mutation Match($entityType: String!, $matches: [SubTxMatchInput]!) {
273 matchApAr(entityType: $entityType, matches: $matches) {
274 results { subTxId entityId depositAccountId }
275 }
276 }
277 ```
278 Variables:
279 - `entityType`: **lowercase** — `"invoice"` or `"bill"`. Uppercase values are rejected with
280 `Invalid entity_type`.
281 - `matches[].subTxId`: string (e.g. `"4548595830"`).
282 - `matches[].entityId`: **integer** — the DB `id` of the invoice/bill (from `erpInvoices.results[].id`
283 / `erpBills.results[].id`), NOT the human-facing `invoiceNumber`/`billNumber`. Passing a string
284 errors with *"Int cannot represent non-integer value"*; passing a bill number looks up nothing
285 and errors with *"One or more Bill IDs not found"*.
286 - `matches[].depositAccountId`: **integer** — the integration account id (see Step 5).
287
2882. **Fiat alignment (only if user opted in):**
289 ```graphql
290 mutation AlignFiat($id: String!, $newFiatValue: String!, $currency: String) {
291 setManualFiatValue(id: $id, newFiatValue: $newFiatValue, currency: $currency) { success }
292 }
293 ```
294 Pass the sub-transaction ID as `id`, the target value as a string in `newFiatValue` (e.g. `"123.45"`, the
295 invoice/bill `origAmount`), and `currency: "usd"`. If the response returns an error about a "locked
296 period", the accounting period containing the tx is closed — surface that to the user; don't try to force.
297
2983. **ERP sync (ask first, every time):** *"Sync this transaction to {erpName} now? (y/n)"* — **never sync
299 without an explicit yes at this point**, even if the user's original ask included "and sync to QBO". The
300 sync call is visible in the ERP and harder to undo than the match itself, so it gets its own gate. If yes:
301 ```graphql
302 mutation Sync($txIds: [String]!, $entityType: String!) {
303 syncSpecificTransactions(transactionIds: $txIds, entitySourceType: $entityType) { status }
304 }
305 ```
306 `entitySourceType` mirrors `entityType` from the match call.
307
308When reporting results back to the user, refer to the transaction by its **tx hash** (truncated) and the
309deposit account by **name** — never by `subTxId` or `depositAccountId`. Those internal IDs are for debugging,
310not user output.
311
312If any mutation errors, surface the error message verbatim and offer to retry. The match is the one that
313actually links the records — if it fails, the rest is moot.
314
315---
316
317## Step 7 — Loop
318
319Ask: *"Match another transaction or invoice/bill? (y/n)"*
320
321- yes → restart from Step 2 (skip Step 1 — keep the cached ERP from this session).
322- no → wrap up: *"Done. Closed {n} item(s) this session."*
323
324---
325
326## Verified TRES MCP operations used
327
328| Purpose | Operation | Type |
329|---|---|---|
330| Org identity | `get_viewer` | MCP tool |
331| Schema discovery | `introspect`, `build_query` | MCP tool |
332| Check ERP connections | `integration` (filter `isErp=true`) | query |
333| Fetch tx by hash | `transaction(identifier:)` | query |
334| Fetch invoices (with embedded suggestions) | `erpInvoices` | query |
335| Fetch bills (with embedded suggestions) | `erpBills` | query |
336| Pre-computed sub-tx → invoice match suggestions | `subTransactionToInvoiceMatchSuggestions` | query |
337| COA-mapped payment accounts | `paymentToInternalAccounts` | query |
338| Match sub-tx ↔ invoice/bill | `matchApAr` | mutation |
339| Align fiat value | `setManualFiatValue` (verify args at runtime) | mutation |
340| Sync transactions to the ERP | `syncSpecificTransactions` | mutation |
341| Undo a match (on user request) | `manualUnmatchSubtransactions` | mutation |
342
343---
344
345## Out of scope (politely redirect if asked)
346
347- Bulk matching (many ↔ many) — not yet supported by this skill.
348- Sending payments (`sendBillPayment`, `sendInvoicePayment`) — separate workflow.
349- Connecting or revoking the ERP itself — use the `tres-settings-management` skill.
350- Explaining a transaction in narrative form — use `tres-tx-story`.
351- Importing an explorer link into the ledger — use `tres-explorer-tx-to-ledger`.