UNPKG

@ekwo-ai/mcp

Version:

MCP server for Ekwo OS: let an AI agent work on the books, under the user's own row level security.

845 lines • 45.5 kB
/** * The reading half. * * Every one of these is a query the signed-in user could have run themselves; * nothing here widens what they may see. The reports come from the schema's * own functions — `trial_balance`, `general_ledger`, `aged_balance`, * `subledger`, `vat_return`, `fec_lines` — rather than from sums computed here, because a * second implementation of a balance is a second answer to the same question. */ import { checkFec, fecFileName, fromQueryRow, generateFec as renderFec, } from '@ekwo-ai/fec'; import { z } from 'zod'; import {} from '../backend.js'; import { DOC_TYPES, REGISTRATION_INVITATION, columns, listApiKeys as listKeys, listBankAccounts as listCompanyBankAccounts, money, moneyFields, namesOf, onlyVisible as only, renderDocumentPdf, } from '@ekwo-ai/core'; // Moved to the core with the writing half they are read back by; exported // from here under the names they always had. export { agedBalance, analyticReport, contactStatement, ecSalesList, financialStatement, generalLedger, getDocument, journalBook, listAnalyticAxes, listDocuments, listStatements, searchContacts, subledger, suggestDuplicateContacts, trialBalance, vatReturn, } from '@ekwo-ai/core'; export const uuid = z.string().uuid(); export const isoDate = z .string() .regex(/^\d{4}-\d{2}-\d{2}$/, 'a calendar date, as YYYY-MM-DD'); export const companyId = uuid.describe('The company to work in. Ask list_companies if unsure.'); // --------------------------------------------------------------------------- // Companies and their settings // --------------------------------------------------------------------------- export const ListCompaniesInput = z.object({}); export async function listCompanies(backend) { const companies = await backend.select({ table: 'companies', columns: ['id', 'name', 'country', 'fiscal_country', 'vat_number', 'currency_code'], order: [{ column: 'name' }], }); // Your role, and only yours. `company_members` shows every member of a // company one is on, so an unfiltered read would give whichever member's // role came last. A key of Ekwo OS is nobody's member: it has no role, and // says so with null rather than borrowing one. const roles = backend.actingAs === undefined ? [] : await backend.select({ table: 'company_members', columns: ['company_id', 'role'], where: [{ column: 'user_id', op: 'eq', value: backend.actingAs }], }); const mine = new Map(roles.map((row) => [row.company_id, row.role])); return { companies: companies.map((company) => ({ ...company, your_role: mine.get(company['id']) ?? null, })), }; } export const GetCompanyInput = z.object({ company_id: companyId }); // Moved to the core, where `ekwo company show` reads the same answer. export { getCompany } from '@ekwo-ai/core'; // --------------------------------------------------------------------------- // Reference data // --------------------------------------------------------------------------- export const ListAccountsInput = z.object({ company_id: companyId, code_prefix: z.string().min(1).optional().describe('Only accounts whose code starts with this, e.g. "70".'), account_type: z.string().min(1).optional().describe('One of the eighteen account types, e.g. asset_receivable.'), search: z.string().min(1).optional().describe('Case-insensitive match on the account name.'), in_use_from: isoDate .optional() .describe('Narrows the movements to entries on or after this date. References and pinned accounts are not dated and stay in.'), in_use_to: isoDate.optional().describe('The other end of that period.'), include_all: z .boolean() .optional() .describe('Return the whole chart instead of the accounts in use. Use it when a search over the working chart found nothing.'), include_deprecated: z .boolean() .optional() .describe('Include deprecated accounts. A deprecated account is never in use, so this returns the whole chart.'), limit: z.number().int().min(1).max(2000).optional(), }); /** * The account ids `accounts_in_use()` gives back. * * A function returning `setof uuid` arrives as a list of strings over * PostgREST and as a list of one-column rows over Postgres, the same split * `member_capabilities` has. Both are read here. */ async function accountsInUse(backend, args) { const rows = await backend.rpc('accounts_in_use', { p_company_id: args.company_id, p_from: args.in_use_from ?? null, p_to: args.in_use_to ?? null, }); return rows .map((row) => typeof row === 'string' ? row : row['accounts_in_use']) .filter((id) => typeof id === 'string'); } export async function listAccounts(backend, args) { const where = [{ column: 'company_id', op: 'eq', value: args.company_id }]; if (args.code_prefix !== undefined) where.push({ column: 'code', op: 'ilike', value: `${args.code_prefix}%` }); if (args.account_type !== undefined) where.push({ column: 'account_type', op: 'eq', value: args.account_type }); if (args.search !== undefined) where.push({ column: 'name', op: 'ilike', value: `%${args.search}%` }); if (args.include_deprecated !== true) where.push({ column: 'deprecated', op: 'eq', value: false }); // A country pack is a transcription of the regulation — three hundred // accounts in Belgium, a thousand in Luxembourg — and a company works with a // few dozen of them. The default is therefore the working chart the schema // computes, and the whole thing is one flag away. Asking for deprecated // accounts is asking for the whole chart by definition: a deprecated account // is never in use. const wholeChart = args.include_all === true || args.include_deprecated === true; let scope = 'whole_chart'; if (!wholeChart) { scope = 'in_use'; const ids = await accountsInUse(backend, args); if (ids.length === 0) { return { accounts: [], count: 0, scope, note: 'No account of this company is in use yet. Pass include_all to see the whole chart.', }; } where.push({ column: 'id', op: 'in', value: ids }); } const accounts = await backend.select({ table: 'accounts', columns: columns.ACCOUNT, where, order: [{ column: 'code' }], limit: args.limit ?? 200, }); return { accounts, count: accounts.length, scope, note: scope === 'in_use' ? 'The accounts this company works with: moved, referenced by its settings, held by a module, or pinned. Pass include_all for the whole chart — any account of it may still be booked on.' : 'The whole chart of the company.', }; } export const SearchContactsInput = z.object({ company_id: companyId, query: z.string().min(1).optional().describe('Case-insensitive match on the contact name.'), contact_type: z.enum(['customer', 'supplier', 'both', 'employee', 'other']).optional(), vat_number: z.string().min(1).optional().describe('Exact match, e.g. BE0123456749.'), limit: z.number().int().min(1).max(200).optional(), }); export const SuggestDuplicateContactsInput = z.object({ company_id: companyId, contact_types: z .array(z.enum(['customer', 'supplier', 'both', 'employee', 'other'])) .min(1) .optional() .describe('Propose only among the contacts of these types; every contact when absent.'), }); export const ContactStatementInput = z.object({ company_id: companyId, contact_id: uuid.describe('The contact, from search_contacts.'), from: isoDate.describe('First day of the period. The balance carried forward is the one before it.'), to: isoDate.describe('Last day of the period.'), }); // --------------------------------------------------------------------------- // Documents // --------------------------------------------------------------------------- export const ListDocumentsInput = z.object({ company_id: companyId, doc_type: z.enum(DOC_TYPES).optional(), state: z.enum(['draft', 'posted', 'cancelled']).optional(), payment_state: z.enum(['not_paid', 'partially_paid', 'paid', 'overpaid', 'reversed']).optional(), contact_id: uuid.optional(), from: isoDate.optional().describe('Earliest document date.'), to: isoDate.optional().describe('Latest document date.'), unpaid: z.boolean().optional().describe('True: posted and still owed — not paid, or partially.'), limit: z.number().int().min(1).max(200).optional(), }); export const GetDocumentInput = z.object({ document_id: uuid }); export const RenderInvoicePdfInput = z.object({ document_id: uuid.describe('A sale invoice or a sale credit note. A draft is rendered titled as a draft, without a number.'), factur_x: z .boolean() .optional() .describe('Embed the CII XML of the document, EN 16931 profile: the PDF becomes a Factur-X PDF/A-3. Only for a posted document; the rules the XML breaks come back in factur_x.violations.'), page_size: z.enum(['A4', 'Letter']).optional().describe('A4 unless Letter is asked for.'), labels: z .record(z.string(), z.union([z.string(), z.record(z.string(), z.string())])) .optional() .describe('Words the layout prints, over the ones it already has in the language of the document — invoice, creditNote, dueDate, amountDue, page ("Page {page} of {pages}"), units (a map of UN/ECE unit codes)… Every word left out is the one the pack of the country of the document names in its language (pack_labels in the answer lists them), else the word of the layout in the language of the document, or English where labels_language in the answer says en.'), }); /** Base64 without Buffer, which a server running outside Node does not have. */ export function base64Of(bytes) { let binary = ''; for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(binary); } /** * The PDF of a sale invoice or credit note, through `renderDocumentPdf()` of * the core — the call `ekwo doc pdf` makes. The logo the company names by URL * is fetched by this server, with `logoFetch`. */ export async function renderInvoicePdf(backend, args, logoFetch) { return renderDocumentPdf(backend, { document_id: args.document_id, factur_x: args.factur_x, page_size: args.page_size, labels: args.labels, }, { fetch: logoFetch }); } // --------------------------------------------------------------------------- // Bank // --------------------------------------------------------------------------- export const ListBankTransactionsInput = z.object({ company_id: companyId, bank_account_id: uuid.optional(), state: z.enum(['pending', 'reconciled', 'ignored', 'all']).optional().describe('Defaults to pending: what still has to be dealt with.'), from: isoDate.optional(), to: isoDate.optional(), limit: z.number().int().min(1).max(200).optional(), }); export async function listBankTransactions(backend, args) { const where = [{ column: 'company_id', op: 'eq', value: args.company_id }]; const state = args.state ?? 'pending'; if (state !== 'all') where.push({ column: 'state', op: 'eq', value: state }); if (args.bank_account_id !== undefined) where.push({ column: 'bank_account_id', op: 'eq', value: args.bank_account_id }); if (args.from !== undefined) where.push({ column: 'transaction_date', op: 'gte', value: args.from }); if (args.to !== undefined) where.push({ column: 'transaction_date', op: 'lte', value: args.to }); const [transactions, bankAccounts] = await Promise.all([ backend.select({ table: 'bank_transactions', columns: columns.BANK_TRANSACTION, where, order: [{ column: 'transaction_date', ascending: false }], limit: args.limit ?? 50, }), backend.select({ table: 'bank_accounts', columns: columns.BANK_ACCOUNT, where: [{ column: 'company_id', op: 'eq', value: args.company_id }], order: [{ column: 'name' }], }), ]); return { transactions, count: transactions.length, bank_accounts: bankAccounts }; } // --------------------------------------------------------------------------- // Reports // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Products // --------------------------------------------------------------------------- export const SearchProductsInput = z.object({ company_id: companyId, query: z.string().min(1).optional().describe('Matches the code, the name or the description.'), kind: z.enum(['service', 'goods']).optional(), include_inactive: z.boolean().optional().describe('Default false: a retired product is hidden.'), limit: z.number().int().min(1).max(200).optional(), }); export async function searchProducts(backend, args) { const where = [{ column: 'company_id', op: 'eq', value: args.company_id }]; if (args.kind !== undefined) where.push({ column: 'kind', op: 'eq', value: args.kind }); if (args.include_inactive !== true) where.push({ column: 'active', op: 'eq', value: true }); const products = await backend.select({ table: 'products', columns: columns.PRODUCT, where, order: [{ column: 'code' }], limit: args.limit ?? 100, }); // The filter on the text is applied here rather than in three `ilike` // clauses, because neither backend offers an OR and a second round trip per // column would be the alternative. const needle = args.query?.toLowerCase(); const matching = needle === undefined ? products : products.filter((product) => [product['code'], product['name'], product['description']] .filter((value) => typeof value === 'string') .some((value) => value.toLowerCase().includes(needle))); return { products: matching }; } export const ListBankAccountsInput = z.object({ company_id: companyId, include_inactive: z.boolean().optional().describe('Default false.'), }); export async function listBankAccounts(backend, args) { const accounts = await listCompanyBankAccounts(backend, args); return { bank_accounts: accounts, note: accounts.length === 0 ? 'This company has no bank account. create_bank_account adds one; until then a payment books on the default account of its journal.' : undefined, }; } // --------------------------------------------------------------------------- // Members and invitations // --------------------------------------------------------------------------- export const ListApiKeysInput = z.object({ company_id: companyId, include_withdrawn: z.boolean().optional().describe('Also the ones withdrawn or expired. Default false.'), }); export async function listApiKeys(backend, args) { return listKeys(backend, args); } export const GetPreferencesInput = z.object({ company_id: uuid .optional() .describe('Resolve the language chain against this company. Left out, only what the user themselves chose is returned.'), }); export async function getPreferences(backend, args) { const [stored] = await backend.select({ table: 'user_preferences', columns: columns.USER_PREFERENCES, limit: 1, }); const chain = await backend.rpc('preferred_languages', { p_company_id: args.company_id ?? null, }); const languages = (chain[0] ?? []); return { preferences: stored ?? null, languages: Array.isArray(languages) ? languages : (languages['preferred_languages'] ?? []), note: 'Every preference may be null, and null is an answer: take the company\u2019s, then the country pack\u2019s. A label is picked with label_for(name, name_i18n, languages), in that order.', }; } export const ListInvitationsInput = z.object({ company_id: companyId, include_settled: z .boolean() .optional() .describe('Also the ones already accepted or withdrawn. Default false.'), }); export async function listInvitations(backend, args) { const invitations = await backend.select({ table: 'company_invitations', columns: columns.INVITATION, where: [{ column: 'company_id', op: 'eq', value: args.company_id }], order: [{ column: 'created_at', ascending: false }], }); const now = Date.now(); const described = invitations.map((invitation) => ({ ...invitation, state: invitationState(invitation, now), })); return { invitations: args.include_settled === true ? described : described.filter((invitation) => invitation.state === 'pending'), note: 'The token is shown once, when the invitation is issued, and is never readable afterwards. A lost one is replaced by inviting the same address again.', }; } export const ListSharesInput = z.object({ company_id: companyId, document_id: uuid.optional().describe('Only the links onto this document. Left out, the whole company.'), include_withdrawn: z .boolean() .optional() .describe('Also the ones withdrawn or expired. Default false.'), }); export async function listShares(backend, args) { const where = [{ column: 'company_id', op: 'eq', value: args.company_id }]; if (args.document_id !== undefined) { where.push({ column: 'document_id', op: 'eq', value: args.document_id }); } const shares = await backend.select({ table: 'document_shares', columns: columns.DOCUMENT_SHARE, where, order: [{ column: 'created_at', ascending: false }], }); const now = Date.now(); const described = shares.map((share) => ({ ...share, state: shareState(share, now) })); return { shares: args.include_withdrawn === true ? described : described.filter((share) => share.state === 'live'), note: 'The token of a link exists only in the answer that created it. A link that is lost is withdrawn and made again.', }; } /** Live, expired or withdrawn — three states off two columns. */ function shareState(share, now) { if (share['revoked_at'] !== null && share['revoked_at'] !== undefined) return 'withdrawn'; const expires = share['expires_at']; if (typeof expires === 'string' && Date.parse(expires) <= now) return 'expired'; return 'live'; } /** Pending, expired, accepted or withdrawn — four states off three columns. */ function invitationState(invitation, now) { if (invitation['accepted_at'] !== null && invitation['accepted_at'] !== undefined) return 'accepted'; if (invitation['revoked_at'] !== null && invitation['revoked_at'] !== undefined) return 'withdrawn'; const expires = Date.parse(String(invitation['expires_at'])); return Number.isNaN(expires) || expires > now ? 'pending' : 'expired'; } export const TrialBalanceInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, }); export const GeneralLedgerInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, account_code: z.string().min(1).optional().describe('The account to detail, by its code, e.g. "400000".'), account_ids: z.array(uuid).optional().describe('The accounts to detail, by id. Leave both out for every account.'), contact_ids: z .array(uuid) .min(1) .optional() .describe('The lines of these contacts only (from search_contacts or subledger), each with its own balance carried forward and running balance. Needs schema 0.26.0.'), }); export const JournalBookInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, journal_code: z.string().min(1).optional().describe('The journal to read, by its code, e.g. "SAL". Leave both out for the book of every journal.'), journal_ids: z.array(uuid).optional().describe('The journals to read, by id.'), }); export const AgedBalanceInput = z.object({ company_id: companyId, at: isoDate.optional().describe('The day to age at. Defaults to today.'), group: z.enum(['receivable', 'payable']).optional(), }); export const SubledgerInput = z.object({ company_id: companyId, from: isoDate.describe('First day of the period. The balance brought forward is the one before it.'), to: isoDate.describe('Last day of the period.'), account_code: z .string() .min(1) .optional() .describe('One control account, by its code. Left out: every receivable and payable account of the chart.'), }); // --------------------------------------------------------------------------- // Open items that settle each other // --------------------------------------------------------------------------- export { matchingDifferenceOptions, suggestItemCombinations } from '@ekwo-ai/core'; export const SuggestItemCombinationsInput = z.object({ company_id: companyId, contact_id: uuid .optional() .describe('One contact; its branches and its parent count as one party. Left out: every counterparty of the company.'), }); export const MatchingDifferenceOptionsInput = z.object({ company_id: companyId, }); // --------------------------------------------------------------------------- // Lines that name nobody // --------------------------------------------------------------------------- export { suggestLineContacts } from '@ekwo-ai/core'; export const SuggestLineContactsInput = z.object({ company_id: companyId, line_ids: z .array(uuid) .min(1) .optional() .describe('The ledger lines to ask about. Left out: every open line of the company on a receivable or payable account that names no contact.'), }); export const VatReturnInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, report_code: z .string() .optional() .describe('Which declaration form, when the country files more than one (BE-VAT-PERIODIC, FR-CA3). Leave it out and the form the company files is used: the one its VAT scheme files where it has recorded a scheme, the periodic return of its country otherwise.'), }); export const InstalmentPlanInput = z.object({ company_id: companyId, from: isoDate.describe('First day of the period of the declaration the instalments are paid on account of — usually 1 January.'), to: isoDate.describe('Last day of that period.'), }); export async function instalmentPlan(backend, args) { const rows = await backend.rpc('instalment_plan', { p_company_id: args.company_id, p_from: args.from, p_to: args.to, }); return { period: { from: args.from, to: args.to }, instalments: moneyFields(rows, ['base', 'amount_due', 'paid', 'outstanding']), note: rows.length === 0 ? 'No instalment: the company has recorded no VAT scheme for this period, or its scheme asks for no payment on account.' : 'One row per payment on account the VAT scheme of the company asks for during the period: the month it falls due in (due_date only where the law gives one day to everybody), the base read on the previous period\'s return — as it was frozen, or as the books compute it where nothing was frozen — the percentage, what was due, what was recorded as paid and what is outstanding. reason no_base means there is no previous period to read, below_minimum that the base is under the minimum of the scheme and nothing is due. It reads; it pays nothing.', }; } export const EcSalesListInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, report_code: z .string() .optional() .describe('Which recapitulative statement form, when the installation carries one and you are filing it. Name it and the period is checked against the cadence this company files that statement on, which is not the cadence of its periodic return in most countries. Leave it out to read the figures without any period being refused.'), }); export const PortfolioUpcomingFilingsInput = z.object({ from: isoDate.describe('First day a return may fall due on. Go back a few days to catch what is already late.'), to: isoDate.describe('Last day a return may fall due on.'), }); export async function portfolioUpcomingFilings(backend, args) { const rows = await backend.rpc('portfolio_upcoming_filings', { p_from: args.from, p_to: args.to, }); const companies = new Set(rows.map((row) => row['company_id'])); return { window: { from: args.from, to: args.to }, companies: companies.size, filings: rows, note: rows.length === 0 ? 'You hold filings.read on no company of this installation, so there is no portfolio to read. It is not the same as nothing being due: a company you could read would be listed even with nothing to say.' : 'One row per period falling due in the window, across every company you hold filings.read on, and at least one row per company. state and filing_id are the declaration already prepared or sent for that period; both empty means nothing has been started. A row without a due_date says why in reason: no_deadline_rule — the country pack names no day for this form, usually because the schedule depends on who is filing, so the period is listed and the date has to come from the administration; nothing_due — the company files, and nothing of it falls in this window; no_form — the installation carries no return for the fiscal country of the company. A row with instalment set is not a return but a payment on account of report_code, which the VAT scheme of the company asks for: its period is the month it falls due in. Name a form to a person by report_short_name, how the accountants of the country call it, and by report_name, its official title, where the short one is empty. Never read a missing date as "not due". It reads a calendar; it prepares and files nothing.', }; } export const PortfolioOverviewInput = z.object({ on: isoDate.optional().describe('The day to read what is overdue on. Defaults to today.'), }); export async function portfolioOverview(backend, args) { const on = args.on ?? new Date().toISOString().slice(0, 10); const rows = await backend.rpc('portfolio_overview', { p_on: on }); return { on, companies: rows.length, overview: moneyFields(rows, [ 'customers_open', 'customers_overdue', 'customers_overdue_over_90', 'suppliers_open', 'suppliers_overdue', 'suppliers_overdue_over_90', ]), note: rows.length === 0 ? 'You hold entries.read on no company of this installation, so there is no portfolio to read. It is not the same as nobody owing anything: a company you could read would be listed even with nothing open.' : 'One row per company you hold entries.read on, every one of them, with zeros where nothing is open. customers_* is what customers owe the company, suppliers_* what the company owes its suppliers, both from aged_balance on that day: open is everything still unmatched, overdue the part past its due date, overdue_over_90 the part more than ninety days past it, late how many parties have something overdue. Amounts are in the currency_code of each row; never add two rows of different currencies. It reads; whether to remind a customer or pay a supplier is for whoever keeps the books.', }; } export const PortfolioFilingsTouchedSinceInput = z.object({ from: isoDate.optional().describe('Only declarations whose period ends on or after this day.'), to: isoDate.optional().describe('Only declarations whose period starts on or before this day.'), }); export async function portfolioFilingsTouchedSince(backend, args) { const rows = await backend.rpc('portfolio_filings_touched_since', { p_from: args.from ?? null, p_to: args.to ?? null, }); const touched = rows.filter((row) => row['filing_id'] !== null); return { companies: new Set(rows.map((row) => row['company_id'])).size, touched: touched.length, filings: touched, untouched: rows .filter((row) => row['filing_id'] === null) .map((row) => ({ company_id: row['company_id'], company_name: row['company_name'], filed: row['filed'], })), note: rows.length === 0 ? 'You hold filings.read on no company of this installation, so nothing was looked at.' : 'filings lists every declaration that has gone and whose period received entries afterwards, latest first, with the company named: entries is how many posted entries carrying a declaration box landed in it, boxes_moved how many filed figures now disagree with the ledger. An entry that moves no figure is still listed. untouched names the companies that were looked at and had nothing to report, with how many filed declarations were examined — filed 0 means the company has sent none, which is different news. Whether a change calls for a corrective is a judgement for whoever keeps the books; this reads, and changes nothing.', }; } export const ListStatementsInput = z.object({ company_id: companyId, at: isoDate .optional() .describe('The day to read the schemes in force at. Defaults to today.'), }); export const FinancialStatementInput = z.object({ company_id: companyId, statement_code: z .string() .min(1) .describe('Which scheme, from list_statements (BE-BNB-ABBR-BS, FR-2050, IFRS-SME-BS).'), from: isoDate, to: isoDate, }); export const FinancialAnalysisInput = z.object({ company_id: companyId, from: isoDate.describe('First day of the period the movements are read on: revenue, purchases, the result.'), to: isoDate.describe('Last day of the period, and the day the balances are read at: equity, assets, debts, cash.'), }); export async function financialAnalysis(backend, args) { const rows = await backend.rpc('financial_analysis', { p_company_id: args.company_id, p_from: args.from, p_to: args.to, }); const aggregates = moneyFields(rows, ['amount']).map((row) => ({ ...row, accounts: moneyFields((row['accounts'] ?? []), ['amount']), })); const signs = 'Each amount is signed as its aggregate is named: revenue, other income and equity positive, net_result positive for a profit, financial_result for a gain, income_tax for a charge, every balance positive. Movements are those of the period; balances are at its last day, and equity includes the result of the years not closed yet. accounts says where each figure comes from.'; const source = rows[0]?.['source'] ?? null; return { period: { from: args.from, to: args.to }, source, aggregates, note: aggregates.length === 0 ? 'Neither the country pack of this company nor a framework says which of its accounts make an analysis, so there is nothing to read: say so rather than working the figures out from account codes.' : source === 'framework' ? `This company's country pack defines no analysis, so these figures are read by account type through the generic framework (source: framework). Staff costs, the financial result and income tax are not among them, because no account type tells them apart: say they are not read, never that they are zero. ${signs}` : signs, }; } export const ListAnalyticAxesInput = z.object({ company_id: companyId, }); export const AnalyticReportInput = z.object({ company_id: companyId, axis: z.string().min(1).describe('The analytic axis, by its code or its id: list_analytic_axes names them.'), from: isoDate.describe('First day of the period.'), to: isoDate.describe('Last day of the period.'), }); export const GenerateFecInput = z.object({ company_id: companyId, from: isoDate, to: isoDate, }); export async function generateFec(backend, args) { const rows = await backend.rpc('fec_lines', { p_company_id: args.company_id, p_from: args.from, p_to: args.to, }); const lines = rows.map(fromQueryRow); const violations = checkFec(lines); const file = renderFec(lines); const company = only(await backend.select({ table: 'companies', columns: ['id', 'name', 'registration_number', 'fiscal_country'], where: [{ column: 'id', op: 'eq', value: args.company_id }], }), `company ${args.company_id}`); const siren = String(company['registration_number'] ?? '').replace(/\D/g, ''); let filename = null; let filename_note = null; if (siren.length === 9) { filename = fecFileName(siren, args.to); } else { filename_note = 'No filename: the FEC name is built from a nine-digit SIREN, and this company has no such registration number.'; } return { period: { from: args.from, to: args.to }, lines: lines.length, violations, filename, filename_note, file, }; } // --------------------------------------------------------------------------- // describe_pack // --------------------------------------------------------------------------- export const DescribePackInput = z.object({ country: z .string() .length(2) .optional() .describe('ISO 3166-1 alpha-2, upper case. Left out, every pack this installation holds.'), }); /** * Where a country's rules come from, and how much anyone has read them. * * The pack is the transcription of a régime — a chart of accounts, the taxes * and the boxes of the return — and a transcription is only worth what its * sources are worth. `certification_status` says whether a named professional * has read it, or whether it reproduced a real company's accepted filing, and * `sources` is the register the pack declares: the texts it was built from, each with the publisher that serves it, an absolute link and * the day somebody opened it. * * It answers a question that used to have no answer here: shown a rate or a * grid, where is the text it comes from. The article itself is on the tax and * on the box — `legal_reference` — and `source_key` there names which of these * entries it is in. */ export async function describePack(backend, args) { const where = args.country === undefined ? [] : [{ column: 'country', op: 'eq', value: args.country.toUpperCase() }]; const packs = await backend.select({ table: 'country_packs', columns: columns.COUNTRY_PACK, where, order: [{ column: 'country' }], }); if (packs.length === 0) { return { packs: [], count: 0, note: args.country === undefined ? 'This installation holds no country pack. Its seeds have not been applied.' : `No pack is loaded for ${args.country.toUpperCase()}. A company of that country cannot be installed until its seed has run.`, }; } // The fiscalisation regime the socle compiled beside each pack, where it // holds the column: a socle older than the column answers without it. let fiscalisation = new Map(); try { const regimes = await backend.select({ table: 'country_defaults', columns: ['country', 'einvoice_fiscalisation'], where: [{ column: 'country', op: 'in', value: packs.map((pack) => String(pack['country'])) }], }); fiscalisation = new Map(regimes.map((row) => [row['country'], row['einvoice_fiscalisation'] ?? null])); } catch { // No column, nothing to say: the pack is described as before. } return { packs: packs.map((pack) => ({ ...pack, einvoicing_fiscalisation: fiscalisation.get(pack['country']) ?? null })), count: packs.length, note: 'einvoicing_fiscalisation is the fiscalisation regime of the country, or null where it has none. Its kind is chained — a record the invoicing software keeps for every invoice, with the hash, the QR code and the sentence the invoice carries; einvoicing_fiscalise writes one — or clearance — every invoice validated by the authority before it is issued, nothing chained; clearance says where the verification link comes from and, as ISO 8601 durations, how long the issuer may cancel and the buyer reject; einvoicing_clearance records a submission and its answer — or reporting — the documents\' data reported to the authority, nothing chained, written by the brick its format names. mandatory_from is when it binds, with turnover_above where the law phases it by size, and exemption the dated thresholds below which a taxpayer is exempted; announced_from, with announced_by and announced_on, is a day only announced, with no text in force, and binds nobody yet. submission says how records reach the authority, cadence the periods where the law sets them, reported what is reported and by whom. certification_status is what somebody claims, not a certificate: community means nobody has read it, maintained means the maintainers keep it current and nobody has reviewed it, proven means a maintained pack reproduced, after the books of a real company were imported, the statements that company filed and the administration accepted — it proves the cases that company uses, never every regime of the country, and `evidence` lists per scope the kind of filing, the financial year, what was reproduced and what was not tested — reviewed means the named professional in certified_by read it on certified_at. `sources` is the register the pack declares — each entry is a text, its official publisher, an absolute link and the day it was opened — and it holds no copy of the law itself. A tax and a box of the declaration each carry their own article in legal_reference and name the register entry it is in; a link that no longer answers is the register being stale, never the rule being wrong.', }; } // --------------------------------------------------------------------------- // status // --------------------------------------------------------------------------- export const StatusInput = z.object({}); export async function status(backend, options = {}) { const version = await backend.rpc('ekwo_schema_version'); const instance = await backend.select({ table: 'instance', columns: columns.INSTANCE }); const companies = await backend.select({ table: 'companies', columns: ['id', 'name', 'country', 'currency_code', 'agent_posting'], order: [{ column: 'name' }], }); const posting = await postingOf(backend, companies); return { schema_version: version[0] ?? null, connection: { mode: backend.mode, acting_as: backend.actingAs ?? null }, posting: posting.session, companies: posting.companies, instance: instance[0] ?? null, // Whether this installation is registered with Ekwo, which is optional, // and — only where the server was started to say so — the invitation // the agent may relay once to the person it works for. registration: registrationOf(instance[0], options.inviteToRegister === true), note: backend.mode === 'postgrest' ? 'Reading and writing as the signed-in user, over PostgREST. Row level security decides what is visible.' : 'Reading and writing over a direct Postgres connection, with the claims and the role of the user this server acts for.', }; } /** What a session chose, in words a model and a person read the same way. */ export const SESSION_POSTING_NOTE = { autopilot: 'This session runs in autopilot, as the person who started it chose: you post a document without an approval in every company whose agent_posting allows it, and each posting is on the audit trail with this session. A company that forbids autopilot refuses it (autopilot_forbidden). Still tell the user what you post.', review: 'This session runs in review, as the person who started it chose: you post a document only once a person approved that draft as it stands, whatever the company says.', company: "This session follows each company's agent_posting: posting_mode says, company by company, whether you post directly (autopilot) or once a person approved the draft (review).", }; /** * How this session posts, and how that comes out in each company: the * session's choice, and `agent_posting_mode()` of every company — `review`, * `autopilot`, or `autopilot_forbidden` where the session asked for autopilot * in a company that forbids it. */ export async function postingOf(backend, companies) { const choice = backend.agent?.posting ?? null; const withMode = await Promise.all(companies.map(async (company) => ({ ...company, posting_mode: (await backend.rpc('agent_posting_mode', { p_company_id: company['id'] }))[0] ?? null, }))); return { session: { mode: choice, session_id: backend.agent?.id ?? null, note: SESSION_POSTING_NOTE[choice ?? 'company'] }, companies: withMode, }; } function registrationOf(instance, invite) { if (instance === undefined) return { registered: null, invitation: null }; const registeredAt = instance['registered_at'] ?? null; return { registered: registeredAt !== null, invitation: invite && registeredAt === null ? REGISTRATION_INVITATION : null, }; } /** Re-exported so the write tools can format the same way. */ export { money }; // --------------------------------------------------------------------------- // The audit trail // --------------------------------------------------------------------------- export const ReadAuditLogInput = z.object({ company_id: companyId, table: z .string() .optional() .describe('One table of the schema: accounts, journals, taxes, tax_postings, contacts, products, bank_accounts, companies, fiscal_years, company_members, company_packs, api_keys, documents, payments, entries, reconciliations.'), record_key: z .string() .optional() .describe('The natural key of one row — an account code, a tax code, an invoice number.'), actor_id: uuid.optional().describe('Only what this user changed. Their auth.users id.'), action: z .string() .optional() .describe('One act: document_posted, document_cancelled, entry_posted, entry_reversed, payment_posted, payment_reconciled, payment_unreconciled, fiscal_year_closed, fiscal_year_reopened, fiscal_year_finally_closed, pack_upgraded.'), operation: z.enum(['insert', 'update', 'delete']).optional(), from: isoDate.optional().describe('Earliest date, inclusive.'), to: isoDate.optional().describe('Latest date, inclusive — the whole of that day.'), limit: z.number().int().min(1).max(200).optional(), }); export async function readAuditLog(backend, args) { const where = [{ column: 'company_id', op: 'eq', value: args.company_id }]; if (args.table !== undefined) where.push({ column: 'table_name', op: 'eq', value: args.table }); if (args.record_key !== undefined) where.push({ column: 'record_key', op: 'eq', value: args.record_key }); if (args.actor_id !== undefined) where.push({ column: 'actor_id', op: 'eq', value: args.actor_id }); if (args.action !== undefined) where.push({ column: 'action', op: 'eq', value: args.action }); if (args.operation !== undefined) where.push({ column: 'operation', op: 'eq', value: args.operation }); if (args.from !== undefined) where.push({ column: 'occurred_at', op: 'gte', value: args.from }); // A date names a day, not the instant it begins: `to: 2026-06-15` has to // include everything that happened that afternoon. if (args.to !== undefined) { where.push({ column: 'occurred_at', op: 'lt', value: nextDay(args.to) }); } const entries = await backend.select({ table: 'audit_log', columns: columns.AUDIT_LOG, where, order: [{ column: 'occurred_at', ascending: false }, { column: 'sequence', ascending: false }], limit: args.limit ?? 50, }); return { changes: entries, count: entries.length, note: 'Append-only for every client. Nothing writes this trail but the database itself, and no client removes a row from it: rows leave only through a dated purge by the operator, which leaves a line saying so.', }; } /** The day after an ISO date, so a range on a timestamp can end on a day. */ function nextDay(date) { const day = new Date(`${date}T00:00:00Z`); day.setUTCDate(day.getUTCDate() + 1); return day.toISOString().slice(0, 10); } //# sourceMappingURL=read.js.map