@baseworks/invoice 1.0.0 → 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 +23 -0
- package/dist/{chunk-ITMZVGLQ.js → chunk-335MPCTE.js} +55 -0
- package/dist/cli.js +20 -4
- package/dist/client.d.ts +118 -7
- package/dist/client.js +18 -0
- package/dist/events.d.ts +108 -3
- package/dist/events.js +5 -1
- package/dist/mcp.js +19 -4
- package/dist/projections.js +37 -2
- package/package.json +1 -1
- package/src/__tests__/cli.test.ts +18 -0
- package/src/__tests__/client.test.ts +40 -1
- package/src/__tests__/mcp.test.ts +13 -0
- package/src/cli.ts +36 -11
- package/src/client.ts +34 -1
- package/src/events.ts +44 -0
- package/src/mcp.ts +18 -6
- package/src/projections.ts +35 -0
- package/src/types.ts +114 -2
package/dist/mcp.js
CHANGED
|
@@ -14,22 +14,36 @@ function invoiceTools() {
|
|
|
14
14
|
defineTool({
|
|
15
15
|
name: "invoice_list",
|
|
16
16
|
title: "List invoices",
|
|
17
|
-
description:
|
|
17
|
+
description: 'Lists the organization\'s invoices, newest first. Narrow with `status`: draft (being prepared, no number yet), finalized (issued, owed), paid or void. 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: filter with `payment_status`, `overdue`, `source`, `fiscal_status` and `customer_id`; filters combine. Money is integer cents. Returns `{ invoices }`. Read only.',
|
|
18
18
|
input: z.object({
|
|
19
19
|
status: z.enum(["draft", "finalized", "paid", "void"]).optional().describe("Only invoices in this status."),
|
|
20
|
+
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."),
|
|
21
|
+
overdue: z.boolean().optional().describe("true: only what is owed and past its due date."),
|
|
22
|
+
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."),
|
|
23
|
+
fiscal_status: z.enum(["not_submitted", "queued", "submitted", "accepted", "rejected", "cancelled"]).optional().describe("Only invoices in this state with a tax system."),
|
|
24
|
+
customer_id: z.string().optional().describe("Only this customer's invoices: the customer's id."),
|
|
20
25
|
limit: z.number().int().min(1).max(100).optional().describe("Page size, 1 to 100 (default 25)."),
|
|
21
26
|
offset: z.number().int().min(0).optional().describe("How many to skip, for the next page.")
|
|
22
27
|
}),
|
|
23
28
|
access: "read",
|
|
24
29
|
permission: "invoice.read",
|
|
25
30
|
run: async (ctx, a) => ({
|
|
26
|
-
invoices: await ctx.clients.invoice.list({
|
|
31
|
+
invoices: await ctx.clients.invoice.list({
|
|
32
|
+
limit: a.limit ?? 25,
|
|
33
|
+
...a.offset ? { offset: a.offset } : {},
|
|
34
|
+
...a.status ? { status: a.status } : {},
|
|
35
|
+
...a.payment_status ? { payment_status: a.payment_status } : {},
|
|
36
|
+
...a.overdue !== void 0 ? { overdue: a.overdue } : {},
|
|
37
|
+
...a.source ? { source: a.source } : {},
|
|
38
|
+
...a.fiscal_status ? { fiscal_status: a.fiscal_status } : {},
|
|
39
|
+
...a.customer_id ? { customer_id: a.customer_id } : {}
|
|
40
|
+
})
|
|
27
41
|
})
|
|
28
42
|
}),
|
|
29
43
|
defineTool({
|
|
30
44
|
name: "invoice_get",
|
|
31
45
|
title: "Get one invoice",
|
|
32
|
-
description: "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, total, amount paid, balance, issue and due dates. `ref` is the invoice's id or short id. Fails with `not_found` if there is no such invoice. Read only.",
|
|
46
|
+
description: "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. `ref` is the invoice's id or short id. Fails with `not_found` if there is no such invoice. Read only.",
|
|
33
47
|
input: z.object({ ref: REF }),
|
|
34
48
|
access: "read",
|
|
35
49
|
permission: "invoice.read",
|
|
@@ -106,7 +120,8 @@ function invoiceTools() {
|
|
|
106
120
|
ref: REF,
|
|
107
121
|
amount_cents: z.number().int().positive().describe("Integer cents received: 100.00 is 10000."),
|
|
108
122
|
method: z.string().optional().describe("e.g. bank, cash, card."),
|
|
109
|
-
reference: z.string().optional().describe("The payer's or processor's own id for this payment; makes a retry safe.")
|
|
123
|
+
reference: z.string().optional().describe("The payer's or processor's own id for this payment; makes a retry safe."),
|
|
124
|
+
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.")
|
|
110
125
|
}),
|
|
111
126
|
access: "write",
|
|
112
127
|
permission: "invoice.record_payment",
|
package/dist/projections.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
InvoiceEvents,
|
|
3
3
|
TransactionEvents
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-335MPCTE.js";
|
|
5
5
|
|
|
6
6
|
// src/projections.ts
|
|
7
7
|
import { defineProjection } from "@baseworks/foldbase";
|
|
@@ -19,6 +19,8 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
|
|
|
19
19
|
issued_at: 0,
|
|
20
20
|
due_at: 0,
|
|
21
21
|
short_id: e.short_id,
|
|
22
|
+
source: e.source ?? null,
|
|
23
|
+
metadata: e.metadata ?? null,
|
|
22
24
|
created_at: e.at
|
|
23
25
|
})),
|
|
24
26
|
InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
|
|
@@ -26,7 +28,8 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
|
|
|
26
28
|
customer_name: e.customer_name,
|
|
27
29
|
lines: e.lines,
|
|
28
30
|
subtotal_cents: e.subtotal_cents,
|
|
29
|
-
total_cents: e.total_cents
|
|
31
|
+
total_cents: e.total_cents,
|
|
32
|
+
metadata: e.metadata ?? null
|
|
30
33
|
})),
|
|
31
34
|
InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
|
|
32
35
|
number: e.number,
|
|
@@ -43,6 +46,37 @@ var readInvoices = defineProjection("invoices", InvoiceEvents, (on) => ({
|
|
|
43
46
|
})),
|
|
44
47
|
InvoiceVoided: on.InvoiceVoided.upsert(() => ({
|
|
45
48
|
status: "void"
|
|
49
|
+
})),
|
|
50
|
+
// The provider's whole document. `number` is 0 and stays 0: a mirror has no number of the organization's own.
|
|
51
|
+
InvoiceMirrored: on.InvoiceMirrored.upsert((e) => ({
|
|
52
|
+
source: e.source,
|
|
53
|
+
mirror_key: e.mirror_key,
|
|
54
|
+
external_refs: e.external_refs,
|
|
55
|
+
customer_id: e.customer_id,
|
|
56
|
+
customer_name: e.customer_name,
|
|
57
|
+
currency: e.currency,
|
|
58
|
+
lines: e.lines,
|
|
59
|
+
number: 0,
|
|
60
|
+
status: e.status,
|
|
61
|
+
subtotal_cents: e.subtotal_cents,
|
|
62
|
+
tax_cents: e.tax_cents,
|
|
63
|
+
total_cents: e.total_cents,
|
|
64
|
+
amount_paid_cents: e.amount_paid_cents,
|
|
65
|
+
issued_at: e.issued_at,
|
|
66
|
+
due_at: e.due_at,
|
|
67
|
+
paid_at: e.paid_at,
|
|
68
|
+
voided_at: e.voided_at,
|
|
69
|
+
provider_updated_at: e.provider_updated_at,
|
|
70
|
+
metadata: e.metadata,
|
|
71
|
+
short_id: e.short_id,
|
|
72
|
+
created_at: e.created_at
|
|
73
|
+
})),
|
|
74
|
+
InvoiceFiscalChanged: on.InvoiceFiscalChanged.upsert((e) => ({
|
|
75
|
+
fiscal_status: e.status,
|
|
76
|
+
fiscal_system: e.system,
|
|
77
|
+
fiscal_external_id: e.external_id,
|
|
78
|
+
fiscal_message: e.message,
|
|
79
|
+
fiscal_updated_at: e.at
|
|
46
80
|
}))
|
|
47
81
|
}));
|
|
48
82
|
var readTransactions = defineProjection("transactions", TransactionEvents, (on) => ({
|
|
@@ -56,6 +90,7 @@ var readTransactions = defineProjection("transactions", TransactionEvents, (on)
|
|
|
56
90
|
currency: e.currency,
|
|
57
91
|
method: e.method,
|
|
58
92
|
reference: e.reference,
|
|
93
|
+
payment_id: e.payment_id ?? null,
|
|
59
94
|
created_at: e.at
|
|
60
95
|
}))
|
|
61
96
|
}));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baseworks/invoice",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Invoice capability: typed HTTP client, event catalog, projections, and CLI plugin for invoice-service (AR ledger). Contract-first, versioned with the service.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -29,6 +29,24 @@ const DRAFT = {
|
|
|
29
29
|
const FINAL = { ...DRAFT, number: 1, status: 'finalized', issued_at: 1784200000000 }
|
|
30
30
|
const PAID = { ...FINAL, status: 'paid', amount_paid_cents: 150000, balance_cents: 0 }
|
|
31
31
|
|
|
32
|
+
describe('dtab invoices (list filters)', () => {
|
|
33
|
+
it('sends every filter, on the bare command and on ls, and shows the payment column', async () => {
|
|
34
|
+
let seen = ''
|
|
35
|
+
server.use(http.get(`${TEST_BASE}/invoices`, ({ request }) => {
|
|
36
|
+
seen = new URL(request.url).search
|
|
37
|
+
return HttpResponse.json({ invoices: [{ ...DRAFT, status: 'finalized', payment_status: 'unpaid' }] })
|
|
38
|
+
}))
|
|
39
|
+
const r = await run(['invoices', '--payment-status', 'unpaid,partially_paid', '--overdue', '--source', 'stripe', '--fiscal-status', 'queued', '--customer-id', 'cst1', '--status', 'finalized'])
|
|
40
|
+
expect(r.exitCode).toBe(0)
|
|
41
|
+
const q = Object.fromEntries(new URLSearchParams(seen))
|
|
42
|
+
expect(q).toEqual({ status: 'finalized', payment_status: 'unpaid,partially_paid', overdue: 'true', source: 'stripe', fiscal_status: 'queued', customer_id: 'cst1' })
|
|
43
|
+
expect(r.stdout).toContain('PAYMENT')
|
|
44
|
+
expect(r.stdout).toContain('unpaid')
|
|
45
|
+
await run(['invoices', 'ls', '--overdue', '--payment-status', 'paid'])
|
|
46
|
+
expect(Object.fromEntries(new URLSearchParams(seen))).toEqual({ payment_status: 'paid', overdue: 'true' })
|
|
47
|
+
})
|
|
48
|
+
})
|
|
49
|
+
|
|
32
50
|
describe('dtab invoices (list)', () => {
|
|
33
51
|
it('columns incl. NO/STATUS/TOTAL/BALANCE, draft NO shows —', async () => {
|
|
34
52
|
mocks.mockGet('/invoices', { invoices: [DRAFT, FINAL] })
|
|
@@ -93,6 +93,44 @@ describe('what goes out', () => {
|
|
|
93
93
|
})
|
|
94
94
|
})
|
|
95
95
|
|
|
96
|
+
describe('1.1.0: the list filters, the mirror, the fiscal state', () => {
|
|
97
|
+
const sent: Array<{ method: string; url: string; body: unknown }> = []
|
|
98
|
+
const g = (async (url: string, init?: RequestInit) => {
|
|
99
|
+
sent.push({ method: init?.method ?? 'GET', url: String(url), body: init?.body ? JSON.parse(String(init.body)) : undefined })
|
|
100
|
+
if (String(url).includes('/mirror')) return new Response(JSON.stringify({ invoice: INVOICE, created: true }))
|
|
101
|
+
if (init?.method === 'POST') return new Response(JSON.stringify({ invoice: INVOICE }))
|
|
102
|
+
if (String(url).includes('/fiscal')) return new Response(JSON.stringify({ invoice: { ...INVOICE, fiscal: { status: 'queued' } } }))
|
|
103
|
+
return new Response(JSON.stringify({ invoices: [INVOICE] }))
|
|
104
|
+
}) as unknown as typeof fetch
|
|
105
|
+
const c = () => new InvoiceClient({ base_url: 'http://i.test/api', fetch: g })
|
|
106
|
+
|
|
107
|
+
it('list sends every filter, several payment statuses comma-separated', async () => {
|
|
108
|
+
sent.length = 0
|
|
109
|
+
await c().list({ status: 'finalized', payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1', limit: 5 })
|
|
110
|
+
const q = new URL(sent[0]!.url).searchParams
|
|
111
|
+
expect(Object.fromEntries(q)).toEqual({ limit: '5', status: 'finalized', payment_status: 'unpaid,partially_paid', overdue: 'true', source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' })
|
|
112
|
+
sent.length = 0
|
|
113
|
+
await c().list({ payment_status: 'paid', overdue: false })
|
|
114
|
+
expect(Object.fromEntries(new URL(sent[0]!.url).searchParams)).toEqual({ payment_status: 'paid', overdue: 'false' })
|
|
115
|
+
})
|
|
116
|
+
it('mirror PUTs the whole document; setFiscal PUTs the state; both read the old names too', async () => {
|
|
117
|
+
sent.length = 0
|
|
118
|
+
const doc = { source: 'stripe' as const, external_ref: { system: 'stripe', id: 'in_1' }, customer_id: 'c1', currency: 'USD', lines: [], subtotal_cents: 0, tax_cents: 0, total_cents: 0, status: 'finalized' as const, issued_at: 1, provider_updated_at: 2 }
|
|
119
|
+
const r = await c().mirror(doc)
|
|
120
|
+
expect(sent[0]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/mirror', body: doc })
|
|
121
|
+
expect(r.created).toBe(true)
|
|
122
|
+
expect(r.invoice.totalCents).toBe(1000)
|
|
123
|
+
const inv = await c().setFiscal('i1', { status: 'queued', system: 'gib' })
|
|
124
|
+
expect(sent[1]).toEqual({ method: 'PUT', url: 'http://i.test/api/invoices/i1/fiscal', body: { status: 'queued', system: 'gib' } })
|
|
125
|
+
expect(inv.fiscal?.status).toBe('queued')
|
|
126
|
+
})
|
|
127
|
+
it('recordPayment sends payment_id', async () => {
|
|
128
|
+
sent.length = 0
|
|
129
|
+
await c().recordPayment('i1', { amount_cents: 5, payment_id: 'pay_1' })
|
|
130
|
+
expect(sent[0]!.body).toEqual({ amount_cents: 5, payment_id: 'pay_1' })
|
|
131
|
+
})
|
|
132
|
+
})
|
|
133
|
+
|
|
96
134
|
describe('the source is snake_case', () => {
|
|
97
135
|
it('compat.ts is the only place the old names live', async () => {
|
|
98
136
|
const { readdirSync, readFileSync } = await import('node:fs')
|
|
@@ -100,7 +138,8 @@ describe('the source is snake_case', () => {
|
|
|
100
138
|
const { fileURLToPath } = await import('node:url')
|
|
101
139
|
const src = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
|
102
140
|
const OLD = /\.(customerId|customerName|shortId|subtotalCents|totalCents|amountPaidCents|balanceCents|issuedAt|dueAt|createdAt|updatedAt|unitPriceCents|amountCents|productId|invoiceId|invoiceNumber|userId|orgId|baseUrl)\b/
|
|
103
|
-
|
|
141
|
+
// cli.ts is left out: `opts.customerId` is the name commander gives `--customer-id`
|
|
142
|
+
for (const f of readdirSync(src).filter((x) => x.endsWith('.ts') && !['compat.ts', 'graphql.ts', 'cli.ts'].includes(x))) {
|
|
104
143
|
const hits = readFileSync(join(src, f), 'utf8').split('\n').map((l, i) => [i + 1, l] as const).filter(([, l]) => OLD.test(l) && !/deprecated|Deprecated/i.test(l))
|
|
105
144
|
expect(hits, f).toEqual([])
|
|
106
145
|
}
|
|
@@ -73,6 +73,19 @@ describe('through a real MCP client', () => {
|
|
|
73
73
|
expect((t.find((x) => x.name === 'invoice_create')!.inputSchema as { required?: string[] }).required).toEqual(['customer_id', 'currency', 'lines'])
|
|
74
74
|
})
|
|
75
75
|
|
|
76
|
+
it('list: the filters reach the client; payment_status is a list', async () => {
|
|
77
|
+
const c = await session()
|
|
78
|
+
await c.callTool({ name: 'invoice_list', arguments: { payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' } })
|
|
79
|
+
expect(calls).toEqual([['list', { limit: 25, payment_status: ['unpaid', 'partially_paid'], overdue: true, source: 'stripe', fiscal_status: 'queued', customer_id: 'c1' }]])
|
|
80
|
+
for (const bad of [{ payment_status: [] }, { payment_status: ['late'] }, { source: 'paypal' }]) expect(await refused(c, 'invoice_list', bad), JSON.stringify(bad)).toBeTruthy()
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
it('record_payment: payment_id is passed on', async () => {
|
|
84
|
+
const c = await session()
|
|
85
|
+
await c.callTool({ name: 'invoice_record_payment', arguments: { ref: 'i1', amount_cents: 5, payment_id: 'pay_1' } })
|
|
86
|
+
expect(calls).toEqual([['recordPayment', 'i1', { amount_cents: 5, payment_id: 'pay_1' }]])
|
|
87
|
+
})
|
|
88
|
+
|
|
76
89
|
it('list: a status and a page; defaults to 25', async () => {
|
|
77
90
|
const c = await session()
|
|
78
91
|
expect(out(await c.callTool({ name: 'invoice_list', arguments: { status: 'finalized', limit: 5, offset: 10 } }))).toEqual({ invoices: [{ id: 'i1' }] })
|
package/src/cli.ts
CHANGED
|
@@ -33,6 +33,9 @@ type InvoiceRow = {
|
|
|
33
33
|
amount_paid_cents: number
|
|
34
34
|
balance_cents: number
|
|
35
35
|
created_at?: number
|
|
36
|
+
payment_status?: string
|
|
37
|
+
source?: string
|
|
38
|
+
fiscal?: { status: string } | null
|
|
36
39
|
}
|
|
37
40
|
|
|
38
41
|
const die = (e: unknown): never => fatal(e instanceof Error ? e.message : String(e))
|
|
@@ -64,21 +67,40 @@ function parseLine(spec: string): { description: string; quantity: number; unit_
|
|
|
64
67
|
|
|
65
68
|
const NUMBER_COL = (v: unknown): string => (v ? `#${v}` : '—')
|
|
66
69
|
|
|
70
|
+
/** The list's filters, on the bare command and on `ls`. */
|
|
71
|
+
const filterOptions = (c: Command): Command =>
|
|
72
|
+
c.option('--status <status>', 'Filter: draft | finalized | paid | void')
|
|
73
|
+
.option('--payment-status <list>', 'unpaid | partially_paid | paid | not_due (comma-separated)')
|
|
74
|
+
.option('--overdue', 'Owed, with a due date in the past')
|
|
75
|
+
.option('--source <source>', 'local | stripe | manual')
|
|
76
|
+
.option('--fiscal-status <status>', 'not_submitted | queued | submitted | accepted | rejected | cancelled')
|
|
77
|
+
.option('--customer-id <id>', 'Only this customer (its id)')
|
|
78
|
+
|
|
67
79
|
export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
68
80
|
const { http } = deps
|
|
69
81
|
const cli = deps.cliName ?? 'cli'
|
|
70
82
|
|
|
71
|
-
|
|
72
|
-
|
|
83
|
+
type ListOpts = { output: string; status?: string; paymentStatus?: string; overdue?: boolean; source?: string; fiscalStatus?: string; customerId?: string }
|
|
84
|
+
const listInvoices = async (opts: ListOpts) => {
|
|
85
|
+
const params = new URLSearchParams()
|
|
86
|
+
if (opts.status) params.set('status', opts.status)
|
|
87
|
+
if (opts.paymentStatus) params.set('payment_status', opts.paymentStatus)
|
|
88
|
+
if (opts.overdue) params.set('overdue', 'true')
|
|
89
|
+
if (opts.source) params.set('source', opts.source)
|
|
90
|
+
if (opts.fiscalStatus) params.set('fiscal_status', opts.fiscalStatus)
|
|
91
|
+
if (opts.customerId) params.set('customer_id', opts.customerId)
|
|
92
|
+
const q = params.toString() ? `?${params}` : ''
|
|
73
93
|
const res = await http.get<{ invoices: InvoiceRow[] }>(`/invoices${q}`).catch(die)
|
|
74
94
|
printOutput(res.invoices, opts.output, (wide) => {
|
|
75
95
|
table(res.invoices, [
|
|
76
96
|
{ key: 'short_id', label: 'ID' },
|
|
77
97
|
{ key: 'number', label: 'NO', fmt: NUMBER_COL },
|
|
78
98
|
{ key: 'status', label: 'STATUS' },
|
|
99
|
+
{ key: 'payment_status', label: 'PAYMENT', fmt: (v) => (v as string) ?? '' },
|
|
79
100
|
{ key: 'customer_name', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customer_id },
|
|
80
101
|
{ key: 'total_cents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
|
|
81
102
|
{ key: 'balance_cents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
|
|
103
|
+
{ key: 'source', label: 'SOURCE', wide: true, fmt: (v) => (v as string) ?? 'local' },
|
|
82
104
|
{ key: 'created_at', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
|
|
83
105
|
{ key: 'id', label: 'FULL ID', wide: true },
|
|
84
106
|
] as ColDef<InvoiceRow>[], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` })
|
|
@@ -86,24 +108,27 @@ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
|
|
|
86
108
|
}, 'id')
|
|
87
109
|
}
|
|
88
110
|
|
|
89
|
-
const cmd = new Command('invoices')
|
|
111
|
+
const cmd: Command = new Command('invoices')
|
|
90
112
|
.aliases(['inv', 'invoice'])
|
|
91
113
|
.description('Manage invoices (org-scoped — run `use <org>` first)')
|
|
92
114
|
.option(...outputOption())
|
|
93
|
-
|
|
94
|
-
.action(listInvoices)
|
|
115
|
+
filterOptions(cmd).action(listInvoices)
|
|
95
116
|
|
|
96
117
|
cmd.addCommand(
|
|
97
|
-
new Command('ls')
|
|
118
|
+
filterOptions(new Command('ls')
|
|
98
119
|
.description('List invoices (alias of the bare command)')
|
|
99
|
-
.option(...outputOption())
|
|
100
|
-
.option('--status <status>', 'Filter by status')
|
|
120
|
+
.option(...outputOption()))
|
|
101
121
|
.action(function (this: Command) {
|
|
102
|
-
const self = this.opts() as
|
|
103
|
-
const parent = (this.parent?.opts() ?? {}) as
|
|
122
|
+
const self = this.opts() as ListOpts
|
|
123
|
+
const parent = (this.parent?.opts() ?? {}) as ListOpts
|
|
104
124
|
return listInvoices({
|
|
105
125
|
output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
|
|
106
|
-
status: self.status ?? parent.status,
|
|
126
|
+
...(self.status ?? parent.status ? { status: (self.status ?? parent.status) as string } : {}),
|
|
127
|
+
...(self.paymentStatus ?? parent.paymentStatus ? { paymentStatus: (self.paymentStatus ?? parent.paymentStatus) as string } : {}),
|
|
128
|
+
...(self.overdue ?? parent.overdue ? { overdue: true } : {}),
|
|
129
|
+
...(self.source ?? parent.source ? { source: (self.source ?? parent.source) as string } : {}),
|
|
130
|
+
...(self.fiscalStatus ?? parent.fiscalStatus ? { fiscalStatus: (self.fiscalStatus ?? parent.fiscalStatus) as string } : {}),
|
|
131
|
+
...(self.customerId ?? parent.customerId ? { customerId: (self.customerId ?? parent.customerId) as string } : {}),
|
|
107
132
|
})
|
|
108
133
|
}),
|
|
109
134
|
)
|
package/src/client.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { newNamesOnFinalize, newNamesOnLines, newNamesOnPayment, oldNamesOnInvoice, oldNamesOnTransaction } from './compat.js'
|
|
2
2
|
import type {
|
|
3
3
|
Invoice,
|
|
4
|
+
ListInvoicesOptions,
|
|
5
|
+
MirrorInvoiceInput,
|
|
6
|
+
MirrorResult,
|
|
7
|
+
FiscalInput,
|
|
4
8
|
Transaction,
|
|
5
9
|
CreateInvoiceInput,
|
|
6
10
|
UpdateInvoiceInput,
|
|
@@ -15,6 +19,17 @@ export type {
|
|
|
15
19
|
InvoiceLine,
|
|
16
20
|
InvoiceLineDto,
|
|
17
21
|
InvoiceDeprecated,
|
|
22
|
+
ExternalRef,
|
|
23
|
+
Fiscal,
|
|
24
|
+
FiscalInput,
|
|
25
|
+
FiscalStatus,
|
|
26
|
+
InvoicePayment,
|
|
27
|
+
InvoiceSource,
|
|
28
|
+
ListInvoicesOptions,
|
|
29
|
+
Metadata,
|
|
30
|
+
MirrorInvoiceInput,
|
|
31
|
+
MirrorResult,
|
|
32
|
+
PaymentStatus,
|
|
18
33
|
InvoiceLineDeprecated,
|
|
19
34
|
TransactionDeprecated,
|
|
20
35
|
InvoiceLineInput,
|
|
@@ -128,11 +143,16 @@ export class InvoiceClient {
|
|
|
128
143
|
|
|
129
144
|
// ── invoices ──────────────────────────────────────────────────────────────
|
|
130
145
|
|
|
131
|
-
async list(opts:
|
|
146
|
+
async list(opts: ListInvoicesOptions = {}): Promise<Invoice[]> {
|
|
132
147
|
const q = new URLSearchParams()
|
|
133
148
|
if (opts.limit !== undefined) q.set('limit', String(opts.limit))
|
|
134
149
|
if (opts.offset !== undefined) q.set('offset', String(opts.offset))
|
|
135
150
|
if (opts.status) q.set('status', opts.status)
|
|
151
|
+
if (opts.payment_status) q.set('payment_status', [opts.payment_status].flat().join(','))
|
|
152
|
+
if (opts.overdue !== undefined) q.set('overdue', String(opts.overdue))
|
|
153
|
+
if (opts.source) q.set('source', opts.source)
|
|
154
|
+
if (opts.fiscal_status) q.set('fiscal_status', opts.fiscal_status)
|
|
155
|
+
if (opts.customer_id) q.set('customer_id', opts.customer_id)
|
|
136
156
|
const qs = q.toString()
|
|
137
157
|
const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/invoices${qs ? `?${qs}` : ''}`)
|
|
138
158
|
return invoices.map(oldNamesOnInvoice)
|
|
@@ -149,6 +169,19 @@ export class InvoiceClient {
|
|
|
149
169
|
const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/invoices/${ref}`, newNamesOnLines(input))
|
|
150
170
|
return oldNamesOnInvoice(invoice)
|
|
151
171
|
}
|
|
172
|
+
/**
|
|
173
|
+
* Keep the provider's document (Stripe's invoice, a hand-entered one) as this invoice: creates it or replaces it by
|
|
174
|
+
* `external_ref` (system + id). An older document than the one stored is ignored (`stale`). Needs `invoice.mirror`.
|
|
175
|
+
*/
|
|
176
|
+
async mirror(input: MirrorInvoiceInput): Promise<MirrorResult> {
|
|
177
|
+
const r = await this.api<MirrorResult>('PUT', '/invoices/mirror', input)
|
|
178
|
+
return { ...r, invoice: oldNamesOnInvoice(r.invoice) }
|
|
179
|
+
}
|
|
180
|
+
/** Record where the invoice stands with a tax system. Needs `invoice.fiscal_update`; nothing is sent to any tax system. */
|
|
181
|
+
async setFiscal(ref: string, input: FiscalInput): Promise<Invoice> {
|
|
182
|
+
const { invoice } = await this.api<{ invoice: Invoice }>('PUT', `/invoices/${ref}/fiscal`, input)
|
|
183
|
+
return oldNamesOnInvoice(invoice)
|
|
184
|
+
}
|
|
152
185
|
async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
|
|
153
186
|
const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/invoices/${ref}/finalize`, newNamesOnFinalize(input))
|
|
154
187
|
return oldNamesOnInvoice(invoice)
|
package/src/events.ts
CHANGED
|
@@ -37,6 +37,9 @@ export const InvoiceEvents = defineAggregate('invoice', {
|
|
|
37
37
|
subtotal_cents: z.number().int(),
|
|
38
38
|
total_cents: z.number().int(),
|
|
39
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
|
|
40
43
|
at: z.number().int(),
|
|
41
44
|
}),
|
|
42
45
|
// Draft edited (customer / lines). Only valid while status = draft.
|
|
@@ -46,6 +49,7 @@ export const InvoiceEvents = defineAggregate('invoice', {
|
|
|
46
49
|
lines: z.string(),
|
|
47
50
|
subtotal_cents: z.number().int(),
|
|
48
51
|
total_cents: z.number().int(),
|
|
52
|
+
metadata: z.string().optional(), // 1.1.0
|
|
49
53
|
at: z.number().int(),
|
|
50
54
|
}),
|
|
51
55
|
// Finalize: assign the per-org number, freeze lines + totals, set issue/due.
|
|
@@ -67,14 +71,53 @@ export const InvoiceEvents = defineAggregate('invoice', {
|
|
|
67
71
|
status: InvoiceStatus,
|
|
68
72
|
method: z.string(),
|
|
69
73
|
reference: z.string(),
|
|
74
|
+
payment_id: z.string().optional(), // 1.1.0: the pay record this settles; the idempotency key when present
|
|
70
75
|
at: z.number().int(),
|
|
71
76
|
}),
|
|
72
77
|
InvoiceVoided: z.object({
|
|
73
78
|
reason: z.string(),
|
|
74
79
|
at: z.number().int(),
|
|
75
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
|
+
}),
|
|
76
114
|
})
|
|
77
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
|
+
|
|
78
121
|
/**
|
|
79
122
|
* The transaction ledger — one stream (and one read-model row) PER money movement,
|
|
80
123
|
* unlike the invoice's cached `amount_paid`. A payment emits BOTH `PaymentRecorded`
|
|
@@ -96,6 +139,7 @@ export const TransactionEvents = defineAggregate('transaction', {
|
|
|
96
139
|
currency: z.string().length(3),
|
|
97
140
|
method: z.string(),
|
|
98
141
|
reference: z.string(),
|
|
142
|
+
payment_id: z.string().optional(), // 1.1.0
|
|
99
143
|
at: z.number().int(),
|
|
100
144
|
}),
|
|
101
145
|
})
|
package/src/mcp.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
*/
|
|
15
15
|
import { z } from 'zod'
|
|
16
16
|
import { defineTool, type McpTool } from '@baseworks/mcp'
|
|
17
|
-
import type { InvoiceClient } from './client.js'
|
|
17
|
+
import type { FiscalStatus, InvoiceClient, InvoiceSource, PaymentStatus } from './client.js'
|
|
18
18
|
|
|
19
19
|
/** What `ctx.clients` must hold for these tools. */
|
|
20
20
|
export interface InvoiceMcpClients { invoice: InvoiceClient }
|
|
@@ -37,16 +37,27 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
|
|
|
37
37
|
title: 'List invoices',
|
|
38
38
|
description:
|
|
39
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
|
|
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.',
|
|
41
42
|
input: z.object({
|
|
42
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.'),
|
|
43
49
|
limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
|
|
44
50
|
offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
|
|
45
51
|
}),
|
|
46
52
|
access: 'read',
|
|
47
53
|
permission: 'invoice.read',
|
|
48
|
-
run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; limit?: number; offset?: number }) => ({
|
|
49
|
-
invoices: await ctx.clients.invoice.list({
|
|
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
|
+
}),
|
|
50
61
|
}),
|
|
51
62
|
}),
|
|
52
63
|
|
|
@@ -54,7 +65,7 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
|
|
|
54
65
|
name: 'invoice_get',
|
|
55
66
|
title: 'Get one invoice',
|
|
56
67
|
description:
|
|
57
|
-
'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, total, amount paid, balance, issue and due dates. ' +
|
|
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. ' +
|
|
58
69
|
'`ref` is the invoice\'s id or short id. Fails with `not_found` if there is no such invoice. Read only.',
|
|
59
70
|
input: z.object({ ref: REF }),
|
|
60
71
|
access: 'read',
|
|
@@ -155,10 +166,11 @@ export function invoiceTools(): McpTool<InvoiceMcpClients>[] {
|
|
|
155
166
|
amount_cents: z.number().int().positive().describe('Integer cents received: 100.00 is 10000.'),
|
|
156
167
|
method: z.string().optional().describe('e.g. bank, cash, card.'),
|
|
157
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.'),
|
|
158
170
|
}),
|
|
159
171
|
access: 'write',
|
|
160
172
|
permission: 'invoice.record_payment',
|
|
161
|
-
async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string }) {
|
|
173
|
+
async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string; payment_id?: string }) {
|
|
162
174
|
const { ref, ...input } = a
|
|
163
175
|
return { invoice: await ctx.clients.invoice.recordPayment(ref, input) }
|
|
164
176
|
},
|
package/src/projections.ts
CHANGED
|
@@ -23,6 +23,8 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
|
|
|
23
23
|
issued_at: 0,
|
|
24
24
|
due_at: 0,
|
|
25
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) => ({
|
|
@@ -31,6 +33,7 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
|
|
|
31
33
|
lines: e.lines,
|
|
32
34
|
subtotal_cents: e.subtotal_cents,
|
|
33
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,
|
|
@@ -48,6 +51,37 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
|
|
|
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
|
/**
|
|
@@ -65,6 +99,7 @@ export const readTransactions = defineProjection('transactions', TransactionEven
|
|
|
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
|
}))
|