@baseworks/invoice 0.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/src/cli.ts ADDED
@@ -0,0 +1,255 @@
1
+ import { Command } from 'commander'
2
+ import { clr, kv, table, summary, success, fatal, printOutput, outputOption } from '@baseworks/cli/display'
3
+ import { fmtDate } from '@baseworks/cli/fmt'
4
+ import type { ColDef } from '@baseworks/cli/display'
5
+ import type { ApiClient } from '@baseworks/cli/client'
6
+
7
+ /**
8
+ * Importable `invoices` command group. The `http` ApiClient points at the app's
9
+ * invoice mount, carries the caller's identity token, and must send the active
10
+ * org (X-Org-Id) — invoices are org-scoped. Mounts as:
11
+ *
12
+ * program.addCommand(buildInvoiceCommand({ http, cliName: 'dtab' }))
13
+ *
14
+ * Usage: `dtab invoices` (list) · `inv` alias · `invoices create --customer <ref>
15
+ * --currency USD --line "Consulting|10|150.00"` · `invoices get <ref>` ·
16
+ * `invoices finalize <ref>` · `invoices pay <ref> --amount 150.00` ·
17
+ * `invoices void <ref>`
18
+ */
19
+ export interface InvoiceCliDeps {
20
+ http: ApiClient
21
+ cliName?: string
22
+ }
23
+
24
+ type InvoiceRow = {
25
+ id: string
26
+ shortId: string
27
+ number: number | null
28
+ status: string
29
+ customerName: string | null
30
+ customerId: string
31
+ currency: string
32
+ totalCents: number
33
+ amountPaidCents: number
34
+ balanceCents: number
35
+ createdAt?: number
36
+ }
37
+
38
+ const die = (e: unknown): never => fatal(e instanceof Error ? e.message : String(e))
39
+
40
+ /** integer cents + currency → display (`1500.00 USD`). */
41
+ function fmtMoney(cents: number, currency: string): string {
42
+ return `${(cents / 100).toFixed(2)} ${currency}`
43
+ }
44
+
45
+ /** `12.50` | `12` → integer cents; rejects sub-cent / negatives. */
46
+ function toCents(amount: string, flag = '--amount'): number {
47
+ const n = Number(amount)
48
+ if (!Number.isFinite(n) || n < 0) fatal(`${flag} must be a non-negative number, got '${amount}'`)
49
+ const cents = Math.round(n * 100)
50
+ if (Math.abs(cents - n * 100) > 1e-6) fatal(`${flag} has sub-cent precision: '${amount}'`)
51
+ return cents
52
+ }
53
+
54
+ /** `"<description>|<qty>|<unitPrice>"` → a line input. */
55
+ function parseLine(spec: string): { description: string; quantity: number; unitPriceCents: number } {
56
+ const parts = spec.split('|')
57
+ if (parts.length !== 3) fatal(`--line expects "description|qty|unitPrice", got '${spec}'`)
58
+ const description = parts[0]!.trim()
59
+ const quantity = Number(parts[1])
60
+ if (!description) fatal(`--line description is empty in '${spec}'`)
61
+ if (!Number.isFinite(quantity) || quantity <= 0) fatal(`--line qty must be > 0 in '${spec}'`)
62
+ return { description, quantity, unitPriceCents: toCents(parts[2]!.trim(), '--line unitPrice') }
63
+ }
64
+
65
+ const NUMBER_COL = (v: unknown): string => (v ? `#${v}` : '—')
66
+
67
+ export function buildInvoiceCommand(deps: InvoiceCliDeps): Command {
68
+ const { http } = deps
69
+ const cli = deps.cliName ?? 'cli'
70
+
71
+ const listInvoices = async (opts: { output: string; status?: string }) => {
72
+ const q = opts.status ? `?status=${encodeURIComponent(opts.status)}` : ''
73
+ const res = await http.get<{ invoices: InvoiceRow[] }>(`/v1/invoices${q}`).catch(die)
74
+ printOutput(res.invoices, opts.output, (wide) => {
75
+ table(res.invoices, [
76
+ { key: 'shortId', label: 'ID' },
77
+ { key: 'number', label: 'NO', fmt: NUMBER_COL },
78
+ { key: 'status', label: 'STATUS' },
79
+ { key: 'customerName', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as InvoiceRow).customerId },
80
+ { key: 'totalCents', label: 'TOTAL', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
81
+ { key: 'balanceCents', label: 'BALANCE', fmt: (v, r) => fmtMoney(v as number, (r as InvoiceRow).currency) },
82
+ { key: 'createdAt', label: 'CREATED', wide: true, fmt: (v) => fmtDate(v as number) },
83
+ { key: 'id', label: 'FULL ID', wide: true },
84
+ ] as ColDef<InvoiceRow>[], { wide, emptyHint: `No invoices yet. Run: ${cli} invoices create --customer <ref> --currency USD --line "<desc>|<qty>|<price>"` })
85
+ summary(`${res.invoices.length} invoice${res.invoices.length !== 1 ? 's' : ''}`)
86
+ }, 'id')
87
+ }
88
+
89
+ const cmd = new Command('invoices')
90
+ .aliases(['inv', 'invoice'])
91
+ .description('Manage invoices (org-scoped — run `use <org>` first)')
92
+ .option(...outputOption())
93
+ .option('--status <status>', 'Filter: draft | finalized | paid | void')
94
+ .action(listInvoices)
95
+
96
+ cmd.addCommand(
97
+ new Command('ls')
98
+ .description('List invoices (alias of the bare command)')
99
+ .option(...outputOption())
100
+ .option('--status <status>', 'Filter by status')
101
+ .action(function (this: Command) {
102
+ const self = this.opts() as { output?: string; status?: string }
103
+ const parent = (this.parent?.opts() ?? {}) as { output?: string; status?: string }
104
+ return listInvoices({
105
+ output: self.output && self.output !== 'table' ? self.output : parent.output ?? 'table',
106
+ status: self.status ?? parent.status,
107
+ })
108
+ }),
109
+ )
110
+
111
+ cmd.addCommand(
112
+ new Command('create')
113
+ .description('Create a draft invoice')
114
+ .requiredOption('--customer <ref>', 'Customer id, short_id, or external_id')
115
+ .requiredOption('--currency <cur>', 'ISO-4217 currency (e.g. USD)')
116
+ .requiredOption('--line <spec...>', 'Line "description|qty|unitPrice" (repeatable)')
117
+ .action(async (opts: { customer: string; currency: string; line: string[] }) => {
118
+ const lines = opts.line.map(parseLine)
119
+ const res = await http.post<{ invoice: InvoiceRow }>('/v1/invoices', {
120
+ customerId: opts.customer,
121
+ currency: opts.currency,
122
+ lines,
123
+ }).catch(die)
124
+ success(`Draft invoice created for ${res.invoice.customerName ?? res.invoice.customerId}`)
125
+ kv([['id', res.invoice.shortId], ['status', res.invoice.status], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)]])
126
+ }),
127
+ )
128
+
129
+ cmd.addCommand(
130
+ new Command('get').argument('<ref>', 'id or short_id')
131
+ .description('Show invoice details (lines, totals, balance)')
132
+ .option(...outputOption())
133
+ .action(async (ref: string, opts: { output: string }) => {
134
+ const res = await http.get<{ invoice: Record<string, unknown> }>(`/v1/invoices/${ref}`).catch(die)
135
+ const inv = res.invoice as Record<string, unknown>
136
+ const cur = String(inv['currency'])
137
+ printOutput(inv, opts.output, () => {
138
+ kv([
139
+ ['id', String(inv['shortId'])],
140
+ ['number', inv['number'] ? `#${inv['number']}` : '— (draft)'],
141
+ ['status', String(inv['status'])],
142
+ ['customer', String(inv['customerName'] ?? inv['customerId'])],
143
+ ['issued', inv['issuedAt'] ? fmtDate(inv['issuedAt'] as number) : '—'],
144
+ ['due', inv['dueAt'] ? fmtDate(inv['dueAt'] as number) : '—'],
145
+ ])
146
+ const lines = (inv['lines'] as Array<{ description: string; quantity: number; unitPriceCents: number; amountCents: number }>) ?? []
147
+ if (lines.length) {
148
+ console.log(` ${clr.dim}── lines ──${clr.reset}`)
149
+ table(lines, [
150
+ { key: 'description', label: 'DESCRIPTION' },
151
+ { key: 'quantity', label: 'QTY' },
152
+ { key: 'unitPriceCents', label: 'UNIT', fmt: (v) => fmtMoney(v as number, cur) },
153
+ { key: 'amountCents', label: 'AMOUNT', fmt: (v) => fmtMoney(v as number, cur) },
154
+ ] as ColDef<(typeof lines)[number]>[])
155
+ }
156
+ kv([
157
+ ['subtotal', fmtMoney(inv['subtotalCents'] as number, cur)],
158
+ ['total', fmtMoney(inv['totalCents'] as number, cur)],
159
+ ['paid', fmtMoney(inv['amountPaidCents'] as number, cur)],
160
+ ['balance', fmtMoney(inv['balanceCents'] as number, cur)],
161
+ ['full_id', String(inv['id'])],
162
+ ])
163
+ }, 'id')
164
+ }),
165
+ )
166
+
167
+ cmd.addCommand(
168
+ new Command('update').argument('<ref>')
169
+ .description('Edit a DRAFT invoice (replaces lines / customer)')
170
+ .option('--customer <ref>', 'New customer ref')
171
+ .option('--line <spec...>', 'Replace lines: "description|qty|unitPrice" (repeatable)')
172
+ .action(async (ref: string, opts: { customer?: string; line?: string[] }) => {
173
+ const body: Record<string, unknown> = {}
174
+ if (opts.customer !== undefined) body['customerId'] = opts.customer
175
+ if (opts.line !== undefined) body['lines'] = opts.line.map(parseLine)
176
+ if (!Object.keys(body).length) fatal('Provide --customer and/or --line')
177
+ const res = await http.patch<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}`, body).catch(die)
178
+ success('Draft updated.')
179
+ kv([['id', res.invoice.shortId], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)]])
180
+ }),
181
+ )
182
+
183
+ cmd.addCommand(
184
+ new Command('finalize').argument('<ref>')
185
+ .description('Finalize a draft — assigns a number, freezes it (immutable)')
186
+ .option('--due <date>', 'Due date YYYY-MM-DD')
187
+ .action(async (ref: string, opts: { due?: string }) => {
188
+ const body: Record<string, unknown> = {}
189
+ if (opts.due) {
190
+ const ms = Date.parse(opts.due)
191
+ if (Number.isNaN(ms)) fatal(`--due is not a valid date: '${opts.due}'`)
192
+ body['dueAt'] = ms
193
+ }
194
+ const res = await http.post<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}/finalize`, body).catch(die)
195
+ success(`Invoice finalized: #${res.invoice.number}`)
196
+ kv([['id', res.invoice.shortId], ['number', `#${res.invoice.number}`], ['total', fmtMoney(res.invoice.totalCents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balanceCents, res.invoice.currency)]])
197
+ }),
198
+ )
199
+
200
+ cmd.addCommand(
201
+ new Command('pay').argument('<ref>')
202
+ .description('Record a payment against a finalized invoice')
203
+ .requiredOption('--amount <amount>', 'Amount, e.g. 150.00')
204
+ .option('--method <method>', 'e.g. bank, cash, card')
205
+ .option('--ref <reference>', 'External payment reference')
206
+ .action(async (ref: string, opts: { amount: string; method?: string; ref?: string }) => {
207
+ const res = await http.post<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}/payments`, {
208
+ amountCents: toCents(opts.amount),
209
+ ...(opts.method ? { method: opts.method } : {}),
210
+ ...(opts.ref ? { reference: opts.ref } : {}),
211
+ }).catch(die)
212
+ success(`Payment recorded. Invoice is now ${res.invoice.status}.`)
213
+ kv([['id', res.invoice.shortId], ['paid', fmtMoney(res.invoice.amountPaidCents, res.invoice.currency)], ['balance', fmtMoney(res.invoice.balanceCents, res.invoice.currency)]])
214
+ }),
215
+ )
216
+
217
+ cmd.addCommand(
218
+ new Command('void').argument('<ref>')
219
+ .description('Void a finalized invoice')
220
+ .option('--reason <reason>', 'Reason')
221
+ .action(async (ref: string, opts: { reason?: string }) => {
222
+ const res = await http.post<{ invoice: InvoiceRow }>(`/v1/invoices/${ref}/void`, { reason: opts.reason ?? '' }).catch(die)
223
+ success(`Invoice voided: ${res.invoice.shortId}`)
224
+ }),
225
+ )
226
+
227
+ type TxnRow = {
228
+ id: string; invoiceNumber: number; customerName: string | null; customerId: string
229
+ kind: string; amountCents: number; currency: string; method: string | null; reference: string | null; createdAt?: number
230
+ }
231
+ cmd.addCommand(
232
+ new Command('payments').alias('transactions').argument('[ref]', 'invoice id/short_id (omit for all org transactions)')
233
+ .description('List payments / transactions (the money ledger)')
234
+ .option(...outputOption())
235
+ .action(async (ref: string | undefined, opts: { output: string }) => {
236
+ const path = ref ? `/v1/invoices/${ref}/payments` : '/v1/transactions'
237
+ const res = await http.get<{ transactions: TxnRow[] }>(path).catch(die)
238
+ printOutput(res.transactions, opts.output, (wide) => {
239
+ table(res.transactions, [
240
+ { key: 'createdAt', label: 'DATE', fmt: (v) => fmtDate(v as number) },
241
+ { key: 'invoiceNumber', label: 'INVOICE', fmt: (v) => (v ? `#${v}` : '—') },
242
+ { key: 'customerName', label: 'CUSTOMER', fmt: (v, r) => (v as string) ?? (r as TxnRow).customerId },
243
+ { key: 'kind', label: 'KIND' },
244
+ { key: 'amountCents', label: 'AMOUNT', fmt: (v, r) => fmtMoney(v as number, (r as TxnRow).currency) },
245
+ { key: 'method', label: 'METHOD', fmt: (v) => (v as string) ?? '' },
246
+ { key: 'reference', label: 'REF', wide: true, fmt: (v) => (v as string) ?? '' },
247
+ { key: 'id', label: 'TXN ID', wide: true },
248
+ ] as ColDef<TxnRow>[], { wide, emptyHint: 'No transactions yet.' })
249
+ summary(`${res.transactions.length} transaction${res.transactions.length !== 1 ? 's' : ''}`)
250
+ }, 'id')
251
+ }),
252
+ )
253
+
254
+ return cmd
255
+ }
package/src/client.ts ADDED
@@ -0,0 +1,168 @@
1
+ import type {
2
+ Invoice,
3
+ Transaction,
4
+ CreateInvoiceInput,
5
+ UpdateInvoiceInput,
6
+ FinalizeInvoiceInput,
7
+ RecordPaymentInput,
8
+ } from './types.js'
9
+
10
+ export type {
11
+ Invoice,
12
+ InvoiceRow,
13
+ InvoiceLine,
14
+ InvoiceLineInput,
15
+ InvoiceStatus,
16
+ Transaction,
17
+ TransactionRow,
18
+ CreateInvoiceInput,
19
+ UpdateInvoiceInput,
20
+ FinalizeInvoiceInput,
21
+ RecordPaymentInput,
22
+ } from './types.js'
23
+
24
+ export interface InvoiceClientOptions {
25
+ /** Base URL of invoice-service (resolved by the SDK, e.g. INVOICE_SERVICE_URL). */
26
+ baseUrl: string
27
+ /** Bearer token — the caller's identity JWT. */
28
+ token?: string
29
+ /** Active org id — sent as X-Org-Id (invoices are org-scoped, tenant = org). */
30
+ orgId?: string
31
+ /** Injectable fetch (tests / non-global environments). */
32
+ fetch?: typeof fetch
33
+ }
34
+
35
+ /** Thrown on any non-2xx response from invoice-service. */
36
+ export class InvoiceError extends Error {
37
+ constructor(
38
+ readonly status: number,
39
+ readonly code: string,
40
+ message?: string,
41
+ ) {
42
+ super(message ?? code)
43
+ this.name = 'InvoiceError'
44
+ }
45
+ }
46
+
47
+ /** Minimal ApiClient shape — structurally compatible with @baseworks/cli. */
48
+ export interface HttpClient {
49
+ api<T>(method: string, path: string, body?: unknown, headers?: Record<string, string>): Promise<T>
50
+ get<T>(path: string, headers?: Record<string, string>): Promise<T>
51
+ post<T>(path: string, body: unknown, headers?: Record<string, string>): Promise<T>
52
+ patch<T>(path: string, body: unknown, headers?: Record<string, string>): Promise<T>
53
+ del<T>(path: string, headers?: Record<string, string>): Promise<T>
54
+ }
55
+
56
+ /**
57
+ * Typed HTTP client for invoice-service. Thin wrapper over the REST surface; the
58
+ * service validates + owns the ledger math. Every call carries the org id
59
+ * (X-Org-Id) — invoices are per-org, and the identity JWT is org-less (ADR-009).
60
+ */
61
+ export class InvoiceClient {
62
+ private readonly baseUrl: string
63
+ private readonly fetchImpl: typeof fetch
64
+ constructor(private readonly opts: InvoiceClientOptions) {
65
+ this.baseUrl = opts.baseUrl.replace(/\/$/, '')
66
+ this.fetchImpl = opts.fetch ?? globalThis.fetch
67
+ }
68
+
69
+ withOrg(orgId: string): InvoiceClient {
70
+ return new InvoiceClient({ ...this.opts, orgId })
71
+ }
72
+
73
+ private headers(json: boolean, extra: Record<string, string> = {}): Record<string, string> {
74
+ const h: Record<string, string> = {}
75
+ if (json) h['Content-Type'] = 'application/json'
76
+ if (this.opts.token) h['Authorization'] = `Bearer ${this.opts.token}`
77
+ if (this.opts.orgId) h['X-Org-Id'] = this.opts.orgId
78
+ return { ...h, ...extra }
79
+ }
80
+
81
+ async api<T>(method: string, path: string, body?: unknown, extra: Record<string, string> = {}): Promise<T> {
82
+ const res = await this.fetchImpl(`${this.baseUrl}${path}`, {
83
+ method,
84
+ headers: this.headers(body !== undefined, extra),
85
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
86
+ })
87
+ if (res.status === 204) return null as T
88
+ const text = await res.text()
89
+ const data = text ? (JSON.parse(text) as unknown) : undefined
90
+ if (!res.ok) {
91
+ const e = (data ?? {}) as { error?: string | { code?: string; message?: string }; message?: string }
92
+ const code = typeof e.error === 'string' ? e.error : e.error?.code ?? 'error'
93
+ const msg = typeof e.error === 'object' ? e.error?.message : e.message
94
+ throw new InvoiceError(res.status, code, msg)
95
+ }
96
+ return data as T
97
+ }
98
+
99
+ /** Generic ApiClient (get/post/patch/del) — used by the CLI plugin. */
100
+ get http(): HttpClient {
101
+ return {
102
+ api: this.api.bind(this),
103
+ get: <T>(p: string, h?: Record<string, string>) => this.api<T>('GET', p, undefined, h),
104
+ post: <T>(p: string, b: unknown, h?: Record<string, string>) => this.api<T>('POST', p, b, h),
105
+ patch: <T>(p: string, b: unknown, h?: Record<string, string>) => this.api<T>('PATCH', p, b, h),
106
+ del: <T>(p: string, h?: Record<string, string>) => this.api<T>('DELETE', p, undefined, h),
107
+ }
108
+ }
109
+
110
+ // ── invoices ──────────────────────────────────────────────────────────────
111
+
112
+ async list(opts: { limit?: number; offset?: number; status?: string } = {}): Promise<Invoice[]> {
113
+ const q = new URLSearchParams()
114
+ if (opts.limit !== undefined) q.set('limit', String(opts.limit))
115
+ if (opts.offset !== undefined) q.set('offset', String(opts.offset))
116
+ if (opts.status) q.set('status', opts.status)
117
+ const qs = q.toString()
118
+ const { invoices } = await this.api<{ invoices: Invoice[] }>('GET', `/v1/invoices${qs ? `?${qs}` : ''}`)
119
+ return invoices
120
+ }
121
+ async get(ref: string): Promise<Invoice> {
122
+ const { invoice } = await this.api<{ invoice: Invoice }>('GET', `/v1/invoices/${ref}`)
123
+ return invoice
124
+ }
125
+ async create(input: CreateInvoiceInput): Promise<Invoice> {
126
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', '/v1/invoices', input)
127
+ return invoice
128
+ }
129
+ async update(ref: string, input: UpdateInvoiceInput): Promise<Invoice> {
130
+ const { invoice } = await this.api<{ invoice: Invoice }>('PATCH', `/v1/invoices/${ref}`, input)
131
+ return invoice
132
+ }
133
+ async finalize(ref: string, input: FinalizeInvoiceInput = {}): Promise<Invoice> {
134
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/v1/invoices/${ref}/finalize`, input)
135
+ return invoice
136
+ }
137
+ async recordPayment(ref: string, input: RecordPaymentInput): Promise<Invoice> {
138
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/v1/invoices/${ref}/payments`, input)
139
+ return invoice
140
+ }
141
+ async void(ref: string, reason?: string): Promise<Invoice> {
142
+ const { invoice } = await this.api<{ invoice: Invoice }>('POST', `/v1/invoices/${ref}/void`, { reason: reason ?? '' })
143
+ return invoice
144
+ }
145
+
146
+ // ── transactions (the payment ledger) ───────────────────────────────────────
147
+
148
+ /** All transactions for the org, newest first. */
149
+ async transactions(opts: { limit?: number; offset?: number } = {}): Promise<Transaction[]> {
150
+ const q = new URLSearchParams()
151
+ if (opts.limit !== undefined) q.set('limit', String(opts.limit))
152
+ if (opts.offset !== undefined) q.set('offset', String(opts.offset))
153
+ const qs = q.toString()
154
+ const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/v1/transactions${qs ? `?${qs}` : ''}`)
155
+ return transactions
156
+ }
157
+
158
+ /** Transactions recorded against one invoice. */
159
+ async invoiceTransactions(ref: string): Promise<Transaction[]> {
160
+ const { transactions } = await this.api<{ transactions: Transaction[] }>('GET', `/v1/invoices/${ref}/payments`)
161
+ return transactions
162
+ }
163
+ }
164
+
165
+ /** Factory used by the SDK capability registry. */
166
+ export function createInvoiceClient(opts: InvoiceClientOptions): InvoiceClient {
167
+ return new InvoiceClient(opts)
168
+ }
package/src/events.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { z } from 'zod'
2
+ import { defineAggregate } from '@baseworks/foldbase'
3
+
4
+ /**
5
+ * Event catalog — the single source of truth for invoice-service payloads.
6
+ * One aggregate: `invoice`, the AR ledger entry. Status machine:
7
+ *
8
+ * draft ──finalize──▶ finalized ──recordPayment(balance≤0)──▶ paid
9
+ * │ │
10
+ * update void│──────────────────────────────────▶ void
11
+ *
12
+ * MONEY IS INTEGER CENTS everywhere (never a float). Derived state — line
13
+ * amounts, subtotal/total, the running amount-paid, the per-org invoice number,
14
+ * and the resulting status — is computed by the STORE before emit and carried as
15
+ * absolute values in the event, so the projection is a plain upsert (no
16
+ * accumulation). `lines` is a serialized JSON array. Timestamps are epoch millis.
17
+ * A FINALIZED invoice is immutable: only PaymentRecorded / InvoiceVoided follow.
18
+ */
19
+
20
+ export const InvoiceStatus = z.enum(['draft', 'finalized', 'paid', 'void'])
21
+ export type InvoiceStatus = z.infer<typeof InvoiceStatus>
22
+
23
+ export const InvoiceEvents = defineAggregate('invoice', {
24
+ // Draft created (with its initial lines + computed totals). Numeric fields are
25
+ // initialised to 0 so their read-model columns are stable integers.
26
+ InvoiceDrafted: z.object({
27
+ customerId: z.string().min(1),
28
+ customerName: z.string(), // snapshot at draft time; '' if unknown
29
+ currency: z.string().length(3),
30
+ lines: z.string(), // JSON array of { description, quantity, unitPriceCents, amountCents, productId }
31
+ subtotalCents: z.number().int(),
32
+ totalCents: z.number().int(),
33
+ shortId: z.string().min(1),
34
+ at: z.number().int(),
35
+ }),
36
+ // Draft edited (customer / lines). Only valid while status = draft.
37
+ InvoiceUpdated: z.object({
38
+ customerId: z.string().min(1),
39
+ customerName: z.string(),
40
+ lines: z.string(),
41
+ subtotalCents: z.number().int(),
42
+ totalCents: z.number().int(),
43
+ at: z.number().int(),
44
+ }),
45
+ // Finalize: assign the per-org number, freeze lines + totals, set issue/due.
46
+ InvoiceFinalized: z.object({
47
+ number: z.number().int(),
48
+ lines: z.string(),
49
+ subtotalCents: z.number().int(),
50
+ totalCents: z.number().int(),
51
+ issuedAt: z.number().int(),
52
+ dueAt: z.number().int(), // 0 = no due date
53
+ at: z.number().int(),
54
+ }),
55
+ // A payment applied to a finalized invoice. `amountPaidCents` is the new running
56
+ // total; `status` is the resulting status ('paid' when balance ≤ 0, else
57
+ // 'finalized') — both computed by the store.
58
+ PaymentRecorded: z.object({
59
+ amountCents: z.number().int(),
60
+ amountPaidCents: z.number().int(),
61
+ status: InvoiceStatus,
62
+ method: z.string(),
63
+ reference: z.string(),
64
+ at: z.number().int(),
65
+ }),
66
+ InvoiceVoided: z.object({
67
+ reason: z.string(),
68
+ at: z.number().int(),
69
+ }),
70
+ })
71
+
72
+ /**
73
+ * The transaction ledger — one stream (and one read-model row) PER money movement,
74
+ * unlike the invoice's cached `amount_paid`. A payment emits BOTH `PaymentRecorded`
75
+ * (on the invoice, to keep its balance/status fast) AND `TransactionRecorded` (here,
76
+ * a durable per-payment record). `kind` is 'payment' today; 'refund' / 'adjustment'
77
+ * extend it later without touching the invoice aggregate.
78
+ */
79
+ export const TransactionKind = z.enum(['payment', 'refund', 'adjustment'])
80
+ export type TransactionKind = z.infer<typeof TransactionKind>
81
+
82
+ export const TransactionEvents = defineAggregate('transaction', {
83
+ TransactionRecorded: z.object({
84
+ invoiceId: z.string().min(1),
85
+ invoiceNumber: z.number().int(), // the invoice's number at the time
86
+ customerId: z.string(),
87
+ customerName: z.string(),
88
+ kind: TransactionKind,
89
+ amountCents: z.number().int(),
90
+ currency: z.string().length(3),
91
+ method: z.string(),
92
+ reference: z.string(),
93
+ at: z.number().int(),
94
+ }),
95
+ })
package/src/index.ts ADDED
@@ -0,0 +1 @@
1
+ export * from './client.js'
@@ -0,0 +1,78 @@
1
+ import { defineProjection, type PolicyDef } from '@baseworks/foldbase'
2
+ import { InvoiceEvents, TransactionEvents } from './events.js'
3
+
4
+ /**
5
+ * Read-model definition registered on boot (idempotent). Each event upserts an
6
+ * absolute snapshot — the store computed the derived state — so no fold needs to
7
+ * read the current row. Numeric columns are seeded to 0 at draft so their types
8
+ * stay integer. Projection name has NO `read_` prefix (foldbase adds it → table
9
+ * `read_invoices`). Archive/void keeps the row (an invoice is a durable record);
10
+ * only status changes.
11
+ */
12
+ export const readInvoices = defineProjection('invoices', InvoiceEvents, (on) => ({
13
+ InvoiceDrafted: on.InvoiceDrafted.upsert((e) => ({
14
+ customer_id: e.customerId,
15
+ customer_name: e.customerName,
16
+ currency: e.currency,
17
+ lines: e.lines,
18
+ number: 0,
19
+ status: 'draft',
20
+ subtotal_cents: e.subtotalCents,
21
+ total_cents: e.totalCents,
22
+ amount_paid_cents: 0,
23
+ issued_at: 0,
24
+ due_at: 0,
25
+ short_id: e.shortId,
26
+ created_at: e.at,
27
+ })),
28
+ InvoiceUpdated: on.InvoiceUpdated.upsert((e) => ({
29
+ customer_id: e.customerId,
30
+ customer_name: e.customerName,
31
+ lines: e.lines,
32
+ subtotal_cents: e.subtotalCents,
33
+ total_cents: e.totalCents,
34
+ })),
35
+ InvoiceFinalized: on.InvoiceFinalized.upsert((e) => ({
36
+ number: e.number,
37
+ status: 'finalized',
38
+ lines: e.lines,
39
+ subtotal_cents: e.subtotalCents,
40
+ total_cents: e.totalCents,
41
+ issued_at: e.issuedAt,
42
+ due_at: e.dueAt,
43
+ })),
44
+ PaymentRecorded: on.PaymentRecorded.upsert((e) => ({
45
+ amount_paid_cents: e.amountPaidCents,
46
+ status: e.status,
47
+ })),
48
+ InvoiceVoided: on.InvoiceVoided.upsert(() => ({
49
+ status: 'void',
50
+ })),
51
+ }))
52
+
53
+ /**
54
+ * The transaction ledger read model — one row per money movement (keyed by the
55
+ * transaction's own stream id). Immutable records: no update/delete events.
56
+ */
57
+ export const readTransactions = defineProjection('transactions', TransactionEvents, (on) => ({
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,
63
+ kind: e.kind,
64
+ amount_cents: e.amountCents,
65
+ currency: e.currency,
66
+ method: e.method,
67
+ reference: e.reference,
68
+ created_at: e.at,
69
+ })),
70
+ }))
71
+
72
+ export const PROJECTIONS = [readInvoices, readTransactions] as const
73
+
74
+ /** Permissive policies for the service's own `admin` identity (see ADR 0001). */
75
+ export const POLICIES: PolicyDef[] = [
76
+ { name: 'invoices', role: 'admin' },
77
+ { name: 'transactions', role: 'admin' },
78
+ ]