@baseworks/invoice 0.1.0 → 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/dist/client.js CHANGED
@@ -1,3 +1,58 @@
1
+ // src/compat.ts
2
+ var INVOICE = {
3
+ shortId: "short_id",
4
+ customerId: "customer_id",
5
+ customerName: "customer_name",
6
+ subtotalCents: "subtotal_cents",
7
+ totalCents: "total_cents",
8
+ amountPaidCents: "amount_paid_cents",
9
+ balanceCents: "balance_cents",
10
+ issuedAt: "issued_at",
11
+ dueAt: "due_at",
12
+ createdAt: "created_at",
13
+ updatedAt: "updated_at"
14
+ };
15
+ var LINE = { unitPriceCents: "unit_price_cents", amountCents: "amount_cents", productId: "product_id" };
16
+ var TRANSACTION = {
17
+ invoiceId: "invoice_id",
18
+ invoiceNumber: "invoice_number",
19
+ customerId: "customer_id",
20
+ customerName: "customer_name",
21
+ amountCents: "amount_cents",
22
+ createdAt: "created_at"
23
+ };
24
+ function alias(o, names) {
25
+ for (const [old, now] of Object.entries(names)) {
26
+ if (old in o) continue;
27
+ Object.defineProperty(o, old, { get: () => o[now], enumerable: false, configurable: true });
28
+ }
29
+ return o;
30
+ }
31
+ function oldNamesOnInvoice(invoice) {
32
+ const o = invoice;
33
+ if (Array.isArray(o.lines)) o.lines.forEach((l) => alias(l, LINE));
34
+ return alias(o, INVOICE);
35
+ }
36
+ function oldNamesOnTransaction(t) {
37
+ return alias(t, TRANSACTION);
38
+ }
39
+ function renamed(body, names) {
40
+ const out = {};
41
+ for (const [k, v] of Object.entries(body ?? {})) {
42
+ const key = names[k] ?? k;
43
+ if (key !== k && key in body) continue;
44
+ out[key] = v;
45
+ }
46
+ return out;
47
+ }
48
+ function newNamesOnLines(body) {
49
+ const out = renamed(body, { customerId: "customer_id" });
50
+ if (Array.isArray(out["lines"])) out["lines"] = out["lines"].map((l) => renamed(l, LINE));
51
+ return out;
52
+ }
53
+ var newNamesOnFinalize = (b) => renamed(b, { issuedAt: "issued_at", dueAt: "due_at" });
54
+ var newNamesOnPayment = (b) => renamed(b, { amountCents: "amount_cents" });
55
+
1
56
  // src/client.ts
2
57
  var InvoiceError = class extends Error {
3
58
  constructor(status, code, message) {
@@ -12,24 +67,27 @@ var InvoiceError = class extends Error {
12
67
  var InvoiceClient = class _InvoiceClient {
13
68
  constructor(opts) {
14
69
  this.opts = opts;
15
- this.baseUrl = opts.baseUrl.replace(/\/$/, "");
70
+ const base = opts.base_url ?? opts.baseUrl;
71
+ if (!base) throw new Error("InvoiceClient needs base_url");
72
+ this.root = base.replace(/\/$/, "");
16
73
  this.fetchImpl = opts.fetch ?? globalThis.fetch;
17
74
  }
18
75
  opts;
19
- baseUrl;
76
+ root;
20
77
  fetchImpl;
21
78
  withOrg(orgId) {
22
- return new _InvoiceClient({ ...this.opts, orgId });
79
+ return new _InvoiceClient({ ...this.opts, org_id: orgId, orgId });
23
80
  }
24
81
  headers(json, extra = {}) {
25
82
  const h = {};
26
83
  if (json) h["Content-Type"] = "application/json";
27
84
  if (this.opts.token) h["Authorization"] = `Bearer ${this.opts.token}`;
28
- if (this.opts.orgId) h["X-Org-Id"] = this.opts.orgId;
85
+ const org = this.opts.org_id ?? this.opts.orgId;
86
+ if (org) h["X-Org-Id"] = org;
29
87
  return { ...h, ...extra };
30
88
  }
31
89
  async api(method, path, body, extra = {}) {
32
- const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
90
+ const res = await this.fetchImpl(`${this.root}${path}`, {
33
91
  method,
34
92
  headers: this.headers(body !== void 0, extra),
35
93
  ...body !== void 0 ? { body: JSON.stringify(body) } : {}
@@ -62,32 +120,32 @@ var InvoiceClient = class _InvoiceClient {
62
120
  if (opts.offset !== void 0) q.set("offset", String(opts.offset));
63
121
  if (opts.status) q.set("status", opts.status);
64
122
  const qs = q.toString();
65
- const { invoices } = await this.api("GET", `/v1/invoices${qs ? `?${qs}` : ""}`);
66
- return invoices;
123
+ const { invoices } = await this.api("GET", `/invoices${qs ? `?${qs}` : ""}`);
124
+ return invoices.map(oldNamesOnInvoice);
67
125
  }
68
126
  async get(ref) {
69
- const { invoice } = await this.api("GET", `/v1/invoices/${ref}`);
70
- return invoice;
127
+ const { invoice } = await this.api("GET", `/invoices/${ref}`);
128
+ return oldNamesOnInvoice(invoice);
71
129
  }
72
130
  async create(input) {
73
- const { invoice } = await this.api("POST", "/v1/invoices", input);
74
- return invoice;
131
+ const { invoice } = await this.api("POST", "/invoices", newNamesOnLines(input));
132
+ return oldNamesOnInvoice(invoice);
75
133
  }
76
134
  async update(ref, input) {
77
- const { invoice } = await this.api("PATCH", `/v1/invoices/${ref}`, input);
78
- return invoice;
135
+ const { invoice } = await this.api("PATCH", `/invoices/${ref}`, newNamesOnLines(input));
136
+ return oldNamesOnInvoice(invoice);
79
137
  }
80
138
  async finalize(ref, input = {}) {
81
- const { invoice } = await this.api("POST", `/v1/invoices/${ref}/finalize`, input);
82
- return invoice;
139
+ const { invoice } = await this.api("POST", `/invoices/${ref}/finalize`, newNamesOnFinalize(input));
140
+ return oldNamesOnInvoice(invoice);
83
141
  }
84
142
  async recordPayment(ref, input) {
85
- const { invoice } = await this.api("POST", `/v1/invoices/${ref}/payments`, input);
86
- return invoice;
143
+ const { invoice } = await this.api("POST", `/invoices/${ref}/payments`, newNamesOnPayment(input));
144
+ return oldNamesOnInvoice(invoice);
87
145
  }
88
146
  async void(ref, reason) {
89
- const { invoice } = await this.api("POST", `/v1/invoices/${ref}/void`, { reason: reason ?? "" });
90
- return invoice;
147
+ const { invoice } = await this.api("POST", `/invoices/${ref}/void`, { reason: reason ?? "" });
148
+ return oldNamesOnInvoice(invoice);
91
149
  }
92
150
  // ── transactions (the payment ledger) ───────────────────────────────────────
93
151
  /** All transactions for the org, newest first. */
@@ -96,13 +154,13 @@ var InvoiceClient = class _InvoiceClient {
96
154
  if (opts.limit !== void 0) q.set("limit", String(opts.limit));
97
155
  if (opts.offset !== void 0) q.set("offset", String(opts.offset));
98
156
  const qs = q.toString();
99
- const { transactions } = await this.api("GET", `/v1/transactions${qs ? `?${qs}` : ""}`);
100
- return transactions;
157
+ const { transactions } = await this.api("GET", `/transactions${qs ? `?${qs}` : ""}`);
158
+ return transactions.map(oldNamesOnTransaction);
101
159
  }
102
160
  /** Transactions recorded against one invoice. */
103
161
  async invoiceTransactions(ref) {
104
- const { transactions } = await this.api("GET", `/v1/invoices/${ref}/payments`);
105
- return transactions;
162
+ const { transactions } = await this.api("GET", `/invoices/${ref}/payments`);
163
+ return transactions.map(oldNamesOnTransaction);
106
164
  }
107
165
  };
108
166
  function createInvoiceClient(opts) {
package/dist/events.d.ts CHANGED
@@ -15,88 +15,94 @@ import { z } from 'zod';
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
  declare const InvoiceStatus: z.ZodEnum<["draft", "finalized", "paid", "void"]>;
20
26
  type InvoiceStatus = z.infer<typeof InvoiceStatus>;
21
27
  declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
22
28
  InvoiceDrafted: z.ZodObject<{
23
- customerId: z.ZodString;
24
- customerName: z.ZodString;
29
+ customer_id: z.ZodString;
30
+ customer_name: z.ZodString;
25
31
  currency: z.ZodString;
26
32
  lines: z.ZodString;
27
- subtotalCents: z.ZodNumber;
28
- totalCents: z.ZodNumber;
29
- shortId: z.ZodString;
33
+ subtotal_cents: z.ZodNumber;
34
+ total_cents: z.ZodNumber;
35
+ short_id: z.ZodString;
30
36
  at: z.ZodNumber;
31
37
  }, "strip", z.ZodTypeAny, {
32
38
  at: number;
33
- customerId: string;
34
- customerName: string;
35
- currency: string;
36
39
  lines: string;
37
- subtotalCents: number;
38
- totalCents: number;
39
- shortId: string;
40
+ short_id: string;
41
+ customer_id: string;
42
+ customer_name: string;
43
+ currency: string;
44
+ subtotal_cents: number;
45
+ total_cents: number;
40
46
  }, {
41
47
  at: number;
42
- customerId: string;
43
- customerName: string;
44
- currency: string;
45
48
  lines: string;
46
- subtotalCents: number;
47
- totalCents: number;
48
- shortId: string;
49
+ short_id: string;
50
+ customer_id: string;
51
+ customer_name: string;
52
+ currency: string;
53
+ subtotal_cents: number;
54
+ total_cents: number;
49
55
  }>;
50
56
  InvoiceUpdated: z.ZodObject<{
51
- customerId: z.ZodString;
52
- customerName: z.ZodString;
57
+ customer_id: z.ZodString;
58
+ customer_name: z.ZodString;
53
59
  lines: z.ZodString;
54
- subtotalCents: z.ZodNumber;
55
- totalCents: z.ZodNumber;
60
+ subtotal_cents: z.ZodNumber;
61
+ total_cents: z.ZodNumber;
56
62
  at: z.ZodNumber;
57
63
  }, "strip", z.ZodTypeAny, {
58
64
  at: number;
59
- customerId: string;
60
- customerName: string;
61
65
  lines: string;
62
- subtotalCents: number;
63
- totalCents: number;
66
+ customer_id: string;
67
+ customer_name: string;
68
+ subtotal_cents: number;
69
+ total_cents: number;
64
70
  }, {
65
71
  at: number;
66
- customerId: string;
67
- customerName: string;
68
72
  lines: string;
69
- subtotalCents: number;
70
- totalCents: number;
73
+ customer_id: string;
74
+ customer_name: string;
75
+ subtotal_cents: number;
76
+ total_cents: number;
71
77
  }>;
72
78
  InvoiceFinalized: z.ZodObject<{
73
79
  number: z.ZodNumber;
74
80
  lines: z.ZodString;
75
- subtotalCents: z.ZodNumber;
76
- totalCents: z.ZodNumber;
77
- issuedAt: z.ZodNumber;
78
- dueAt: z.ZodNumber;
81
+ subtotal_cents: z.ZodNumber;
82
+ total_cents: z.ZodNumber;
83
+ issued_at: z.ZodNumber;
84
+ due_at: z.ZodNumber;
79
85
  at: z.ZodNumber;
80
86
  }, "strip", z.ZodTypeAny, {
81
87
  number: number;
82
88
  at: number;
83
89
  lines: string;
84
- subtotalCents: number;
85
- totalCents: number;
86
- issuedAt: number;
87
- dueAt: number;
90
+ subtotal_cents: number;
91
+ total_cents: number;
92
+ issued_at: number;
93
+ due_at: number;
88
94
  }, {
89
95
  number: number;
90
96
  at: number;
91
97
  lines: string;
92
- subtotalCents: number;
93
- totalCents: number;
94
- issuedAt: number;
95
- dueAt: number;
98
+ subtotal_cents: number;
99
+ total_cents: number;
100
+ issued_at: number;
101
+ due_at: number;
96
102
  }>;
97
103
  PaymentRecorded: z.ZodObject<{
98
- amountCents: z.ZodNumber;
99
- amountPaidCents: z.ZodNumber;
104
+ amount_cents: z.ZodNumber;
105
+ amount_paid_cents: z.ZodNumber;
100
106
  status: z.ZodEnum<["draft", "finalized", "paid", "void"]>;
101
107
  method: z.ZodString;
102
108
  reference: z.ZodString;
@@ -105,15 +111,15 @@ declare const InvoiceEvents: _baseworks_foldbase.EventCatalog<{
105
111
  method: string;
106
112
  at: number;
107
113
  status: "draft" | "finalized" | "paid" | "void";
108
- amountCents: number;
109
- amountPaidCents: number;
114
+ amount_paid_cents: number;
115
+ amount_cents: number;
110
116
  reference: string;
111
117
  }, {
112
118
  method: string;
113
119
  at: number;
114
120
  status: "draft" | "finalized" | "paid" | "void";
115
- amountCents: number;
116
- amountPaidCents: number;
121
+ amount_paid_cents: number;
122
+ amount_cents: number;
117
123
  reference: string;
118
124
  }>;
119
125
  InvoiceVoided: z.ZodObject<{
@@ -140,12 +146,12 @@ declare const TransactionKind: z.ZodEnum<["payment", "refund", "adjustment"]>;
140
146
  type TransactionKind = z.infer<typeof TransactionKind>;
141
147
  declare const TransactionEvents: _baseworks_foldbase.EventCatalog<{
142
148
  TransactionRecorded: z.ZodObject<{
143
- invoiceId: z.ZodString;
144
- invoiceNumber: z.ZodNumber;
145
- customerId: z.ZodString;
146
- customerName: z.ZodString;
149
+ invoice_id: z.ZodString;
150
+ invoice_number: z.ZodNumber;
151
+ customer_id: z.ZodString;
152
+ customer_name: z.ZodString;
147
153
  kind: z.ZodEnum<["payment", "refund", "adjustment"]>;
148
- amountCents: z.ZodNumber;
154
+ amount_cents: z.ZodNumber;
149
155
  currency: z.ZodString;
150
156
  method: z.ZodString;
151
157
  reference: z.ZodString;
@@ -153,24 +159,24 @@ declare const TransactionEvents: _baseworks_foldbase.EventCatalog<{
153
159
  }, "strip", z.ZodTypeAny, {
154
160
  method: string;
155
161
  at: number;
156
- customerId: string;
157
- customerName: string;
162
+ customer_id: string;
163
+ customer_name: string;
158
164
  currency: string;
159
- amountCents: number;
165
+ amount_cents: number;
166
+ invoice_id: string;
167
+ invoice_number: number;
160
168
  reference: string;
161
- invoiceId: string;
162
- invoiceNumber: number;
163
169
  kind: "payment" | "refund" | "adjustment";
164
170
  }, {
165
171
  method: string;
166
172
  at: number;
167
- customerId: string;
168
- customerName: string;
173
+ customer_id: string;
174
+ customer_name: string;
169
175
  currency: string;
170
- amountCents: number;
176
+ amount_cents: number;
177
+ invoice_id: string;
178
+ invoice_number: number;
171
179
  reference: string;
172
- invoiceId: string;
173
- invoiceNumber: number;
174
180
  kind: "payment" | "refund" | "adjustment";
175
181
  }>;
176
182
  }> & {
package/dist/events.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  InvoiceStatus,
4
4
  TransactionEvents,
5
5
  TransactionKind
6
- } from "./chunk-7P7ARN3X.js";
6
+ } from "./chunk-ITMZVGLQ.js";
7
7
  export {
8
8
  InvoiceEvents,
9
9
  InvoiceStatus,
@@ -0,0 +1,58 @@
1
+ import { createInvoiceClient, Invoice, Transaction } from './client.js';
2
+ import './events.js';
3
+ import '@baseworks/foldbase';
4
+ import 'zod';
5
+
6
+ /** GraphQL read module for invoices — invoices + transactions, `extend`s Customer. */
7
+ interface InvoiceGraphContext {
8
+ invoice: ReturnType<typeof createInvoiceClient>;
9
+ customerLoader: {
10
+ load(id: string): Promise<unknown>;
11
+ };
12
+ }
13
+ declare const typeDefs = "\n type Invoice {\n id: ID!\n number: Int\n status: String!\n currency: String!\n subtotalCents: Int!\n totalCents: Int!\n amountPaidCents: Int!\n balanceCents: Int!\n dueAt: Float\n createdAt: Float!\n lines: [InvoiceLine!]!\n customer: Customer\n transactions: [Transaction!]!\n }\n type InvoiceLine {\n description: String!\n quantity: Float!\n unitPriceCents: Int!\n amountCents: Int!\n }\n type Transaction {\n id: ID!\n kind: String!\n amountCents: Int!\n currency: String!\n method: String\n reference: String\n createdAt: Float!\n }\n extend type Query {\n invoice(ref: String!): Invoice\n invoices(status: String): [Invoice!]!\n }\n extend type Customer {\n invoices(status: String): [Invoice!]!\n }\n";
14
+ declare const resolvers: {
15
+ Query: {
16
+ invoice: (_: unknown, { ref }: {
17
+ ref: string;
18
+ }, ctx: InvoiceGraphContext) => Promise<Invoice | null>;
19
+ invoices: (_: unknown, { status }: {
20
+ status?: string;
21
+ }, ctx: InvoiceGraphContext) => Promise<Invoice[]>;
22
+ };
23
+ Customer: {
24
+ invoices: (parent: {
25
+ id: string;
26
+ }, { status }: {
27
+ status?: string;
28
+ }, ctx: InvoiceGraphContext) => Promise<Invoice[]>;
29
+ };
30
+ InvoiceLine: {
31
+ unitPriceCents: (l: {
32
+ unit_price_cents: number;
33
+ }) => number;
34
+ amountCents: (l: {
35
+ amount_cents: number;
36
+ }) => number;
37
+ };
38
+ Transaction: {
39
+ amountCents: (t: {
40
+ amount_cents: number;
41
+ }) => number;
42
+ createdAt: (t: {
43
+ created_at: number;
44
+ }) => number;
45
+ };
46
+ Invoice: {
47
+ subtotalCents: (p: Invoice) => number;
48
+ totalCents: (p: Invoice) => number;
49
+ amountPaidCents: (p: Invoice) => number;
50
+ balanceCents: (p: Invoice) => number;
51
+ dueAt: (p: Invoice) => number | null;
52
+ createdAt: (p: Invoice) => number;
53
+ customer: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => Promise<unknown>;
54
+ transactions: (parent: Invoice, _: unknown, ctx: InvoiceGraphContext) => Promise<never[] | Transaction[]>;
55
+ };
56
+ };
57
+
58
+ export { type InvoiceGraphContext, resolvers, typeDefs };
@@ -0,0 +1,75 @@
1
+ // src/graphql.ts
2
+ var typeDefs = (
3
+ /* GraphQL */
4
+ `
5
+ type Invoice {
6
+ id: ID!
7
+ number: Int
8
+ status: String!
9
+ currency: String!
10
+ subtotalCents: Int!
11
+ totalCents: Int!
12
+ amountPaidCents: Int!
13
+ balanceCents: Int!
14
+ dueAt: Float
15
+ createdAt: Float!
16
+ lines: [InvoiceLine!]!
17
+ customer: Customer
18
+ transactions: [Transaction!]!
19
+ }
20
+ type InvoiceLine {
21
+ description: String!
22
+ quantity: Float!
23
+ unitPriceCents: Int!
24
+ amountCents: Int!
25
+ }
26
+ type Transaction {
27
+ id: ID!
28
+ kind: String!
29
+ amountCents: Int!
30
+ currency: String!
31
+ method: String
32
+ reference: String
33
+ createdAt: Float!
34
+ }
35
+ extend type Query {
36
+ invoice(ref: String!): Invoice
37
+ invoices(status: String): [Invoice!]!
38
+ }
39
+ extend type Customer {
40
+ invoices(status: String): [Invoice!]!
41
+ }
42
+ `
43
+ );
44
+ var resolvers = {
45
+ Query: {
46
+ invoice: (_, { ref }, ctx) => ctx.invoice.get(ref).catch(() => null),
47
+ invoices: (_, { status }, ctx) => ctx.invoice.list(status ? { status } : {})
48
+ },
49
+ Customer: {
50
+ invoices: async (parent, { status }, ctx) => (await ctx.invoice.list(status ? { status } : {})).filter((i) => i.customer_id === parent.id)
51
+ },
52
+ InvoiceLine: {
53
+ unitPriceCents: (l) => l.unit_price_cents,
54
+ amountCents: (l) => l.amount_cents
55
+ },
56
+ Transaction: {
57
+ amountCents: (t) => t.amount_cents,
58
+ createdAt: (t) => t.created_at
59
+ },
60
+ Invoice: {
61
+ // The schema is camelCase (that contract's own); the data is snake_case.
62
+ subtotalCents: (p) => p.subtotal_cents,
63
+ totalCents: (p) => p.total_cents,
64
+ amountPaidCents: (p) => p.amount_paid_cents,
65
+ balanceCents: (p) => p.balance_cents,
66
+ dueAt: (p) => p.due_at,
67
+ createdAt: (p) => p.created_at,
68
+ customer: (parent, _, ctx) => ctx.customerLoader.load(parent.customer_id),
69
+ transactions: (parent, _, ctx) => ctx.invoice.invoiceTransactions(parent.id).catch(() => [])
70
+ }
71
+ };
72
+ export {
73
+ resolvers,
74
+ typeDefs
75
+ };
package/dist/mcp.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { McpTool } from '@baseworks/mcp';
2
+ import { InvoiceClient } from './client.js';
3
+ import './events.js';
4
+ import '@baseworks/foldbase';
5
+ import 'zod';
6
+
7
+ /** What `ctx.clients` must hold for these tools. */
8
+ interface InvoiceMcpClients {
9
+ invoice: InvoiceClient;
10
+ }
11
+ declare function invoiceTools(): McpTool<InvoiceMcpClients>[];
12
+
13
+ export { type InvoiceMcpClients, invoiceTools };
package/dist/mcp.js ADDED
@@ -0,0 +1,131 @@
1
+ // src/mcp.ts
2
+ import { z } from "zod";
3
+ import { defineTool } from "@baseworks/mcp";
4
+ var REF = z.string().min(1).describe("The invoice's id or its short id.");
5
+ var Line = z.object({
6
+ description: z.string().min(1).describe("What is being charged for."),
7
+ quantity: z.number().positive().describe("How many (may be fractional, e.g. 2.5 hours)."),
8
+ unit_price_cents: z.number().int().min(0).describe("Price of one unit in integer cents: 150.00 is 15000."),
9
+ product_id: z.string().optional().describe("The id of a catalog product, if the line is one.")
10
+ });
11
+ var 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.");
12
+ function invoiceTools() {
13
+ return [
14
+ defineTool({
15
+ name: "invoice_list",
16
+ title: "List invoices",
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 and the `balance_cents` still owed; money is integer cents. Returns `{ invoices }`. Read only.",
18
+ input: z.object({
19
+ status: z.enum(["draft", "finalized", "paid", "void"]).optional().describe("Only invoices in this status."),
20
+ limit: z.number().int().min(1).max(100).optional().describe("Page size, 1 to 100 (default 25)."),
21
+ offset: z.number().int().min(0).optional().describe("How many to skip, for the next page.")
22
+ }),
23
+ access: "read",
24
+ permission: "invoice.read",
25
+ run: async (ctx, a) => ({
26
+ invoices: await ctx.clients.invoice.list({ limit: a.limit ?? 25, ...a.offset ? { offset: a.offset } : {}, ...a.status ? { status: a.status } : {} })
27
+ })
28
+ }),
29
+ defineTool({
30
+ name: "invoice_get",
31
+ 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.",
33
+ input: z.object({ ref: REF }),
34
+ access: "read",
35
+ permission: "invoice.read",
36
+ run: async (ctx, a) => ({ invoice: await ctx.clients.invoice.get(a.ref) })
37
+ }),
38
+ defineTool({
39
+ name: "invoice_transactions",
40
+ title: "List payments",
41
+ description: "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. Each entry says the invoice number, the customer, the amount in cents, the method and the reference. Read only.",
42
+ input: z.object({
43
+ ref: REF.optional().describe("An invoice id or short id; leave out for the whole organization."),
44
+ limit: z.number().int().min(1).max(100).optional().describe("Page size when listing the whole organization, 1 to 100 (default 25)."),
45
+ offset: z.number().int().min(0).optional()
46
+ }),
47
+ access: "read",
48
+ permission: "invoice.read",
49
+ run: async (ctx, a) => ({
50
+ transactions: a.ref ? await ctx.clients.invoice.invoiceTransactions(a.ref) : await ctx.clients.invoice.transactions({ limit: a.limit ?? 25, ...a.offset ? { offset: a.offset } : {} })
51
+ })
52
+ }),
53
+ defineTool({
54
+ name: "invoice_create",
55
+ title: "Draft an invoice",
56
+ description: "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. The customer must already exist: find it with customers_list; an unknown one is refused with `customer_not_found`. 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. It is recorded as you, the agent acting for the person who connected you.",
57
+ input: z.object({
58
+ customer_id,
59
+ currency: z.string().length(3).describe("ISO 4217 code, e.g. EUR, USD, TRY."),
60
+ lines: z.array(Line).min(1).describe("At least one line.")
61
+ }),
62
+ access: "write",
63
+ permission: "invoice.write",
64
+ run: async (ctx, a) => ({
65
+ invoice: await ctx.clients.invoice.create(a)
66
+ })
67
+ }),
68
+ defineTool({
69
+ name: "invoice_update",
70
+ title: "Edit a draft invoice",
71
+ description: "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. 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).",
72
+ input: z.object({
73
+ ref: REF,
74
+ customer_id: customer_id.optional(),
75
+ lines: z.array(Line).min(1).optional().describe("The complete new set of lines.")
76
+ }),
77
+ access: "write",
78
+ permission: "invoice.write",
79
+ async run(ctx, a) {
80
+ const { ref, ...patch } = a;
81
+ if (patch.customer_id === void 0 && patch.lines === void 0) throw Object.assign(new Error("Send customer_id and/or lines"), { code: "nothing_to_update", status: 400 });
82
+ return { invoice: await ctx.clients.invoice.update(ref, patch) };
83
+ }
84
+ }),
85
+ defineTool({
86
+ name: "invoice_finalize",
87
+ title: "Finalize an invoice",
88
+ description: "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). 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). Only a draft can be finalized: otherwise `not_draft`.",
89
+ input: z.object({
90
+ ref: REF,
91
+ issued_at: z.number().int().optional().describe("Epoch milliseconds; default now."),
92
+ due_at: z.number().int().optional().describe("Epoch milliseconds; omit for no due date.")
93
+ }),
94
+ access: "write",
95
+ permission: "invoice.finalize",
96
+ async run(ctx, a) {
97
+ const { ref, ...input } = a;
98
+ return { invoice: await ctx.clients.invoice.finalize(ref, input) };
99
+ }
100
+ }),
101
+ defineTool({
102
+ name: "invoice_record_payment",
103
+ title: "Record a payment",
104
+ description: "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. The amount is integer cents and cannot exceed the balance (`overpayment`); a draft, void or already paid invoice is refused. 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. This records a payment that happened; it does not charge anybody.",
105
+ input: z.object({
106
+ ref: REF,
107
+ amount_cents: z.number().int().positive().describe("Integer cents received: 100.00 is 10000."),
108
+ 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.")
110
+ }),
111
+ access: "write",
112
+ permission: "invoice.record_payment",
113
+ async run(ctx, a) {
114
+ const { ref, ...input } = a;
115
+ return { invoice: await ctx.clients.invoice.recordPayment(ref, input) };
116
+ }
117
+ }),
118
+ defineTool({
119
+ name: "invoice_void",
120
+ title: "Void an invoice",
121
+ description: "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. 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`.",
122
+ input: z.object({ ref: REF, reason: z.string().optional().describe("Why it is being voided; kept on the record.") }),
123
+ access: "write",
124
+ permission: "invoice.void",
125
+ run: async (ctx, a) => ({ invoice: await ctx.clients.invoice.void(a.ref, a.reason) })
126
+ })
127
+ ];
128
+ }
129
+ export {
130
+ invoiceTools
131
+ };