@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,019 lines • 62.2 kB
JavaScript
/**
* The writing half.
*
* One rule holds everywhere here: the ledger is written by the schema, never
* by this package. `post_document`, `post_payment`, `post_entry`, `reconcile`
* and `unreconcile` carry the accounting rules — balance, numbering, period
* locks, the counterpart that is the difference of everything else — and this
* server calls them. Nothing in this file inserts an `entries` or an
* `entry_lines` row. Direct inserts are for the objects a person types:
* contacts, draft documents and their lines, payments, bank transactions.
*
* The second rule is that a refusal from the database is the answer. A
* `period_locked:` raise is not an error to be worked around by moving a
* date; it is the company telling the agent that the month is closed.
*/
import { z } from 'zod';
import { EkwoMcpError } from '../backend.js';
import { AGENT_POSTING, DOC_TYPES, KEY_POSTING, STATEMENT_FORMATS, amountIn, bankAccountScheme, columns, companyBankAccountScheme, companyCurrency, createApiKey as issueKey, idsByCode, importStatementFile, setBankAccountStatementProfile, moneyFields, only, } from '@ekwo-ai/core';
import { companyId, isoDate, uuid } from './read.js';
export * from './import-books.js';
// What a contact, a document, a payment and a matching are written with moved
// to the core, where the command line calls the same functions. The inputs a
// model fills in stay here, beside their descriptions; the functions are
// exported from here under the names they always had.
export { acceptDocument, cancelDocument, closeFiscalYear, closeFiscalYearFinally, createContact, createDocument, declineDocument, leaveLineUnnamed, lockPeriod, mergeContacts, postDocument, reconcile, reconcileMany, reconcileWithDifference, recordPayment, reopenFiscalYear, reverseEntry, setLineContact, settleFromStatement, undoDocument, undoDocumentAnswer, undoLeaveLineUnnamed, unreconcile, updateDocumentLines, } from '@ekwo-ai/core';
// ---------------------------------------------------------------------------
// Contacts
// ---------------------------------------------------------------------------
export const CreateContactInput = z.object({
company_id: companyId,
name: z.string().min(1),
contact_type: z.enum(['customer', 'supplier', 'both', 'employee', 'other']),
vat_number: z.string().min(1).optional(),
registration_number: z.string().min(1).optional().describe('The number of the commercial register of its country.'),
identifiers: z
.record(z.string().min(1), z.string().min(1))
.optional()
.describe("Every identifier with no column of its own, by the code of its scheme — {\"<scheme>\": \"<identifier>\"}. The schemes a country's e-invoice reads are on its set-up page and in describe_pack."),
email: z.string().min(1).optional(),
phone: z.string().min(1).optional().describe('As the party writes it, international form where the e-invoice of its country asks for one.'),
country: z.string().length(2).optional().describe('ISO country code, e.g. BE.'),
payment_terms_days: z.number().int().min(0).max(365).optional(),
auxiliary_code: z.string().min(1).optional().describe('Sub-ledger code; the French FEC reports it.'),
address_line1: z.string().min(1).optional(),
postal_code: z.string().min(1).optional(),
city: z.string().min(1).optional(),
client_ref: z.string().min(1).max(200).optional().describe('Your own reference for this creation. Calling again with the same one returns what was created the first time (`replayed: true`) instead of creating a second — use it whenever a call might be repeated after a timeout.'),
});
export const MergeContactsInput = z.object({
keep_contact_id: uuid.describe('The contact that stays and takes the history of the other — the one the user chose to keep, as search_contacts returns it.'),
absorb_contact_id: uuid.describe('The duplicate the user chose to retire: everything naming it will name the kept contact. A contact of the same company.'),
});
// ---------------------------------------------------------------------------
// The working chart
// ---------------------------------------------------------------------------
export const PinAccountsInput = z.object({
company_id: companyId,
account_codes: z
.array(z.string().min(1))
.min(1)
.describe('Codes in this company\'s chart. list_accounts with include_all says what exists.'),
pinned: z
.boolean()
.optional()
.describe('True pins, false unpins. Defaults to true.'),
});
export async function pinAccounts(backend, args) {
const pinned = args.pinned ?? true;
const ids = await idsByCode(backend, 'accounts', args.company_id, args.account_codes);
const updated = await backend.update('accounts', { pinned }, [
{ column: 'company_id', op: 'eq', value: args.company_id },
{ column: 'id', op: 'in', value: [...ids.values()] },
], ['code', 'name', 'pinned']);
if (updated.length === 0) {
throw new EkwoMcpError('not_found: none of those accounts could be changed. Either they are not in this company, or your role on it does not allow writing its chart.');
}
return { accounts: updated, pinned, count: updated.length };
}
// ---------------------------------------------------------------------------
// Products
// ---------------------------------------------------------------------------
const UNIT_CODE = z
.string()
.min(1)
.max(3)
.describe('UN/ECE recommendation 20: C62 a piece, HUR an hour, DAY a day, MON a month, KGM, LTR, MTR, KWH. Defaults to C62.');
export const CreateProductInput = z.object({
company_id: companyId,
code: z.string().min(1).describe("Your own reference for the item. Unique in the company, and what EN 16931 calls the seller's item identifier (BT-155)."),
name: z.string().min(1).describe('What appears on the invoice line (BT-153).'),
description: z.string().min(1).optional().describe('The longer text under the name (BT-154).'),
kind: z.enum(['service', 'goods']).optional().describe('Defaults to service. Goods and services are not taxed alike and do not feed the same declaration boxes.'),
unit_code: UNIT_CODE.optional(),
currency_code: z.string().length(3).optional(),
sale_price: z.union([z.string(), z.number()]).optional().describe('Net unit price on a sale. A line may still carry another.'),
purchase_price: z.union([z.string(), z.number()]).optional(),
sale_account_id: uuid.optional(),
sale_account_code: z.string().min(1).optional().describe('Income account a sale of this books to.'),
purchase_account_id: uuid.optional(),
purchase_account_code: z.string().min(1).optional().describe('Expense account a purchase of this books to.'),
sale_tax_id: uuid.optional(),
sale_tax_code: z.string().min(1).optional().describe('Tax applied when it is sold, by code.'),
purchase_tax_id: uuid.optional(),
purchase_tax_code: z.string().min(1).optional(),
attributes: z
.record(z.string().min(1), z.string().min(1))
.optional()
.describe('What the electronic invoice format of the country asks of a line selling this item that no other field says, by the name its brick reads — describe_pack lists them (line_attributes). A line filled in from the product takes the names it does not give itself.'),
});
/** Turns the four `*_code` arguments into ids, in one query per table. */
async function productReferences(backend, company, args) {
const [accounts, taxes] = await Promise.all([
idsByCode(backend, 'accounts', company, [args.sale_account_code, args.purchase_account_code].filter((c) => typeof c === 'string')),
idsByCode(backend, 'taxes', company, [args.sale_tax_code, args.purchase_tax_code].filter((c) => typeof c === 'string')),
]);
return { accounts, taxes };
}
export async function createProduct(backend, args) {
const { accounts, taxes } = await productReferences(backend, args.company_id, args);
const currency = args.currency_code ?? (await companyCurrency(backend, args.company_id));
const created = only(await backend.insert('products', [
{
company_id: args.company_id,
code: args.code.trim(),
name: args.name,
description: args.description ?? null,
kind: args.kind ?? 'service',
unit_code: (args.unit_code ?? 'C62').toUpperCase(),
currency_code: currency,
sale_price: args.sale_price === undefined ? null : amountIn(args.sale_price),
purchase_price: args.purchase_price === undefined ? null : amountIn(args.purchase_price),
sale_account_id: args.sale_account_id ?? (args.sale_account_code === undefined ? null : accounts.get(args.sale_account_code)),
purchase_account_id: args.purchase_account_id ??
(args.purchase_account_code === undefined ? null : accounts.get(args.purchase_account_code)),
sale_tax_id: args.sale_tax_id ?? (args.sale_tax_code === undefined ? null : taxes.get(args.sale_tax_code)),
purchase_tax_id: args.purchase_tax_id ?? (args.purchase_tax_code === undefined ? null : taxes.get(args.purchase_tax_code)),
attributes: args.attributes ?? {},
},
], columns.PRODUCT), 'the product could not be created');
return {
product: created,
note: 'A product fills a line in and never constrains it: create_document takes product_code, and anything the line carries wins over it.',
};
}
export const UpdateProductInput = z.object({
product_id: uuid.optional(),
company_id: companyId.optional().describe('Needed with product_code, to say which company the code belongs to.'),
product_code: z.string().min(1).optional().describe('Instead of product_id, with company_id.'),
code: z.string().min(1).optional().describe('A new reference for it.'),
name: z.string().min(1).optional(),
description: z.string().nullable().optional(),
kind: z.enum(['service', 'goods']).optional(),
unit_code: UNIT_CODE.optional(),
sale_price: z.union([z.string(), z.number()]).nullable().optional(),
purchase_price: z.union([z.string(), z.number()]).nullable().optional(),
sale_account_code: z.string().min(1).optional(),
purchase_account_code: z.string().min(1).optional(),
sale_tax_code: z.string().min(1).optional(),
purchase_tax_code: z.string().min(1).optional(),
active: z.boolean().optional().describe('False retires it: searches stop offering it and the lines that already carry it are untouched.'),
attributes: z
.record(z.string().min(1), z.string().min(1))
.optional()
.describe('The whole new set of attributes, replacing what is there; {} clears them. Lines already written keep theirs.'),
});
/**
* Changes a product. What it does not do is reach into the documents that
* already reference it: a line keeps the text, the price and the account it
* was invoiced with, because an invoice is a statement about a day and a
* catalogue edited afterwards must not be able to rewrite it.
*/
export async function updateProduct(backend, args) {
const where = args.product_id !== undefined
? [{ column: 'id', op: 'eq', value: args.product_id }]
: [
{ column: 'company_id', op: 'eq', value: args.company_id ?? '' },
{ column: 'code', op: 'eq', value: args.product_code ?? '' },
];
if (args.product_id === undefined && (args.company_id === undefined || args.product_code === undefined)) {
throw new EkwoMcpError('missing_product: give product_id, or company_id together with product_code.');
}
const existing = only(await backend.select({ table: 'products', columns: columns.PRODUCT, where }), args.product_id === undefined ? `product "${String(args.product_code)}"` : `product ${args.product_id}`);
const company = existing['company_id'];
const { accounts, taxes } = await productReferences(backend, company, args);
const patch = {};
if (args.code !== undefined)
patch['code'] = args.code.trim();
if (args.name !== undefined)
patch['name'] = args.name;
if (args.description !== undefined)
patch['description'] = args.description;
if (args.kind !== undefined)
patch['kind'] = args.kind;
if (args.unit_code !== undefined)
patch['unit_code'] = args.unit_code.toUpperCase();
if (args.sale_price !== undefined) {
patch['sale_price'] = args.sale_price === null ? null : amountIn(args.sale_price);
}
if (args.purchase_price !== undefined) {
patch['purchase_price'] = args.purchase_price === null ? null : amountIn(args.purchase_price);
}
if (args.sale_account_code !== undefined)
patch['sale_account_id'] = accounts.get(args.sale_account_code);
if (args.purchase_account_code !== undefined) {
patch['purchase_account_id'] = accounts.get(args.purchase_account_code);
}
if (args.sale_tax_code !== undefined)
patch['sale_tax_id'] = taxes.get(args.sale_tax_code);
if (args.purchase_tax_code !== undefined)
patch['purchase_tax_id'] = taxes.get(args.purchase_tax_code);
if (args.active !== undefined)
patch['active'] = args.active;
if (args.attributes !== undefined)
patch['attributes'] = args.attributes;
if (Object.keys(patch).length === 0) {
throw new EkwoMcpError('nothing_to_update: give at least one field to change.');
}
const updated = only(await backend.update('products', patch, [{ column: 'id', op: 'eq', value: existing['id'] }], columns.PRODUCT), 'the product could not be updated, and your role on that company may be the reason');
return {
product: updated,
note: 'Documents already booked are untouched: a line keeps the text, the price and the account it was invoiced with.',
};
}
// ---------------------------------------------------------------------------
// Documents
// ---------------------------------------------------------------------------
const LineInput = z.object({
name: z.string().min(1).optional().describe('What is billed, as it appears on the invoice. Required unless a product supplies it.'),
description: z.string().min(1).optional().describe('EN 16931 BT-154, under the name. A product supplies it when the line does not.'),
quantity: z.union([z.string(), z.number()]).optional().describe('Defaults to 1.'),
unit_code: z.string().min(1).max(3).optional().describe('Unit of measure, UN/ECE rec. 20: C62 a piece, HUR an hour, DAY a day, KGM, LTR, MTR. From the product, then C62.'),
unit_price: z.union([z.string(), z.number()]).optional().describe("Price of one unit, excluding tax, as a decimal string. Left out, the product's price; without either, the line is refused."),
discount_percent: z.union([z.string(), z.number()]).optional().describe('A percentage off this line, 0 to 99.'),
product_id: uuid.optional(),
product_code: z.string().min(1).optional().describe('A catalogue row, by code. It fills in the text, the price, the unit, the account and the tax; anything given on the line wins.'),
account_id: uuid.optional(),
account_code: z.string().min(1).optional().describe('The income or expense account, by code. Left out: the product, then the company default, then the one its country model names. A company with none of them refuses the line.'),
tax_id: uuid.optional(),
tax_code: z.string().min(1).optional().describe('The tax, by code, e.g. BE-S-21. Left out, the tax of the product. With no product either, the line books a base with no VAT box, which is not the same as 0 %.'),
attributes: z
.record(z.string().min(1), z.string().min(1))
.optional()
.describe('What the electronic invoice format of the country asks of this line that no other field says, by the name its brick reads — describe_pack lists the names its format reads (line_attributes, tax_attributes). The product fills in the names the line leaves out; the line wins over the pack.'),
});
export const CreateDocumentInput = z.object({
company_id: companyId,
doc_type: z.enum(DOC_TYPES),
contact_id: uuid,
document_date: isoDate,
due_date: isoDate.optional(),
accounting_date: isoDate.optional().describe('The date the entry is booked on, when it differs from the document date.'),
number: z.string().min(1).optional().describe('Your own number. Left out, posting takes the entry number.'),
supplier_reference: z.string().min(1).optional().describe("The supplier's own invoice number, on a purchase."),
currency_code: z.string().length(3).optional(),
journal_id: uuid.optional(),
payment_reference: z.string().min(1).optional(),
client_ref: z.string().min(1).max(200).optional().describe('Your own reference for this creation. Calling again with the same one returns what was created the first time (`replayed: true`) instead of creating a second — use it whenever a call might be repeated after a timeout.'),
lines: z.array(LineInput).min(1),
});
export const UpdateDocumentLinesInput = z.object({
document_id: uuid,
lines: z.array(LineInput).min(1).describe('The complete new set of lines; what is there now is replaced.'),
});
export const PostDocumentInput = z.object({
document_id: uuid,
dry_run: z
.boolean()
.optional()
.describe('True: the database posts for real and takes it back, and the entry it would have written is returned. Nothing is written; a refusal is the one posting would give.'),
});
const answeredAt = z
.string()
.min(10)
.optional()
.describe('When the other party answered: an ISO date or timestamp, as the user says it. Left out: now. Never in the future (answer_in_the_future).');
export const AcceptDocumentInput = z.object({
document_id: uuid.describe('The sale quote or purchase order the other party accepted.'),
accepted_by: z
.string()
.min(1)
.max(200)
.optional()
.describe('Who accepted it, in the user\'s words: a name, a role, the reference of a signed copy.'),
at: answeredAt,
});
export const DeclineDocumentInput = z.object({
document_id: uuid.describe('The sale quote or purchase order the other party declined.'),
at: answeredAt,
});
export const UndoDocumentAnswerInput = z.object({
document_id: uuid.describe('The sale quote or purchase order whose answer was recorded by mistake.'),
});
export const CancelDocumentInput = z.object({
document_id: uuid.describe('The posted sale or purchase invoice to undo.'),
date: isoDate
.optional()
.describe("The day a credit note is issued and booked on. Given, it asks for the credit note. Left out: the invoice's own booking day, and refused by name (reversal_date_needed) when that period is no longer open — then ask the user which open date to use; never pick one."),
credit_note: z
.boolean()
.optional()
.describe('True: undo it with a credit note even where it could go back to draft — the user wants the correction on the record.'),
});
// ---------------------------------------------------------------------------
// Undoing an entry
// ---------------------------------------------------------------------------
export const ReverseEntryInput = z.object({
entry_id: uuid.describe("The posted entry to undo. An entry a document wrote is undone with the document, by cancel_document."),
date: isoDate
.optional()
.describe("The day the reversal is booked on. Left out: the original entry's day, and refused by name (reversal_date_needed) when that period is no longer open — then ask the user which open date to use; never pick one."),
});
// ---------------------------------------------------------------------------
// Payments and matching
// ---------------------------------------------------------------------------
export const RecordPaymentInput = z.object({
company_id: companyId,
direction: z.enum(['inbound', 'outbound']).optional().describe('inbound: a customer paid you. outbound: you paid a supplier. May be left out when document_id is given.'),
amount: z.union([z.string(), z.number()]).describe('A positive decimal string; the direction carries the sign.'),
payment_date: isoDate,
contact_id: uuid.optional().describe('Who paid or was paid. Needed for the payment to be matched against their invoices.'),
journal_id: uuid.optional(),
journal_code: z.string().min(1).optional().describe('The bank or cash journal, by code, e.g. BNK. Not needed when bank_account_id is given: the account knows its journal.'),
bank_account_id: uuid
.optional()
.describe('Which bank account the money moved on. list_bank_accounts says what exists. Given alone, it also names the journal; left out, the default account of the journal is used.'),
reference: z.string().min(1).optional(),
memo: z.string().min(1).optional(),
currency_code: z.string().length(3).optional().describe('Left out: the currency the company keeps its books in.'),
exchange_rate: z.union([z.string(), z.number()]).optional().describe('Units of the payment currency for one unit of the company currency, as a rate table states it. Only needed when the payment is in another currency; the realised difference against the invoice is booked at matching.'),
document_id: uuid.optional().describe('The posted document this money pays. It names the contact and the direction, read off what is still open on it, and the matching is offered to that document alone rather than to the oldest open items.'),
client_ref: z.string().min(1).max(200).optional().describe('Your own reference for this creation. Calling again with the same one returns what was created the first time (`replayed: true`) instead of creating a second — use it whenever a call might be repeated after a timeout.'),
match_open_items: z.boolean().optional().describe('Default true: match the payment against the oldest open invoices of that contact, up to the amount paid.'),
});
export const ReconcileInput = z.object({
line_a: uuid.describe('A ledger line to match. Either side; the schema works out which is the debit.'),
line_b: uuid.describe('The line it settles. Both must be on the same reconcilable account.'),
amount: z.union([z.string(), z.number()]).optional().describe('Left out: the smaller of the two open amounts.'),
});
export const UnreconcileInput = z.object({
reconciliation_id: uuid.describe('The matching to undo, as returned by reconcile or read from the ledger line.'),
});
export const SetLineContactInput = z.object({
line_id: uuid.describe('The open ledger line on a receivable or payable account that names nobody, as suggest_line_contacts returns it.'),
contact_id: uuid.describe('The contact the user chose for it — one of the candidates, or one they created with create_contact. A contact of the same company.'),
});
const matchedLines = z
.array(uuid)
.min(2)
.describe('The ledger lines to match together, as suggest_item_combinations returns them: the line and the lines it settles. One counterparty, one account, at least one debit and one credit.');
export const ReconcileManyInput = z.object({
line_ids: matchedLines,
});
export const ReconcileWithDifferenceInput = z.object({
line_ids: matchedLines,
reason: z
.string()
.describe('Why the lines differ, as matching_difference_options lists it: rounding or exchange_difference. The user chooses it.'),
});
export const LeaveLineUnnamedInput = z.object({
line_id: uuid.describe('The open line on a receivable or payable account that names nobody, as suggest_line_contacts returns it.'),
reason: z.string().min(1).max(500).describe('Why the line names nobody, in the user\'s words.'),
});
export const UndoLeaveLineUnnamedInput = z.object({
line_id: uuid.describe('A line left unnamed by leave_line_unnamed.'),
});
const decimal = z.union([z.string(), z.number()]);
export const SettleFromStatementInput = z.object({
transaction_id: uuid.describe('The statement line, as list_bank_transactions returns it. It is settled once.'),
document_id: uuid.optional().describe('The posted document the line pays; its open items are what is settled.'),
document_ids: z.array(uuid).min(1).optional().describe('Several documents the one line pays, in the order amounts follows.'),
line_ids: z.array(uuid).min(1).optional().describe('Or the open items themselves, by ledger line.'),
amounts: z
.array(decimal)
.min(1)
.optional()
.describe('How much of the line settles each item — one per line_ids, or one per document — as decimal strings. Left out, the items are settled oldest first, and in full when there are extra_lines. Less than an item has open settles it in part, which is the user\'s decision, never yours.'),
extra_lines: z
.array(z.object({
account: z.string().min(1).describe('The account, by code: an expense for a fee or a charge, an income for a surplus. Never a customer or supplier account.'),
amount: decimal.describe('A decimal string. Positive is a charge (debited), negative a credit. With a tax, the tax is inside it.'),
tax: z.string().min(1).optional().describe('The tax the charge bears, by code, when the provider or the bank invoices it with one. Ask the user; do not choose.'),
description: z.string().min(1).optional(),
}).strict())
.optional()
.describe('Lines booked in the same entry beside the settlement: the fee a payment provider kept from a payout, the charges of a bank, a small difference. Money in is the items less these; money out the items plus these; to the cent, or settlement_unbalanced names the difference. Alone, with no document and no line, they settle a bank charge.'),
});
// ---------------------------------------------------------------------------
// Bank
// ---------------------------------------------------------------------------
export const CreateBankAccountInput = z.object({
company_id: companyId,
account_identifier: z
.string()
.min(1)
.optional()
.describe("What identifies the account at its bank, in the scheme of the company's country: an IBAN, an ABA routing number and an account number, a sort code and an account number, a BSB and an account number, an IFSC and an account number, a CLABE… `list_bank_accounts` and `describe_pack` say which. Separators are ignored and the value is stored in the canonical form of its scheme; it is the natural key of a bank account in a company. Where the country's pack declares no scheme, any account number as the bank wrote it."),
iban: z.string().min(5).optional().describe('Deprecated: an alias of account_identifier, accepted only where the country identifies accounts by IBAN.'),
label: z.string().min(1).optional().describe('What it is called in the books. Defaults to the bank name, then to the identifier.'),
bic: z.string().min(1).optional().describe('The bank identifier code, where the bank has one.'),
bank_name: z.string().min(1).optional(),
currency_code: z.string().length(3).optional().describe("Defaults to the company's own currency."),
journal_id: uuid.optional(),
journal_code: z.string().min(1).optional().describe('The financial journal it books through. Left out, the bank journal of the company.'),
account_id: uuid.optional(),
account_code: z.string().min(1).optional().describe("The ledger account behind it. Left out, the journal's default account, which the country template chose."),
});
/**
* A bank account, wired to a journal and to a ledger account.
*
* `create_bank_account()` of the schema does the work — reads the identifier
* in the scheme of the company's country, picks the bank journal and the
* ledger account the country template chose, refuses a name already taken —
* so this tool, a web application and a script calling the REST API take one
* road. What is left here is the deprecated `iban` alias, and the codes a
* model may give in place of ids.
*/
export async function createBankAccount(backend, args) {
if (args.iban !== undefined) {
const schemeKey = await companyBankAccountScheme(backend, args.company_id);
if (schemeKey !== 'iban') {
const scheme = bankAccountScheme(schemeKey);
throw new EkwoMcpError(`not_an_iban_country: banks in this company's country identify an account by its ${scheme?.label ?? schemeKey ?? 'account number'}, not by an IBAN. Give account_identifier.`);
}
}
let journalId = args.journal_id;
if (journalId === undefined && args.journal_code !== undefined) {
journalId = (await idsByCode(backend, 'journals', args.company_id, [args.journal_code])).get(args.journal_code);
}
let accountId = args.account_id;
if (accountId === undefined && args.account_code !== undefined) {
accountId = (await idsByCode(backend, 'accounts', args.company_id, [args.account_code])).get(args.account_code);
}
const answer = only(await backend.rpc('create_bank_account', {
p_company_id: args.company_id,
p_account_identifier: args.account_identifier ?? args.iban ?? null,
p_name: args.label ?? null,
p_bank_name: args.bank_name ?? null,
p_bic: args.bic ?? null,
p_currency_code: args.currency_code ?? null,
p_journal_id: journalId ?? null,
p_account_id: accountId ?? null,
}), 'the bank account could not be created');
const account = answer['bank_account'];
const created = answer['created'] === true;
return {
bank_account: Object.fromEntries(columns.BANK_ACCOUNT.map((column) => [column, account[column] ?? null])),
created,
journal: answer['journal'],
note: created
? 'Payments through this journal now book against this account. record_payment takes its id as bank_account_id.'
: 'A bank account with this identifier was already there; nothing was created.',
};
}
export const CreateBankTransactionInput = z.object({
company_id: companyId,
bank_account_id: uuid,
transaction_date: isoDate,
amount: z.union([z.string(), z.number()]).describe('Signed: positive is money in, negative is money out.'),
description: z.string().min(1).optional(),
counterpart_name: z.string().min(1).optional(),
counterpart_iban: z.string().min(1).optional(),
reference: z.string().min(1).optional(),
structured_reference: z.string().min(1).optional().describe('A structured communication, e.g. +++000/0000/00000+++ or RF…'),
statement_id: uuid.optional(),
contact_id: uuid.optional(),
value_date: isoDate.optional(),
});
export async function createBankTransaction(backend, args) {
const created = only(await backend.insert('bank_transactions', [
{
company_id: args.company_id,
bank_account_id: args.bank_account_id,
statement_id: args.statement_id ?? null,
transaction_date: args.transaction_date,
value_date: args.value_date ?? null,
amount: amountIn(args.amount),
description: args.description ?? null,
counterpart_name: args.counterpart_name ?? null,
counterpart_iban: args.counterpart_iban ?? null,
reference: args.reference ?? null,
structured_reference: args.structured_reference ?? null,
contact_id: args.contact_id ?? null,
},
], columns.BANK_TRANSACTION), 'the bank transaction could not be created');
return {
transaction: created,
note: 'A statement line is not an entry. It waits as `pending` until settle_from_statement books it as the payment it is.',
};
}
/**
* The statement formats this server has a reader for. A pack names more than
* these — MT940, OFX, BAI2 — and a format is offered here the day a brick
* reads it, not the day a pack mentions it.
*
* The list moved to the core when a second caller needed it: `describePack()`
* of the command line answers, for every format a pack names, read or not yet,
* and it cannot reach this package — the command line depends on the core and
* on one driver, and a list of three strings is not a reason to make it depend
* on an MCP server. It is exported from here under the name it always had.
*/
export { STATEMENT_FORMATS } from '@ekwo-ai/core';
/** A column of a CSV: its header as written, or its position counted from 1. */
const csvColumn = z.union([z.string().min(1), z.number().int().min(1)]);
/** The profile of a CSV's columns, as `@ekwo-ai/csv-statement` describes it. The reader checks it again. */
export const CsvProfileInput = z.object({
delimiter: z.string().min(1).describe('The character between two fields: `,`, `;`, a tab, `|`.'),
encoding: z.enum(['utf-8', 'iso-8859-1', 'windows-1252']).optional().describe('Default utf-8. Never guessed.'),
skipRows: z.number().int().min(0).optional().describe('Lines above the header: a title, an account line.'),
header: z.boolean().optional().describe('Whether the first row read is a header. Default true; without one, columns are named by position.'),
skipFooterRows: z.number().int().min(0).optional().describe('Rows at the end that are not movements: a total.'),
dateFormat: z.string().min(1).describe('How a date is written, with DD, MM and YYYY (or YY): `DD/MM/YYYY`, `MM/DD/YYYY`, `YYYY-MM-DD`.'),
decimalSeparator: z.enum(['.', ',']),
thousandsSeparator: z.string().max(1).optional().describe('The mark between groups of three digits, when the file writes one.'),
sign: z.enum(['as-written', 'inverted']).optional().describe('`inverted` when a positive amount is money out, as a card statement writes a purchase.'),
newestFirst: z.boolean().optional().describe('The file lists the newest row first.'),
columns: z
.object({
date: csvColumn,
valueDate: csvColumn.optional(),
amount: csvColumn.optional(),
debit: csvColumn.optional(),
credit: csvColumn.optional(),
fee: csvColumn.optional(),
currency: csvColumn.optional(),
counterparty: csvColumn.optional(),
counterpartyAccount: csvColumn.optional(),
description: z.union([csvColumn, z.array(csvColumn)]).optional(),
reference: csvColumn.optional(),
balance: csvColumn.optional(),
})
.describe('Which column says what, by header or by position from 1. `date` is required, and either `amount` or `debit`/`credit`. A `fee` column makes a second line of each row with a fee. A `balance` column (the running balance) proves the statement.'),
});
export const ImportBankStatementInput = z.object({
company_id: companyId,
format: z
.enum(STATEMENT_FORMATS)
.describe('What the file is. Required, and never guessed from the content: `camt.053` is the ISO 20022 XML statement, `coda` the coded statement of account of 128-character records, `cfonb120` the statement of 120-character records, `csv` a statement exported as CSV, read with `csv_profile`.'),
content: z.string().min(1).describe('The file itself, as text (UTF-8).'),
file_name: z.string().min(1).optional().describe('The name the file had, kept on the statement.'),
storage_path: z
.string()
.min(1)
.optional()
.describe('Where the caller stored the file, if it did. With it the file is recorded in attachments, on the statement; this server stores no bytes.'),
bank_account_id: uuid
.optional()
.describe('Only for a file of one statement whose account the company identifies otherwise than the file does. Left out, the account is found by the identifier the statement carries, and an unknown one is refused.'),
iban_country: z
.string()
.length(2)
.optional()
.describe('Only for `cfonb120`, which identifies an account by a bank code, a branch code and a number, and names no country. With the two letters of the country the account is held in, the statement is matched on the IBAN those make there; left out, on the three joined, as written. Never guessed.'),
csv_profile: CsvProfileInput.optional().describe("Only for `csv`: the lay-out of the file. Left out, the profile kept on the bank account (`statement_profile` in list_bank_accounts) is used, and the import is refused csv_profile_required only when the account has none. Given, and the import succeeds, it is kept on the account for every later file of that bank, whoever imports it. A CSV names no account either, so `bank_account_id` is required with it."),
opening_balance: z
.string()
.regex(/^-?[0-9]+(\.[0-9]+)?$/)
.optional()
.describe('Only for `csv` without a running balance column: the opening balance the bank shows for the period, as a decimal string. The import needs both balances to prove no line is missing.'),
closing_balance: z
.string()
.regex(/^-?[0-9]+(\.[0-9]+)?$/)
.optional()
.describe('Only for `csv`: the closing balance the bank shows, the same way.'),
});
export const UpdateBankAccountInput = z.object({
company_id: companyId,
bank_account_id: uuid,
statement_profile: CsvProfileInput.nullable().describe('The lay-out of the CSV statements this account\'s bank exports, kept on the account for every member and every import; null forgets it. Checked as the reader checks it (invalid_profile otherwise). An import given csv_profile keeps it here too.'),
});
/**
* Changes a bank account: today, the profile of its CSV statements — the
* lay-out of its bank's export, described once on the account. The core does
* the work, so the command line's `ekwo bank profile` takes the same road.
*/
export async function updateBankAccount(backend, args) {
const account = await setBankAccountStatementProfile(backend, args);
return {
bank_account: account,
note: args.statement_profile === null
? 'The account keeps no profile now: a CSV of it is imported with csv_profile again, which the account then keeps.'
: 'A CSV of this account is now imported without csv_profile: import_bank_statement reads this one.',
};
}
/**
* Reads the file with the brick of its format and hands the statements to
* `import_bank_statement()`. The reading moved to the core when the command
* line needed it too (`ekwo import camt.053 <file>`); this is the same call.
*/
export async function importBankStatement(backend, args) {
return importStatementFile(backend, args);
}
// ---------------------------------------------------------------------------
// Locks
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Members
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// The company itself
// ---------------------------------------------------------------------------
export const CreateCompanyInput = z.object({
name: z.string().min(1),
country: z
.string()
.length(2)
.describe('Which country pack: its chart of accounts, its taxes and its declaration form. list_companies shows what the installation already uses.'),
currency_code: z.string().length(3).optional().describe("Left out, the country pack's."),
language: z
.string()
.length(2)
.optional()
.describe("Language the books are kept in — it decides the labels of the chart. Left out, the country pack's."),
chart_code: z.string().optional().describe('Which chart, where the country offers several.'),
fiscal_year: z.number().int().min(1900).max(2200).optional().describe('Calendar year the first financial year opens in. Default this year.'),
fiscal_year_start: isoDate
.optional()
.describe('First day of it. Left out, the month the country pack opens a year on — and a pack that names none is a refusal, not a January.'),
});
export async function createCompany(backend, args) {
const company = only(await backend.rpc('create_company', {
p_name: args.name,
p_country: args.country.toUpperCase(),
p_currency_code: args.currency_code?.toUpperCase() ?? null,
p_language: args.language?.toLowerCase() ?? null,
p_chart_code: args.chart_code ?? null,
p_fiscal_year: args.fiscal_year ?? null,
p_fiscal_year_start: args.fiscal_year_start ?? null,
}), 'the company could not be created. Creating one is an instance-level act: it needs an instance administrator');
const years = await backend.select({
table: 'fiscal_years',
columns: columns.FISCAL_YEAR,
where: [{ column: 'company_id', op: 'eq', value: company['id'] }],
order: [{ column: 'start_date' }],
});
return {
company,
fiscal_years: years,
note: 'The chart of accounts, the journals and the taxes of the country pack have been copied into it, and you are its first member.',
};
}
export const UpdateCompanyProfileInput = z.object({
company_id: companyId,
name: z.string().min(1).optional(),
trade_name: z.string().nullable().optional().describe('The name it trades under, if not the statutory one.'),
legal_name: z.string().nullable().optional(),
legal_form: z.string().nullable().optional(),
vat_number: z.string().nullable().optional(),
registration_number: z
.string()
.nullable()
.optional()
.describe('The number of the commercial register of its country. There is no second column for it.'),
address_line1: z.string().nullable().optional(),
address_line2: z.string().nullable().optional(),
postal_code: z.string().nullable().optional(),
city: z.string().nullable().optional(),
email: z.string().nullable().optional(),
phone: z.string().nullable().optional(),
website: z.string().nullable().optional(),
logo_url: z
.string()
.nullable()
.optional()
.describe('Where the logo is. A URL or a storage path: the core keeps no file.'),
share_capital: z
.string()
.nullable()
.optional()
.describe('A decimal string. Several legal forms must state it on every document.'),
share_capital_currency: z
.string()
.length(3)
.nullable()
.optional()
.describe("Left out, the company's own currency."),
activity_code: z.string().nullable().optional().describe('NACE, APE, SIC — the code itself.'),
activity_scheme: z.string().nullable().optional().describe('Which register the code belongs to.'),
activity_description: z
.string()
.nullable()
.optional()
.describe("The company's own words for its activity, which an e-invoice carries beside the code."),
identifiers: z
.record(z.string().min(1), z.string().min(1))
.optional()
.describe("Every identifier with no column of its own, by the code of its scheme — {\"<scheme>\": \"<identifier>\"}: replaces the whole set. The schemes a country's e-invoice reads are on its set-up page and in describe_pack."),
default_bank_account_id: uuid
.nullable()
.optional()
.describe('Fills the payee IBAN of a sales document that names none. list_bank_accounts says what exists.'),
document_template: z.string().nullable().optional().describe('A code the renderer interprets.'),
invoice_accent_color: z
.string()
.regex(/^#[0-9A-Fa-f]{6}$/, 'a colour written #rrggbb')
.nullable()
.optional()
.describe('The accent colour of its invoice PDF, #rrggbb: the title, the rules and the bands. Null puts back the default.'),
invoice_logo_position: z
.enum(['left', 'right'])
.nullable()
.optional()
.describe('The side of its invoice PDF the logo is printed on. Null puts back the default, left.'),
number_format: z
.string()
.min(1)
.nullable()
.optional()
.describe("The pattern of its document numbers: {CODE} (each journal's prefix, required), {YYYY} or {YY}, {MM}, and {N...} padded to as many N as are written, e.g. {CODE}-{YYYY}-{NNNNNN}. A pattern with the year restarts each year. Changing it on the way continues the series where it stood. Null puts back the country pack's."),
invoice_typeface: z
.enum(['classic', 'elegant'])
.nullable()
.optional()
.describe('The typefaces of its invoice PDF: elegant (Inter, with Fraunces for the title, the names and the headings) or classic (Noto Sans). Null puts back the default, elegant.'),
agent_posting: z
.enum(AGENT_POSTING)
.optional()
.describe("How agents post its documents: review (the default) once a person approved the draft, unless a session opted into autopilot; autopilot, directly; review_only, review with autopilot forbidden to every session. The person's choice: you may make it stricter when they ask, never looser (agent_posting_by_a_person)."),
invoice_late_payment_mention: z
.boolean()
.optional()
.describe("Whether its sale invoices to a business print the late payment mention of its country pack, true by default. Never on a credit note, nor on an invoice to a consumer, whatever this says."),
});
export async function updateCompanyProfile(backend, args) {
const { company_id, ...rest } = args;
const patch = {};
for (const [key, value] of Object.entries(rest)) {
if (value !== undefined)
patch[key] = value;
}
if (Object.keys(patch).length === 0) {
throw new EkwoMcpError('nothing_to_change: name at least one field of the profile to change.');
}
const updated = only(await backend.update('companies', patch, [{ column: 'id', op: 'eq', value: company_id }], columns.COMPANY), 'the company could not be changed. Changing the company itself needs company.write, which the owner preset holds');
return { company: updated };
}
export const SetNumberPrefixInput = z.object({
company_id: companyId,
journal_id: uuid.optional(),
journal_code: z.string().min(1).optional().describe('The journal by its code, e.g. SAL. get_company lists the journals.'),
number_prefix: z
.string()
.min(1)
.max(20)
.nullable()
.describe("What {CODE} prints in the numbers this journal draws, e.g. FAC. Null prints the journal's code again. The code itself never changes."),
});
/** The prefix one journal prints in its numbers, in place of its code. */
export async function setNumberPrefix(backend, args) {
let journalId = args.journal_id;
if (journalId === undefined) {
if (args.journal_code === undefined) {
throw new EkwoMcpError('missing_journal: name the journal, by journal_id or journal_code.');
}
journalId = (await idsByCode(backend, 'journals', args.company_id, [args.journal_code])).get(args.journal_code);
}
const updated = only(await backend.update('journals', { number_prefix: args.number_prefix }, [
{ column: 'id', op: 'eq', value: journalId },
{ column: 'company_id', op: 'eq', value: args.company_id },
], [...columns.JOURNAL, 'number_prefix']), 'the journal could not be changed. Changing a journal needs settings.write');
return { journal: updated };
}
// ---------------------------------------------------------------------------
// Preferences
// ---------------------------------------------------------------------------
export const SetPreferencesInput = z.object({
preferred_company_id: uuid.nullable().optional().describe('The company to open on.'),
language: z
.string()
.nullable()
.optional()
.describe('Two letters, optionally a region. Labels are read in it first.'),
timezone: z.string().nullable().optional().describe('An IANA name.'),
date_display_format: z.string().nullable().optional().describe('How this person likes a date written.'),
number_display_format: z
.string()
.nullable()
.optional()
.describe('How this person likes a number written. Not the pattern a document number is built from, which belongs to the country.'),
theme: z.string().nullable().optional(),
});
export async function setPreferences(backend, args) {
// Only what the caller actually named crosses: an absent key leaves the
// preference alone and an explicit null clears it, which is a distinction
// the schema makes and this tool must not flatten.
const patch = {};
for (const [key, value] of Object.entries(args)) {
if (value !== undefined)
patch[key] = value;
}
const saved = only(await backend.rpc('set_preferences', { p_patch: patch }), 'the preferences could not be saved');
return { preferences: saved };
}
export const InviteMemberInput = z.object({
company_id: companyId,
email: z.string().min(3).describe('The address the invitation is for. Matched when it is accepted.'),
role: z
.enum(['owner', 'accountant', 'viewer', 'client'])
.optional()
.describe('The preset. Default viewer, which reads and changes nothing. client is the person whose company it is, invited by whoever keeps their books: it reads the same, and may also hand a file over (documents.deposit).'),
capabilities: z
.array(z.string())
.optional()
.describe('Capability codes granted on top of the preset, e.g. members.manage. get_company lists what this installation knows.'),
valid_for_days: z.number().int().min(1).max(365).optional().describe('Default 14.'),
});
export async function inviteMember(backend, args) {
const answer = only(await backend.rpc('invite_member', {
p_company_id: args.company_id,
p_email: args.email,
p_role: args.role ?? 'viewer',
p_capabilities: args.capabilities ?? [],
p_valid_for: `${args.valid_for_days ?? 14} days`,
}), 'the invitation could not be issued');
return {
invitation: answer,
note: 'The token is in this answer and nowhere else — only its hash is stored. Give it to the person you invited; they accept it signed in with the address above.',
};
}
export const CreateApiKeyInput = z.object({
company_id: companyId,
name: z.string().min(1).describe('What this key is for, in the words an operator will read a year from now.'),
capabilities: z
.array(z.string())
.min(1)
.describe('Exactly what the machine may do, e.g. ["bank.write"]. You cannot put a capability on a key that you do not hold yourself.'),
expires_at: z
.string()
.nullable()
.optional()
.describe('When it stops working, as a timestamp. Left out, it does not expire on its own.'),
posting_mode: z
.enum(KEY_POSTING)
.optional()
.describe('How the key posts a document, fixed for good: review (the default) — as the company\u2019s agent_posting says, so a person approves each draft unless the company chose autopilot; autopilot — directly, on the audit trail. Autopilot needs company.write, is refused where the company is review_only, and is refused to a session that is not itself in autopilot there. Only on the user\u2019s explicit request: a key is never raised afterwards, another one is issued.'),
});
export async function createApiKey(backend, args) {
return issueKey(backend, args);
}
export const RevokeApiKeyInput = z.object({
api_key_id: uuid,
});
export async function revokeApiKey(backend, args) {
const revoked = only(await backend.rpc('revoke_api_key', { p_api_key_id: args.api_key_id }), 'the key could not be withdrawn');
return { api_key: revoked };
}
export const RevokeInvitationInput = z.object({
invitation_id: uuid,
});
export async function revokeInvitation(backend, args) {
const answer = only(await backend.rpc('revoke_invitation', { p_invitation_id: args.invitation_id }), 'the invitation could not be withdrawn');
return { invitation: answer };
}
export const RemoveMemberInput = z.object({
company_id: companyId,
user_id: uuid.describe('The member to take out. Your own id leaves the company, which needs no members.manage.'),
});
export async function removeMember(backend, args) {
const removed = only(await backend.rpc('remove_member', { p_company_id: args.company_id, p_user_id: args.user_id }), 'the member could not be removed');
return { removed };
}
export const SetMemberRoleInput = z.object({
company_id: companyId,
user_id: uuid,
role: z
.enum(['owner', 'accountant', 'viewer', 'client'])
.describe('The new preset. The capabilities granted or revoked on this member so far are cleared.'),
capabilities: z
.array(z.string())
.optional()
.describe('Capability codes granted on top of the new preset, as invite_member takes them. Default none.'),
});
export async function setMemberRole(backend, args) {
const member = only(await backend.rpc('set_member_role', {
p_company_id: args.company_id,
p_user_id: args.user_id,
p_role: args.role,
p_capabilities: args.capabilities ?? [],
}), 'the role could not be changed');
return { member };
}
export const ShareDocumentInput = z.object({
document_id: uuid.describe('The sales document to publish. A purchase document and a draft are refused.'),
expires_at: z
.string()
.nullable()
.optional()
.describe('When the link stops answering, as a timestamp. Left out, it answers until it is withdrawn.'),
});
export async function shareDocument(backend, args) {
const share = only(await backend.rpc('share_document', {
p_document_id: args.document_id,
p_expires_at: args.expires_at ?? null,
}), 'the link could not be created');
return {
share,
note: 'The token is in this answer and nowhere else — only its hash is stored. Give the url to the customer; anyone holding it can open the document without an account. A link is never edited: to change when it expires, withdraw it and make another. `url` is null when the installation has not recorded its public address.',
};
}
export const RevokeShareInput = z.object({
share_id: uuid,
});
export async function revokeShare(backend, args) {
const share = only(await backend.rpc('revoke_share', { p_share_id: args.share_id }), 'the link could not be withdrawn');
return { share };
}
export const LockPeriodInput = z.object({
company_id: companyId,
lock_date: isoDate.nullable().optional().describe('Nothing may be booked on or before this date. null lifts the lock.'),
tax_lock_date: isoDate.nullable().optional().describe('Additionally freezes anything carrying a VAT box. null lifts it.'),
});
// ---------------------------------------------------------------------------
// Opening a set of books, and closing a year
//
// All three go straight to the schema function. The rules about which account
// the result travels through, which entries are written and when a year may
// be closed live in `close_fiscal_year`, next to the ones about balance and
// locks, and this server does not repeat a word of them.
// ---------------------------------------------------------------------------
export const OpeningBalanceInput = z.object({
company_id: companyId,
fiscal_year_id: uuid.describe('The year the balance opens. The entry is dated on its first day unless opening_date says otherwise.'),
opening_date: isoDate
.optional()
.describe('The day the books were taken over, inside that year. Left out, its first day. The balance is what the previous system held at the end of the day before.'),
lines: z
.array(z.object({
account_code: z.string().min(1).describe('Code in this company\'s chart. list_accounts says what exists; the codes are the pack\'s, not ours.'),
debit: z.union([z.string(), z.number()]).optional().describe('A positive decimal string. A line carries a debit or a credit, never both.'),
credit: z.union([z.string(), z.number()]).optional(),
contact_id: uuid.optional().describe('The customer or supplier behind a receivable or payable line, so the aged balance knows whose it is.'),
label: z.string().min(1).optional(),
}))
.min(1)
.describe('The trial balance of the previous system, one entry per row. Total debit must equal total credit.'),
allow_result_accounts: z
.boolean()
.optional()
.describe('Default false: an opening balance is made of the balance sheet. Pass true only when taking books over in the middle of a year that has already run.'),
items: z
.array(z.object({
doc_type: z.enum(['sale_invoice', 'sale_credit_note', 'purchase_invoice', 'purchase_credit_note']),
number: z.string().min(1).describe('The number the document had. Unique among the documents of its type in this company.'),
contact_id: uuid.describe('The customer or supplier who owes it or is owed it.'),
amount: z.union([z.string(), z.number()]).describe('What is still open of it: a positive decimal string. The type says the side.'),
document_date: isoDate.describe('The day it was issued, on or before the opening.'),
due_date: isoDate.optional(),
payment_reference: z.string().min(1).optional().describe('The reference a payment of it quotes — the structured one where the country has them. What statement matching finds it by.'),
supplier_reference: z.string().min(1).optional().describe('On a purchase, the supplier\'s own number.'),
label: z.string().min(1).optional(),
}))
.optional()
.describe('The invoices and credit notes still open on the opening day. Each becomes a posted document on the opening journal, with its number, reference and dates, against the suspense account — nothing is booked to revenue or expense again — so statement matching finds it like an invoice issued here. The items of a receivable or payable account replace its line of the balance and must add up to it exactly.'),
});
export async function openingBalance(backend, args) {
const lines = args.lines.map((line) => ({
account_code: line.account_code,
debit: amountIn(line.debit ?? 0),
credit: amountIn(line.credit ?? 0),
...(line.contact_id === undefined ? {} : { contact_id: line.contact_id }),
...(line.label === undefined ? {} : { label: line.label }),
}));
const items = args.items?.map((item) => ({
doc_type: item.doc_type,
number: item.number,
contact_id: item.contact_id,
amount: amountIn(item.amount),
document_date: item.document_date,
...(item.due_date === undefined ? {} : { due_date: item.due_date }),
...(item.payment_reference === undefined ? {} : { payment_reference: item.payment_reference }),
...(item.supplier_reference === undefined ? {} : { supplier_reference: item.supplier_reference }),
...(item.label === undefined ? {} : { label: item.label }),
}));
const answer = await backend.rpc('opening_balance', {
p_company_id: args.company_id,
p_fiscal_year_id: args.fiscal_year_id,
p_lines: lines,
p_allow_result_accounts: args.allow_result_accounts ?? false,
...(args.opening_date === undefined ? {} : { p_opening_date: args.opening_date }),
...(items === undefined ? {} : { p_items: items }),
});
const entryId = only(answer, 'the opening balance produced no entry');
const entries = await backend.select({
table: 'entries',
columns: ['id', 'number', 'journal_id', 'entry_date::text', 'description', 'state', 'kind', 'total_debit::text', 'total_credit::text'],
where: [{ column: 'id', op: 'eq', value: entryId }],
});
const entry = only(entries, `entry ${entryId}`);
const { journal_id: journalId, ...shown } = entry;
const documents = items === undefined || items.length === 0
? []
: await backend.select({
table: 'documents',
columns: ['id', 'doc_type', 'number', 'contact_id', 'document_date::text', 'due_date::text', 'payment_reference', 'amount_total::text', 'state'],
where: [
{ column: 'company_id', op: 'eq', value: args.company_id },
{ column: 'journal_id', op: 'eq', value: journalId },
{ column: 'accounting_date', op: 'eq', value: shown['entry_date'] },
{ column: 'number', op: 'in', value: items.map((item) => item.number) },
],
order: [{ column: 'number' }],
});
return {
entry: shown,
...(documents.length === 0 ? {} : { documents }),
note: documents.length === 0
? 'The opening entry is posted. A year holds one; a second call is refused rather than adding to it.'
: 'The opening entry is posted, and each open item is a posted document on the opening journal, matched by statements like any invoice. A year holds one opening; a second call is refused rather than adding to it.',
};
}
export const CloseFiscalYearInput = z.object({
fiscal_year_id: uuid.describe('The year to close. Every entry in it must be posted.'),
});
export const ReopenFiscalYearInput = z.object({
fiscal_year_id: uuid.describe('The closed year to open again.'),
});
export const CloseFiscalYearFinallyInput = z.object({
fiscal_year_id: uuid.describe('The closed year to close for good. Every closed year before it must already be finally closed.'),
});
//# sourceMappingURL=write.js.map