Установка
SKILL.md
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_viewerand 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>)orbuild_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:<!-- -->
balanceFactornegative → outflow → look for a bill to close.balanceFactorpositive → 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:<!-- -->
<!-- -->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.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 } } } } } - Fallback (zero invoice suggestions, or always for bills): query
erpInvoices(inflow) orerpBills(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 onfreeTextovervendor/customerfields. Rank the fallback set client-side by: amount proximity → date proximity (prefer the most recent bill/invoice before the tx) → name hits infreeTextoutput.
- amount window:
- 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 theprimaryMatchFactors(e.g.amount_exact,contact_match). Best-fit first.
Branch B — User has an invoice/bill ID or number
- Resolve the entity. Try
erpInvoicesfirst, thenerpBillsif it's not an invoice (or vice versa if the user said "bill"). For invoices, include the embedded suggestions:<!-- -->
<!-- -->For bills, queryquery 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 } } } } } }erpBills— note that bills do not exposesuggestedSubTransactionMatches, 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. Ifidlookup returns nothing, retry withfreeText: $userInput. - For invoices, use the embedded
suggestedSubTransactionMatchesas 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
transactionwith 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'sconfiguredAsset.identifier(e.g. the USDC contract), or the invoice's expected asset,children_FiatValue_Between: "<low>,<high>"→ fiat window aroundorigAmount(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) or1(inflow, for invoices). - Use
children_Amount_Betweenas 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.
- 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
- 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 likesubTxIdto the user — they're meaningless to them. Hold thesubTxIdinternally 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 againstschema_integrationaccount; the value lives onErpBill.depositAccount/ErpInvoice.depositAccountasIntegrationAccountQuery { 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(orerpInvoices.results[].depositAccount.id). If it's non-null, use that id asdepositAccountIdand 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 chosenintegrationAccount.id. paymentToInternalAccountsmaps wallet → asset on the tres side and is useful for payout workflows — it is not the source ofdepositAccountIdformatchApAr. Don't reach for it here.
- 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
-
Fiat alignment. Compare the sub-tx
fiatValueto the invoice/billorigAmount. Three cases:fiatValueis 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.fiatValuediffers fromorigAmount: 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
setManualFiatValuewithout 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 withInvalid entity_type.matches[].subTxId: string (e.g."4548595830").matches[].entityId: integer — the DBidof the invoice/bill (fromerpInvoices.results[].id/erpBills.results[].id), NOT the human-facinginvoiceNumber/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 innewFiatValue(e.g."123.45", the invoice/billorigAmount), andcurrency: "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): Синхронизировать эту транзакцию с {erpName} сейчас? (y/n) — никогда не синхронизировать без явного подтверждения на этом этапе, даже если исходный запрос пользователя включал «и синхронизировать с QBO». Вызов синхронизации виден в ERP и отменяется сложнее, чем сам матчинг, поэтому для него нужен отдельный шаг подтверждения. Если да:
mutation Sync($txIds: [String]!, $entityType: String!) { syncSpecificTransactions(transactionIds: $txIds, entitySourceType: $entityType) { status } }entitySourceTypeотражаетentityTypeиз вызова матчинга.
При отчёте о результатах пользователю ссылайтесь на транзакцию по её tx hash (в усечённом виде), а на депозитный счёт — по name — никогда по subTxId or depositAccountId. Эти внутренние ID предназначены для отладки, а не для вывода пользователю.
Если какая-либо мутация завершается ошибкой, покажите сообщение об ошибке дословно и предложите повторить. Именно матчинг фактически связывает записи — если он не удался, остальное не имеет смысла.
Шаг 7 — Цикл
Спросите: «Сопоставить другую транзакцию или счёт/счёт-фактуру? (y/n)»
- да → перезапустить со Шага 2 (пропустить Шаг 1 — сохранить кэшированный ERP из этой сессии).
- нет → завершить: «Готово. Закрыто {n} элемент(ов) за эту сессию.»
Использованные проверенные операции TRES MCP
| Назначение | Операция | Тип |
|---|---|---|
| Идентичность организации | get_viewer | MCP tool |
| Обнаружение схемы | introspect, build_query | MCP tool |
| Проверить подключения ERP | integration (фильтр isErp=true) | query |
| Получить транзакцию по хэшу | transaction(identifier:) | query |
| Получить счета-фактуры (со встроенными предложениями) | erpInvoices | query |
| Получить счета (со встроенными предложениями) | erpBills | query |
| Предвычисленные предложения сопоставления субтранзакций → счетов-фактур | subTransactionToInvoiceMatchSuggestions | query |
| Платёжные счета с маппингом COA | paymentToInternalAccounts | query |
| Сопоставить субтранзакцию ↔ счёт-фактуру/счёт | matchApAr | mutation |
| Выровнять фиатную стоимость | setManualFiatValue (проверить аргументы во время выполнения) | mutation |
| Синхронизировать транзакции с ERP | syncSpecificTransactions | mutation |
| Отменить сопоставление (по запросу пользователя) | manualUnmatchSubtransactions | mutation |
Вне области действия (вежливо перенаправить при запросе)
- Массовое сопоставление (многие ↔ многие) — пока не поддерживается этим навыком.
- Отправка платежей (
sendBillPayment,sendInvoicePayment) — отдельный рабочий процесс. - Подключение или отзыв ERP — используйте навык
tres-settings-management. - Объяснение транзакции в повествовательной форме — используйте
tres-tx-story. - Импорт ссылки из обозревателя в реестр — используйте
tres-explorer-tx-to-ledger.
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: tres-invoice-bill-matching](https://darkplay.ru/ai/skills/anthropics-claude-plugins-community-tres-invoice-bill-matching)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
bmad-party-modebmad-code-org · Многоперспективные круглые столы — столкновение точек зрения агентов или пользовательских…
airwallex-agentosanthropics · Глобальная финансовая инфраструктура Airwallex в Claude. Управляйте действиями по счёту…
clickhouseanthropics · Подключение Claude к базам данных ClickHouse Cloud. Просмотр организаций, сервисов, баз…
migration-to-awsanthropics · Планирование миграции с Google Cloud Platform (и AI-нагрузок OpenAI/Gemini) на AWS…
payment-processingwshobson · Интеграция платёжных шлюзов Stripe и PayPal, реализация checkout-процесса, подписочный…
airwallex-agentosanthropics · Доступ к глобальной финансовой инфраструктуре Airwallex из Claude. Управление действиями…
Devils Advocategithub · Играет роль адвоката дьявола, проверяя ваши идеи на прочность: ищет недостатки, риски и…
executive-mentoralirezarezvani · Партнёр по адверсариальному мышлению для основателей и руководителей: стресс-тест планов…
accountsosanthropics · Бухгалтерия для британских компаний и ИП на естественном языке: транзакции, НДС, сроки…
acumatica-pluginanthropics · Что входит: финансы (счета, платежи, проводки, кассовые счета), запасы и закупки (товары…Лучшие ИИ-инструменты для музыки, голоса и озвучки
Подборка нейросетей для генерации музыки, голоса и озвучки. Сервисы, которые помогают создавать треки, синтезировать речь и чистить аудио без студии и дикторов. Подходит для видеом
BigspeakBigspeak
WavToolWavtool
LoquoraLoquora
WunjoWunjo
NexaraNexara
pitch coachApple
audio-transcription.ruAudio-transcription
SoundfulSoundfulЛучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachat