@baseworks/invoice 0.1.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +81 -14
- package/dist/chunk-335MPCTE.js +133 -0
- package/dist/cli.js +58 -42
- package/dist/client.d.ts +216 -29
- package/dist/client.js +99 -23
- package/dist/events.d.ts +180 -69
- package/dist/events.js +5 -1
- package/dist/graphql.d.ts +22 -0
- package/dist/graphql.js +17 -2
- package/dist/mcp.d.ts +13 -0
- package/dist/mcp.js +146 -0
- package/dist/projections.js +55 -20
- package/package.json +14 -3
- package/src/__tests__/cli.test.ts +43 -25
- package/src/__tests__/client.test.ts +147 -0
- package/src/__tests__/dts-exports.test.ts +75 -0
- package/src/__tests__/mcp.test.ts +163 -0
- package/src/cli.ts +85 -60
- package/src/client.ts +78 -26
- package/src/compat.ts +61 -0
- package/src/events.ts +72 -22
- package/src/graphql.ts +17 -2
- package/src/mcp.ts +191 -0
- package/src/projections.ts +54 -19
- package/src/types.ts +208 -22
- package/dist/chunk-7P7ARN3X.js +0 -78
package/src/compat.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The camelCase names this client spoke until 0.3.0, kept for callers that have not moved
|
|
3
|
+
* (billing-service, stripe-service, apps). Everything here is deprecated and goes when the last
|
|
4
|
+
* caller has moved:
|
|
5
|
+
*
|
|
6
|
+
* - answers: each old name is put back on the object as a non-enumerable getter of the snake_case
|
|
7
|
+
* field, so `invoice.totalCents` still reads while `JSON.stringify` and `toEqual` see only the
|
|
8
|
+
* snake_case object;
|
|
9
|
+
* - requests: old input names are renamed to snake_case before they are sent. The new name wins
|
|
10
|
+
* when both are given.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const INVOICE: Record<string, string> = {
|
|
14
|
+
shortId: 'short_id', customerId: 'customer_id', customerName: 'customer_name', subtotalCents: 'subtotal_cents',
|
|
15
|
+
totalCents: 'total_cents', amountPaidCents: 'amount_paid_cents', balanceCents: 'balance_cents', issuedAt: 'issued_at',
|
|
16
|
+
dueAt: 'due_at', createdAt: 'created_at', updatedAt: 'updated_at',
|
|
17
|
+
}
|
|
18
|
+
const LINE: Record<string, string> = { unitPriceCents: 'unit_price_cents', amountCents: 'amount_cents', productId: 'product_id' }
|
|
19
|
+
const TRANSACTION: Record<string, string> = {
|
|
20
|
+
invoiceId: 'invoice_id', invoiceNumber: 'invoice_number', customerId: 'customer_id', customerName: 'customer_name',
|
|
21
|
+
amountCents: 'amount_cents', createdAt: 'created_at',
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function alias<T extends object>(o: T, names: Record<string, string>): T {
|
|
25
|
+
for (const [old, now] of Object.entries(names)) {
|
|
26
|
+
if (old in o) continue
|
|
27
|
+
Object.defineProperty(o, old, { get: () => (o as Record<string, unknown>)[now], enumerable: false, configurable: true })
|
|
28
|
+
}
|
|
29
|
+
return o
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** An invoice as the service answered it, with the old names readable. */
|
|
33
|
+
export function oldNamesOnInvoice<T extends { lines?: unknown }>(invoice: T): T {
|
|
34
|
+
const o = invoice as T & { lines?: object[] }
|
|
35
|
+
if (Array.isArray(o.lines)) o.lines.forEach((l) => alias(l, LINE))
|
|
36
|
+
return alias(o, INVOICE)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function oldNamesOnTransaction<T extends object>(t: T): T {
|
|
40
|
+
return alias(t, TRANSACTION)
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** A request body with the old names renamed to snake_case; `rename` lists the old → new pairs; `lines` are renamed too. */
|
|
44
|
+
function renamed(body: object | undefined, names: Record<string, string>): Record<string, unknown> {
|
|
45
|
+
const out: Record<string, unknown> = {}
|
|
46
|
+
for (const [k, v] of Object.entries(body ?? {})) {
|
|
47
|
+
const key = names[k] ?? k
|
|
48
|
+
if (key !== k && key in (body as object)) continue // the new name wins
|
|
49
|
+
out[key] = v
|
|
50
|
+
}
|
|
51
|
+
return out
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function newNamesOnLines<T extends { lines?: unknown }>(body: T): Record<string, unknown> {
|
|
55
|
+
const out = renamed(body, { customerId: 'customer_id' })
|
|
56
|
+
if (Array.isArray(out['lines'])) out['lines'] = (out['lines'] as object[]).map((l) => renamed(l, LINE))
|
|
57
|
+
return out
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export const newNamesOnFinalize = (b: object) => renamed(b, { issuedAt: 'issued_at', dueAt: 'due_at' })
|
|
61
|
+
export const newNamesOnPayment = (b: object) => renamed(b, { amountCents: 'amount_cents' })
|
package/src/events.ts
CHANGED
|
@@ -15,6 +15,12 @@ import { defineAggregate } from '@baseworks/foldbase'
|
|
|
15
15
|
* absolute values in the event, so the projection is a plain upsert (no
|
|
16
16
|
* accumulation). `lines` is a serialized JSON array. Timestamps are epoch millis.
|
|
17
17
|
* A FINALIZED invoice is immutable: only PaymentRecorded / InvoiceVoided follow.
|
|
18
|
+
*
|
|
19
|
+
* Payload fields are snake_case (0.3.0). Events written before are camelCase
|
|
20
|
+
* (`customerId`, `totalCents`, …) and stay so in the log: foldbase reads a
|
|
21
|
+
* snake_case path from a camelCase payload when the snake_case key is absent, so
|
|
22
|
+
* the projections fold both. The `lines` JSON inside a payload is the same: old
|
|
23
|
+
* lines carry `unitPriceCents`, `amountCents`, `productId`; the service reads both.
|
|
18
24
|
*/
|
|
19
25
|
|
|
20
26
|
export const InvoiceStatus = z.enum(['draft', 'finalized', 'paid', 'void'])
|
|
@@ -24,51 +30,94 @@ export const InvoiceEvents = defineAggregate('invoice', {
|
|
|
24
30
|
// Draft created (with its initial lines + computed totals). Numeric fields are
|
|
25
31
|
// initialised to 0 so their read-model columns are stable integers.
|
|
26
32
|
InvoiceDrafted: z.object({
|
|
27
|
-
|
|
28
|
-
|
|
33
|
+
customer_id: z.string().min(1),
|
|
34
|
+
customer_name: z.string(), // snapshot at draft time; '' if unknown
|
|
29
35
|
currency: z.string().length(3),
|
|
30
|
-
lines: z.string(), // JSON array of { description, quantity,
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
36
|
+
lines: z.string(), // JSON array of { description, quantity, unit_price_cents, amount_cents, product_id }
|
|
37
|
+
subtotal_cents: z.number().int(),
|
|
38
|
+
total_cents: z.number().int(),
|
|
39
|
+
short_id: z.string().min(1),
|
|
40
|
+
// 1.1.0. Absent from older events: the read model holds NULL, and the service reads that as `local` and `{}`.
|
|
41
|
+
source: z.string().optional(),
|
|
42
|
+
metadata: z.string().optional(), // JSON object, serialized
|
|
34
43
|
at: z.number().int(),
|
|
35
44
|
}),
|
|
36
45
|
// Draft edited (customer / lines). Only valid while status = draft.
|
|
37
46
|
InvoiceUpdated: z.object({
|
|
38
|
-
|
|
39
|
-
|
|
47
|
+
customer_id: z.string().min(1),
|
|
48
|
+
customer_name: z.string(),
|
|
40
49
|
lines: z.string(),
|
|
41
|
-
|
|
42
|
-
|
|
50
|
+
subtotal_cents: z.number().int(),
|
|
51
|
+
total_cents: z.number().int(),
|
|
52
|
+
metadata: z.string().optional(), // 1.1.0
|
|
43
53
|
at: z.number().int(),
|
|
44
54
|
}),
|
|
45
55
|
// Finalize: assign the per-org number, freeze lines + totals, set issue/due.
|
|
46
56
|
InvoiceFinalized: z.object({
|
|
47
57
|
number: z.number().int(),
|
|
48
58
|
lines: z.string(),
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
59
|
+
subtotal_cents: z.number().int(),
|
|
60
|
+
total_cents: z.number().int(),
|
|
61
|
+
issued_at: z.number().int(),
|
|
62
|
+
due_at: z.number().int(), // 0 = no due date
|
|
53
63
|
at: z.number().int(),
|
|
54
64
|
}),
|
|
55
|
-
// A payment applied to a finalized invoice. `
|
|
65
|
+
// A payment applied to a finalized invoice. `amount_paid_cents` is the new running
|
|
56
66
|
// total; `status` is the resulting status ('paid' when balance ≤ 0, else
|
|
57
67
|
// 'finalized') — both computed by the store.
|
|
58
68
|
PaymentRecorded: z.object({
|
|
59
|
-
|
|
60
|
-
|
|
69
|
+
amount_cents: z.number().int(),
|
|
70
|
+
amount_paid_cents: z.number().int(),
|
|
61
71
|
status: InvoiceStatus,
|
|
62
72
|
method: z.string(),
|
|
63
73
|
reference: z.string(),
|
|
74
|
+
payment_id: z.string().optional(), // 1.1.0: the pay record this settles; the idempotency key when present
|
|
64
75
|
at: z.number().int(),
|
|
65
76
|
}),
|
|
66
77
|
InvoiceVoided: z.object({
|
|
67
78
|
reason: z.string(),
|
|
68
79
|
at: z.number().int(),
|
|
69
80
|
}),
|
|
81
|
+
// 1.1.0. The provider's document, whole (absolute values like every event here), by (system, external id): the
|
|
82
|
+
// first one creates the invoice, the next ones replace it. A mirror never takes a number: `number` stays 0.
|
|
83
|
+
InvoiceMirrored: z.object({
|
|
84
|
+
source: z.string(), // 'stripe' | 'manual'
|
|
85
|
+
mirror_key: z.string().min(1), // `${system}:${external_id}`
|
|
86
|
+
external_refs: z.string(), // JSON array, serialized
|
|
87
|
+
customer_id: z.string().min(1),
|
|
88
|
+
customer_name: z.string(),
|
|
89
|
+
currency: z.string().length(3),
|
|
90
|
+
lines: z.string(),
|
|
91
|
+
subtotal_cents: z.number().int(),
|
|
92
|
+
tax_cents: z.number().int(),
|
|
93
|
+
total_cents: z.number().int(),
|
|
94
|
+
amount_paid_cents: z.number().int(), // from the payment entries, not from the provider
|
|
95
|
+
status: InvoiceStatus,
|
|
96
|
+
issued_at: z.number().int(),
|
|
97
|
+
due_at: z.number().int(), // 0 = none
|
|
98
|
+
paid_at: z.number().int(), // 0 = none
|
|
99
|
+
voided_at: z.number().int(), // 0 = none
|
|
100
|
+
provider_updated_at: z.number().int(),
|
|
101
|
+
metadata: z.string(),
|
|
102
|
+
short_id: z.string().min(1),
|
|
103
|
+
created_at: z.number().int(),
|
|
104
|
+
at: z.number().int(),
|
|
105
|
+
}),
|
|
106
|
+
// 1.1.0. Where the invoice stands with a tax system. Only changed through `invoice.fiscal_update`.
|
|
107
|
+
InvoiceFiscalChanged: z.object({
|
|
108
|
+
status: z.string(), // FISCAL_STATUSES
|
|
109
|
+
system: z.string(),
|
|
110
|
+
external_id: z.string(),
|
|
111
|
+
message: z.string(),
|
|
112
|
+
at: z.number().int(),
|
|
113
|
+
}),
|
|
70
114
|
})
|
|
71
115
|
|
|
116
|
+
export const FISCAL_STATUSES = ['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled'] as const
|
|
117
|
+
export type FiscalStatus = (typeof FISCAL_STATUSES)[number]
|
|
118
|
+
export const INVOICE_SOURCES = ['local', 'stripe', 'manual'] as const
|
|
119
|
+
export type InvoiceSource = (typeof INVOICE_SOURCES)[number]
|
|
120
|
+
|
|
72
121
|
/**
|
|
73
122
|
* The transaction ledger — one stream (and one read-model row) PER money movement,
|
|
74
123
|
* unlike the invoice's cached `amount_paid`. A payment emits BOTH `PaymentRecorded`
|
|
@@ -81,15 +130,16 @@ export type TransactionKind = z.infer<typeof TransactionKind>
|
|
|
81
130
|
|
|
82
131
|
export const TransactionEvents = defineAggregate('transaction', {
|
|
83
132
|
TransactionRecorded: z.object({
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
133
|
+
invoice_id: z.string().min(1),
|
|
134
|
+
invoice_number: z.number().int(), // the invoice's number at the time
|
|
135
|
+
customer_id: z.string(),
|
|
136
|
+
customer_name: z.string(),
|
|
88
137
|
kind: TransactionKind,
|
|
89
|
-
|
|
138
|
+
amount_cents: z.number().int(),
|
|
90
139
|
currency: z.string().length(3),
|
|
91
140
|
method: z.string(),
|
|
92
141
|
reference: z.string(),
|
|
142
|
+
payment_id: z.string().optional(), // 1.1.0
|
|
93
143
|
at: z.number().int(),
|
|
94
144
|
}),
|
|
95
145
|
})
|
package/src/graphql.ts
CHANGED
|
@@ -53,10 +53,25 @@ export const resolvers = {
|
|
|
53
53
|
},
|
|
54
54
|
Customer: {
|
|
55
55
|
invoices: async (parent: { id: string }, { status }: { status?: string }, ctx: InvoiceGraphContext) =>
|
|
56
|
-
(await ctx.invoice.list(status ? { status } : {})).filter((i) => i.
|
|
56
|
+
(await ctx.invoice.list(status ? { status } : {})).filter((i) => i.customer_id === parent.id),
|
|
57
|
+
},
|
|
58
|
+
InvoiceLine: {
|
|
59
|
+
unitPriceCents: (l: { unit_price_cents: number }) => l.unit_price_cents,
|
|
60
|
+
amountCents: (l: { amount_cents: number }) => l.amount_cents,
|
|
61
|
+
},
|
|
62
|
+
Transaction: {
|
|
63
|
+
amountCents: (t: { amount_cents: number }) => t.amount_cents,
|
|
64
|
+
createdAt: (t: { created_at: number }) => t.created_at,
|
|
57
65
|
},
|
|
58
66
|
Invoice: {
|
|
59
|
-
|
|
67
|
+
// The schema is camelCase (that contract's own); the data is snake_case.
|
|
68
|
+
subtotalCents: (p: Invoice) => p.subtotal_cents,
|
|
69
|
+
totalCents: (p: Invoice) => p.total_cents,
|
|
70
|
+
amountPaidCents: (p: Invoice) => p.amount_paid_cents,
|
|
71
|
+
balanceCents: (p: Invoice) => p.balance_cents,
|
|
72
|
+
dueAt: (p: Invoice) => p.due_at,
|
|
73
|
+
createdAt: (p: Invoice) => p.created_at,
|
|
74
|
+
customer: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.customerLoader.load(parent.customer_id),
|
|
60
75
|
transactions: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => ctx.invoice.invoiceTransactions(parent.id).catch(() => []),
|
|
61
76
|
},
|
|
62
77
|
}
|
package/src/mcp.ts
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The invoice tools for an MCP server (`@baseworks/mcp`), over the same typed client the CLI uses:
|
|
3
|
+
* a tool is a thin wrapper over invoice-service's `/api`, so it can never do what the API would
|
|
4
|
+
* refuse. `permission` is the name the service registered with org-service (`invoice.read`,
|
|
5
|
+
* `invoice.write`, …), used to hide a tool from somebody who may not use it.
|
|
6
|
+
*
|
|
7
|
+
* import { invoiceTools } from '@baseworks/invoice/mcp'
|
|
8
|
+
* composeTools(invoiceTools())
|
|
9
|
+
* // ctx.clients.invoice is an InvoiceClient built from the realm token
|
|
10
|
+
*
|
|
11
|
+
* Money is integer cents everywhere. A finalized invoice is a legal record: there is no tool that
|
|
12
|
+
* edits one, and recording a payment and voiding are separate permissions so an organization can
|
|
13
|
+
* give a model drafts and not the books.
|
|
14
|
+
*/
|
|
15
|
+
import { z } from 'zod'
|
|
16
|
+
import { defineTool, type McpTool } from '@baseworks/mcp'
|
|
17
|
+
import type { FiscalStatus, InvoiceClient, InvoiceSource, PaymentStatus } from './client.js'
|
|
18
|
+
|
|
19
|
+
/** What `ctx.clients` must hold for these tools. */
|
|
20
|
+
export interface InvoiceMcpClients { invoice: InvoiceClient }
|
|
21
|
+
|
|
22
|
+
const REF = z.string().min(1).describe('The invoice\'s id or its short id.')
|
|
23
|
+
|
|
24
|
+
const Line = z.object({
|
|
25
|
+
description: z.string().min(1).describe('What is being charged for.'),
|
|
26
|
+
quantity: z.number().positive().describe('How many (may be fractional, e.g. 2.5 hours).'),
|
|
27
|
+
unit_price_cents: z.number().int().min(0).describe('Price of one unit in integer cents: 150.00 is 15000.'),
|
|
28
|
+
product_id: z.string().optional().describe('The id of a catalog product, if the line is one.'),
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
const customer_id = z.string().min(1).describe('The customer: its id, short id or external id in the customer directory (see customers_list). It must exist.')
|
|
32
|
+
|
|
33
|
+
export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
|
|
34
|
+
return [
|
|
35
|
+
defineTool({
|
|
36
|
+
name: 'invoice_list',
|
|
37
|
+
title: 'List invoices',
|
|
38
|
+
description:
|
|
39
|
+
'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. ' +
|
|
40
|
+
'Each invoice has its totals, the amount paid, the `balance_cents` still owed and a `payment_status` (unpaid, partially_paid, paid; not_due for a draft or void invoice), so the answer to "what is unpaid" is one call: ' +
|
|
41
|
+
'filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
|
|
42
|
+
input: z.object({
|
|
43
|
+
status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
|
|
44
|
+
payment_status: z.array(z.enum(['unpaid', 'partially_paid', 'paid', 'not_due'])).min(1).optional().describe('Only invoices in one of these payment states. `unpaid` and `partially_paid` are what is still owed; `not_due` is a draft or void invoice.'),
|
|
45
|
+
overdue: z.boolean().optional().describe('true: only what is owed and past its due date.'),
|
|
46
|
+
source: z.enum(['local', 'stripe', 'manual']).optional().describe('`local` was made here, `stripe` mirrors a Stripe invoice, `manual` was entered from a document issued elsewhere.'),
|
|
47
|
+
fiscal_status: z.enum(['not_submitted', 'queued', 'submitted', 'accepted', 'rejected', 'cancelled']).optional().describe('Only invoices in this state with a tax system.'),
|
|
48
|
+
customer_id: z.string().optional().describe('Only this customer\'s invoices: the customer\'s id.'),
|
|
49
|
+
limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
|
|
50
|
+
offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
|
|
51
|
+
}),
|
|
52
|
+
access: 'read',
|
|
53
|
+
permission: 'invoice.read',
|
|
54
|
+
run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; payment_status?: PaymentStatus[]; overdue?: boolean; source?: InvoiceSource; fiscal_status?: FiscalStatus; customer_id?: string; limit?: number; offset?: number }) => ({
|
|
55
|
+
invoices: await ctx.clients.invoice.list({
|
|
56
|
+
limit: a.limit ?? 25,
|
|
57
|
+
...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}),
|
|
58
|
+
...(a.payment_status ? { payment_status: a.payment_status } : {}), ...(a.overdue !== undefined ? { overdue: a.overdue } : {}),
|
|
59
|
+
...(a.source ? { source: a.source } : {}), ...(a.fiscal_status ? { fiscal_status: a.fiscal_status } : {}), ...(a.customer_id ? { customer_id: a.customer_id } : {}),
|
|
60
|
+
}),
|
|
61
|
+
}),
|
|
62
|
+
}),
|
|
63
|
+
|
|
64
|
+
defineTool({
|
|
65
|
+
name: 'invoice_get',
|
|
66
|
+
title: 'Get one invoice',
|
|
67
|
+
description:
|
|
68
|
+
'Returns one invoice in full: status, number (null while a draft), the customer (id and the name as it was when the invoice was drafted), every line, subtotal, tax, total, amount paid, balance, payment status, issue and due dates, where it came from (`source`, `external_refs`) and every payment recorded on it. ' +
|
|
69
|
+
'`ref` is the invoice\'s id or short id. Fails with `not_found` if there is no such invoice. Read only.',
|
|
70
|
+
input: z.object({ ref: REF }),
|
|
71
|
+
access: 'read',
|
|
72
|
+
permission: 'invoice.read',
|
|
73
|
+
run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string }) => ({ invoice: await ctx.clients.invoice.get(a.ref) }),
|
|
74
|
+
}),
|
|
75
|
+
|
|
76
|
+
defineTool({
|
|
77
|
+
name: 'invoice_transactions',
|
|
78
|
+
title: 'List payments',
|
|
79
|
+
description:
|
|
80
|
+
'The money ledger: one entry per payment recorded, newest first. Give `ref` for one invoice\'s payments, or leave it out for every payment of the organization. ' +
|
|
81
|
+
'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.',
|
|
82
|
+
input: z.object({
|
|
83
|
+
ref: REF.optional().describe('An invoice id or short id; leave out for the whole organization.'),
|
|
84
|
+
limit: z.number().int().min(1).max(100).optional().describe('Page size when listing the whole organization, 1 to 100 (default 25).'),
|
|
85
|
+
offset: z.number().int().min(0).optional(),
|
|
86
|
+
}),
|
|
87
|
+
access: 'read',
|
|
88
|
+
permission: 'invoice.read',
|
|
89
|
+
run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; offset?: number }) => ({
|
|
90
|
+
transactions: a.ref
|
|
91
|
+
? await ctx.clients.invoice.invoiceTransactions(a.ref)
|
|
92
|
+
: await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...(a.offset ? { offset: a.offset } : {}) }),
|
|
93
|
+
}),
|
|
94
|
+
}),
|
|
95
|
+
|
|
96
|
+
defineTool({
|
|
97
|
+
name: 'invoice_create',
|
|
98
|
+
title: 'Draft an invoice',
|
|
99
|
+
description:
|
|
100
|
+
'Creates a DRAFT invoice for a customer and returns it. WRITES. The draft has no number and nothing is owed until it is finalized (invoice_finalize), so it is safe to prepare and then show the user. ' +
|
|
101
|
+
'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
|
|
102
|
+
'Lines carry a description, a quantity and a unit price in integer cents; the amounts and totals are computed for you. There is no tax in this version. ' +
|
|
103
|
+
'It is recorded as you, the agent acting for the person who connected you.',
|
|
104
|
+
input: z.object({
|
|
105
|
+
customer_id,
|
|
106
|
+
currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
|
|
107
|
+
lines: z.array(Line).min(1).describe('At least one line.'),
|
|
108
|
+
}),
|
|
109
|
+
access: 'write',
|
|
110
|
+
permission: 'invoice.write',
|
|
111
|
+
run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[] }) => ({
|
|
112
|
+
invoice: await ctx.clients.invoice.create(a),
|
|
113
|
+
}),
|
|
114
|
+
}),
|
|
115
|
+
|
|
116
|
+
defineTool({
|
|
117
|
+
name: 'invoice_update',
|
|
118
|
+
title: 'Edit a draft invoice',
|
|
119
|
+
description:
|
|
120
|
+
'Changes a DRAFT invoice\'s customer and/or replaces ALL its lines, and returns it. WRITES. Send the full new list of lines, not a delta. ' +
|
|
121
|
+
'Only drafts can be edited: a finalized, paid or void invoice is refused with `not_draft` (a finalized invoice is a legal record; to undo one, void it and draft a new one).',
|
|
122
|
+
input: z.object({
|
|
123
|
+
ref: REF,
|
|
124
|
+
customer_id: customer_id.optional(),
|
|
125
|
+
lines: z.array(Line).min(1).optional().describe('The complete new set of lines.'),
|
|
126
|
+
}),
|
|
127
|
+
access: 'write',
|
|
128
|
+
permission: 'invoice.write',
|
|
129
|
+
async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; customer_id?: string; lines?: z.infer<typeof Line>[] }) {
|
|
130
|
+
const { ref, ...patch } = a
|
|
131
|
+
if (patch.customer_id === undefined && patch.lines === undefined) throw Object.assign(new Error('Send customer_id and/or lines'), { code: 'nothing_to_update', status: 400 })
|
|
132
|
+
return { invoice: await ctx.clients.invoice.update(ref, patch) }
|
|
133
|
+
},
|
|
134
|
+
}),
|
|
135
|
+
|
|
136
|
+
defineTool({
|
|
137
|
+
name: 'invoice_finalize',
|
|
138
|
+
title: 'Finalize an invoice',
|
|
139
|
+
description:
|
|
140
|
+
'Issues a draft: it gets the next number of the organization, its lines and totals are frozen for good, and it becomes owed. WRITES, and it cannot be undone (only voided). ' +
|
|
141
|
+
'Ask the user to confirm before you do it. Optionally set `issued_at` and `due_at` (epoch milliseconds; the issue date defaults to now, no due date by default). ' +
|
|
142
|
+
'Only a draft can be finalized: otherwise `not_draft`.',
|
|
143
|
+
input: z.object({
|
|
144
|
+
ref: REF,
|
|
145
|
+
issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
|
|
146
|
+
due_at: z.number().int().optional().describe('Epoch milliseconds; omit for no due date.'),
|
|
147
|
+
}),
|
|
148
|
+
access: 'write',
|
|
149
|
+
permission: 'invoice.finalize',
|
|
150
|
+
async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number }) {
|
|
151
|
+
const { ref, ...input } = a
|
|
152
|
+
return { invoice: await ctx.clients.invoice.finalize(ref, input) }
|
|
153
|
+
},
|
|
154
|
+
}),
|
|
155
|
+
|
|
156
|
+
defineTool({
|
|
157
|
+
name: 'invoice_record_payment',
|
|
158
|
+
title: 'Record a payment',
|
|
159
|
+
description:
|
|
160
|
+
'Records that money was received against a FINALIZED invoice, and returns the invoice with its new balance; when the balance reaches zero it becomes `paid`. WRITES to the books. ' +
|
|
161
|
+
'The amount is integer cents and cannot exceed the balance (`overpayment`); a draft, void or already paid invoice is refused. ' +
|
|
162
|
+
'Give `reference` (the bank or processor\'s own id) whenever you have one: a second call with the same reference on the same invoice changes nothing, so a retry is safe. ' +
|
|
163
|
+
'This records a payment that happened; it does not charge anybody.',
|
|
164
|
+
input: z.object({
|
|
165
|
+
ref: REF,
|
|
166
|
+
amount_cents: z.number().int().positive().describe('Integer cents received: 100.00 is 10000.'),
|
|
167
|
+
method: z.string().optional().describe('e.g. bank, cash, card.'),
|
|
168
|
+
reference: z.string().optional().describe('The payer\'s or processor\'s own id for this payment; makes a retry safe.'),
|
|
169
|
+
payment_id: z.string().optional().describe('The id of the payment record this settles (from pay-service); the same payment_id twice records it once. Needed to record a payment on an invoice that mirrors Stripe\'s.'),
|
|
170
|
+
}),
|
|
171
|
+
access: 'write',
|
|
172
|
+
permission: 'invoice.record_payment',
|
|
173
|
+
async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string; payment_id?: string }) {
|
|
174
|
+
const { ref, ...input } = a
|
|
175
|
+
return { invoice: await ctx.clients.invoice.recordPayment(ref, input) }
|
|
176
|
+
},
|
|
177
|
+
}),
|
|
178
|
+
|
|
179
|
+
defineTool({
|
|
180
|
+
name: 'invoice_void',
|
|
181
|
+
title: 'Void an invoice',
|
|
182
|
+
description:
|
|
183
|
+
'Cancels a FINALIZED invoice that has no payments: its status becomes `void` and it stays on record. WRITES, and it cannot be undone. Ask the user to confirm first. ' +
|
|
184
|
+
'Drafts are not voided (edit them or leave them); an invoice with payments or already paid is refused (`has_payments`, `already_paid`). Give a `reason`.',
|
|
185
|
+
input: z.object({ ref: REF, reason: z.string().optional().describe('Why it is being voided; kept on the record.') }),
|
|
186
|
+
access: 'write',
|
|
187
|
+
permission: 'invoice.void',
|
|
188
|
+
run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; reason?: string }) => ({ invoice: await ctx.clients.invoice.void(a.ref, a.reason) }),
|
|
189
|
+
}),
|
|
190
|
+
]
|
|
191
|
+
}
|
package/src/projections.ts
CHANGED
|
@@ -11,43 +11,77 @@ import { InvoiceEvents, TransactionEvents } from './events.js'
|
|
|
11
11
|
*/
|
|
12
12
|
export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) => ({
|
|
13
13
|
InvoiceDrafted: on.InvoiceDrafted.upsert((e) => ({
|
|
14
|
-
customer_id: e.
|
|
15
|
-
customer_name: e.
|
|
14
|
+
customer_id: e.customer_id,
|
|
15
|
+
customer_name: e.customer_name,
|
|
16
16
|
currency: e.currency,
|
|
17
17
|
lines: e.lines,
|
|
18
18
|
number: 0,
|
|
19
19
|
status: 'draft',
|
|
20
|
-
subtotal_cents: e.
|
|
21
|
-
total_cents: e.
|
|
20
|
+
subtotal_cents: e.subtotal_cents,
|
|
21
|
+
total_cents: e.total_cents,
|
|
22
22
|
amount_paid_cents: 0,
|
|
23
23
|
issued_at: 0,
|
|
24
24
|
due_at: 0,
|
|
25
|
-
short_id: e.
|
|
25
|
+
short_id: e.short_id,
|
|
26
|
+
source: e.source ?? null,
|
|
27
|
+
metadata: e.metadata ?? null,
|
|
26
28
|
created_at: e.at,
|
|
27
29
|
})),
|
|
28
30
|
InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
|
|
29
|
-
customer_id: e.
|
|
30
|
-
customer_name: e.
|
|
31
|
+
customer_id: e.customer_id,
|
|
32
|
+
customer_name: e.customer_name,
|
|
31
33
|
lines: e.lines,
|
|
32
|
-
subtotal_cents: e.
|
|
33
|
-
total_cents: e.
|
|
34
|
+
subtotal_cents: e.subtotal_cents,
|
|
35
|
+
total_cents: e.total_cents,
|
|
36
|
+
metadata: e.metadata ?? null,
|
|
34
37
|
})),
|
|
35
38
|
InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
|
|
36
39
|
number: e.number,
|
|
37
40
|
status: 'finalized',
|
|
38
41
|
lines: e.lines,
|
|
39
|
-
subtotal_cents: e.
|
|
40
|
-
total_cents: e.
|
|
41
|
-
issued_at: e.
|
|
42
|
-
due_at: e.
|
|
42
|
+
subtotal_cents: e.subtotal_cents,
|
|
43
|
+
total_cents: e.total_cents,
|
|
44
|
+
issued_at: e.issued_at,
|
|
45
|
+
due_at: e.due_at,
|
|
43
46
|
})),
|
|
44
47
|
PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
|
|
45
|
-
amount_paid_cents: e.
|
|
48
|
+
amount_paid_cents: e.amount_paid_cents,
|
|
46
49
|
status: e.status,
|
|
47
50
|
})),
|
|
48
51
|
InvoiceVoided: on.InvoiceVoided.upsert(() => ({
|
|
49
52
|
status: 'void',
|
|
50
53
|
})),
|
|
54
|
+
// The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
|
|
55
|
+
InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
|
|
56
|
+
source: e.source,
|
|
57
|
+
mirror_key: e.mirror_key,
|
|
58
|
+
external_refs: e.external_refs,
|
|
59
|
+
customer_id: e.customer_id,
|
|
60
|
+
customer_name: e.customer_name,
|
|
61
|
+
currency: e.currency,
|
|
62
|
+
lines: e.lines,
|
|
63
|
+
number: 0,
|
|
64
|
+
status: e.status,
|
|
65
|
+
subtotal_cents: e.subtotal_cents,
|
|
66
|
+
tax_cents: e.tax_cents,
|
|
67
|
+
total_cents: e.total_cents,
|
|
68
|
+
amount_paid_cents: e.amount_paid_cents,
|
|
69
|
+
issued_at: e.issued_at,
|
|
70
|
+
due_at: e.due_at,
|
|
71
|
+
paid_at: e.paid_at,
|
|
72
|
+
voided_at: e.voided_at,
|
|
73
|
+
provider_updated_at: e.provider_updated_at,
|
|
74
|
+
metadata: e.metadata,
|
|
75
|
+
short_id: e.short_id,
|
|
76
|
+
created_at: e.created_at,
|
|
77
|
+
})),
|
|
78
|
+
InvoiceFiscalChanged: on.InvoiceFiscalChanged.upsert((e) => ({
|
|
79
|
+
fiscal_status: e.status,
|
|
80
|
+
fiscal_system: e.system,
|
|
81
|
+
fiscal_external_id: e.external_id,
|
|
82
|
+
fiscal_message: e.message,
|
|
83
|
+
fiscal_updated_at: e.at,
|
|
84
|
+
})),
|
|
51
85
|
}))
|
|
52
86
|
|
|
53
87
|
/**
|
|
@@ -56,15 +90,16 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
|
|
|
56
90
|
*/
|
|
57
91
|
export const readTransactions = defineProjection('transactions', TransactionEvents, (on) => ({
|
|
58
92
|
TransactionRecorded: on.TransactionRecorded.upsert((e) => ({
|
|
59
|
-
invoice_id: e.
|
|
60
|
-
invoice_number: e.
|
|
61
|
-
customer_id: e.
|
|
62
|
-
customer_name: e.
|
|
93
|
+
invoice_id: e.invoice_id,
|
|
94
|
+
invoice_number: e.invoice_number,
|
|
95
|
+
customer_id: e.customer_id,
|
|
96
|
+
customer_name: e.customer_name,
|
|
63
97
|
kind: e.kind,
|
|
64
|
-
amount_cents: e.
|
|
98
|
+
amount_cents: e.amount_cents,
|
|
65
99
|
currency: e.currency,
|
|
66
100
|
method: e.method,
|
|
67
101
|
reference: e.reference,
|
|
102
|
+
payment_id: e.payment_id ?? null,
|
|
68
103
|
created_at: e.at,
|
|
69
104
|
})),
|
|
70
105
|
}))
|