@baseworks/invoice 0.1.1 → 1.0.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/src/mcp.ts ADDED
@@ -0,0 +1,179 @@
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 { InvoiceClient } 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 and the `balance_cents` still owed; money is integer cents. Returns `{ invoices }`. Read only.',
41
+ input: z.object({
42
+ status: z.enum(['draft', 'finalized', 'paid', 'void']).optional().describe('Only invoices in this status.'),
43
+ limit: z.number().int().min(1).max(100).optional().describe('Page size, 1 to 100 (default 25).'),
44
+ offset: z.number().int().min(0).optional().describe('How many to skip, for the next page.'),
45
+ }),
46
+ access: 'read',
47
+ permission: 'invoice.read',
48
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { status?: string; limit?: number; offset?: number }) => ({
49
+ invoices: await ctx.clients.invoice.list({ limit: a.limit ?? 25, ...(a.offset ? { offset: a.offset } : {}), ...(a.status ? { status: a.status } : {}) }),
50
+ }),
51
+ }),
52
+
53
+ defineTool({
54
+ name: 'invoice_get',
55
+ title: 'Get one invoice',
56
+ 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. ' +
58
+ '`ref` is the invoice\'s id or short id. Fails with `not_found` if there is no such invoice. Read only.',
59
+ input: z.object({ ref: REF }),
60
+ access: 'read',
61
+ permission: 'invoice.read',
62
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string }) => ({ invoice: await ctx.clients.invoice.get(a.ref) }),
63
+ }),
64
+
65
+ defineTool({
66
+ name: 'invoice_transactions',
67
+ title: 'List payments',
68
+ description:
69
+ '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. ' +
70
+ 'Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.',
71
+ input: z.object({
72
+ ref: REF.optional().describe('An invoice id or short id; leave out for the whole organization.'),
73
+ limit: z.number().int().min(1).max(100).optional().describe('Page size when listing the whole organization, 1 to 100 (default 25).'),
74
+ offset: z.number().int().min(0).optional(),
75
+ }),
76
+ access: 'read',
77
+ permission: 'invoice.read',
78
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref?: string; limit?: number; offset?: number }) => ({
79
+ transactions: a.ref
80
+ ? await ctx.clients.invoice.invoiceTransactions(a.ref)
81
+ : await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...(a.offset ? { offset: a.offset } : {}) }),
82
+ }),
83
+ }),
84
+
85
+ defineTool({
86
+ name: 'invoice_create',
87
+ title: 'Draft an invoice',
88
+ description:
89
+ '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. ' +
90
+ 'The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. ' +
91
+ '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. ' +
92
+ 'It is recorded as you, the agent acting for the person who connected you.',
93
+ input: z.object({
94
+ customer_id,
95
+ currency: z.string().length(3).describe('ISO 4217 code, e.g. EUR, USD, TRY.'),
96
+ lines: z.array(Line).min(1).describe('At least one line.'),
97
+ }),
98
+ access: 'write',
99
+ permission: 'invoice.write',
100
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { customer_id: string; currency: string; lines: z.infer<typeof Line>[] }) => ({
101
+ invoice: await ctx.clients.invoice.create(a),
102
+ }),
103
+ }),
104
+
105
+ defineTool({
106
+ name: 'invoice_update',
107
+ title: 'Edit a draft invoice',
108
+ description:
109
+ '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. ' +
110
+ '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).',
111
+ input: z.object({
112
+ ref: REF,
113
+ customer_id: customer_id.optional(),
114
+ lines: z.array(Line).min(1).optional().describe('The complete new set of lines.'),
115
+ }),
116
+ access: 'write',
117
+ permission: 'invoice.write',
118
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; customer_id?: string; lines?: z.infer<typeof Line>[] }) {
119
+ const { ref, ...patch } = a
120
+ 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 })
121
+ return { invoice: await ctx.clients.invoice.update(ref, patch) }
122
+ },
123
+ }),
124
+
125
+ defineTool({
126
+ name: 'invoice_finalize',
127
+ title: 'Finalize an invoice',
128
+ description:
129
+ '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). ' +
130
+ '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). ' +
131
+ 'Only a draft can be finalized: otherwise `not_draft`.',
132
+ input: z.object({
133
+ ref: REF,
134
+ issued_at: z.number().int().optional().describe('Epoch milliseconds; default now.'),
135
+ due_at: z.number().int().optional().describe('Epoch milliseconds; omit for no due date.'),
136
+ }),
137
+ access: 'write',
138
+ permission: 'invoice.finalize',
139
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; issued_at?: number; due_at?: number }) {
140
+ const { ref, ...input } = a
141
+ return { invoice: await ctx.clients.invoice.finalize(ref, input) }
142
+ },
143
+ }),
144
+
145
+ defineTool({
146
+ name: 'invoice_record_payment',
147
+ title: 'Record a payment',
148
+ description:
149
+ '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. ' +
150
+ 'The amount is integer cents and cannot exceed the balance (`overpayment`); a draft, void or already paid invoice is refused. ' +
151
+ '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. ' +
152
+ 'This records a payment that happened; it does not charge anybody.',
153
+ input: z.object({
154
+ ref: REF,
155
+ amount_cents: z.number().int().positive().describe('Integer cents received: 100.00 is 10000.'),
156
+ method: z.string().optional().describe('e.g. bank, cash, card.'),
157
+ reference: z.string().optional().describe('The payer\'s or processor\'s own id for this payment; makes a retry safe.'),
158
+ }),
159
+ access: 'write',
160
+ permission: 'invoice.record_payment',
161
+ async run(ctx: { clients: InvoiceMcpClients }, a: { ref: string; amount_cents: number; method?: string; reference?: string }) {
162
+ const { ref, ...input } = a
163
+ return { invoice: await ctx.clients.invoice.recordPayment(ref, input) }
164
+ },
165
+ }),
166
+
167
+ defineTool({
168
+ name: 'invoice_void',
169
+ title: 'Void an invoice',
170
+ description:
171
+ '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. ' +
172
+ '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`.',
173
+ input: z.object({ ref: REF, reason: z.string().optional().describe('Why it is being voided; kept on the record.') }),
174
+ access: 'write',
175
+ permission: 'invoice.void',
176
+ run: async (ctx: { clients: InvoiceMcpClients }, a: { ref: string; reason?: string }) => ({ invoice: await ctx.clients.invoice.void(a.ref, a.reason) }),
177
+ }),
178
+ ]
179
+ }
@@ -11,38 +11,38 @@ 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.customerId,
15
- customer_name: e.customerName,
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.subtotalCents,
21
- total_cents: e.totalCents,
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.shortId,
25
+ short_id: e.short_id,
26
26
  created_at: e.at,
27
27
  })),
28
28
  InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
29
- customer_id: e.customerId,
30
- customer_name: e.customerName,
29
+ customer_id: e.customer_id,
30
+ customer_name: e.customer_name,
31
31
  lines: e.lines,
32
- subtotal_cents: e.subtotalCents,
33
- total_cents: e.totalCents,
32
+ subtotal_cents: e.subtotal_cents,
33
+ total_cents: e.total_cents,
34
34
  })),
35
35
  InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
36
36
  number: e.number,
37
37
  status: 'finalized',
38
38
  lines: e.lines,
39
- subtotal_cents: e.subtotalCents,
40
- total_cents: e.totalCents,
41
- issued_at: e.issuedAt,
42
- due_at: e.dueAt,
39
+ subtotal_cents: e.subtotal_cents,
40
+ total_cents: e.total_cents,
41
+ issued_at: e.issued_at,
42
+ due_at: e.due_at,
43
43
  })),
44
44
  PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
45
- amount_paid_cents: e.amountPaidCents,
45
+ amount_paid_cents: e.amount_paid_cents,
46
46
  status: e.status,
47
47
  })),
48
48
  InvoiceVoided: on.InvoiceVoided.upsert(() => ({
@@ -56,12 +56,12 @@ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) =>
56
56
  */
57
57
  export const readTransactions = defineProjection('transactions', TransactionEvents, (on) => ({
58
58
  TransactionRecorded: on.TransactionRecorded.upsert((e) => ({
59
- invoice_id: e.invoiceId,
60
- invoice_number: e.invoiceNumber,
61
- customer_id: e.customerId,
62
- customer_name: e.customerName,
59
+ invoice_id: e.invoice_id,
60
+ invoice_number: e.invoice_number,
61
+ customer_id: e.customer_id,
62
+ customer_name: e.customer_name,
63
63
  kind: e.kind,
64
- amount_cents: e.amountCents,
64
+ amount_cents: e.amount_cents,
65
65
  currency: e.currency,
66
66
  method: e.method,
67
67
  reference: e.reference,
package/src/types.ts CHANGED
@@ -21,71 +21,129 @@ export interface InvoiceRow {
21
21
  updated_at: number
22
22
  }
23
23
 
24
- // ── REST DTOs (camelCase) ─────────────────────────────────────────────────────
24
+ // ── REST DTOs (snake_case, as every service in the realm speaks: ADR-0003) ───
25
+ //
26
+ // Until 0.3.0 the wire was camelCase. The service now answers snake_case only;
27
+ // this client puts the old camelCase names back on what it returns, as
28
+ // non-enumerable properties (readable, but `JSON.stringify` and
29
+ // `toEqual` do not see them), so a caller that has not moved still builds and
30
+ // runs. Every such name is marked @deprecated and listed in the README.
25
31
 
26
- export interface InvoiceLine {
32
+ export interface InvoiceLineDto {
27
33
  description: string
28
34
  /** May be fractional (e.g. hours). */
29
35
  quantity: number
30
36
  /** Unit price in integer cents. */
37
+ unit_price_cents: number
38
+ /** quantity × unit_price_cents, rounded to cents. */
39
+ amount_cents: number
40
+ /** Optional catalog product reference. */
41
+ product_id: string | null
42
+ }
43
+
44
+ export interface InvoiceLineDeprecated {
45
+ /** @deprecated Read `unit_price_cents`. */
31
46
  unitPriceCents: number
32
- /** quantity × unitPriceCents, rounded to cents. */
47
+ /** @deprecated Read `amount_cents`. */
33
48
  amountCents: number
34
- /** Optional catalog product reference. */
49
+ /** @deprecated Read `product_id`. */
35
50
  productId: string | null
36
51
  }
52
+ export type InvoiceLine = InvoiceLineDto & InvoiceLineDeprecated
37
53
 
38
- export interface Invoice {
54
+ export interface InvoiceDto {
39
55
  id: string
40
- shortId: string
56
+ short_id: string
41
57
  /** Per-org invoice number; `null` while draft. */
42
58
  number: number | null
43
59
  status: InvoiceStatus
60
+ customer_id: string
61
+ customer_name: string | null
62
+ currency: string
63
+ lines: InvoiceLineDto[]
64
+ subtotal_cents: number
65
+ total_cents: number
66
+ amount_paid_cents: number
67
+ /** total_cents − amount_paid_cents (0 for draft/void semantics aside). */
68
+ balance_cents: number
69
+ issued_at: number | null
70
+ due_at: number | null
71
+ created_at: number
72
+ updated_at: number
73
+ }
74
+
75
+ export interface InvoiceDeprecated {
76
+ /** @deprecated Read `short_id`. */
77
+ shortId: string
78
+ /** @deprecated Read `customer_id`. */
44
79
  customerId: string
80
+ /** @deprecated Read `customer_name`. */
45
81
  customerName: string | null
46
- currency: string
47
- lines: InvoiceLine[]
82
+ /** @deprecated Read `subtotal_cents`. */
48
83
  subtotalCents: number
84
+ /** @deprecated Read `total_cents`. */
49
85
  totalCents: number
86
+ /** @deprecated Read `amount_paid_cents`. */
50
87
  amountPaidCents: number
51
- /** totalCents − amountPaidCents (0 for draft/void semantics aside). */
88
+ /** @deprecated Read `balance_cents`. */
52
89
  balanceCents: number
90
+ /** @deprecated Read `issued_at`. */
53
91
  issuedAt: number | null
92
+ /** @deprecated Read `due_at`. */
54
93
  dueAt: number | null
94
+ /** @deprecated Read `created_at`. */
55
95
  createdAt: number
96
+ /** @deprecated Read `updated_at`. */
56
97
  updatedAt: number
57
98
  }
99
+ export type Invoice = Omit<InvoiceDto, 'lines'> & { lines: InvoiceLine[] } & InvoiceDeprecated
58
100
 
59
- /** A line as supplied by the caller (amountCents is computed server-side). */
101
+ /** A line as supplied by the caller (amount_cents is computed server-side). */
60
102
  export interface InvoiceLineInput {
61
103
  description: string
62
104
  quantity: number
63
- unitPriceCents: number
105
+ /** Integer cents. */
106
+ unit_price_cents?: number
107
+ product_id?: string
108
+ /** @deprecated Send `unit_price_cents`. */
109
+ unitPriceCents?: number
110
+ /** @deprecated Send `product_id`. */
64
111
  productId?: string
65
112
  }
66
113
 
67
114
  export interface CreateInvoiceInput {
68
- customerId: string
115
+ /** A customers-service ref: id, short id or external id. */
116
+ customer_id?: string
69
117
  currency: string
70
118
  lines: InvoiceLineInput[]
119
+ /** @deprecated Send `customer_id`. */
120
+ customerId?: string
71
121
  }
72
122
 
73
123
  export interface UpdateInvoiceInput {
74
- customerId?: string
124
+ customer_id?: string
75
125
  lines?: InvoiceLineInput[]
126
+ /** @deprecated Send `customer_id`. */
127
+ customerId?: string
76
128
  }
77
129
 
78
130
  export interface FinalizeInvoiceInput {
79
131
  /** Epoch millis; defaults to now server-side. */
80
- issuedAt?: number
132
+ issued_at?: number
81
133
  /** Epoch millis; 0/omitted = no due date. */
134
+ due_at?: number
135
+ /** @deprecated Send `issued_at`. */
136
+ issuedAt?: number
137
+ /** @deprecated Send `due_at`. */
82
138
  dueAt?: number
83
139
  }
84
140
 
85
141
  export interface RecordPaymentInput {
86
- amountCents: number
142
+ amount_cents?: number
87
143
  method?: string
88
144
  reference?: string
145
+ /** @deprecated Send `amount_cents`. */
146
+ amountCents?: number
89
147
  }
90
148
 
91
149
  // ── transactions (the ledger) ─────────────────────────────────────────────────
@@ -105,16 +163,32 @@ export interface TransactionRow {
105
163
  updated_at: number
106
164
  }
107
165
 
108
- export interface Transaction {
166
+ export interface TransactionDto {
109
167
  id: string
168
+ invoice_id: string
169
+ invoice_number: number
170
+ customer_id: string
171
+ customer_name: string | null
172
+ kind: string
173
+ amount_cents: number
174
+ currency: string
175
+ method: string | null
176
+ reference: string | null
177
+ created_at: number
178
+ }
179
+
180
+ export interface TransactionDeprecated {
181
+ /** @deprecated Read `invoice_id`. */
110
182
  invoiceId: string
183
+ /** @deprecated Read `invoice_number`. */
111
184
  invoiceNumber: number
185
+ /** @deprecated Read `customer_id`. */
112
186
  customerId: string
187
+ /** @deprecated Read `customer_name`. */
113
188
  customerName: string | null
114
- kind: string
189
+ /** @deprecated Read `amount_cents`. */
115
190
  amountCents: number
116
- currency: string
117
- method: string | null
118
- reference: string | null
191
+ /** @deprecated Read `created_at`. */
119
192
  createdAt: number
120
193
  }
194
+ export type Transaction = TransactionDto & TransactionDeprecated