@rowbind/sdk 0.0.0-stage → 0.1.0-alpha.1
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 +537 -2
- package/dist/generated/catalog.d.ts +22 -0
- package/dist/generated/catalog.js +7 -0
- package/dist/generated/http.d.ts +1740 -0
- package/dist/generated/http.js +843 -0
- package/dist/generated/raw.d.ts +39 -0
- package/dist/generated/raw.js +14 -0
- package/dist/generated/validators.d.ts +1411 -0
- package/dist/generated/validators.js +993 -0
- package/dist/http-error.d.ts +5 -0
- package/dist/http-error.js +2 -0
- package/dist/http-request.d.ts +17 -0
- package/dist/http-request.js +73 -0
- package/dist/index.d.ts +622 -0
- package/dist/index.js +256 -0
- package/dist/inputs.d.ts +145 -0
- package/dist/inputs.js +46 -0
- package/dist/ledger.d.ts +98 -0
- package/dist/ledger.js +218 -0
- package/dist/raw-invoice-query.d.ts +2 -0
- package/dist/raw-invoice-query.js +10 -0
- package/dist/transport.d.ts +344 -0
- package/dist/transport.js +276 -0
- package/dist/wire.d.ts +16 -0
- package/dist/wire.js +8 -0
- package/examples/catalog-invoice.mts +30 -0
- package/examples/connection-health.mts +21 -0
- package/examples/department-quickbooks/example.mts +12 -0
- package/examples/department-quickbooks/tsconfig.json +4 -0
- package/examples/facturar.mts +34 -0
- package/examples/first-customer.mts +72 -0
- package/examples/invoice-balances.mts +60 -0
- package/examples/invoice-settlement.mts +86 -0
- package/examples/invoice-sync.mts +46 -0
- package/examples/invoice-traces.mts +65 -0
- package/examples/invoice.mts +27 -0
- package/examples/mixed-providers/example.mts +12 -0
- package/examples/mixed-providers/tsconfig.json +4 -0
- package/examples/native-query.mts +28 -0
- package/examples/native-quickstart.mts +46 -0
- package/examples/observed-payments.mts +29 -0
- package/examples/quickstart.mts +11 -0
- package/examples/reimbursement-batch.mts +36 -0
- package/examples/resume-invoice.mts +52 -0
- package/examples/tsconfig.editor.json +11 -0
- package/examples/webhook-receiver.mts +142 -0
- package/package.json +78 -4
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
|
+
import * as http from "./generated/http.js";
|
|
3
|
+
import { ApplyCreditMemoResponse, CreateCreditMemoResponse, CreateReceivedPaymentResponse, SearchCatalogParams, SearchCatalogQueryParams, SearchCatalogResponse, LinkCatalogParams, LinkCatalogBody, LinkCatalogResponse, CreateBatchResponse, CreateCompanyResponse, CreateConnectSessionResponse, CreateInvoiceResponse, CreateWebhookEndpointResponse, ListConnectionsResponse, ListWebhookDeliveriesResponse, ReplayWebhookDeliveryResponse, EnableReceivedPaymentSyncParams, EnableReceivedPaymentSyncResponse, RetrieveReceivedPaymentSyncParams, RetrieveReceivedPaymentSyncResponse, ListObservedPaymentsParams, ListObservedPaymentsQueryParams, ListObservedPaymentsResponse, MatchObservedPaymentParams, MatchObservedPaymentBody, MatchObservedPaymentResponse, RetrieveConnectionHealthParams, RetrieveConnectionHealthResponse, CheckConnectionHealthParams, CheckConnectionHealthResponse, ReadRawBody, ReadRawParams, ReadRawResponse, ListInvoiceTracesQueryParams, ListInvoiceTracesResponse, ListSyncedInvoicesParams, ListSyncedInvoicesQueryParams, ListSyncedInvoicesResponse, RetrieveInvoiceRecoveryParams, RetrieveInvoiceRecoveryQueryParams, RetrieveInvoiceRecoveryResponse, RetrieveBatchResponse, RetrieveConnectionResponse, RetrieveInvoiceSyncResponse, RetrieveConnectSessionResponse, RetrieveOperationResponse, } from "./generated/validators.js";
|
|
4
|
+
import { QueryRawBody, QueryRawParams, QueryRawResponse } from "./wire.js";
|
|
5
|
+
import { parseInput } from "./inputs.js";
|
|
6
|
+
import { LedgerError } from "./ledger.js";
|
|
7
|
+
export class OperationWaitError extends LedgerError {
|
|
8
|
+
operationId;
|
|
9
|
+
diagnosis;
|
|
10
|
+
constructor(code, message, operationId, diagnosis, requestId) {
|
|
11
|
+
super(code, message, requestId);
|
|
12
|
+
this.operationId = operationId;
|
|
13
|
+
this.diagnosis = diagnosis;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function forConnection(result, connectionId) {
|
|
17
|
+
if (result.connectionId !== connectionId)
|
|
18
|
+
throw new LedgerError("invalid_response", "Rowbind returned a result for another connection.");
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
export class PilotTransport {
|
|
22
|
+
fetch;
|
|
23
|
+
base;
|
|
24
|
+
key;
|
|
25
|
+
constructor(url, key, fetch) {
|
|
26
|
+
this.fetch = fetch;
|
|
27
|
+
try {
|
|
28
|
+
this.base = new URL(url);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
throw new LedgerError("invalid_configuration", "The Rowbind origin must be a valid HTTP(S) URL.");
|
|
32
|
+
}
|
|
33
|
+
const local = ["127.0.0.1", "[::1]", "localhost"].includes(this.base.hostname);
|
|
34
|
+
if (!key || this.base.username || this.base.password || this.base.search || this.base.hash ||
|
|
35
|
+
this.base.pathname !== "/" || !(this.base.protocol === "https:" || (local && this.base.protocol === "http:"))) {
|
|
36
|
+
throw new LedgerError("invalid_configuration", "Set a Rowbind origin (HTTPS or loopback HTTP) and its project API key.");
|
|
37
|
+
}
|
|
38
|
+
this.key = key;
|
|
39
|
+
}
|
|
40
|
+
options(deadline = Date.now() + 15_000) {
|
|
41
|
+
return { rowbind: { origin: this.base, key: this.key, deadline, fetch: this.fetch } };
|
|
42
|
+
}
|
|
43
|
+
async createCompany(input) {
|
|
44
|
+
return CreateCompanyResponse.parse(await http.createCompany(input, this.options()));
|
|
45
|
+
}
|
|
46
|
+
async createConnectSession(input) {
|
|
47
|
+
return CreateConnectSessionResponse.parse(await http.createConnectSession(input, this.options()));
|
|
48
|
+
}
|
|
49
|
+
async connectSession(id) {
|
|
50
|
+
const session = RetrieveConnectSessionResponse.parse(await http.retrieveConnectSession(id, this.options()));
|
|
51
|
+
if (session.id !== id)
|
|
52
|
+
throw new LedgerError("invalid_response", "Rowbind returned a different Connect session.");
|
|
53
|
+
return session;
|
|
54
|
+
}
|
|
55
|
+
async readRaw(id, input) {
|
|
56
|
+
parseInput(ReadRawParams, { id });
|
|
57
|
+
const body = parseInput(ReadRawBody, input);
|
|
58
|
+
const responseMetadata = {};
|
|
59
|
+
const result = ReadRawResponse.safeParse(await http.readRaw(id, body, {
|
|
60
|
+
...this.options(), responseMetadata, preserveServiceErrors: ["source_offline", "upstream_unavailable"],
|
|
61
|
+
}));
|
|
62
|
+
if (!result.success || result.data.provider !== body.provider) {
|
|
63
|
+
throw new LedgerError("invalid_response", "Rowbind did not return a valid raw result for this provider.", responseMetadata.requestId);
|
|
64
|
+
}
|
|
65
|
+
return { ...result.data, ...responseMetadata };
|
|
66
|
+
}
|
|
67
|
+
async queryRaw(id, input) {
|
|
68
|
+
parseInput(QueryRawParams, { id });
|
|
69
|
+
const body = parseInput(QueryRawBody, input);
|
|
70
|
+
const responseMetadata = {};
|
|
71
|
+
const result = QueryRawResponse.safeParse(await http.queryRaw(id, body, {
|
|
72
|
+
...this.options(), responseMetadata, preserveServiceErrors: ["source_offline", "upstream_unavailable"],
|
|
73
|
+
}));
|
|
74
|
+
if (!result.success || result.data.provider !== body.provider) {
|
|
75
|
+
throw new LedgerError("invalid_response", "Rowbind did not return a valid native query result for this provider.", responseMetadata.requestId);
|
|
76
|
+
}
|
|
77
|
+
if (result.data.provider === "netsuite" && body.provider === "netsuite") {
|
|
78
|
+
const page = result.data.page;
|
|
79
|
+
if (page.offset !== (body.offset ?? 0) || page.count !== page.items.length || page.count > (body.limit ?? 10)) {
|
|
80
|
+
throw new LedgerError("invalid_response", "Rowbind returned a different SuiteQL page.", responseMetadata.requestId);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return { ...result.data, ...responseMetadata };
|
|
84
|
+
}
|
|
85
|
+
async createReceivedPayment(body, key) {
|
|
86
|
+
return CreateReceivedPaymentResponse.parse(await http.createReceivedPayment(body, { "Idempotency-Key": key }, this.options()));
|
|
87
|
+
}
|
|
88
|
+
async createCreditMemo(body, key) {
|
|
89
|
+
return CreateCreditMemoResponse.parse(await http.createCreditMemo(body, { "Idempotency-Key": key }, this.options()));
|
|
90
|
+
}
|
|
91
|
+
async applyCreditMemo(id, body, key) {
|
|
92
|
+
return ApplyCreditMemoResponse.parse(await http.applyCreditMemo(id, body, { "Idempotency-Key": key }, this.options()));
|
|
93
|
+
}
|
|
94
|
+
async createBatch(body, idempotencyKey) {
|
|
95
|
+
const result = await http.createBatch(body, { "Idempotency-Key": idempotencyKey }, this.options());
|
|
96
|
+
return CreateBatchResponse.parse(result);
|
|
97
|
+
}
|
|
98
|
+
async batch(id) {
|
|
99
|
+
const result = RetrieveBatchResponse.parse(await http.retrieveBatch(id, this.options()));
|
|
100
|
+
if (result.id !== id)
|
|
101
|
+
throw new LedgerError("invalid_response", "Rowbind returned a different batch.");
|
|
102
|
+
return result;
|
|
103
|
+
}
|
|
104
|
+
async searchCatalog(id, kind, params) {
|
|
105
|
+
parseInput(SearchCatalogParams, { id, kind });
|
|
106
|
+
const query = parseInput(SearchCatalogQueryParams, params);
|
|
107
|
+
return SearchCatalogResponse.parse(await http.searchCatalog(id, kind, query, this.options()));
|
|
108
|
+
}
|
|
109
|
+
async linkCatalog(id, kind, input) {
|
|
110
|
+
parseInput(LinkCatalogParams, { id, kind });
|
|
111
|
+
const body = parseInput(LinkCatalogBody, input);
|
|
112
|
+
const link = LinkCatalogResponse.parse(await http.linkCatalog(id, kind, body, this.options()));
|
|
113
|
+
if (link.kind !== kind || link.externalId !== body.externalId || link.nativeId !== body.nativeId) {
|
|
114
|
+
throw new LedgerError("invalid_response", "Rowbind confirmed a different catalog link.");
|
|
115
|
+
}
|
|
116
|
+
return link;
|
|
117
|
+
}
|
|
118
|
+
async enableInvoiceSync(connectionId) {
|
|
119
|
+
const result = await http.enableInvoiceSync(connectionId, this.options());
|
|
120
|
+
return forConnection(RetrieveInvoiceSyncResponse.parse(result), connectionId);
|
|
121
|
+
}
|
|
122
|
+
async retrieveInvoiceSync(connectionId) {
|
|
123
|
+
const result = await http.retrieveInvoiceSync(connectionId, this.options());
|
|
124
|
+
return forConnection(RetrieveInvoiceSyncResponse.parse(result), connectionId);
|
|
125
|
+
}
|
|
126
|
+
async listSyncedInvoices(connectionId, params = {}) {
|
|
127
|
+
parseInput(ListSyncedInvoicesParams, { id: connectionId });
|
|
128
|
+
const query = parseInput(ListSyncedInvoicesQueryParams, params);
|
|
129
|
+
const result = await http.listSyncedInvoices(connectionId, query, this.options());
|
|
130
|
+
const page = forConnection(ListSyncedInvoicesResponse.parse(result), connectionId);
|
|
131
|
+
if (page.invoices.some(invoice => invoice.revision > page.snapshotRevision)) {
|
|
132
|
+
throw new LedgerError("invalid_response", "Rowbind returned an invoice revision beyond the snapshot cutoff.");
|
|
133
|
+
}
|
|
134
|
+
return page;
|
|
135
|
+
}
|
|
136
|
+
async enableReceivedPaymentSync(connectionId) {
|
|
137
|
+
parseInput(EnableReceivedPaymentSyncParams, { id: connectionId });
|
|
138
|
+
const result = await http.enableReceivedPaymentSync(connectionId, this.options());
|
|
139
|
+
return forConnection(EnableReceivedPaymentSyncResponse.parse(result), connectionId);
|
|
140
|
+
}
|
|
141
|
+
async retrieveReceivedPaymentSync(connectionId) {
|
|
142
|
+
parseInput(RetrieveReceivedPaymentSyncParams, { id: connectionId });
|
|
143
|
+
const result = await http.retrieveReceivedPaymentSync(connectionId, this.options());
|
|
144
|
+
return forConnection(RetrieveReceivedPaymentSyncResponse.parse(result), connectionId);
|
|
145
|
+
}
|
|
146
|
+
async listObservedPayments(connectionId, params = {}) {
|
|
147
|
+
parseInput(ListObservedPaymentsParams, { id: connectionId });
|
|
148
|
+
const query = parseInput(ListObservedPaymentsQueryParams, params);
|
|
149
|
+
const page = ListObservedPaymentsResponse.parse(await http.listObservedPayments(connectionId, query, this.options()));
|
|
150
|
+
for (const observation of page.observations) {
|
|
151
|
+
if (observation.connectionId !== connectionId || (query.status && observation.status !== query.status) ||
|
|
152
|
+
(observation.status === "matched") !== (observation.externalInvoiceId !== null)) {
|
|
153
|
+
throw new LedgerError("invalid_response", "Rowbind returned a payment outside the requested book or match state.");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return page;
|
|
157
|
+
}
|
|
158
|
+
async matchObservedPayment(id, input) {
|
|
159
|
+
parseInput(MatchObservedPaymentParams, { id });
|
|
160
|
+
const body = parseInput(MatchObservedPaymentBody, input);
|
|
161
|
+
const observation = MatchObservedPaymentResponse.parse(await http.matchObservedPayment(id, body, this.options()));
|
|
162
|
+
if (observation.id !== id || observation.status !== "matched" || observation.externalInvoiceId !== body.externalInvoiceId) {
|
|
163
|
+
throw new LedgerError("invalid_response", "Rowbind did not confirm this observation for the requested invoice.");
|
|
164
|
+
}
|
|
165
|
+
return observation;
|
|
166
|
+
}
|
|
167
|
+
async createWebhookEndpoint(body) {
|
|
168
|
+
const endpoint = CreateWebhookEndpointResponse.parse(await http.createWebhookEndpoint(body, this.options()));
|
|
169
|
+
if (endpoint.destination !== body.destination)
|
|
170
|
+
throw new LedgerError("invalid_response", "Rowbind returned another webhook destination.");
|
|
171
|
+
if (endpoint.eventType !== (body.eventType ?? "operation.verified"))
|
|
172
|
+
throw new LedgerError("invalid_response", "Rowbind subscribed another event type.");
|
|
173
|
+
return endpoint;
|
|
174
|
+
}
|
|
175
|
+
async webhookDeliveries(id) {
|
|
176
|
+
return ListWebhookDeliveriesResponse.parse(await http.listWebhookDeliveries(id, this.options()));
|
|
177
|
+
}
|
|
178
|
+
async replayWebhookDelivery(id, eventId) {
|
|
179
|
+
const result = ReplayWebhookDeliveryResponse.parse(await http.replayWebhookDelivery(id, eventId, this.options()));
|
|
180
|
+
if (result.eventId !== eventId)
|
|
181
|
+
throw new LedgerError("invalid_response", "Rowbind returned a different webhook event.");
|
|
182
|
+
return result;
|
|
183
|
+
}
|
|
184
|
+
async connections() {
|
|
185
|
+
return ListConnectionsResponse.parse(await http.listConnections(this.options()));
|
|
186
|
+
}
|
|
187
|
+
async connection(id) {
|
|
188
|
+
const book = RetrieveConnectionResponse.parse(await http.retrieveConnection(id, this.options()));
|
|
189
|
+
if (book.id !== id)
|
|
190
|
+
throw new LedgerError("invalid_response", "Rowbind returned a different invoice destination.");
|
|
191
|
+
return book;
|
|
192
|
+
}
|
|
193
|
+
async connectionHealth(id) {
|
|
194
|
+
parseInput(RetrieveConnectionHealthParams, { id });
|
|
195
|
+
const result = RetrieveConnectionHealthResponse.parse(await http.retrieveConnectionHealth(id, { ...this.options(), preserveServiceErrors: ["health_storage_unavailable"] }));
|
|
196
|
+
return forConnection(result, id);
|
|
197
|
+
}
|
|
198
|
+
async checkConnectionHealth(id) {
|
|
199
|
+
parseInput(CheckConnectionHealthParams, { id });
|
|
200
|
+
const result = CheckConnectionHealthResponse.parse(await http.checkConnectionHealth(id, { ...this.options(), preserveServiceErrors: ["health_storage_unavailable"] }));
|
|
201
|
+
return forConnection(result, id);
|
|
202
|
+
}
|
|
203
|
+
async create(body, idempotencyKey, responseMetadata) {
|
|
204
|
+
const { providerOptions, lines, ...common } = body;
|
|
205
|
+
const invoiceRequest = { ...common, lines: [...lines], ...(providerOptions && { providerOptions }) };
|
|
206
|
+
const options = { ...this.options(), ...(responseMetadata && { responseMetadata }) };
|
|
207
|
+
const result = await http.createInvoice(invoiceRequest, { "Idempotency-Key": idempotencyKey }, options);
|
|
208
|
+
return CreateInvoiceResponse.parse(result);
|
|
209
|
+
}
|
|
210
|
+
async invoiceTraces(lookup) {
|
|
211
|
+
const query = parseInput(ListInvoiceTracesQueryParams, lookup);
|
|
212
|
+
if ([query.requestId, query.reference, query.operationId].filter(value => value !== undefined).length !== 1) {
|
|
213
|
+
throw new LedgerError("invalid_input", "Provide exactly one of requestId, reference or operationId.");
|
|
214
|
+
}
|
|
215
|
+
const page = ListInvoiceTracesResponse.parse(await http.listInvoiceTraces(query, this.options()));
|
|
216
|
+
for (const request of page.requests) {
|
|
217
|
+
if ((query.requestId !== undefined && request.requestId !== query.requestId) ||
|
|
218
|
+
(query.operationId !== undefined && request.operationId !== query.operationId) ||
|
|
219
|
+
(query.connectionId !== undefined && request.connectionId !== query.connectionId)) {
|
|
220
|
+
throw new LedgerError("invalid_response", "Rowbind returned an invoice request outside the requested lookup.");
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return page;
|
|
224
|
+
}
|
|
225
|
+
async invoiceRecovery(id, params = {}) {
|
|
226
|
+
parseInput(RetrieveInvoiceRecoveryParams, { id });
|
|
227
|
+
const query = parseInput(RetrieveInvoiceRecoveryQueryParams, params);
|
|
228
|
+
const page = RetrieveInvoiceRecoveryResponse.parse(await http.retrieveInvoiceRecovery(id, query, this.options()));
|
|
229
|
+
if (page.operationId !== id)
|
|
230
|
+
throw new LedgerError("invalid_response", "Rowbind returned history for another operation.");
|
|
231
|
+
let previous = query.after ?? 0;
|
|
232
|
+
for (const entry of page.entries) {
|
|
233
|
+
if (entry.sequence <= previous)
|
|
234
|
+
throw new LedgerError("invalid_response", "Recovery entries were out of order.");
|
|
235
|
+
previous = entry.sequence;
|
|
236
|
+
}
|
|
237
|
+
if (page.nextCursor !== null && page.nextCursor !== page.entries.at(-1)?.sequence) {
|
|
238
|
+
throw new LedgerError("invalid_response", "Rowbind returned an inconsistent recovery cursor.");
|
|
239
|
+
}
|
|
240
|
+
return page;
|
|
241
|
+
}
|
|
242
|
+
async operation(id, deadline = Date.now() + 15_000) {
|
|
243
|
+
const result = RetrieveOperationResponse.parse(await http.retrieveOperation(id, this.options(deadline)));
|
|
244
|
+
if (result.id !== id)
|
|
245
|
+
throw new LedgerError("invalid_response", "Rowbind returned another operation.");
|
|
246
|
+
return result;
|
|
247
|
+
}
|
|
248
|
+
async wait(id, timeoutMs) {
|
|
249
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0)
|
|
250
|
+
throw new LedgerError("invalid_input", "timeoutMs must be a positive integer.");
|
|
251
|
+
const deadline = Date.now() + timeoutMs;
|
|
252
|
+
let detail = "No verified upstream record yet.";
|
|
253
|
+
let diagnosis;
|
|
254
|
+
while (Date.now() < deadline) {
|
|
255
|
+
let op;
|
|
256
|
+
try {
|
|
257
|
+
op = await this.operation(id, deadline);
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
if (!(error instanceof LedgerError) || (error.code !== "transport_unavailable" && error.code !== "core_storage_unavailable"))
|
|
261
|
+
throw error;
|
|
262
|
+
throw new OperationWaitError(error.code, `${error.message} Resume with operation ${id}.`, id, diagnosis, error.requestId);
|
|
263
|
+
}
|
|
264
|
+
if (op.status === "verified")
|
|
265
|
+
return op.record;
|
|
266
|
+
if (op.status !== "pending")
|
|
267
|
+
throw new LedgerError(op.code, `${op.message} (operation ${id})`);
|
|
268
|
+
if (op.detail)
|
|
269
|
+
detail = op.detail;
|
|
270
|
+
if (op.diagnosis)
|
|
271
|
+
diagnosis = op.diagnosis;
|
|
272
|
+
await sleep(Math.min(500, Math.max(0, deadline - Date.now())));
|
|
273
|
+
}
|
|
274
|
+
throw new OperationWaitError("verification_pending", `${detail} Resume with operation ${id}.`, id, diagnosis);
|
|
275
|
+
}
|
|
276
|
+
}
|
package/dist/wire.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const QueryRawBody: import("zod").ZodUnion<readonly [import("zod").ZodObject<{
|
|
2
|
+
provider: import("zod").ZodEnum<{
|
|
3
|
+
quickbooksDesktop: "quickbooksDesktop";
|
|
4
|
+
}>;
|
|
5
|
+
qbxml: import("zod").ZodString;
|
|
6
|
+
}, import("zod/v4/core").$strict>, import("zod").ZodObject<{
|
|
7
|
+
provider: import("zod").ZodEnum<{
|
|
8
|
+
netsuite: "netsuite";
|
|
9
|
+
}>;
|
|
10
|
+
q: import("zod").ZodString;
|
|
11
|
+
limit: import("zod").ZodExactOptional<import("zod").ZodInt>;
|
|
12
|
+
offset: import("zod").ZodExactOptional<import("zod").ZodInt>;
|
|
13
|
+
}, import("zod/v4/core").$strict>]>;
|
|
14
|
+
export { SearchCatalogParams, SearchCatalogQueryParams, SearchCatalogResponse, LinkCatalogParams, LinkCatalogBody, LinkCatalogResponse, QueryRawParams, QueryRawResponse, ReadRawBody, ReadRawParams, ReadRawResponse, EnableInvoiceSyncParams, EnableInvoiceSyncResponse, RetrieveInvoiceSyncParams, RetrieveInvoiceSyncResponse, EnableReceivedPaymentSyncParams, EnableReceivedPaymentSyncResponse, RetrieveReceivedPaymentSyncParams, RetrieveReceivedPaymentSyncResponse, ListSyncedInvoicesParams, ListSyncedInvoicesQueryParams, ListSyncedInvoicesResponse, ListObservedPaymentsParams, ListObservedPaymentsQueryParams, ListObservedPaymentsResponse, MatchObservedPaymentParams, MatchObservedPaymentBody, MatchObservedPaymentResponse, CreateReceivedPaymentBody, CreateReceivedPaymentResponse, CreateCreditMemoBody, CreateCreditMemoResponse, ApplyCreditMemoBody, ApplyCreditMemoParams, ApplyCreditMemoResponse, CreateBatchBody, CreateBatchResponse, RetrieveBatchParams, RetrieveBatchResponse, CreateWebhookEndpointBody, CreateWebhookEndpointResponse, ListWebhookDeliveriesParams, ListWebhookDeliveriesResponse, ReplayWebhookDeliveryParams, ReplayWebhookDeliveryResponse, CreateCompanyBody, CreateCompanyResponse, CreateConnectSessionBody, CreateConnectSessionResponse, RetrieveConnectSessionParams, RetrieveConnectSessionResponse, ListConnectionsResponse, RetrieveConnectionHealthParams, RetrieveConnectionHealthResponse, CheckConnectionHealthParams, CheckConnectionHealthResponse, RetrieveConnectionParams, RetrieveConnectionResponse, CreateInvoiceBody, CreateInvoiceResponse, ListInvoiceTracesQueryParams, ListInvoiceTracesResponse, RetrieveInvoiceRecoveryParams, RetrieveInvoiceRecoveryQueryParams, RetrieveInvoiceRecoveryResponse, RetrieveOperationParams, RetrieveOperationResponse, } from "./generated/validators.js";
|
|
15
|
+
export { rawInvoiceLookupId } from "./raw-invoice-query.js";
|
|
16
|
+
export { httpError } from "./http-error.js";
|
package/dist/wire.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
// Wire schemas shared with the API without importing the Node sandbox runtime.
|
|
2
|
+
import { QueryRawBody as generatedQueryRawBody } from "./generated/validators.js";
|
|
3
|
+
// OpenAPI describes the page size and offset bounds separately. SuiteTalk also
|
|
4
|
+
// requires every offset to fall on a page boundary.
|
|
5
|
+
export const QueryRawBody = generatedQueryRawBody.refine(input => input.provider !== "netsuite" || (input.offset ?? 0) % (input.limit ?? 10) === 0, { path: ["offset"], message: "Provide an offset divisible by the page limit." });
|
|
6
|
+
export { SearchCatalogParams, SearchCatalogQueryParams, SearchCatalogResponse, LinkCatalogParams, LinkCatalogBody, LinkCatalogResponse, QueryRawParams, QueryRawResponse, ReadRawBody, ReadRawParams, ReadRawResponse, EnableInvoiceSyncParams, EnableInvoiceSyncResponse, RetrieveInvoiceSyncParams, RetrieveInvoiceSyncResponse, EnableReceivedPaymentSyncParams, EnableReceivedPaymentSyncResponse, RetrieveReceivedPaymentSyncParams, RetrieveReceivedPaymentSyncResponse, ListSyncedInvoicesParams, ListSyncedInvoicesQueryParams, ListSyncedInvoicesResponse, ListObservedPaymentsParams, ListObservedPaymentsQueryParams, ListObservedPaymentsResponse, MatchObservedPaymentParams, MatchObservedPaymentBody, MatchObservedPaymentResponse, CreateReceivedPaymentBody, CreateReceivedPaymentResponse, CreateCreditMemoBody, CreateCreditMemoResponse, ApplyCreditMemoBody, ApplyCreditMemoParams, ApplyCreditMemoResponse, CreateBatchBody, CreateBatchResponse, RetrieveBatchParams, RetrieveBatchResponse, CreateWebhookEndpointBody, CreateWebhookEndpointResponse, ListWebhookDeliveriesParams, ListWebhookDeliveriesResponse, ReplayWebhookDeliveryParams, ReplayWebhookDeliveryResponse, CreateCompanyBody, CreateCompanyResponse, CreateConnectSessionBody, CreateConnectSessionResponse, RetrieveConnectSessionParams, RetrieveConnectSessionResponse, ListConnectionsResponse, RetrieveConnectionHealthParams, RetrieveConnectionHealthResponse, CheckConnectionHealthParams, CheckConnectionHealthResponse, RetrieveConnectionParams, RetrieveConnectionResponse, CreateInvoiceBody, CreateInvoiceResponse, ListInvoiceTracesQueryParams, ListInvoiceTracesResponse, RetrieveInvoiceRecoveryParams, RetrieveInvoiceRecoveryQueryParams, RetrieveInvoiceRecoveryResponse, RetrieveOperationParams, RetrieveOperationResponse, } from "./generated/validators.js";
|
|
7
|
+
export { rawInvoiceLookupId } from "./raw-invoice-query.js";
|
|
8
|
+
export { httpError } from "./http-error.js";
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Rowbind } from "@rowbind/sdk"
|
|
2
|
+
|
|
3
|
+
const [action, connectionId, ...args] = process.argv.slice(2)
|
|
4
|
+
const usage = "Usage: catalog-invoice.mts search BOOK customer|item QUERY [AFTER] | link BOOK customer|item EXTERNAL_ID NATIVE_ID | invoice BOOK SALE_REF CUSTOMER_REF SKU"
|
|
5
|
+
|
|
6
|
+
async function main() {
|
|
7
|
+
if (!connectionId) throw new Error(usage)
|
|
8
|
+
const rb = new Rowbind()
|
|
9
|
+
if (action === "invoice" && args.length === 3) {
|
|
10
|
+
const [externalReference, customer, sku] = args
|
|
11
|
+
const book = await rb.connections.retrieve(connectionId)
|
|
12
|
+
const op = await rb.invoices.create({
|
|
13
|
+
...book.invoiceTarget, externalReference, customerRef: { externalId: customer },
|
|
14
|
+
lines: [{ itemRef: { externalId: sku }, quantity: 2, unitPrice: "60.00" }],
|
|
15
|
+
currency: "USD", idempotencyKey: "sale/" + externalReference,
|
|
16
|
+
})
|
|
17
|
+
return { operationId: op.id, invoice: await rb.operations.waitForVerifiedRecord(op.id) }
|
|
18
|
+
}
|
|
19
|
+
const [kind, value, extra] = args
|
|
20
|
+
if (kind !== "customer" && kind !== "item") throw new Error(usage)
|
|
21
|
+
if (action === "search" && (args.length === 2 || args.length === 3)) {
|
|
22
|
+
return rb.catalog.search(connectionId, { kind, query: value, ...(extra && { after: extra }) })
|
|
23
|
+
}
|
|
24
|
+
if (action === "link" && args.length === 3) {
|
|
25
|
+
return rb.catalog.link(connectionId, { kind, externalId: value, nativeId: extra })
|
|
26
|
+
}
|
|
27
|
+
throw new Error(usage)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
console.log(JSON.stringify(await main()))
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { Rowbind } from "@rowbind/sdk"
|
|
2
|
+
|
|
3
|
+
async function main() {
|
|
4
|
+
const [action, id, ...extra] = process.argv.slice(2)
|
|
5
|
+
if (!id || extra.length || (action !== "status" && action !== "check")) {
|
|
6
|
+
throw new Error("Usage: bun connection-health.mts status|check <connectionId>")
|
|
7
|
+
}
|
|
8
|
+
const rowbind = new Rowbind()
|
|
9
|
+
try {
|
|
10
|
+
return action === "check" ? await rowbind.platform.connections.checkHealth(id) : await rowbind.platform.connections.health(id)
|
|
11
|
+
} finally {
|
|
12
|
+
rowbind.close()
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
try {
|
|
17
|
+
console.log(JSON.stringify(await main(), null, 2))
|
|
18
|
+
} catch (error) {
|
|
19
|
+
console.error(error instanceof Error ? error.message : "Could not retrieve connection health.")
|
|
20
|
+
process.exitCode = 1
|
|
21
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Rowbind } from "@rowbind/sdk"
|
|
2
|
+
import { ventaConDepartamento } from "../facturar.mts"
|
|
3
|
+
|
|
4
|
+
// Cambia quickbooksDesktop por netsuite en connectionId para corregir el error.
|
|
5
|
+
export async function departamentoEnQuickBooks(rowbind: Rowbind) {
|
|
6
|
+
const demo = await rowbind.sandbox.fixtures.retrieve("quickstart-v1")
|
|
7
|
+
return rowbind.invoices.create({
|
|
8
|
+
...ventaConDepartamento,
|
|
9
|
+
connectionId: demo.quickbooksDesktop.connectionId,
|
|
10
|
+
providerOptions: { netsuite: { ...demo.netsuite.invoiceTarget.providerOptions.netsuite, departmentId: "7" } },
|
|
11
|
+
})
|
|
12
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { Connection, Rowbind, InvoiceInput, InvoiceTarget } from "@rowbind/sdk"
|
|
2
|
+
|
|
3
|
+
export const venta = {
|
|
4
|
+
customerRef: { externalId: "tienda-norte" },
|
|
5
|
+
externalReference: "RB-1001",
|
|
6
|
+
currency: "USD",
|
|
7
|
+
lines: [
|
|
8
|
+
{ itemRef: { externalId: "mano-de-obra" }, quantity: 1, unitPrice: "80.00" },
|
|
9
|
+
{ itemRef: { externalId: "material" }, quantity: 1, unitPrice: "40.00" },
|
|
10
|
+
],
|
|
11
|
+
idempotencyKey: "quickstart-invoice-1001",
|
|
12
|
+
} satisfies InvoiceInput
|
|
13
|
+
|
|
14
|
+
export const ventaConDepartamento = {
|
|
15
|
+
...venta, externalReference: "RB-DEPT-1", idempotencyKey: "quickstart-invoice-dept-1",
|
|
16
|
+
} satisfies InvoiceInput
|
|
17
|
+
|
|
18
|
+
export async function facturar(rowbind: Rowbind, destino: InvoiceTarget, facturaSolicitada: InvoiceInput = venta) {
|
|
19
|
+
const op = await rowbind.invoices.create({ ...facturaSolicitada, ...destino })
|
|
20
|
+
console.log("Operación admitida:", op.id)
|
|
21
|
+
const factura = await rowbind.operations.waitForVerifiedRecord(op.id)
|
|
22
|
+
console.log(`Factura ${factura.externalReference} en ${factura.connectionId}: ${factura.balanceDue} ${factura.currency}`)
|
|
23
|
+
console.log(" ID nativo:", factura.id, "· Cliente:", factura.customerId)
|
|
24
|
+
if (factura.departmentId) console.log(" Departamento de cabecera:", factura.departmentId)
|
|
25
|
+
return factura
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function facturarConDepartamento(rowbind: Rowbind, libro: Extract<Connection, { provider: "netsuite" }>, departmentId: string) {
|
|
29
|
+
const { connectionId, providerOptions } = libro.invoiceTarget
|
|
30
|
+
return facturar(rowbind, {
|
|
31
|
+
connectionId,
|
|
32
|
+
providerOptions: { netsuite: { ...providerOptions.netsuite, departmentId } },
|
|
33
|
+
}, ventaConDepartamento)
|
|
34
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import assert from "node:assert/strict"
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises"
|
|
3
|
+
import { Rowbind, RowbindError } from "@rowbind/sdk"
|
|
4
|
+
import { venta } from "./facturar.mts"
|
|
5
|
+
|
|
6
|
+
async function firstInvoice() {
|
|
7
|
+
const [provider, mode, ...rest] = process.argv.slice(2)
|
|
8
|
+
if ((provider !== "quickbooksDesktop" && provider !== "netsuite") ||
|
|
9
|
+
(mode !== undefined && mode !== "--simulate-admin") || rest.length) {
|
|
10
|
+
throw new Error("Uso: bun first-customer.mts quickbooksDesktop|netsuite [--simulate-admin]")
|
|
11
|
+
}
|
|
12
|
+
const rowbind = new Rowbind()
|
|
13
|
+
try {
|
|
14
|
+
const company = await rowbind.platform.companies.create({ externalId: "saas-acme-taller", name: "Taller Demo" })
|
|
15
|
+
const session = await rowbind.platform.connect.sessions.create({ companyId: company.id, provider })
|
|
16
|
+
if (mode === "--simulate-admin") {
|
|
17
|
+
// This client represents the customer's browser. It never gets the SaaS key.
|
|
18
|
+
const link = new URL(session.url)
|
|
19
|
+
if (!["127.0.0.1", "localhost", "[::1]"].includes(link.hostname) || link.protocol !== "http:") {
|
|
20
|
+
throw new Error("La aprobación automática requiere un enlace HTTP al simulador local.")
|
|
21
|
+
}
|
|
22
|
+
const form = await fetch(link, { redirect: "error" })
|
|
23
|
+
if (!form.ok || !(await form.text()).includes('name="consent"')) throw new Error("No se pudo abrir el formulario de Connect.")
|
|
24
|
+
const approval = await fetch(link, { method: "POST", redirect: "error", body: new URLSearchParams({ consent: "connect" }) })
|
|
25
|
+
if (!approval.ok) throw new Error(`Connect devolvió HTTP ${approval.status} al confirmar.`)
|
|
26
|
+
} else {
|
|
27
|
+
console.log("Abre este enlace privado como administrador de Taller Demo y pulsa Connect sandbox:\n" + session.url)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
let consent = await rowbind.platform.connect.sessions.retrieve(session.id)
|
|
31
|
+
while (consent.status === "pending" && Date.now() < Date.parse(session.expiresAt)) {
|
|
32
|
+
await sleep(1000)
|
|
33
|
+
consent = await rowbind.platform.connect.sessions.retrieve(session.id)
|
|
34
|
+
}
|
|
35
|
+
if (consent.status !== "connected" || !consent.connectionId) throw new Error("El administrador no confirmó antes de caducar la sesión.")
|
|
36
|
+
assert.equal(consent.companyId, company.id)
|
|
37
|
+
const book = await rowbind.platform.connections.retrieve(consent.connectionId)
|
|
38
|
+
assert.equal(book.provider, provider)
|
|
39
|
+
|
|
40
|
+
const invoice = { ...venta, ...book.invoiceTarget }
|
|
41
|
+
const receipt = await rowbind.invoices.create(invoice)
|
|
42
|
+
const record = await rowbind.operations.waitForVerifiedRecord(receipt.id)
|
|
43
|
+
assert.equal(record.connectionId, book.id)
|
|
44
|
+
assert.equal(record.externalReference, venta.externalReference)
|
|
45
|
+
assert.equal(record.currency, "USD")
|
|
46
|
+
assert.equal(record.total, "120.00")
|
|
47
|
+
assert.equal(record.balanceDue, "120.00")
|
|
48
|
+
const prefix = provider === "netsuite" ? "ns" : "qbd"
|
|
49
|
+
assert.equal(record.customerId, prefix + "-customer-norte")
|
|
50
|
+
assert.deepEqual(record.lines, [
|
|
51
|
+
{ itemId: prefix + "-labor", quantity: 1, unitPrice: "80.00" },
|
|
52
|
+
{ itemId: prefix + "-material", quantity: 1, unitPrice: "40.00" },
|
|
53
|
+
])
|
|
54
|
+
if (book.provider === "netsuite") assert.equal(record.subsidiaryId, book.invoiceTarget.providerOptions.netsuite.subsidiaryId)
|
|
55
|
+
|
|
56
|
+
const replay = await rowbind.invoices.create(invoice)
|
|
57
|
+
assert.equal(replay.id, receipt.id)
|
|
58
|
+
assert.equal((await rowbind.operations.waitForVerifiedRecord(replay.id)).id, record.id)
|
|
59
|
+
console.log(JSON.stringify({ companyId: company.id, provider, connectionId: book.id, operationId: receipt.id,
|
|
60
|
+
invoiceId: record.id, reference: record.externalReference, total: record.total, balanceDue: record.balanceDue,
|
|
61
|
+
currency: record.currency, status: "verified", replay: "same_operation_and_invoice" }, null, 2))
|
|
62
|
+
} finally {
|
|
63
|
+
rowbind.close()
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
try {
|
|
68
|
+
await firstInvoice()
|
|
69
|
+
} catch (error) {
|
|
70
|
+
console.error(error instanceof RowbindError ? `${error.code}: ${error.message}` : error instanceof Error ? error.message : "Falló la prueba.")
|
|
71
|
+
process.exitCode = 1
|
|
72
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { SyncedInvoice } from "@rowbind/sdk"
|
|
2
|
+
import { mkdirSync } from "node:fs"
|
|
3
|
+
import { createRequire } from "node:module"
|
|
4
|
+
import { dirname } from "node:path"
|
|
5
|
+
|
|
6
|
+
type BalanceDatabase = {
|
|
7
|
+
run(sql: string, ...params: Array<string | number | null>): { changes: number }
|
|
8
|
+
query(sql: string): { get(): unknown }
|
|
9
|
+
transaction<Args extends unknown[]>(fn: (...args: Args) => void): { (...args: Args): void; immediate(...args: Args): void }
|
|
10
|
+
close(): void
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function openBalanceDatabase(path: string) {
|
|
14
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
15
|
+
const { Database }: { Database: new (path: string) => BalanceDatabase } = createRequire(import.meta.url)("bun:sqlite")
|
|
16
|
+
const db = new Database(path)
|
|
17
|
+
db.run("PRAGMA busy_timeout = 5000")
|
|
18
|
+
db.transaction(() => {
|
|
19
|
+
db.run(`CREATE TABLE IF NOT EXISTS invoice_balances (
|
|
20
|
+
connection_id TEXT NOT NULL, invoice_id TEXT NOT NULL, revision INTEGER NOT NULL,
|
|
21
|
+
currency TEXT NOT NULL, balance_due TEXT NOT NULL, details TEXT, status TEXT, PRIMARY KEY (connection_id, invoice_id)
|
|
22
|
+
)`)
|
|
23
|
+
if (!db.query("SELECT 1 FROM pragma_table_info('invoice_balances') WHERE name='details'").get()) {
|
|
24
|
+
db.run("ALTER TABLE invoice_balances ADD COLUMN details TEXT")
|
|
25
|
+
}
|
|
26
|
+
if (!db.query("SELECT 1 FROM pragma_table_info('invoice_balances') WHERE name='status'").get()) {
|
|
27
|
+
db.run("ALTER TABLE invoice_balances ADD COLUMN status TEXT")
|
|
28
|
+
}
|
|
29
|
+
db.run(`CREATE TABLE IF NOT EXISTS invoice_deletions (
|
|
30
|
+
connection_id TEXT NOT NULL, invoice_id TEXT NOT NULL, revision INTEGER NOT NULL, PRIMARY KEY (connection_id, invoice_id)
|
|
31
|
+
)`)
|
|
32
|
+
}).immediate()
|
|
33
|
+
return db
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// A pinned page can arrive after the deletion webhook, even before this SaaS ever saw the invoice.
|
|
37
|
+
export function saveInvoiceBalance(db: BalanceDatabase, connectionId: string, row: SyncedInvoice) {
|
|
38
|
+
db.run(`INSERT INTO invoice_balances(connection_id, invoice_id, revision, currency, balance_due, details, status)
|
|
39
|
+
SELECT ?1, ?2, ?3, ?4, ?5, ?6, ?7 WHERE NOT EXISTS (
|
|
40
|
+
SELECT 1 FROM invoice_deletions WHERE connection_id=?1 AND invoice_id=?2 AND revision>=?3
|
|
41
|
+
) ON CONFLICT(connection_id, invoice_id) DO UPDATE SET
|
|
42
|
+
revision=excluded.revision, currency=excluded.currency, balance_due=excluded.balance_due,
|
|
43
|
+
details=CASE WHEN excluded.revision=invoice_balances.revision THEN coalesce(invoice_balances.details,excluded.details) ELSE excluded.details END,
|
|
44
|
+
status=CASE WHEN excluded.revision=invoice_balances.revision THEN coalesce(invoice_balances.status,excluded.status) ELSE excluded.status END
|
|
45
|
+
WHERE excluded.revision > invoice_balances.revision
|
|
46
|
+
OR (excluded.revision=invoice_balances.revision AND excluded.currency=invoice_balances.currency
|
|
47
|
+
AND excluded.balance_due=invoice_balances.balance_due
|
|
48
|
+
AND ((invoice_balances.details IS NULL AND excluded.details IS NOT NULL)
|
|
49
|
+
OR (invoice_balances.status IS NULL AND excluded.status IS NOT NULL)))`,
|
|
50
|
+
connectionId, row.invoiceId, row.revision, row.currency, row.balanceDue,
|
|
51
|
+
row.details === undefined ? null : JSON.stringify(row.details), row.status ?? null)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Call inside the inbox transaction so acknowledging a deletion also persists the revision fence.
|
|
55
|
+
export function deleteInvoiceBalance(db: BalanceDatabase, connectionId: string, invoiceId: string, revision: number) {
|
|
56
|
+
db.run(`INSERT INTO invoice_deletions(connection_id, invoice_id, revision) VALUES (?, ?, ?)
|
|
57
|
+
ON CONFLICT(connection_id, invoice_id) DO UPDATE SET revision=excluded.revision
|
|
58
|
+
WHERE excluded.revision>invoice_deletions.revision`, connectionId, invoiceId, revision)
|
|
59
|
+
db.run("DELETE FROM invoice_balances WHERE connection_id=? AND invoice_id=? AND revision<=?", connectionId, invoiceId, revision)
|
|
60
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import assert from "node:assert/strict"
|
|
2
|
+
import { Rowbind, type InvoiceRecord } from "@rowbind/sdk"
|
|
3
|
+
|
|
4
|
+
// Start with an untouched 120 USD Tienda Norte invoice from the sandbox quickstart.
|
|
5
|
+
// Repeat with the same source ID: bun invoice-settlement.mts "$INVOICE_OPERATION_ID" > settlement.json
|
|
6
|
+
function checkPosting(
|
|
7
|
+
record: { connectionId: string; customerId: string; currency: string; amount: string },
|
|
8
|
+
invoice: InvoiceRecord,
|
|
9
|
+
amount: string,
|
|
10
|
+
) {
|
|
11
|
+
assert.equal(record.connectionId, invoice.connectionId)
|
|
12
|
+
assert.equal(record.customerId, invoice.customerId)
|
|
13
|
+
assert.equal(record.currency, invoice.currency)
|
|
14
|
+
assert.equal(record.amount, amount)
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
async function settle(rowbind: Rowbind, invoiceOperationId: string) {
|
|
18
|
+
const invoice = await rowbind.operations.waitForVerifiedRecord(invoiceOperationId)
|
|
19
|
+
assert.equal(invoice.kind, "invoice", "Use the operation ID of the invoice from the sandbox quickstart.")
|
|
20
|
+
assert.equal(invoice.currency, "USD")
|
|
21
|
+
assert.equal(invoice.total, "120.00")
|
|
22
|
+
assert.equal(invoice.balanceDue, "120.00", "Expected the original receipt for an unpaid 120 USD invoice.")
|
|
23
|
+
|
|
24
|
+
// The same source operation reproduces all three keys, including after a partial run.
|
|
25
|
+
const prefix = `invoice-settlement/${invoiceOperationId}/`
|
|
26
|
+
const paymentKey = prefix + "payment"
|
|
27
|
+
const creditKey = prefix + "credit-memo"
|
|
28
|
+
const applicationKey = prefix + "apply-credit"
|
|
29
|
+
const book = { connectionId: invoice.connectionId, currency: "USD" as const }
|
|
30
|
+
const customerRef = { externalId: "tienda-norte" }
|
|
31
|
+
|
|
32
|
+
const payment = await rowbind.receivedPayments.create({
|
|
33
|
+
...book, customerRef, invoiceId: invoice.id, amount: "50.00", idempotencyKey: paymentKey,
|
|
34
|
+
})
|
|
35
|
+
const paid = await rowbind.operations.waitForVerifiedRecord(payment.id)
|
|
36
|
+
assert.equal(paid.kind, "received_payment")
|
|
37
|
+
checkPosting(paid, invoice, "50.00")
|
|
38
|
+
assert.equal(paid.invoiceId, invoice.id)
|
|
39
|
+
assert.equal(paid.balanceDue, "70.00")
|
|
40
|
+
|
|
41
|
+
const creditMemo = await rowbind.creditMemos.create({
|
|
42
|
+
...book, customerRef, amount: "20.00", idempotencyKey: creditKey,
|
|
43
|
+
})
|
|
44
|
+
const issued = await rowbind.operations.waitForVerifiedRecord(creditMemo.id)
|
|
45
|
+
assert.equal(issued.kind, "credit_memo")
|
|
46
|
+
checkPosting(issued, invoice, "20.00")
|
|
47
|
+
assert.equal(issued.remainingCredit, "20.00")
|
|
48
|
+
|
|
49
|
+
const application = await rowbind.creditMemos.apply(issued.id, {
|
|
50
|
+
...book, invoiceId: invoice.id, amount: "20.00", idempotencyKey: applicationKey,
|
|
51
|
+
})
|
|
52
|
+
const applied = await rowbind.operations.waitForVerifiedRecord(application.id)
|
|
53
|
+
assert.equal(applied.kind, "credit_application")
|
|
54
|
+
checkPosting(applied, invoice, "20.00")
|
|
55
|
+
assert.equal(applied.invoiceId, invoice.id)
|
|
56
|
+
assert.equal(applied.creditMemoId, issued.id)
|
|
57
|
+
assert.equal(applied.remainingCredit, "0.00")
|
|
58
|
+
assert.equal(applied.balanceDue, "50.00")
|
|
59
|
+
|
|
60
|
+
// Each record is the durable readback at that step. Issuing or applying credit moves no cash.
|
|
61
|
+
return {
|
|
62
|
+
invoice: { operationId: invoiceOperationId, record: invoice },
|
|
63
|
+
payment: { idempotencyKey: paymentKey, operationId: payment.id, record: paid },
|
|
64
|
+
creditMemo: { idempotencyKey: creditKey, operationId: creditMemo.id, record: issued },
|
|
65
|
+
creditApplication: { idempotencyKey: applicationKey, operationId: application.id, record: applied },
|
|
66
|
+
cashReceived: paid.amount, balanceDueAfterApplication: applied.balanceDue,
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function main() {
|
|
71
|
+
const [invoiceOperationId, ...extra] = process.argv.slice(2)
|
|
72
|
+
if (!invoiceOperationId || extra.length) throw new Error("Usage: bun invoice-settlement.mts <invoiceOperationId>")
|
|
73
|
+
const rowbind = new Rowbind()
|
|
74
|
+
try {
|
|
75
|
+
return await settle(rowbind, invoiceOperationId)
|
|
76
|
+
} finally {
|
|
77
|
+
rowbind.close()
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
console.log(JSON.stringify(await main(), null, 2))
|
|
83
|
+
} catch (error) {
|
|
84
|
+
console.error(error instanceof Error ? error.message : "Could not settle the sandbox invoice.")
|
|
85
|
+
process.exitCode = 1
|
|
86
|
+
}
|