@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.
1,467 lines • 95.5 kB
JavaScript
/**
* The tools of the modules, and the loader that puts them on the server.
*
* A module is a schema of its own, so its tools are named after it —
* `fixed_assets_list`, `budgets_variance`, `crm_search` — and a model
* reading a tool list can tell which module answers for what. The prefix is in `module.json`, and
* a test holds the tool names to it.
*
* **Nothing here decides what is installed.** `public.modules` does, and the
* server asks it at startup: a module whose migrations have never run has no
* row, so its tools are not offered, and a tool a model cannot use is worse
* than a tool it cannot see. What the registry below carries is the other
* half — the handlers this release knows how to write — and a module installed
* in the database that this release has no handlers for is simply not exposed.
*
* **PostgREST has to be told.** A schema other than `public` is served only
* once the project lists it under its exposed schemas, which no migration can
* set. The refusal that comes back is a 406 about a profile, which says
* nothing useful to a model, so every module tool turns it into the sentence
* that names the setting.
*/
import { z } from 'zod';
import { EkwoMcpError } from '../backend.js';
import { CLEARANCE_ANSWERS, TRANSMISSION_STATES, amountIn, decimal, FISCAL_RECORD_KINDS, FISCAL_SUBMISSION_MODES, einvoiceStatus, fiscalisationStatus, fiscaliseDocument, issueEinvoice, parseFiscalSystem, listEinvoiceTransmissions, recordClearanceAnswer, recordClearanceSubmission, money, moneyFields, validateEinvoice, CRM_ACTIVITY_KINDS, CRM_PRIORITIES, CRM_RELATIONSHIP_STATUSES, crmBoard, crmCard, crmContactVcard, crmDealOfDocument, crmJoinSegment, crmLeaveSegment, crmLogActivity, crmMoveDeal, crmAttachDocument, crmDetachDocument, crmOpenDeal, crmSearch, crmSegments, crmTimeline, crmUpsertCard, CONTRACT_AMENDMENT_KINDS, CONTRACT_DEADLINE_KINDS, CONTRACT_DIRECTIONS, CONTRACT_FIELDS, CONTRACT_FREQUENCIES, CONTRACT_KINDS, CONTRACT_RENEWALS, CONTRACT_SCHEDULE_FIELDS, CONTRACT_STATES, contractsAmend, contractsCard, contractsDeadlines, contractsFromTemplate, contractsIssueDue, contractsList, contractsSchedule, contractsUpsert, } from '@ekwo-ai/core';
import { companyId, isoDate, uuid } from './read.js';
/**
* A schema the project has not exposed answers with a profile error, which
* reads like a bug in this server. It is a setting, so say which one.
*/
export async function inSchema(schema, run) {
try {
return await run();
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (/profile|schema must be one of|PGRST106|acceptable/i.test(message)) {
throw new EkwoMcpError(`schema_not_exposed: the \`${schema}\` schema is not served by this project's API. ` +
`Add it in Supabase → Project Settings → API → Exposed schemas, or to \`[api] schemas\` ` +
`in supabase/config.toml, and try again. ${message}`);
}
throw error;
}
}
// ---------------------------------------------------------------------------
// fixed assets — module code `assets`, schema `fixed_assets`
// ---------------------------------------------------------------------------
const FIXED_ASSETS = {
code: 'assets',
prefix: 'fixed_assets',
schema: 'fixed_assets',
tools: [
{
verb: 'list',
title: 'Fixed assets',
effect: 'read',
description: 'The register of fixed assets of a company at a date: what each one cost, what has been written off it and what is left. It reads what has been *booked*, so it ties back to the accumulated depreciation account on the balance sheet. An asset disposed of before that date is not in it.',
input: z.object({
company_id: companyId,
at: isoDate.describe('The date to read the register at.'),
}),
async run(backend, args) {
const at = args['at'];
const rows = await inSchema('fixed_assets', () => backend.rpc('register', { p_company_id: args['company_id'], p_at: at }, 'fixed_assets'));
return {
at,
fixed_assets: rows.map((row) => ({
...row,
cost: money(row['cost']),
accumulated: money(row['accumulated']),
net_book_value: money(row['net_book_value']),
})),
};
},
},
{
verb: 'create',
title: 'Record a fixed asset',
effect: 'destructive',
description: 'Creates a fixed asset and writes its depreciation schedule in one call. Give a `category_code` of the country pack — the categories are those of its `fixed_assets.json` — and the method, the duration and the coefficient come from it; anything you pass yourself wins over the category. The three accounts are the asset account, the accumulated depreciation account and the depreciation charge. Nothing is booked here: fixed_assets_run_depreciation is what posts.',
input: z.object({
company_id: companyId,
code: z.string().min(1).describe('Your own reference for the asset. Unique in the company.'),
name: z.string().min(1),
acquisition_date: isoDate,
cost: z.number().positive().describe('What it cost, excluding recoverable tax.'),
asset_account: z.string().describe('Account code the asset itself sits on.'),
depreciation_account: z.string().describe('Account code of the accumulated depreciation.'),
expense_account: z.string().describe('Account code the depreciation charge lands on.'),
category_code: z.string().optional().describe('A category of the country pack.'),
duration_months: z.number().int().positive().optional(),
method: z.enum(['straight_line', 'declining_balance']).optional(),
coefficient: z.number().positive().optional().describe('Required by a declining balance.'),
residual_value: z.number().min(0).optional(),
in_service_date: isoDate.optional().describe('When it started being used, if not the day it was bought.'),
description: z.string().optional(),
}),
async run(backend, args) {
// A function returning a scalar comes back as the scalar, on either
// backend: `opening_balance` is read the same way.
const created = await inSchema('fixed_assets', () => backend.rpc('create_fixed_asset', {
p_company_id: args['company_id'],
p_code: args['code'],
p_name: args['name'],
p_acquisition_date: args['acquisition_date'],
p_cost: args['cost'],
p_asset_account: args['asset_account'],
p_depreciation_account: args['depreciation_account'],
p_expense_account: args['expense_account'],
p_category_code: args['category_code'] ?? null,
p_duration_months: args['duration_months'] ?? null,
p_method: args['method'] ?? null,
p_coefficient: args['coefficient'] ?? null,
p_residual_value: args['residual_value'] ?? 0,
p_in_service_date: args['in_service_date'] ?? null,
p_description: args['description'] ?? null,
}, 'fixed_assets'));
return { asset_id: created[0] ?? null };
},
},
{
verb: 'schedule',
title: 'Depreciation schedule',
effect: 'read',
description: 'The planned depreciation of one asset, period by period, with the amount, the accumulated total and the net book value after each one, and the entry that booked it where it has been booked. The schedule always sums to exactly the cost less the residual value: the last line takes the remainder.',
input: z.object({ company_id: companyId, asset_id: uuid }),
async run(backend, args) {
const lines = await inSchema('fixed_assets', () => backend.select({
schema: 'fixed_assets',
table: 'depreciation_lines',
columns: [
'sequence',
'period_start',
'period_end',
'amount::text',
'accumulated::text',
'net_book_value::text',
'entry_id',
'posted_at',
],
where: [
{ column: 'company_id', op: 'eq', value: args['company_id'] },
{ column: 'asset_id', op: 'eq', value: args['asset_id'] },
],
order: [{ column: 'sequence' }],
}));
return { lines };
},
},
{
verb: 'run_depreciation',
title: 'Book the depreciation',
effect: 'destructive',
idempotent: true,
description: 'Books every planned period that ends on or before a date, one ledger entry per period, through the socle\'s own posting function. It is idempotent: a period already booked is skipped, and the database refuses a second entry for it anyway. A closed financial year or a locked period refuses the posting — report the refusal, do not move the date.',
input: z.object({
company_id: companyId,
period_end: isoDate.describe('Book everything up to and including this date.'),
}),
async run(backend, args) {
const result = await inSchema('fixed_assets', () => backend.rpc('run_depreciation', { p_company_id: args['company_id'], p_period_end: args['period_end'] }, 'fixed_assets'));
return result[0] ?? { entries: [] };
},
},
{
verb: 'dispose',
title: 'Dispose of a fixed asset',
effect: 'destructive',
description: 'Takes an asset off the books on a date: clears its cost and its accumulated depreciation, books the proceeds against the account you name, and presents the result the way the country pack says — one gain or loss line, or the value sold and the proceeds in full. Run fixed_assets_run_depreciation first: a disposal is refused while a period that has already ended is still unbooked. There is no undo.',
input: z.object({
company_id: companyId,
asset_id: uuid,
disposal_date: isoDate,
proceeds: z.number().min(0).default(0).describe('What it was sold for, excluding tax. Zero when it was scrapped.'),
counterpart_account: z
.string()
.optional()
.describe('Account code the proceeds are owed on. The receivable account of the company by default.'),
contact_id: uuid.optional().describe('Who bought it.'),
}),
async run(backend, args) {
const result = await inSchema('fixed_assets', () => backend.rpc('dispose_fixed_asset', {
p_asset_id: args['asset_id'],
p_date: args['disposal_date'],
p_proceeds: args['proceeds'] ?? 0,
p_counterpart_account: args['counterpart_account'] ?? null,
p_contact_id: args['contact_id'] ?? null,
}, 'fixed_assets'));
return { entry_id: result[0] ?? null };
},
},
],
};
// ---------------------------------------------------------------------------
// budgets
// ---------------------------------------------------------------------------
const BUDGETS = {
code: 'budgets',
prefix: 'budgets',
schema: 'budgets',
tools: [
{
verb: 'list',
title: 'Budgets',
effect: 'read',
description: 'The budgets of a company, with the financial year each one is for and whether it is a draft, approved or closed. Start here: budgets_variance needs a budget_id.',
input: z.object({ company_id: companyId }),
async run(backend, args) {
const budgets = await inSchema('budgets', () => backend.select({
schema: 'budgets',
table: 'budgets',
columns: ['id', 'code', 'name', 'state', 'fiscal_year_id', 'notes'],
where: [{ column: 'company_id', op: 'eq', value: args['company_id'] }],
order: [{ column: 'code' }],
}));
return { budgets };
},
},
{
verb: 'upsert_lines',
title: 'Write budget lines',
effect: 'destructive',
idempotent: true,
description: 'Adds lines to a budget: one figure per account and per period. State the amount the way a business says it out loud — an income and a cost are both positive — and the comparison flips the ledger, not you. A line already there for the same account and period is replaced.',
input: z.object({
company_id: companyId,
budget_id: uuid,
lines: z
.array(z.object({
account_code: z.string(),
period_start: isoDate,
period_end: isoDate,
amount: z.number(),
note: z.string().optional(),
}))
.min(1),
}),
async run(backend, args) {
const companyIdValue = args['company_id'];
const budgetIdValue = args['budget_id'];
const lines = args['lines'];
const codes = [...new Set(lines.map((line) => line.account_code))];
const accounts = await backend.select({
table: 'accounts',
columns: ['id', 'code'],
where: [
{ column: 'company_id', op: 'eq', value: companyIdValue },
{ column: 'code', op: 'in', value: codes },
],
});
const byCode = new Map(accounts.map((account) => [account.code, account.id]));
const missing = codes.filter((code) => !byCode.has(code));
if (missing.length > 0) {
throw new EkwoMcpError(`unknown_account: ${missing.join(', ')} — not an account of this company. Use list_accounts to find the right code.`);
}
return inSchema('budgets', async () => {
for (const line of lines) {
await backend.remove('lines', [
{ column: 'budget_id', op: 'eq', value: budgetIdValue },
{ column: 'account_id', op: 'eq', value: byCode.get(line.account_code) },
{ column: 'period_start', op: 'eq', value: line.period_start },
{ column: 'period_end', op: 'eq', value: line.period_end },
], 'budgets');
}
const written = await backend.insert('lines', lines.map((line) => ({
budget_id: budgetIdValue,
company_id: companyIdValue,
account_id: byCode.get(line.account_code),
period_start: line.period_start,
period_end: line.period_end,
amount: line.amount,
note: line.note ?? null,
})), ['id'], 'budgets');
return { written: written.length };
});
},
},
{
verb: 'variance',
title: 'Budget against ledger',
effect: 'read',
description: 'What was planned against what was booked, per account, over a period. Both figures are in the sign a business states them in, and the variance is the actual less the plan — so a negative figure on an income account is revenue that did not arrive, and a positive one on a cost account is overspending. It reads posted entries of kind `normal`: a closing or appropriation entry is not what a period earned. A budget line is taken whole or not at all, so ask for a window that contains the periods the budget was written in.',
input: z.object({
company_id: companyId,
budget_id: uuid,
from: isoDate,
to: isoDate,
}),
async run(backend, args) {
const rows = await inSchema('budgets', () => backend.rpc('variance', {
p_company_id: args['company_id'],
p_budget_id: args['budget_id'],
p_from: args['from'],
p_to: args['to'],
}, 'budgets'));
return {
from: args['from'],
to: args['to'],
lines: rows.map((row) => ({
...row,
budget: money(row['budget']),
actual: money(row['actual']),
variance: money(row['variance']),
})),
};
},
},
],
};
// ---------------------------------------------------------------------------
// electronic invoicing — module code `einvoicing`, schema `einvoicing`
//
// The four functions of the core the command line calls too. Which format a
// document is written in is the profile of its company's country pack; which
// transport a file leaves through is the server's, set by whoever runs it
// (EKWO_EINVOICE_DIRECTORY for the folder that ships) and never by a model.
// ---------------------------------------------------------------------------
const documentId = uuid.describe('The posted sale invoice or credit note. list_documents finds it.');
const EINVOICING = {
code: 'einvoicing',
prefix: 'einvoicing',
schema: 'einvoicing',
tools: [
{
verb: 'validate',
title: 'Check an electronic invoice',
effect: 'read',
description: 'Writes the electronic invoice of a posted sale invoice or credit note, in the profile its company\'s country pack declares, and lists every rule of the format it breaks — as the format names them, word for word. Records nothing and sends nothing. A broken rule is fixed in the books (the customer\'s electronic address, a due date, a reference), never in the file. A profile no brick writes is refused as format_without_brick.',
input: z.object({
document_id: documentId,
include_file: z.boolean().optional().describe('Hand the file back too. Left out, the answer is what is wrong with it.'),
}),
async run(backend, args) {
return inSchema('einvoicing', () => validateEinvoice(backend, {
document_id: args['document_id'],
...(args['include_file'] === undefined ? {} : { include_file: args['include_file'] }),
}));
},
},
{
verb: 'issue',
title: 'Issue an electronic invoice',
effect: 'destructive',
idempotent: true,
openWorld: true,
description: 'Writes the electronic invoice of a posted sale and keeps it — the exact file, its checksum and the rules it breaks; the same file twice is one issue. With send, also hands it to the transport this server is configured with and records what came back. A file that breaks a rule is kept and never sent (einvoice_not_sendable, with the rules); a document already on its way is refused (einvoice_already_sent). Submitted is not delivered: follow it with einvoicing_status. Ask the user before sending: a file that leaves is in a customer\'s hands.',
input: z.object({
document_id: documentId,
send: z.boolean().optional().describe('Send it as well, through the configured transport. Left out, nothing leaves.'),
include_file: z.boolean().optional().describe('Hand the file back too.'),
}),
async run(backend, args, context) {
return inSchema('einvoicing', () => issueEinvoice(backend, {
document_id: args['document_id'],
...(args['send'] === undefined ? {} : { send: args['send'] }),
...(args['include_file'] === undefined ? {} : { include_file: args['include_file'] }),
}, context.einvoiceTransport));
},
},
{
verb: 'status',
title: 'Where an electronic invoice stands',
effect: 'additive',
idempotent: true,
openWorld: true,
description: 'Everything known of the electronic invoice of one document: each file issued, each sending and every answer the service gave, verbatim. state is not_issued, issued, or the state of the latest sending: prepared, submitted, accepted_by_access_point, delivered, rejected or failed. With refresh, asks the configured transport again about the sending still open and records its answer. A rejected or failed document is sent again with einvoicing_issue.',
input: z.object({
document_id: documentId,
refresh: z.boolean().optional().describe('Ask the transport again about the open sending, and record what it says.'),
}),
async run(backend, args, context) {
return inSchema('einvoicing', () => einvoiceStatus(backend, {
document_id: args['document_id'],
...(args['refresh'] === undefined ? {} : { refresh: args['refresh'] }),
}, context.einvoiceTransport));
},
},
{
verb: 'fiscalise',
title: 'Chain the fiscal record of an invoice',
effect: 'destructive',
description: 'Writes the fiscal record of a posted sale — the record its company\'s country pack requires the invoicing software to keep for every invoice, in the format of its einvoicing.fiscalisation block — chains it after the last record of the invoicing system, with the hash of that record, and keeps its file. Records nothing when the record breaks a rule (the rules are listed, as the format names them) or with dry_run. A record once chained is never changed: a mistake is an anulacion, then a new alta. The answer carries verification_url, what the QR code of the invoice encodes. Refused by name where the pack declares no regime (no_fiscalisation_regime) or no brick writes its format (format_without_brick). Ask the user before chaining: a record is kept as the law requires, for good.',
input: z.object({
document_id: documentId,
kind: z.enum(FISCAL_RECORD_KINDS).optional().describe('alta (the default) when the invoice is issued; anulacion to cancel its record.'),
mode: z.enum(FISCAL_SUBMISSION_MODES).optional().describe('How the record reaches the authority, among the modes the pack allows. The pack\'s default when left out.'),
rectification: z.string().min(1).max(10).optional().describe('For a credit note: why it rectifies, in the regime\'s own code, where the regime asks and the books do not say. Ask the user; never guess it.'),
dry_run: z.boolean().optional().describe('Write the record and list what is wrong with it; chain nothing.'),
include_file: z.boolean().optional().describe('Hand the file of the record back too.'),
}),
async run(backend, args, context) {
const system = context.fiscalSystem;
if (system === undefined) {
throw new EkwoMcpError('no_fiscal_system: the invoicing system that chains the records is described by whoever runs this server, as JSON in EKWO_FISCAL_SYSTEM — name, id, version, installation, producerName, producerTaxId — and it is not set. Nothing was chained.');
}
return inSchema('einvoicing', () => fiscaliseDocument(backend, args['document_id'], {
system: parseFiscalSystem(system, 'the fiscal system of this server'),
...(args['kind'] === undefined ? {} : { kind: args['kind'] }),
...(args['mode'] === undefined ? {} : { mode: args['mode'] }),
...(args['rectification'] === undefined ? {} : { rectification: args['rectification'] }),
...(args['dry_run'] === undefined ? {} : { dryRun: args['dry_run'] }),
...(args['include_file'] === undefined ? {} : { includeFile: args['include_file'] }),
}));
},
},
{
verb: 'fiscalisation_status',
title: 'Where the fiscal records of a company stand',
effect: 'read',
description: 'The fiscalisation regime of a company, as its country pack declares it, and where its records stand: each chain of an invoicing system, walked both ways (verified, or the first break), the records still to be sent to the authority, the posted sales from the start of the obligation that have no record — named here, never fiscalised on their own — and the latest events. Under a clearance regime (kind clearance), missing is the posted sales without the authority\'s validation, and clearance counts those validated, waiting, rejected by the authority or by the buyer, and cancelled at the authority while still posted. A broken chain is for the company\'s accountant before anything else.',
input: z.object({
company_id: companyId,
limit: z.number().int().min(1).max(500).optional().describe('At most this many pending records and missing documents listed. 50 by default.'),
}),
async run(backend, args) {
return inSchema('einvoicing', () => fiscalisationStatus(backend, args['company_id'], {
...(args['limit'] === undefined ? {} : { limit: args['limit'] }),
}));
},
},
{
verb: 'clearance',
title: 'Record a submission to the authority, or its answer',
effect: 'additive',
description: 'Under a clearance regime — the authority validates every invoice before it is issued, and an invoice is valid only once validated — records what happened to a posted sale: submitted (it left for the authority, with the reference the authority gave on receipt), validated (with the identifier the authority gave it, the moment it validated it and, where the regime has one, the verification link the invoice carries as a QR code), rejected (by the authority, or by the buyer after validation and within the window the pack declares, with the reason) or cancelled (by the issuer, after validation and within the pack\'s window, with the reason). Nothing is sent by this tool: it records what the host that talks to the authority reports, and the answer verbatim in answer. Every transition that cannot have happened is refused by name (clearance_pending, clearance_state_backwards, clearance_window_closed, clearance_not_cancellable, clearance_verification_missing, clearance_verification_unbuilt…). Refused where the pack declares no clearance regime (fiscal_regime_not_clearance). Never record an answer nobody received: an invoice recorded as validated is one the books treat as valid.',
input: z.object({
document_id: documentId,
what: z.enum(['submitted', ...CLEARANCE_ANSWERS]).describe('What happened: submitted, then one of validated, rejected, cancelled.'),
reference: z.string().min(1).optional().describe('submitted: what the authority named the submission on receipt.'),
issue_id: uuid.optional().describe('submitted: the electronic invoice submitted, where this module kept it (einvoicing_status lists them).'),
identifier: z.string().min(1).optional().describe('validated: the identifier the authority gave the invoice.'),
validated_at: z.string().min(1).optional().describe('validated: when the authority validated it, ISO 8601 with its offset.'),
verification_url: z.string().url().optional().describe('validated: the link to the authority\'s verification, where the regime has one. Left out where the pack builds it (clearance.verification computed): it is then built from identifier and answer.'),
environment: z.enum(['production', 'test']).optional().describe('validated: which environment of the authority answered, where the pack builds the link — production when left out, test for its sandbox.'),
reason: z.string().min(1).optional().describe('rejected, cancelled: why, as it was said.'),
by: z.enum(['authority', 'buyer']).optional().describe('rejected: who rejected it. The authority when left out.'),
at: z.string().min(1).optional().describe('When it happened, ISO 8601 with its offset. Now when left out; the windows of the regime are read against it.'),
answer: z.record(z.string(), z.unknown()).optional().describe('What the authority answered, as it answered it.'),
}),
async run(backend, args) {
const documentId = args['document_id'];
const what = args['what'];
const text = (key) => args[key];
const answer = args['answer'];
return inSchema('einvoicing', () => what === 'submitted'
? recordClearanceSubmission(backend, documentId, {
...(text('reference') === undefined ? {} : { reference: text('reference') }),
...(text('issue_id') === undefined ? {} : { issueId: text('issue_id') }),
...(text('at') === undefined ? {} : { submittedAt: text('at') }),
...(answer === undefined ? {} : { answer }),
})
: recordClearanceAnswer(backend, documentId, {
state: what,
...(text('identifier') === undefined ? {} : { identifier: text('identifier') }),
...(text('validated_at') === undefined ? {} : { validatedAt: text('validated_at') }),
...(text('verification_url') === undefined ? {} : { verificationUrl: text('verification_url') }),
...(text('environment') === undefined ? {} : { environment: text('environment') }),
...(text('reason') === undefined ? {} : { reason: text('reason') }),
...(text('by') === undefined ? {} : { by: text('by') }),
...(text('at') === undefined ? {} : { at: text('at') }),
...(answer === undefined ? {} : { answer }),
}));
},
},
{
verb: 'list',
title: 'Electronic invoices sent',
effect: 'read',
description: 'Every sending of electronic invoices of a company, or of one document, latest first: the document, the file, the channel and the service, the reference it gave, the state and the last words the service said.',
input: z.object({
company_id: companyId,
document_id: uuid.optional().describe('Only the sendings of this document.'),
state: z.enum(TRANSMISSION_STATES).optional().describe('Only the sendings in this state.'),
limit: z.number().int().min(1).max(500).optional().describe('At most this many. 100 by default.'),
}),
async run(backend, args) {
return inSchema('einvoicing', () => listEinvoiceTransmissions(backend, {
company_id: args['company_id'],
...(args['document_id'] === undefined ? {} : { document_id: args['document_id'] }),
...(args['state'] === undefined ? {} : { state: args['state'] }),
...(args['limit'] === undefined ? {} : { limit: args['limit'] }),
}));
},
},
],
};
// ---------------------------------------------------------------------------
// corporate income tax — module code `tax`, schema `tax`
//
// The estimate is `tax.estimate()`, read as it is: every line already names
// its rule and its article, so nothing here explains a figure the database
// did not. What a company declares about itself is written by the person,
// through these tools, and the database checks it against its country's
// rules; a judgement is never worked out here from the books.
// ---------------------------------------------------------------------------
const fiscalYearId = uuid.describe('The financial year. get_company lists them.');
/** The country a company's corporate tax rules are read for, as `tax.estimate()` reads it. */
async function taxCountry(backend, company) {
const rows = await backend.select({
table: 'companies',
columns: ['country', 'fiscal_country'],
where: [{ column: 'id', op: 'eq', value: company }],
});
const row = rows[0];
if (row === undefined)
throw new EkwoMcpError(`unknown_company: ${company}`);
return (row.fiscal_country ?? row.country);
}
/** The first and last day of one financial year of a company. */
async function fiscalYear(backend, company, year) {
const rows = await backend.select({
table: 'fiscal_years',
columns: ['start_date::text', 'end_date::text'],
where: [
{ column: 'company_id', op: 'eq', value: company },
{ column: 'id', op: 'eq', value: year },
],
});
const row = rows[0];
if (row === undefined)
throw new EkwoMcpError(`unknown_fiscal_year: ${year} is not a financial year of this company`);
return row;
}
const TAX = {
code: 'tax',
prefix: 'tax',
schema: 'tax',
tools: [
{
verb: 'estimate',
title: 'Corporate income tax of a year',
effect: 'read',
description: 'The corporate income tax of a financial year as the ledger stands on a day — the whole year when no day is given — line by line, each with its article: the accounting result the country pack starts from, every adjustment with its base and percentage, the losses of earlier years used, the taxable base, every rate with the slice it takes, a rate refused with the parameter in the way (`not_declared` or `not_met`), the credits, and `estimated_tax`. Reads and writes nothing. It is an estimate from what is booked and from a reading of the rules: never call it the tax due, never call it compliant, and say that the user\'s accountant checks it before anything is filed. During the year it is the tax on the year so far; it forecasts nothing. A rate refused as `not_declared` is a question for the user: tax_parameters, then tax_declare_parameter with their answer.',
input: z.object({
company_id: companyId,
fiscal_year_id: fiscalYearId,
at: isoDate.optional().describe('Read the ledger as it stands on this day. Left out, the whole year.'),
}),
async run(backend, args) {
const rows = await inSchema('tax', () => backend.rpc('estimate', { p_company_id: args['company_id'], p_fiscal_year_id: args['fiscal_year_id'], p_at: args['at'] ?? null }, 'tax'));
const lines = moneyFields(rows, ['base', 'amount']).map((line) => ({ ...line, rate: decimal(line['rate']) }));
return {
fiscal_year_id: args['fiscal_year_id'],
at: args['at'] ?? null,
estimated_tax: lines.find((line) => line['kind'] === 'estimated_tax')?.['amount'] ?? null,
lines,
};
},
},
{
verb: 'parameters',
title: 'What the company declares for its tax',
effect: 'read',
description: 'The facts the country pack asks a company to declare for a financial year — a judgement (is it a small company, who holds its capital) or an amount (its turnover, what it paid its director) — each with its article, and the company\'s answer, or `declared: false`. A condition of a rate that is not declared is not met, so a reduced rate waits for these. Only the user answers them: ask, then tax_declare_parameter.',
input: z.object({ company_id: companyId, fiscal_year_id: fiscalYearId }),
async run(backend, args) {
const company = args['company_id'];
const year = args['fiscal_year_id'];
const country = await taxCountry(backend, company);
return inSchema('tax', async () => {
const templates = await backend.select({
schema: 'tax',
table: 'parameter_templates',
columns: ['code', 'name', 'name_i18n', 'value_type', 'legal_reference'],
where: [{ column: 'country', op: 'eq', value: country }],
order: [{ column: 'sequence' }, { column: 'code' }],
});
const declared = await backend.select({
schema: 'tax',
table: 'company_parameters',
columns: ['code', 'value_boolean', 'value_amount::text', 'note'],
where: [
{ column: 'company_id', op: 'eq', value: company },
{ column: 'fiscal_year_id', op: 'eq', value: year },
],
});
const byCode = new Map(declared.map((row) => [row['code'], row]));
return {
fiscal_year_id: year,
parameters: templates.map((template) => {
const answer = byCode.get(template['code']);
return {
...template,
declared: answer !== undefined,
value: answer === undefined ? null : (answer['value_boolean'] ?? answer['value_amount']),
note: answer?.['note'] ?? null,
};
}),
};
});
},
},
{
verb: 'declare_parameter',
title: 'Declare a fact for the tax',
effect: 'additive',
idempotent: true,
description: 'Writes the company\'s answer to one parameter of tax_parameters for one financial year, replacing an earlier answer: `true` or `false` for a judgement, a decimal string for an amount. Write only what the user has stated, in their words — never a judgement you inferred from the books, which say nothing of who holds the capital or whether a condition is met. Ask before writing. The database refuses a code the country does not ask for (`unknown_tax_parameter`) and a value of the wrong kind (`tax_parameter_type`).',
input: z.object({
company_id: companyId,
fiscal_year_id: fiscalYearId,
code: z.string().min(1).describe('The code of the parameter, from tax_parameters.'),
value: z
.union([z.boolean(), z.string(), z.number()])
.describe('true or false for a judgement; a decimal string such as "85000.00" for an amount.'),
note: z.string().optional().describe('What the user said, or where the figure comes from.'),
}),
async run(backend, args) {
const company = args['company_id'];
const year = args['fiscal_year_id'];
const code = args['code'];
const value = args['value'];
const values = typeof value === 'boolean'
? { value_boolean: value, value_amount: null }
: { value_boolean: null, value_amount: amountIn(value) };
const where = [
{ column: 'company_id', op: 'eq', value: company },
{ column: 'fiscal_year_id', op: 'eq', value: year },
{ column: 'code', op: 'eq', value: code },
];
const columns = ['code', 'value_boolean', 'value_amount::text', 'note'];
return inSchema('tax', async () => {
const updated = await backend.update('company_parameters', { ...values, note: args['note'] ?? null }, where, columns, 'tax');
const row = updated[0] ??
(await backend.insert('company_parameters', [{ company_id: company, fiscal_year_id: year, code, ...values, note: args['note'] ?? null }], columns, 'tax'))[0];
return {
fiscal_year_id: year,
code,
value: row?.['value_boolean'] ?? row?.['value_amount'] ?? null,
note: row?.['note'] ?? null,
};
});
},
},
{
verb: 'adjustments',
title: 'What the tax adds back or deducts',
effect: 'read',
description: 'The adjustment rules of the country pack in force for a financial year — what each adds back to the accounting result or deducts from it, its percentage or the formula that works it out, the accounts the pack catches by itself, and its article — with what the company named under each: an account read from the ledger every time, for every year or for this one, or an amount stated for this year. The pack catches by itself only what a chart keeps on an account of its own; everything else counts only once it is named here, with tax_declare_adjustment. `not_in_force` lists what the company named under a rule that does not apply to this year.',
input: z.object({ company_id: companyId, fiscal_year_id: fiscalYearId }),
async run(backend, args) {
const company = args['company_id'];
const year = args['fiscal_year_id'];
const country = await taxCountry(backend, company);
const period = await fiscalYear(backend, company, year);
return inSchema('tax', async () => {
const rules = await backend.select({
schema: 'tax',
table: 'adjustment_rule_templates',
columns: [
'code',
'name',
'name_i18n',
'direction',
'percent::text',
'formula',
'account_rules',
'legal_reference',
'valid_from::text',
'valid_to::text',
'valid_on',
],
where: [{ column: 'country', op: 'eq', value: country }],
order: [{ column: 'sequence' }, { column: 'code' }],
});
// In force as `tax.in_force()` reads it: on the first or the last
// day of the year, whichever the rule says its law is read on.
const inForce = rules.filter((rule) => {
const day = rule['valid_on'] === 'period_end' ? period.end_date : period.start_date;
return rule['valid_from'] <= day && (rule['valid_to'] === null || rule['valid_to'] >= day);
});
const named = (await backend.select({
schema: 'tax',
table: 'adjustments',
columns: ['id', 'rule_code', 'fiscal_year_id', 'account_id', 'amount::text', 'parameters', 'note'],
where: [{ column: 'company_id', op: 'eq', value: company }],
})).filter((row) => row['fiscal_year_id'] === null || row['fiscal_year_id'] === year);
const accountIds = [...new Set(named.map((row) => row['account_id']).filter((id) => typeof id === 'string'))];
const accounts = accountIds.length === 0
? []
: await backend.select({
table: 'accounts',
columns: ['id', 'code', 'name'],
where: [{ column: 'id', op: 'in', value: accountIds }],
});
const byId = new Map(accounts.map((account) => [account.id, account]));
const declaration = (row) => {
const account = typeof row['account_id'] === 'string' ? byId.get(row['account_id']) : undefined;
return {
id: row['id'],
rule_code: row['rule_code'],
account_code: account?.code ?? null,
account_name: account?.name ?? null,
amount: money(row['amount']),
every_year: row['fiscal_year_id'] === null,
parameters: row['parameters'],
note: row['note'],
};
};
const codes = new Set(inForce.map((rule) => rule['code']));
return {
fiscal_year_id: year,
rules: inForce.map((rule) => ({
...rule,
percent: decimal(rule['percent']),
declared: named.filter((row) => row['rule_code'] === rule['code']).map(declaration),
})),
not_in_force: named.filter((row) => !codes.has(row['rule_code'])).map(declaration),
};
});
},
},
{
verb: 'declare_adjustment',
title: 'Name what falls under an adjustment',
effect: 'additive',
idempotent: true,
description: 'Names what falls under one rule of tax_adjustments: an account, whose balance the estimate reads from the ledger every time — for every year, or for one — or an amount stated for one year. A rule whose percentage is a formula needs the parameters the formula names (`adjustment_parameter_missing` says which). Which expense falls under which rule is the user\'s call, or their accountant\'s: take the account and the amount from them, ask before writing, and run tax_estimate afterwards to show what moved. The database refuses a rule the country does not carry (`unknown_adjustment_rule`).',
input: z.object({
company_id: companyId,
rule_code: z.string().min(1).describe('The code of the rule, from tax_adjustments.'),
account_code: z.string().optional().describe('An account whose balance falls under the rule. Give this or amount.'),
amount: z
.union([z.string(), z.number()])
.optional()
.describe('An amount stated for one year, positive; the rule carries the direction. Give this or account_code.'),
fiscal_year_id: fiscalYearId
.optional()
.describe('The financial year. Required with an amount; with an account, left out means every year.'),
parameters: z
.record(z.string(), z.union([z.string(), z.number(), z.boolean()]))
.optional()
.describe('What the formula of the rule reads, by the names it gives them.'),
note: z.string().optional(),
}),
async run(backend, args) {
const company = args['company_id'];
const accountCode = args['account_code'];
const amount = args['amount'];
if ((accountCode === undefined) === (amount === undefined)) {
throw new EkwoMcpError('account_or_amount: name an account_code, or state an amount — one of the two.');
}
let accountId = null;
if (accountCode !== undefined) {
const accounts = await backend.select({
table: 'accounts',
columns: ['id'],
where: [
{ column: 'company_id', op: 'eq', value: company },
{ column: 'code', op: 'eq', value: accountCode },
],
});
accountId = accounts[0]?.id ?? null;
if (accountId === null) {
throw new EkwoMcpError(`unknown_account: ${accountCode} — not an account of this company. Use list_accounts to find the right code.`);
}
}
const written = await inSchema('tax', () => backend.insert('adjustments', [
{
company_id: company,
fiscal_year_id: args['fiscal_year_id'] ?? null,
rule_code: args['rule_code'],
account_id: accountId,
amount: amount === undefined ? null : amountIn(amount),
parameters: args['parameters'] ?? {},
note: args['note'] ?? null,
},
], ['id'], 'tax'));
return { adjustment_id: written[0]?.['id'] ?? null };
},
},
{
verb: 'losses',
title: 'Losses carried forward',
effect: 'read',
description: 'What is left of each loss of an earlier year, by the day its year ended: the loss, what final computations have used of it, and what remains for a later profit. The stock moves only when a computation is called final. How much of it a year may use is the country\'s limit, applied by tax_estimate.',
input: z.object({
company_id: companyId,
before: isoDate.optional().describe('Only the losses of years that ended before this day.'),
}),
async run(backend, args) {
const rows = await inSchema('tax', () => backend.rpc('loss_stock', { p_company_id: args['company_id'], p_before: args['before'] ?? null }, 'tax'));
return { losses: moneyFields(rows, ['amount', 'used', 'remaining']) };
},
},
{
verb: 'record_computation',
title: 'Keep an estimate',
effect: 'additive',
description: 'Keeps what tax_estimate says now as the next computation of the year, numbered, with its lines, so that it can be read again after the ledger moves. It stays an estimate: calling a computation final is the owner\'s act, outside this server, and only a final one names the tax due. Writes nothing to the ledger. Record only when the user asks.',
input: z.object({
company_id: companyId,
fiscal_year_id: fiscalYearId,
at: isoDate.optional().describe('Read the ledger as it stands on this day. Left out, the whole year.'),
}),
async run(backend, args) {
const id = await inSchema('tax', () => backend.rpc('record_computation', { p_company_id: args['company_id'], p_fiscal_year_id: args['fiscal_year_id'], p_at: args['at'] ?? null }, 'tax'));
return { computation_id: id[0] ?? null };
},
},
{
verb: 'computations',
title: 'Computations kept',
effect: 'read',
description: 'The computations kept for a company, latest first, or for one financial year: the version, the day the ledger was read on, the accounting result, the taxable base, the loss of the year and the tax, and the status — `estimate`, `final` (called final by an owner; the only one whose tax is the tax due) or `superseded` (a final one withdrawn, kept).',
input: z.object({
company_id: companyId,
fiscal_year_id: fiscalYearId.optional().describe('Only the computations of this financial year.'),
}),
async run(backend, args) {
const where = [{ column: 'company_id', op: 'eq', value: args['company_id'] }];
if (args['fiscal_year_id'] !== undefined) {
where.push({ column: 'fiscal_year_id', op: 'eq', value: args['fiscal_year_id'] });
}
const computations = await inSchema('tax', () => backend.select({
schema: 'tax',
table: 'computations',
columns: [
'id',
'fiscal_year_id',
'version',
'status',
'computed_at::text',
'tax_code',
'currency_code',
'accounting_result::text',
'taxable_base::text',
'loss_of_period::text',
'tax::text',
'recorded_at',
'finalised_at',
'superseded_at',
],
where,
order: [{ column: 'recorded_at', ascending: false }, { column: 'version', ascending: false }],
}));
return { computations };
},
},
],
prompts: [
{
name: 'review_year',
title: 'Where the corporate income tax of a year stands',
description: 'The estimate of a financial year, explained line by line, with what the company still has to declare — and nothing changed without asking.',
args: {
company_id: 'The company.',
fiscal_year_id: 'The financial year, from get_company.',
},
text: ({ company_id, fiscal_year_id }) => [
`Where does the corporate income tax of company ${company_id} stand for the financial year ${fiscal_year_id}? Work through this in order and report what you find; change nothing without asking.`,
'',
'1. tax_parameters: the facts the country asks the company to declare. Name every one not declared yet, and ask the user for the answer. Never work one out from the books.',
'2. tax_adjustments: the rules in force and what the company has named under each. Where the books carry an expense a rule speaks of and nothing is named, say so and ask; which account falls under which rule is the user\'s call, or their accountant\'s.',
'3. tax_estimate: give the figure line by line — the accounting result, each adjustment with its article, the losses used, the taxable base, each rate and its slice, every rate refused and the parameter that stands in the way, the credits.',
'4. tax_losses: what is left of the losses of earlier years.',
'5. tax_computations: whether a computation was kept for the year, and whether one is final.',
'',
'Finish with the estimated tax, under that name, and what would change it. It is an estimate from what is booked and from a reading of the rules, not tax advice and not a return: say so, and suggest that the user\'s accountant checks it before anything is filed. Keep it with tax_record_computation only if the user asks.',
].join('\n'),
},
],
};
// ---------------------------------------------------------------------------
// customer relationship — module code `crm`, schema `crm`
//
// Every tool is one function of the schema, called through the core — the same
// function `ekwo crm …` calls. The statuses, priorities and kinds a model may
// name are the schema's enums, as the core lists them — a test holds those
// lists to the schema — so a tool says which values exist instead of letting
// a model guess. The refusals of the module are named `crm_<code>: …` and
// travel up word for word.
// ---------------------------------------------------------------------------
const contactId = uuid.describe('The contact: a person or an organisation of public.contacts. crm_search or search_contacts finds it.');
const segmentId = uuid.describe('The segment. crm_segments lists them.');
const words = (values) => values.join(', ');
const status = z.enum(CRM_RELATIONSHIP_STATUSES);
const activityKind = z.enum(CRM_ACTIVITY_KINDS);
const timestamp = z
.string()
.min(1)
.describe('A moment, ISO 8601 — a date, or a date and a time with its offset.');
const CRM = {
code: 'crm',
prefix: 'crm',
schema: 'crm',
tools: [
{
verb: 'search',
title: 'Search the cards',
effect: 'read',
description: 'The contacts the company follows — one card each — filtered: a text found in the name, the e-mail or the organisation\'s name, a relationship status, a segment the contact is in now, a stage one of its deals is at, a country and a language (ISO codes; the organisation\'s where the person has none), an owner, no_outbound, active since or inactive since a moment (inactive includes a card on which nothing ever happened). Every filter is optional. Most recently active first. Each row is the contact, its organisation\'s name, its status, priority, owner, last activity and the slugs of its segments. A contact without a card is not here: crm_upsert_card creates one. Merged contacts are left out.',
input: z.object({
company_id: companyId,
query: z.string().optional().describe('A text found in the name, the e-mail or the organisation\'s name.'),
status: status.optional().describe(`Where the relationship stands: one of ${words(CRM_RELATIONSHIP_STATUSES)}.`),
segment_id: segmentId.optional(),
stage_id: uuid.optional().describe('A stage one of the contact\'s deals is at. crm_board lists the stages.'),
country: z.string().length(2).optional().describe('ISO 3166-1 alpha-2.'),
language: z.string().length(2).optional().describe('ISO 639-1.'),
owner: z.string().optional().describe('The handle on the card, exactly.'),
no_outbound: z.boolean().optional().describe('true: only the contacts nobody may approach; false: only the others.'),
active_since: timestamp.optional().describe('Something happened on or after this moment.'),
inactive_since: timestamp.optional().describe('Nothing has happened since this moment, or ever.'),
limit: z.number().int().min(1).max(200).optional().describe('At most this many cards. 50 by default.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmSearch(backend, {
company_id: args['company_id'],
query: args['query'],
status: args['status'],
segment_id: args['segment_id'],
stage_id: args['stage_id'],
country: args['country'],
language: args['language'],
owner: args['owner'],
no_outbound: args['no_outbound'],
active_since: args['active_since'],
inactive_since: args['inactive_since'],
limit: args['limit'],
}));
},
},
{
verb: 'card',
title: 'One contact, whole',
effect: 'read',
description: 'Everything on one contact in one object: the contact as the books hold it (its contact_type says whether it is a prospect — other — or a customer), its organisation, its card (null when it has none yet), the segments it is in now, the open deals with it — for an organisation, with its people too — and its 20 latest activities. Read this before writing anything about a contact. A contact of another company is refused, crm_unknown_contact.',
input: z.object({ company_id: companyId, contact_id: contactId }),
async run(backend, args) {
return inSchema('crm', () => crmCard(backend, {
company_id: args['company_id'],
contact_id: args['contact_id'],
}));
},
},
{
verb: 'contact_vcard',
title: 'One contact, as a vCard',
effect: 'read',
description: 'One contact as the text of a vCard 3.0 (media_type text/vcard), for an address book: its name as the books hold it, its organisation, the job title and profile URL of its card, its e-mail, telephone, address and note. Hand the text over as a .vcf file when the user wants the contact in their address book; nothing is written. A contact of another company is refused, crm_unknown_contact.',
input: z.object({ company_id: companyId, contact_id: contactId }),
async run(backend, args) {
return inSchema('crm', () => crmContactVcard(backend, {
company_id: args['company_id'],
contact_id: args['contact_id'],
}));
},
},
{
verb: 'segments',
title: 'The segments',
effect: 'read',
description: 'Every segment of the company as a tree — a taxonomy branch, a target segment, a cohort, a brand — each with its parent, its depth, the path of slugs from its root, and how many contacts are in it now (one who left is not counted). A parent comes just before its children. Start here for crm_join_segment, crm_leave_segment or a search by segment.',
input: z.object({ company_id: companyId }),
async run(backend, args) {
return inSchema('crm', () => crmSegments(backend, { company_id: args['company_id'] }));
},
},
{
verb: 'board',
title: 'A pipeline, stage by stage',
effect: 'read',
description: 'A pipeline as a board: its stages in order — each open, won or lost — the deals at each stage with their contact, amount, currency, expected date, owner and the documents they carry with their quote_status, how many there are, and the sum of the amounts by currency, for each stage and for the pipeline. Amounts are never added across currencies. Without pipeline_id, every pipeline of the company: that is where the pipeline and stage ids for crm_open_deal and crm_move_deal come from. Open deals only, unless include_closed. A company starts with no pipeline: one is created by its users, not by this server.',
input: z.object({
company_id: companyId,
pipeline_id: uuid.optional().describe('One pipeline. Left out, all of them.'),
include_closed: z.boolean().optional().describe('Show the deals already won or lost too.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmBoard(backend, {
company_id: args['company_id'],
pipeline_id: args['pipeline_id'],
include_closed: args['include_closed'],
}));
},
},
{
verb: 'deal_of_document',
title: 'The deal a document belongs to',
effect: 'read',
description: 'The deal that carries a document — a quote, an order, an invoice — read from the document\'s side: { deal, available }. deal is its id, title, amount and currency, its stage (id, name, outcome: open, won or lost), closed_at and closed_outcome — the won deal of an accepted quote too, which crm_card no longer lists — or null when no deal carries the document. available is false, and deal null, on a database whose crm module has not received this read yet. A document of another company is refused, crm_unknown_document.',
input: z.object({
company_id: companyId,
document_id: uuid.describe('The document. list_documents gives its id.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmDealOfDocument(backend, {
company_id: args['company_id'],
document_id: args['document_id'],
}));
},
},
{
verb: 'timeline',
title: 'What happened',
effect: 'read',
description: 'The activities of one contact, or of one deal — notes, e-mails, calls, meetings, messages, signals, enrichments, tasks, and the moves the module wrote itself — most recent first. Name a contact, a deal, or both. since keeps what happened from that moment on; kinds keeps those kinds only, each one of ' +
words(CRM_ACTIVITY_KINDS) +
'.',
input: z.object({
company_id: companyId,
contact_id: contactId.optional(),
deal_id: uuid.optional().describe('A deal. crm_board or crm_card gives its id.'),
since: timestamp.optional(),
kinds: z.array(activityKind).min(1).optional().describe(`Only these kinds of activity, each one of ${words(CRM_ACTIVITY_KINDS)}.`),
limit: z.number().int().min(1).max(200).optional().describe('At most this many. 50 by default.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmTimeline(backend, {
company_id: args['company_id'],
contact_id: args['contact_id'],
deal_id: args['deal_id'],
since: args['since'],
kinds: args['kinds'],
limit: args['limit'],
}));
},
},
{
verb: 'upsert_card',
title: 'Write a card',
effect: 'additive',
idempotent: true,
description: 'Creates the card of a contact, or changes it: each key the patch names takes its value, every other field keeps its own. The keys are status (where the relationship stands: one of ' +
words(CRM_RELATIONSHIP_STATUSES) +
'), priority (one of ' +
words(CRM_PRIORITIES) +
'), owner (a handle — a member, a team, an agent — free text), job_title, linkedin_url, source (where the contact came from), tags (a list of words, replacing the list there), no_outbound (true: nobody may approach this contact — respect it everywhere) and custom (a JSON object of your own fields, replacing the one there). Any other key is refused, crm_unknown_field, with the list. Read crm_card first, and ask the user before changing a status, an owner or no_outbound they did not mention.',
input: z.object({
company_id: companyId,
contact_id: contactId,
patch: z
.record(z.string(), z.unknown())
.describe('The fields to set: status, priority, owner, job_title, linkedin_url, source, tags, no_outbound, custom.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmUpsertCard(backend, {
company_id: args['company_id'],
contact_id: args['contact_id'],
patch: args['patch'],
}));
},
},
{
verb: 'log_activity',
title: 'Log an activity',
effect: 'additive',
description: 'Writes one thing that happened with a contact — a note, an e-mail sent or received, a call, a meeting, a message, a signal read elsewhere, an enrichment, a task — optionally about one of the company\'s deals, and moves the card\'s last activity. kind is one of ' +
words(CRM_ACTIVITY_KINDS) +
'. When the activity was read from somewhere else, name source (the mailbox, the network, the calendar) and source_ref (its identifier there, a message-id): the same pair a second time writes nothing and returns the activity already kept, so an import can run twice. A source_ref without its source is refused, crm_bad_activity. Log what the user did or told you; never invent an exchange that did not happen.',
input: z.object({
company_id: companyId,
contact_id: contactId,
kind: activityKind.describe(`What happened: one of ${words(CRM_ACTIVITY_KINDS)}.`),
subject: z.string().optional(),
body: z.string().optional(),
deal_id: uuid.optional().describe('The deal it is about, of the same company.'),
actor: z.string().optional().describe('Who did it: a handle, free text.'),
occurred_at: timestamp.optional().describe('When it happened. Now when left out.'),
link: z.string().optional().describe('Where to read it: a URL.'),
payload: z.record(z.string(), z.unknown()).optional().describe('Anything else, as a JSON object.'),
source: z.string().optional().describe('Where it was read from.'),
source_ref: z.string().optional().describe('Its identifier at that source. Needs source.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmLogActivity(backend, {
company_id: args['company_id'],
contact_id: args['contact_id'],
kind: args['kind'],
subject: args['subject'],
body: args['body'],
deal_id: args['deal_id'],
actor: args['actor'],
occurred_at: args['occurred_at'],
link: args['link'],
payload: args['payload'],
source: args['source'],
source_ref: args['source_ref'],
}));
},
},
{
verb: 'join_segment',
title: 'Put a contact in a segment',
effect: 'additive',
idempotent: true,
description: 'Puts a contact in a segment of the company, or back in it: a contact who had left is in again, with the same membership. added_by is who did it, a handle; note is why. A segment of another company is refused, crm_unknown_segment.',
input: z.object({
company_id: companyId,
segment_id: segmentId,
contact_id: contactId,
added_by: z.string().optional(),
note: z.string().optional(),
}),
async run(backend, args) {
return inSchema('crm', () => crmJoinSegment(backend, {
company_id: args['company_id'],
segment_id: args['segment_id'],
contact_id: args['contact_id'],
added_by: args['added_by'],
note: args['note'],
}));
},
},
{
verb: 'leave_segment',
title: 'Take a contact out of a segment',
effect: 'additive',
description: 'Takes a contact out of a segment. The membership is kept with the moment it ended, so the history stays readable and crm_join_segment can put the contact back. A contact that was never in the segment is refused, crm_not_a_member.',
input: z.object({ company_id: companyId, segment_id: segmentId, contact_id: contactId }),
async run(backend, args) {
return inSchema('crm', () => crmLeaveSegment(backend, {
company_id: args['company_id'],
segment_id: args['segment_id'],
contact_id: args['contact_id'],
}));
},
},
{
verb: 'open_deal',
title: 'Open a deal',
effect: 'additive',
description: 'Opens a piece of business with one contact in one pipeline, at the first open stage of that pipeline. An amount is always in a currency: name currency_code (ISO 4217), or the company\'s own currency is taken. Nothing is written to the books. A pipeline of another company is refused, crm_unknown_pipeline; one with no open stage, crm_pipeline_without_open_stage. Ask the user before opening a deal they did not ask for.',
input: z.object({
company_id: companyId,
pipeline_id: uuid.describe('The pipeline. crm_board without pipeline_id lists them.'),
contact_id: contactId.describe('Who the business is with: a person or an organisation. The organisation becomes the customer if it is won.'),
title: z.string().min(1),
amount: z.union([z.string(), z.number()]).optional().describe('What it is worth, excluding tax.'),
currency_code: z.string().length(3).optional().describe('ISO 4217. The company\'s currency when left out.'),
expected_on: isoDate.optional().describe('When it is expected to close.'),
external_url: z.string().optional().describe('Where else it is followed: a URL.'),
owner: z.string().optional().describe('Who works it: a handle.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmOpenDeal(backend, {
company_id: args['company_id'],
pipeline_id: args['pipeline_id'],
contact_id: args['contact_id'],
title: args['title'],
amount: args['amount'],
currency_code: args['currency_code'],
expected_on: args['expected_on'],
external_url: args['external_url'],
owner: args['owner'],
}));
},
},
{
verb: 'move_deal',
title: 'Move a deal',
effect: 'additive',
idempotent: true,
description: 'Moves a deal to another stage of its own pipeline and logs the move as an activity. A won stage closes the deal and makes its party a customer — the organisation at the root of the contact\'s chain: a prospect becomes customer, a supplier becomes both — which also needs the right to write contacts; a lost stage closes it too; going back to an open stage opens it again. The same stage again changes nothing. A stage of another pipeline is refused, crm_stage_not_in_pipeline. Confirm with the user before moving a deal to won or lost.',
input: z.object({
company_id: companyId,
deal_id: uuid.describe('The deal. crm_board or crm_card gives its id.'),
stage_id: uuid.describe('The stage to move it to, of the same pipeline. crm_board lists them.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmMoveDeal(backend, {
company_id: args['company_id'],
deal_id: args['deal_id'],
stage_id: args['stage_id'],
}));
},
},
{
verb: 'attach_document',
title: 'Attach a quote to a deal',
effect: 'additive',
idempotent: true,
description: 'Attaches a document of the company — a sale quote, a purchase order, an invoice — to a deal of the same company; a deal carries several (versions, phases), a document one deal at most (crm_document_in_another_deal otherwise). From then on the answer recorded on a quote moves the deal, in the database and with no further call: accept_document wins it and makes its party a customer; decline_document loses it once no other quote of the deal is alive (neither declined nor expired); undo_document_answer opens it again. An answer recorded before attaching moves nothing. crm_card and crm_board show each deal\'s documents with their quote_status.',
input: z.object({
company_id: companyId,
deal_id: uuid.describe('The deal. crm_board or crm_card gives its id.'),
document_id: uuid.describe('The document, of the same company. list_documents gives its id.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmAttachDocument(backend, {
company_id: args['company_id'],
deal_id: args['deal_id'],
document_id: args['document_id'],
}));
},
},
{
verb: 'detach_document',
title: 'Take a document off its deal',
effect: 'destructive',
description: 'Takes a document off the deal that carries it; the deal stays at its stage. Refused for a document no deal carries, crm_document_not_attached. Ask the user first.',
input: z.object({
company_id: companyId,
document_id: uuid.describe('The document to take off its deal.'),
}),
async run(backend, args) {
return inSchema('crm', () => crmDetachDocument(backend, {
company_id: args['company_id'],
document_id: args['document_id'],
}));
},
},
],
prompts: [
{
name: 'morning_review',
title: 'Where the relationships stand this morning',
description: 'The relationships that went quiet, the deals past their expected date, and what to suggest to the user — with nothing written without asking.',
args: {
company_id: 'The company.',
quiet_days: 'How many days without an activity make a relationship quiet. 14 if left empty.',
},
text: ({ company_id, quiet_days }) => {
const days = /^\d+$/.test(quiet_days ?? '') ? Number(quiet_days) : 14;
return [
`Review the customer relationships of company ${company_id} for this morning. Work through this in order and report what you find; write nothing without asking.`,
'',
`1. crm_search with inactive_since set to ${days} days before today: the cards on which nothing has happened for ${days} days or more. Leave out the ones with no_outbound. Group them by status and by owner.`,
'2. crm_board without pipeline_id: every open deal whose expected_on is already past, with its stage, its contact and its amount in its currency. Never add amounts of two currencies together.',
'3. For the three that matter most — a high priority, a large amount, a deal at a late stage — read crm_card and crm_timeline, and say in one sentence what last happened.',
'',
'Finish with what you suggest, one line each: who to get back to and why, which deal to move or to close, which card to mark dormant. Each suggestion is a question for the user. Only once they agree, write it with crm_log_activity, crm_upsert_card or crm_move_deal — and never write a contact no_outbound forbids approaching.',
].join('\n');
},
},
],
};
// ---------------------------------------------------------------------------
// contracts — module code `contracts`, schema `contracts`
//
// Every tool is one function of the schema, called through the core — the
// same function `ekwo contracts …` calls. The kinds, states and rhythms a
// model may name are the schema's enums, as the core lists them, and the
// refusals of the module (`contracts_<code>: …`) travel up word for word.
// ---------------------------------------------------------------------------
const contractId = uuid.describe('The contract. contracts_list finds it.');
const contractDirection = z.enum(CONTRACT_DIRECTIONS);
const contractKind = z.enum(CONTRACT_KINDS);
const CONTRACTS = {
code: 'contracts',
prefix: 'contracts',
schema: 'contracts',
tools: [
{
verb: 'list',
title: 'The contracts',
effect: 'read',
description: 'The contracts of the company, each with its party, its kind, its side (sale: the company invoices; purchase: it is invoiced), its state, its dates, its currency and value, and its nearest deadline. Filtered by state (one of ' +
words(CONTRACT_STATES) +
'), side, party, or a text found in the number, the name or the party\'s name; every filter optional. templates: true also lists the active templates a contract can be made from, for contracts_from_template.',
input: z.object({
company_id: companyId,
state: z.enum(CONTRACT_STATES).optional(),
direction: contractDirection.optional().describe('sale or purchase.'),
contact_id: uuid.optional().describe('The party. search_contacts finds it.'),
query: z.string().optional().describe('A text found in the number, the name or the party\'s name.'),
limit: z.number().int().min(1).max(200).optional().describe('At most this many. 50 by default.'),
templates: z.boolean().optional().describe('Also list the templates of the company.'),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsList(backend, {
company_id: args['company_id'],
state: args['state'],
direction: args['direction'],
contact_id: args['contact_id'],
query: args['query'],
limit: args['limit'],
templates: args['templates'],
}));
},
},
{
verb: 'card',
title: 'One contract, whole',
effect: 'read',
description: 'Everything on one contract in one object: the contract, its party, its signed file with its checksum, its schedules, its history — versions, amendments, tacit renewals — the latest documents it issued with their number, state and total, and its deadlines. Read this before changing a contract or issuing from it.',
input: z.object({ company_id: companyId, contract_id: contractId }),
async run(backend, args) {
return inSchema('contracts', () => contractsCard(backend, {
company_id: args['company_id'],
contract_id: args['contract_id'],
}));
},
},
{
verb: 'upsert',
title: 'Write a contract',
effect: 'additive',
idempotent: true,
description: 'Creates the contract of that number, or changes it: each key the patch names takes its value, every other field keeps its own. The keys are ' +
words(CONTRACT_FIELDS) +
'. A new contract needs contact_id, name, kind (one of ' +
words(CONTRACT_KINDS) +
') and direction (sale or purchase); its currency is the company\'s unless currency_code (ISO 4217) is named. renewal is one of ' +
words(CONTRACT_RENEWALS) +
'; a tacit one needs starts_on and ends_on. A state only moves forward (' +
words(CONTRACT_STATES) +
') and the last three are final. Dates are YYYY-MM-DD, amounts decimal strings. Any other key is refused, contracts_unknown_field. Ask the user before writing a contract they did not describe, and before moving its state.',
input: z.object({
company_id: companyId,
number: z.string().min(1).describe('The company\'s own reference for the contract, unique in the company.'),
patch: z.record(z.string(), z.unknown()).describe(`The fields to set: ${words(CONTRACT_FIELDS)}.`),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsUpsert(backend, {
company_id: args['company_id'],
number: args['number'],
patch: args['patch'],
}));
},
},
{
verb: 'schedule',
title: 'Write a schedule',
effect: 'additive',
description: 'Adds a line a contract invoices at its own rhythm, or changes one (schedule_id). The keys are ' +
words(CONTRACT_SCHEDULE_FIELDS) +
'. frequency is one of ' +
words(CONTRACT_FREQUENCIES) +
'; next_on is the first day of the next period to issue; until the last day a period may start. The tax is named by its code in the company\'s list (list_accounts and describe_pack give them), never by a rate. A schedule from a product (product_code) takes the product\'s name, unit, price and tax where the patch gives none. indexation is a JSON object kept as data: index, formula, base, base_on, next_on. auto_post: true books every document it issues, which needs the right to post. Ask the user before setting auto_post.',
input: z.object({
company_id: companyId,
contract_id: contractId,
schedule_id: uuid.optional().describe('The schedule to change. Left out, a new one is added.'),
patch: z.record(z.string(), z.unknown()).describe(`The fields to set: ${words(CONTRACT_SCHEDULE_FIELDS)}.`),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsSchedule(backend, {
company_id: args['company_id'],
contract_id: args['contract_id'],
schedule_id: args['schedule_id'],
patch: args['patch'],
}));
},
},
{
verb: 'issue_due',
title: 'Issue what is due',
effect: 'destructive',
idempotent: true,
description: 'Issues every period that has come on that day: for each schedule of a signed or active contract whose next_on is on or before it, one draft document per period — a sales invoice on a sale, a purchase invoice on a purchase — to the contract\'s party, contract_reference set to its number, and next_on moved on. Renewals and expiries come first. Twice for the same day issues once: the socle refuses a second document for one period. Drafts stay drafts unless the schedule says auto_post. Show the user what is due first (contracts_deadlines, kinds next_issue) and issue only once they agree; then show the drafts before anything is posted.',
input: z.object({
company_id: companyId,
on_date: isoDate.describe('The day: every period starting on or before it is issued.'),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsIssueDue(backend, {
company_id: args['company_id'],
on_date: args['on_date'],
}));
},
},
{
verb: 'deadlines',
title: 'What the contracts ask, and when',
effect: 'read',
description: 'Every date a running contract asks somebody to act on, soonest first: notice (the last day notice can be given before the next term, or before the end), renewal, end, next_issue (the next period a schedule issues) and indexation (when a price is due to be indexed). Filtered by a window of days, a contract, or kinds, each one of ' +
words(CONTRACT_DEADLINE_KINDS) +
'. A notice date is a reading of what was recorded: say so, and let the user and their counsel decide.',
input: z.object({
company_id: companyId,
from: isoDate.optional().describe('On or after this day.'),
to: isoDate.optional().describe('On or before this day.'),
contract_id: contractId.optional(),
kinds: z.array(z.enum(CONTRACT_DEADLINE_KINDS)).min(1).optional(),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsDeadlines(backend, {
company_id: args['company_id'],
from: args['from'],
to: args['to'],
contract_id: args['contract_id'],
kinds: args['kinds'],
}));
},
},
{
verb: 'amend',
title: 'Record an amendment',
effect: 'additive',
description: 'Records what changes in a contract and from when, numbered next in its history, with the signed file (attachment_id) and the day it was signed. kind amendment applies its changes now: the fields of the contract by name, and under "schedules" the fields of each schedule, by id — a new unit_price after an indexation, for instance. kind version records another text of the contract with its file and changes nothing. A renewal is written by the module itself on its day. Kinds: ' +
words(CONTRACT_AMENDMENT_KINDS.filter((kind) => kind !== 'renewal')) +
'. Confirm the changes with the user before recording them.',
input: z.object({
company_id: companyId,
contract_id: contractId,
summary: z.string().min(1).describe('What changes, in words.'),
effective_on: isoDate.describe('From when it holds.'),
changes: z.record(z.string(), z.unknown()).optional().describe('The fields that change, and "schedules": {"<id>": {…}}.'),
kind: z.enum(['version', 'amendment']).optional().describe('amendment by default.'),
signed_on: isoDate.optional(),
attachment_id: uuid.optional().describe('The signed file, an attachment of the company.'),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsAmend(backend, {
company_id: args['company_id'],
contract_id: args['contract_id'],
summary: args['summary'],
effective_on: args['effective_on'],
changes: args['changes'],
kind: args['kind'],
signed_on: args['signed_on'],
attachment_id: args['attachment_id'],
}));
},
},
{
verb: 'from_template',
title: 'A contract from a template',
effect: 'additive',
description: 'Makes a draft contract of one of the company\'s templates (contracts_list with templates: true lists them): the number, party, side and kind given, starting on starts_on, the values of the template\'s variables kept on the contract — a required one left empty is refused, contracts_missing_variable — and the template\'s schedule copied, starting on starts_on. Answers the contract, its schedules, and the clauses: the html with the values in place, or the docx file to fill. Nothing is sent or signed. Ask the user for every value rather than inventing one.',
input: z.object({
company_id: companyId,
template_id: uuid.describe('The template. contracts_list with templates: true lists them.'),
contact_id: uuid.describe('The other party.'),
number: z.string().min(1),
direction: contractDirection,
kind: contractKind,
starts_on: isoDate,
values: z.record(z.string(), z.string()).optional().describe('The value of each variable, by its key.'),
name: z.string().optional().describe('The name of the contract. The template\'s when left out.'),
}),
async run(backend, args) {
return inSchema('contracts', () => contractsFromTemplate(backend, {
company_id: args['company_id'],
template_id: args['template_id'],
contact_id: args['contact_id'],
number: args['number'],
direction: args['direction'],
kind: args['kind'],
starts_on: args['starts_on'],
values: args['values'],
name: args['name'],
}));
},
},
],
};
/** Every module this release knows how to expose, by module code. */
export const MODULE_TOOLSETS = [FIXED_ASSETS, BUDGETS, EINVOICING, TAX, CRM, CONTRACTS];
/** The toolsets for a set of installed module codes, in a fixed order. */
export function toolsetsFor(installed) {
const wanted = new Set(installed);
return MODULE_TOOLSETS.filter((toolset) => wanted.has(toolset.code));
}
/**
* Which modules this installation carries.
*
* `public.modules` is the registry, and it is readable by anyone signed in —
* it says what exists here, not what any company holds. A database that
* predates the module framework has no such table, and the answer is then no
* modules rather than an error.
*/
export async function installedModules(backend) {
try {
const rows = await backend.select({
table: 'modules',
columns: ['code', 'status'],
order: [{ column: 'code' }],
});
return rows.filter((row) => row.status !== 'draft').map((row) => row.code);
}
catch {
return [];
}
}
//# sourceMappingURL=modules.js.map