@processfocus/plugin-xero 0.1.0-next.2 → 0.1.0-next.4
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 +49 -185
- package/dist/index.d.ts +5 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/lib/contact-resolution.d.ts +2 -6
- package/dist/lib/contact-resolution.js +17 -5
- package/dist/lib/contact-resolution.js.map +1 -1
- package/dist/lib/errors.d.ts +4 -0
- package/dist/lib/errors.js.map +1 -1
- package/dist/lib/identities.d.ts +63 -39
- package/dist/lib/identities.js +36 -13
- package/dist/lib/identities.js.map +1 -1
- package/dist/lib/invoice-reconciliation.d.ts +2 -4
- package/dist/lib/invoice-reconciliation.js +23 -13
- package/dist/lib/invoice-reconciliation.js.map +1 -1
- package/dist/lib/money.d.ts +4 -4
- package/dist/lib/money.js +1 -9
- package/dist/lib/money.js.map +1 -1
- package/dist/lib/xero-configuration.d.ts +24 -0
- package/dist/lib/xero-configuration.js +15 -0
- package/dist/lib/xero-configuration.js.map +1 -0
- package/dist/lib/xero-draft-invoice.d.ts +39 -39
- package/dist/lib/xero-draft-invoice.js +25 -22
- package/dist/lib/xero-draft-invoice.js.map +1 -1
- package/dist/lib/xero-http.d.ts +1 -1
- package/dist/lib/xero-http.js.map +1 -1
- package/dist/lib/xero-invoice-cancellation-step.d.ts +16 -0
- package/dist/lib/xero-invoice-cancellation-step.js +17 -0
- package/dist/lib/xero-invoice-cancellation-step.js.map +1 -0
- package/dist/lib/xero-invoice-cancellation.d.ts +19 -0
- package/dist/lib/xero-invoice-cancellation.js +15 -0
- package/dist/lib/xero-invoice-cancellation.js.map +1 -0
- package/dist/lib/xero-invoice-live.d.ts +11 -7
- package/dist/lib/xero-invoice-live.js +468 -210
- package/dist/lib/xero-invoice-live.js.map +1 -1
- package/dist/lib/xero-invoice-lookup.d.ts +13 -13
- package/dist/lib/xero-invoice-lookup.js +1 -1
- package/dist/lib/xero-invoice-lookup.js.map +1 -1
- package/dist/lib/xero-invoice-preparation.d.ts +52 -0
- package/dist/lib/xero-invoice-preparation.js +47 -0
- package/dist/lib/xero-invoice-preparation.js.map +1 -0
- package/dist/lib/xero-invoice-step.d.ts +10 -3
- package/dist/lib/xero-invoice-step.js +4 -1
- package/dist/lib/xero-invoice-step.js.map +1 -1
- package/dist/lib/xero-invoice-test.d.ts +11 -5
- package/dist/lib/xero-invoice-test.js +109 -56
- package/dist/lib/xero-invoice-test.js.map +1 -1
- package/dist/lib/xero-invoice.d.ts +1 -1
- package/dist/lib/xero-invoice.js +2 -2
- package/dist/lib/xero-invoice.js.map +1 -1
- package/dist/lib/xero-repeated-draft-invoice.d.ts +43 -0
- package/dist/lib/xero-repeated-draft-invoice.js +32 -0
- package/dist/lib/xero-repeated-draft-invoice.js.map +1 -0
- package/dist/lib/xero-token.js +2 -2
- package/dist/lib/xero-token.js.map +1 -1
- package/dist/lib/xero-wire.d.ts +96 -62
- package/dist/lib/xero-wire.js +22 -1
- package/dist/lib/xero-wire.js.map +1 -1
- package/dist/runtime.d.ts +2 -1
- package/dist/runtime.js +2 -1
- package/dist/runtime.js.map +1 -1
- package/package.json +3 -4
|
@@ -1,24 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { readConfiguration } from "@processfocus/runtime";
|
|
3
|
+
import { BigDecimal, Clock, Context, Effect, Layer, Option, Redacted, Schema, SchemaGetter, Semaphore, } from "effect";
|
|
4
|
+
import { Headers, HttpClient, HttpClientRequest } from "effect/http";
|
|
3
5
|
import { CurrentStepJobContext } from "processfocus";
|
|
4
6
|
import { isContactNameConflict, resolveInvoiceContact, } from "./contact-resolution.js";
|
|
5
7
|
import { XeroInvoiceError, xeroAuthError, xeroDeploymentError, xeroIdempotencyConflictError, xeroMalformedResponseError, xeroPermissionError, xeroProviderServerError, xeroRateLimitError, xeroTimeoutError, xeroUnknownItemCodeError, xeroUnsupportedOperationError, xeroValidationError, } from "./errors.js";
|
|
6
8
|
import { isXeroIdempotencyConflictMessage, xeroDraftIdempotencyKey, xeroIdempotencyKey, } from "./idempotency.js";
|
|
7
9
|
import { XeroContactId, XeroInvoiceId, XeroInvoiceNumber, normalizeEmail, } from "./identities.js";
|
|
8
10
|
import { decodeIssuedSalesInvoice, reconcileExistingInvoices, wireAmountToMoney, } from "./invoice-reconciliation.js";
|
|
11
|
+
import { XeroConfiguration } from "./xero-configuration.js";
|
|
9
12
|
import { DraftSalesInvoice, XeroDraftInvoice, matchesInvoiceReference, } from "./xero-draft-invoice.js";
|
|
10
13
|
import { mapHttpClientError, parseRetryAfterSeconds, waitForRetryAfter, } from "./xero-http.js";
|
|
11
14
|
import { XeroInvoice } from "./xero-invoice.js";
|
|
15
|
+
import { XeroInvoiceCancellation, decodeCancelSalesInvoiceInput, } from "./xero-invoice-cancellation.js";
|
|
12
16
|
import { XeroInvoiceLookup } from "./xero-invoice-lookup.js";
|
|
17
|
+
import { XeroInvoicePreparation, } from "./xero-invoice-preparation.js";
|
|
18
|
+
import { CreatedRepeatedDraft, RepeatedDraftSalesInvoice, XeroRepeatedDraftInvoice, } from "./xero-repeated-draft-invoice.js";
|
|
13
19
|
import { makeXeroAccessCache, refreshAfterMsFromExpiresIn, } from "./xero-token.js";
|
|
14
|
-
import { XeroConnectionsResponse, XeroContactsResponse, XeroErrorResponse, XeroInvoicesResponse, XeroTokenErrorResponse, XeroTokenResponse, } from "./xero-wire.js";
|
|
20
|
+
import { XeroConnectionsResponse, XeroContactDetailsResponse, XeroContactsResponse, XeroErrorResponse, XeroInvoicesResponse, XeroTokenErrorResponse, XeroTokenResponse, } from "./xero-wire.js";
|
|
15
21
|
export { XERO_TOKEN_REFRESH_BUFFER_MS } from "./xero-token.js";
|
|
16
22
|
const TOKEN_URL = "https://identity.xero.com/connect/token";
|
|
17
23
|
const CONNECTIONS_URL = "https://api.xero.com/connections";
|
|
18
24
|
const ACCOUNTING_URL = "https://api.xero.com/api.xro/2.0";
|
|
19
|
-
|
|
20
|
-
export
|
|
21
|
-
export class XeroInvoiceConfig extends Context.Tag("@processfocus/plugin-xero/XeroInvoiceConfig")() {
|
|
25
|
+
export { XERO_DEFAULT_SCOPES } from "./xero-configuration.js";
|
|
26
|
+
export class XeroInvoiceConfig extends Context.Service()("@processfocus/plugin-xero/XeroInvoiceConfig") {
|
|
22
27
|
}
|
|
23
28
|
const requireXeroInvoiceConfig = (config) => {
|
|
24
29
|
if (config.clientId.trim() === "" ||
|
|
@@ -28,18 +33,10 @@ const requireXeroInvoiceConfig = (config) => {
|
|
|
28
33
|
}
|
|
29
34
|
return Effect.succeed(config);
|
|
30
35
|
};
|
|
31
|
-
export const XeroInvoiceConfigFromEnv = Layer.effect(XeroInvoiceConfig, Effect.
|
|
32
|
-
|
|
33
|
-
clientId: (yield* Config.string("XERO_CLIENT_ID")).trim(),
|
|
34
|
-
clientSecret: yield* Config.redacted("XERO_CLIENT_SECRET"),
|
|
35
|
-
scopes: (yield* Config.withDefault(Config.string("XERO_SCOPES"), DEFAULT_SCOPES)).trim(),
|
|
36
|
-
});
|
|
37
|
-
}).pipe(Effect.mapError((error) => error instanceof XeroInvoiceError
|
|
38
|
-
? error
|
|
39
|
-
: xeroDeploymentError("Xero Custom Connection configuration is missing or malformed"))));
|
|
40
|
-
const decodeJson = (schema, bodyText, message) => Schema.decodeUnknown(Schema.parseJson(schema))(bodyText).pipe(Effect.mapError(() => xeroMalformedResponseError(message)));
|
|
36
|
+
export const XeroInvoiceConfigFromEnv = Layer.effect(XeroInvoiceConfig, readConfiguration(XeroConfiguration).pipe(Effect.mapError(() => xeroDeploymentError("Xero Custom Connection configuration is missing or malformed"))));
|
|
37
|
+
const decodeJson = (schema, bodyText, message) => Schema.decodeUnknownEffect(Schema.fromJsonString(schema))(bodyText).pipe(Effect.mapError(() => xeroMalformedResponseError(message)));
|
|
41
38
|
const validationMessages = (bodyText) => {
|
|
42
|
-
const decoded = Schema.decodeUnknownOption(Schema.
|
|
39
|
+
const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(XeroErrorResponse))(bodyText);
|
|
43
40
|
return Option.match(decoded, {
|
|
44
41
|
onNone: () => [],
|
|
45
42
|
onSome: (value) => [
|
|
@@ -116,7 +113,7 @@ const tokenFailure = (status, bodyText) => {
|
|
|
116
113
|
if (status >= 500) {
|
|
117
114
|
return xeroProviderServerError(status);
|
|
118
115
|
}
|
|
119
|
-
const decoded = Schema.decodeUnknownOption(Schema.
|
|
116
|
+
const decoded = Schema.decodeUnknownOption(Schema.fromJsonString(XeroTokenErrorResponse))(bodyText);
|
|
120
117
|
const description = Option.match(decoded, {
|
|
121
118
|
onNone: () => undefined,
|
|
122
119
|
onSome: (value) => value.error_description,
|
|
@@ -141,18 +138,28 @@ const failRateLimited = (retryAfter) => Effect.gen(function* () {
|
|
|
141
138
|
yield* waitForRetryAfter(retryAfterSeconds);
|
|
142
139
|
return yield* xeroRateLimitError(retryAfterSeconds);
|
|
143
140
|
});
|
|
144
|
-
const interpretXeroResult = (result, productSku) => {
|
|
141
|
+
const interpretXeroResult = (result, productSku, invoiceWrite = false) => {
|
|
145
142
|
if (result.status === 429) {
|
|
146
143
|
return failRateLimited(result.retryAfter);
|
|
147
144
|
}
|
|
148
145
|
if (result.status < 200 || result.status >= 300) {
|
|
149
|
-
|
|
146
|
+
const error = providerFailure(result.status, result.bodyText, productSku);
|
|
147
|
+
return Effect.fail(invoiceWrite &&
|
|
148
|
+
result.status === 400 &&
|
|
149
|
+
validationMessages(result.bodyText).length > 0 &&
|
|
150
|
+
(error.code === "validation" || error.code === "unknown_item_code")
|
|
151
|
+
? new XeroInvoiceError({
|
|
152
|
+
...error,
|
|
153
|
+
message: error.message,
|
|
154
|
+
externalWriteRejected: true,
|
|
155
|
+
})
|
|
156
|
+
: error);
|
|
150
157
|
}
|
|
151
158
|
return Effect.succeed(result);
|
|
152
159
|
};
|
|
153
160
|
const accountingRequest = (method, path, accessToken, tenantId, idempotencyKey) => {
|
|
154
161
|
const url = `${ACCOUNTING_URL}${path}`;
|
|
155
|
-
const base =
|
|
162
|
+
const base = HttpClientRequest.make(method)(url);
|
|
156
163
|
const headers = base.pipe(HttpClientRequest.bearerToken(accessToken), HttpClientRequest.setHeader("Xero-tenant-id", tenantId), HttpClientRequest.setHeader("Accept", "application/json"));
|
|
157
164
|
if (idempotencyKey === undefined) {
|
|
158
165
|
return headers;
|
|
@@ -170,13 +177,23 @@ const xeroStreetAddress = (shipping) => ({
|
|
|
170
177
|
}),
|
|
171
178
|
...(shipping.country !== undefined && { Country: shipping.country }),
|
|
172
179
|
});
|
|
173
|
-
export const xeroContactWritePayload = (input, name, contactId) => ({
|
|
180
|
+
export const xeroContactWritePayload = (input, name, contactId, defaultBilling) => ({
|
|
174
181
|
Contacts: [
|
|
175
182
|
{
|
|
176
183
|
...(contactId !== undefined && { ContactID: contactId }),
|
|
177
184
|
Name: name,
|
|
178
185
|
EmailAddress: input.customer.email,
|
|
179
|
-
Addresses: [
|
|
186
|
+
Addresses: [
|
|
187
|
+
xeroStreetAddress(input.shippingAddress),
|
|
188
|
+
...(defaultBilling
|
|
189
|
+
? [
|
|
190
|
+
{
|
|
191
|
+
...xeroStreetAddress(input.shippingAddress),
|
|
192
|
+
AddressType: "POBOX",
|
|
193
|
+
},
|
|
194
|
+
]
|
|
195
|
+
: []),
|
|
196
|
+
],
|
|
180
197
|
},
|
|
181
198
|
],
|
|
182
199
|
});
|
|
@@ -191,14 +208,12 @@ export const xeroInvoiceWritePayload = (contactId, input) => ({
|
|
|
191
208
|
LineAmountTypes: "Inclusive",
|
|
192
209
|
CurrencyCode: input.currency,
|
|
193
210
|
Reference: input.reference,
|
|
194
|
-
LineItems:
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
},
|
|
201
|
-
],
|
|
211
|
+
LineItems: input.lines.map((line) => ({
|
|
212
|
+
ItemCode: line.productSku,
|
|
213
|
+
// Let Xero snapshot the Item's sales description onto the invoice.
|
|
214
|
+
Quantity: line.quantity,
|
|
215
|
+
UnitAmount: line.unitAmount,
|
|
216
|
+
})),
|
|
202
217
|
},
|
|
203
218
|
],
|
|
204
219
|
});
|
|
@@ -249,16 +264,16 @@ const fetchXeroAccess = (httpClient, config) => Effect.gen(function* () {
|
|
|
249
264
|
refreshAfterMs: refreshAfterMsFromExpiresIn(nowMs, token.expiresIn),
|
|
250
265
|
};
|
|
251
266
|
});
|
|
252
|
-
const sendAccounting = (httpClient, access, build, productSku) => Effect.gen(function* () {
|
|
267
|
+
const sendAccounting = (httpClient, access, build, productSku, invoiceWrite = false) => Effect.gen(function* () {
|
|
253
268
|
const firstAccess = yield* access.get();
|
|
254
269
|
const first = yield* execute(httpClient, build(firstAccess));
|
|
255
270
|
if (first.status !== 401) {
|
|
256
|
-
return yield* interpretXeroResult(first, productSku);
|
|
271
|
+
return yield* interpretXeroResult(first, productSku, invoiceWrite);
|
|
257
272
|
}
|
|
258
273
|
yield* access.invalidate();
|
|
259
274
|
const secondAccess = yield* access.get();
|
|
260
275
|
const second = yield* execute(httpClient, build(secondAccess));
|
|
261
|
-
return yield* interpretXeroResult(second, productSku);
|
|
276
|
+
return yield* interpretXeroResult(second, productSku, invoiceWrite);
|
|
262
277
|
});
|
|
263
278
|
const findContacts = (httpClient, access, where, matches) => Effect.gen(function* () {
|
|
264
279
|
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `/Contacts?where=${encodeURIComponent(where)}`, current.accessToken, current.tenantId), "");
|
|
@@ -272,8 +287,27 @@ const findContacts = (httpClient, access, where, matches) => Effect.gen(function
|
|
|
272
287
|
}));
|
|
273
288
|
});
|
|
274
289
|
const writeContact = (httpClient, access, input, name, contactId, idempotencyKey) => Effect.gen(function* () {
|
|
275
|
-
|
|
276
|
-
|
|
290
|
+
let defaultBilling = true;
|
|
291
|
+
if (contactId !== undefined) {
|
|
292
|
+
const detail = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `/Contacts/${contactId}`, current.accessToken, current.tenantId), "");
|
|
293
|
+
if (detail.status !== 200 || detail.partial) {
|
|
294
|
+
return yield* xeroMalformedResponseError("Incomplete Xero contact address response");
|
|
295
|
+
}
|
|
296
|
+
const decoded = yield* decodeJson(XeroContactDetailsResponse, detail.bodyText, "Malformed Xero contact address response");
|
|
297
|
+
const contact = decoded.Contacts[0];
|
|
298
|
+
if (decoded.Contacts.length !== 1 || contact?.ContactID !== contactId) {
|
|
299
|
+
return yield* xeroMalformedResponseError("Unexpected Xero contact in address response");
|
|
300
|
+
}
|
|
301
|
+
defaultBilling = !contact.Addresses.some(({ AddressType, ...content }) => AddressType === "POBOX" &&
|
|
302
|
+
Object.values(content).some((value) => (value?.trim().length ?? 0) > 0));
|
|
303
|
+
}
|
|
304
|
+
const payload = xeroContactWritePayload(input, name, contactId, defaultBilling);
|
|
305
|
+
// Once read-back confirms billing was filled, retries omit it. Keep that
|
|
306
|
+
// STREET-only update distinct from the original fallback payload.
|
|
307
|
+
const writeKey = contactId !== undefined && defaultBilling
|
|
308
|
+
? `${idempotencyKey}:billing-default`
|
|
309
|
+
: idempotencyKey;
|
|
310
|
+
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("POST", "/Contacts", current.accessToken, current.tenantId, writeKey).pipe(HttpClientRequest.bodyJsonUnsafe(payload)), input.lines.map((line) => line.productSku).join(", "));
|
|
277
311
|
const decoded = yield* decodeJson(XeroContactsResponse, result.bodyText, "Malformed Xero contact response");
|
|
278
312
|
const written = decoded.Contacts[0];
|
|
279
313
|
if (decoded.Contacts.length !== 1 || written === undefined) {
|
|
@@ -294,7 +328,6 @@ const writeContact = (httpClient, access, input, name, contactId, idempotencyKey
|
|
|
294
328
|
};
|
|
295
329
|
});
|
|
296
330
|
const toReconcilableInvoice = (invoice) => {
|
|
297
|
-
const line = invoice.LineItems?.[0];
|
|
298
331
|
return {
|
|
299
332
|
invoiceId: invoice.InvoiceID,
|
|
300
333
|
invoiceNumber: invoice.InvoiceNumber,
|
|
@@ -304,10 +337,13 @@ const toReconcilableInvoice = (invoice) => {
|
|
|
304
337
|
date: invoice.Date ?? "",
|
|
305
338
|
dueDate: invoice.DueDate ?? "",
|
|
306
339
|
contactId: invoice.Contact?.ContactID ?? "",
|
|
307
|
-
|
|
308
|
-
|
|
340
|
+
lines: (invoice.LineItems ?? []).map((line) => ({
|
|
341
|
+
itemCode: line.ItemCode ?? "",
|
|
342
|
+
description: line.Description ?? "",
|
|
343
|
+
quantity: Number(line.Quantity),
|
|
344
|
+
unitAmount: wireAmountToMoney(line.UnitAmount) ?? "",
|
|
345
|
+
})),
|
|
309
346
|
total: wireAmountToMoney(invoice.Total) ?? "",
|
|
310
|
-
lineCount: invoice.LineItems?.length ?? 0,
|
|
311
347
|
};
|
|
312
348
|
};
|
|
313
349
|
const findInvoicesByReference = (httpClient, access, reference) => Effect.gen(function* () {
|
|
@@ -317,7 +353,7 @@ const findInvoicesByReference = (httpClient, access, reference) => Effect.gen(fu
|
|
|
317
353
|
});
|
|
318
354
|
const createInvoice = (httpClient, access, contactId, input, idempotencyKey) => Effect.gen(function* () {
|
|
319
355
|
const payload = xeroInvoiceWritePayload(contactId, input);
|
|
320
|
-
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("POST", "/Invoices", current.accessToken, current.tenantId, idempotencyKey).pipe(HttpClientRequest.appendUrlParam("SummarizeErrors", "true"), HttpClientRequest.
|
|
356
|
+
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("POST", "/Invoices", current.accessToken, current.tenantId, idempotencyKey).pipe(HttpClientRequest.appendUrlParam("SummarizeErrors", "true"), HttpClientRequest.bodyJsonUnsafe(payload)), input.lines.map((line) => line.productSku).join(", "), true);
|
|
321
357
|
const decoded = yield* decodeJson(XeroInvoicesResponse, result.bodyText, "Malformed Xero invoice response");
|
|
322
358
|
const invoice = decoded.Invoices[0];
|
|
323
359
|
if (decoded.Invoices.length !== 1 || invoice === undefined) {
|
|
@@ -326,14 +362,14 @@ const createInvoice = (httpClient, access, contactId, input, idempotencyKey) =>
|
|
|
326
362
|
if (invoice.Status !== "AUTHORISED") {
|
|
327
363
|
return yield* xeroMalformedResponseError("Xero invoice was not created in AUTHORISED state");
|
|
328
364
|
}
|
|
329
|
-
const issued = yield* decodeIssuedSalesInvoice(invoice.InvoiceID, invoice.InvoiceNumber);
|
|
365
|
+
const issued = yield* decodeIssuedSalesInvoice(invoice.InvoiceID, invoice.InvoiceNumber, toReconcilableInvoice(invoice).lines);
|
|
330
366
|
yield* Effect.log("Issued Xero Sales Invoice").pipe(Effect.annotateLogs({
|
|
331
367
|
reference: input.reference,
|
|
332
368
|
invoiceId: issued.invoiceId,
|
|
333
369
|
invoiceNumber: issued.invoiceNumber,
|
|
334
370
|
customerName: input.customer.name,
|
|
335
371
|
customerEmail: input.customer.email,
|
|
336
|
-
|
|
372
|
+
productSkus: input.lines.map((line) => line.productSku),
|
|
337
373
|
contactId,
|
|
338
374
|
}));
|
|
339
375
|
return issued;
|
|
@@ -345,42 +381,135 @@ const logInvoiceFailure = (input, error) => Effect.logWarning("Xero Sales Invoic
|
|
|
345
381
|
code: error.code ?? "unknown",
|
|
346
382
|
retryable: error.retryable,
|
|
347
383
|
}));
|
|
384
|
+
const ensureInvoiceNote = (httpClient, access, invoiceId, note) => Effect.gen(function* () {
|
|
385
|
+
const path = `/Invoices/${invoiceId}/History`;
|
|
386
|
+
const history = Schema.Struct({
|
|
387
|
+
HistoryRecords: Schema.Array(Schema.Struct({
|
|
388
|
+
Details: Schema.String,
|
|
389
|
+
ValidationErrors: Schema.optional(Schema.Array(Schema.Struct({ Message: Schema.String }))),
|
|
390
|
+
})),
|
|
391
|
+
});
|
|
392
|
+
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", path, current.accessToken, current.tenantId), "");
|
|
393
|
+
const existing = yield* decodeJson(history, result.bodyText, "Malformed Xero invoice history response");
|
|
394
|
+
if (existing.HistoryRecords.some((record) => record.Details === note))
|
|
395
|
+
return;
|
|
396
|
+
const written = yield* sendAccounting(httpClient, access, (current) => accountingRequest("PUT", path, current.accessToken, current.tenantId, `pf-invoice-note:${createHash("sha256")
|
|
397
|
+
.update(JSON.stringify([current.tenantId, invoiceId, note]))
|
|
398
|
+
.digest("hex")}`).pipe(HttpClientRequest.bodyJsonUnsafe({
|
|
399
|
+
HistoryRecords: [{ Details: note }],
|
|
400
|
+
})), "");
|
|
401
|
+
const decoded = yield* decodeJson(history, written.bodyText, "Malformed Xero invoice history response");
|
|
402
|
+
const validationErrors = decoded.HistoryRecords.flatMap((record) => record.ValidationErrors ?? []);
|
|
403
|
+
if (validationErrors.length > 0) {
|
|
404
|
+
return yield* xeroValidationError(validationErrors.map((error) => error.Message).join("; "));
|
|
405
|
+
}
|
|
406
|
+
if (!decoded.HistoryRecords.some((record) => record.Details === note)) {
|
|
407
|
+
return yield* xeroMalformedResponseError("Xero did not confirm the invoice history note");
|
|
408
|
+
}
|
|
409
|
+
});
|
|
348
410
|
export const XeroInvoiceLive = Layer.effect(XeroInvoice, Effect.gen(function* () {
|
|
349
411
|
const httpClient = yield* HttpClient.HttpClient;
|
|
350
412
|
const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
|
|
351
413
|
const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
|
|
352
414
|
const issueAuthorisedSalesInvoice = Effect.fn("XeroInvoice.issueAuthorisedSalesInvoice")(function* (input) {
|
|
353
415
|
return yield* Effect.gen(function* () {
|
|
354
|
-
const { todoId } = yield* CurrentStepJobContext;
|
|
416
|
+
const { todoId, externalWriteAttemptId } = yield* CurrentStepJobContext;
|
|
355
417
|
const contactId = yield* resolveInvoiceContact({
|
|
356
418
|
findByName: (name) => findContacts(httpClient, access, xeroWhereEquals("Name", name), (contact) => contact.Name === name),
|
|
357
419
|
findByEmail: (email) => findContacts(httpClient, access, xeroWhereEquals("EmailAddress", normalizeEmail(email)), (contact) => contact.EmailAddress !== undefined &&
|
|
358
420
|
normalizeEmail(contact.EmailAddress) ===
|
|
359
421
|
normalizeEmail(email)),
|
|
360
422
|
create: (invoiceInput, name, idempotencyKey) => writeContact(httpClient, access, invoiceInput, name, undefined, idempotencyKey),
|
|
361
|
-
update: (contact, invoiceInput, idempotencyKey) => writeContact(httpClient, access, invoiceInput,
|
|
423
|
+
update: (contact, invoiceInput, idempotencyKey, name) => writeContact(httpClient, access, invoiceInput, name, contact.contactId, idempotencyKey),
|
|
362
424
|
}, input, todoId);
|
|
363
|
-
const
|
|
425
|
+
const references = [
|
|
426
|
+
...new Set([
|
|
427
|
+
input.reference,
|
|
428
|
+
...(input.legacyReference ? [input.legacyReference] : []),
|
|
429
|
+
]),
|
|
430
|
+
];
|
|
431
|
+
const existing = (yield* Effect.forEach(references, (reference) => findInvoicesByReference(httpClient, access, reference))).flat();
|
|
364
432
|
const reconciled = yield* reconcileExistingInvoices(existing, input, contactId);
|
|
365
|
-
if (reconciled
|
|
366
|
-
return
|
|
433
|
+
if (reconciled === undefined && input.recoveryOnly) {
|
|
434
|
+
return yield* xeroValidationError("No existing invoice found; a customer-facing reference is required before creation");
|
|
367
435
|
}
|
|
368
|
-
|
|
436
|
+
const issued = reconciled ??
|
|
437
|
+
(yield* createInvoice(httpClient, access, contactId, input, xeroIdempotencyKey(externalWriteAttemptId ?? todoId, "invoice.create")));
|
|
438
|
+
if (input.internalNote !== undefined) {
|
|
439
|
+
yield* ensureInvoiceNote(httpClient, access, issued.invoiceId, input.internalNote);
|
|
440
|
+
}
|
|
441
|
+
return issued;
|
|
369
442
|
}).pipe(Effect.tapError((error) => logInvoiceFailure(input, error)));
|
|
370
443
|
});
|
|
371
444
|
return { issueAuthorisedSalesInvoice };
|
|
372
445
|
}));
|
|
446
|
+
const CancellationInvoiceWire = Schema.Struct({
|
|
447
|
+
InvoiceID: XeroInvoiceId,
|
|
448
|
+
InvoiceNumber: XeroInvoiceNumber,
|
|
449
|
+
Type: Schema.Literal("ACCREC"),
|
|
450
|
+
Status: Schema.String,
|
|
451
|
+
HasErrors: Schema.optional(Schema.Boolean),
|
|
452
|
+
ValidationErrors: Schema.optional(Schema.Array(Schema.Struct({ Message: Schema.String }))),
|
|
453
|
+
});
|
|
454
|
+
export const XeroInvoiceCancellationLive = Layer.effect(XeroInvoiceCancellation, Effect.gen(function* () {
|
|
455
|
+
const httpClient = yield* HttpClient.HttpClient;
|
|
456
|
+
const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
|
|
457
|
+
const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
|
|
458
|
+
const cancel = (input) => Effect.gen(function* () {
|
|
459
|
+
const { invoiceId } = yield* decodeCancelSalesInvoiceInput(input);
|
|
460
|
+
const path = `/Invoices/${invoiceId}`;
|
|
461
|
+
const readResponse = (response) => Effect.gen(function* () {
|
|
462
|
+
if (response.status !== 200 || response.partial)
|
|
463
|
+
return yield* xeroMalformedResponseError("Incomplete Xero cancellation response");
|
|
464
|
+
const decoded = yield* decodeJson(Schema.Struct({
|
|
465
|
+
Invoices: Schema.Array(CancellationInvoiceWire),
|
|
466
|
+
}), response.bodyText, "Malformed Xero cancellation response");
|
|
467
|
+
const invoice = decoded.Invoices[0];
|
|
468
|
+
if (decoded.Invoices.length !== 1 ||
|
|
469
|
+
!invoice ||
|
|
470
|
+
invoice.InvoiceID !== invoiceId)
|
|
471
|
+
return yield* xeroMalformedResponseError("Xero cancellation returned an unexpected invoice");
|
|
472
|
+
if (invoice.HasErrors ||
|
|
473
|
+
(invoice.ValidationErrors?.length ?? 0) > 0)
|
|
474
|
+
return yield* xeroValidationError("Xero rejected invoice cancellation");
|
|
475
|
+
return invoice;
|
|
476
|
+
});
|
|
477
|
+
const existing = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", path, current.accessToken, current.tenantId), "").pipe(Effect.flatMap(readResponse));
|
|
478
|
+
// Reconcile provider state even after the idempotency window expires.
|
|
479
|
+
if (existing.Status !== "VOIDED" && existing.Status !== "AUTHORISED")
|
|
480
|
+
return yield* xeroValidationError("Only an authorised Sales Invoice can be cancelled");
|
|
481
|
+
const cancelled = existing.Status === "VOIDED"
|
|
482
|
+
? existing
|
|
483
|
+
: yield* sendAccounting(httpClient, access, (current) => accountingRequest("POST", path, current.accessToken, current.tenantId, `pf-invoice-void:${createHash("sha256")
|
|
484
|
+
.update(JSON.stringify([current.tenantId, invoiceId]))
|
|
485
|
+
.digest("hex")}`).pipe(HttpClientRequest.bodyJsonUnsafe({
|
|
486
|
+
Invoices: [{ InvoiceID: invoiceId, Status: "VOIDED" }],
|
|
487
|
+
})), "").pipe(Effect.flatMap(readResponse));
|
|
488
|
+
if (cancelled.Status !== "VOIDED" ||
|
|
489
|
+
cancelled.InvoiceNumber !== existing.InvoiceNumber)
|
|
490
|
+
return yield* xeroMalformedResponseError("Xero did not confirm cancellation of the original invoice");
|
|
491
|
+
return {
|
|
492
|
+
invoiceId: cancelled.InvoiceID,
|
|
493
|
+
invoiceNumber: cancelled.InvoiceNumber,
|
|
494
|
+
status: "VOIDED",
|
|
495
|
+
};
|
|
496
|
+
});
|
|
497
|
+
return { cancel };
|
|
498
|
+
}));
|
|
499
|
+
// Xero represents absent optional properties as either missing or null.
|
|
500
|
+
const optionalNullable = (schema) => Schema.optional(Schema.NullOr(schema)).pipe(Schema.decodeTo(Schema.optional(Schema.toType(schema)), {
|
|
501
|
+
decode: SchemaGetter.transformOptional(Option.filter((value) => value !== null)),
|
|
502
|
+
encode: SchemaGetter.passthrough(),
|
|
503
|
+
}));
|
|
373
504
|
const DirectoryContact = Schema.Struct({
|
|
374
505
|
ContactID: XeroContactId,
|
|
375
506
|
Name: Schema.String,
|
|
376
|
-
ContactStatus: Schema.
|
|
377
|
-
EmailAddress:
|
|
378
|
-
ContactPersons:
|
|
379
|
-
EmailAddress:
|
|
380
|
-
IncludeInEmails:
|
|
381
|
-
|
|
382
|
-
}),
|
|
383
|
-
})), { nullable: true }),
|
|
507
|
+
ContactStatus: Schema.Literals(["ACTIVE", "ARCHIVED", "GDPRREQUEST"]),
|
|
508
|
+
EmailAddress: optionalNullable(Schema.String),
|
|
509
|
+
ContactPersons: optionalNullable(Schema.Array(Schema.Struct({
|
|
510
|
+
EmailAddress: optionalNullable(Schema.String),
|
|
511
|
+
IncludeInEmails: optionalNullable(Schema.Boolean),
|
|
512
|
+
}))),
|
|
384
513
|
});
|
|
385
514
|
const DirectoryInvoice = Schema.Struct({
|
|
386
515
|
InvoiceID: XeroInvoiceId,
|
|
@@ -398,8 +527,19 @@ const enabledInvoiceEmails = (contact) => [
|
|
|
398
527
|
.map((person) => person.EmailAddress),
|
|
399
528
|
].flatMap((email) => email ? email.split(/[;,]/).map(normalizeEmail).filter(Boolean) : [])),
|
|
400
529
|
];
|
|
401
|
-
|
|
402
|
-
|
|
530
|
+
const invoiceContact = (contact) => ({
|
|
531
|
+
contactId: contact.ContactID,
|
|
532
|
+
name: contact.Name,
|
|
533
|
+
active: contact.ContactStatus === "ACTIVE",
|
|
534
|
+
emails: [
|
|
535
|
+
...new Set([
|
|
536
|
+
contact.EmailAddress,
|
|
537
|
+
...(contact.ContactPersons ?? []).map((person) => person.EmailAddress),
|
|
538
|
+
].flatMap((email) => email ? email.split(/[;,]/).map(normalizeEmail).filter(Boolean) : [])),
|
|
539
|
+
],
|
|
540
|
+
invoiceRecipientEmails: enabledInvoiceEmails(contact),
|
|
541
|
+
});
|
|
542
|
+
const makeDirectoryReader = Effect.gen(function* () {
|
|
403
543
|
const httpClient = yield* HttpClient.HttpClient;
|
|
404
544
|
const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
|
|
405
545
|
const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
|
|
@@ -424,27 +564,19 @@ export const XeroInvoiceLookupLive = Layer.effect(XeroInvoiceLookup, Effect.gen(
|
|
|
424
564
|
}
|
|
425
565
|
return yield* xeroMalformedResponseError("Xero directory pagination limit exceeded");
|
|
426
566
|
});
|
|
567
|
+
return { readPages, httpClient, access };
|
|
568
|
+
});
|
|
569
|
+
/** Read-only companion: shares authentication/error handling, never writes. */
|
|
570
|
+
export const XeroInvoiceLookupLive = Layer.effect(XeroInvoiceLookup, Effect.gen(function* () {
|
|
571
|
+
const { readPages } = yield* makeDirectoryReader;
|
|
427
572
|
const readDirectory = (reference, previousReference) => Effect.gen(function* () {
|
|
428
|
-
const text = yield* Schema.
|
|
429
|
-
const references = yield* Schema.
|
|
573
|
+
const text = yield* Schema.decodeUnknownEffect(Schema.Trim.pipe(Schema.check(Schema.isMinLength(1))))(reference).pipe(Effect.mapError(() => xeroValidationError("An invoice reference is required")));
|
|
574
|
+
const references = yield* Schema.decodeUnknownEffect(Schema.Array(Schema.Trim.pipe(Schema.check(Schema.isMinLength(1)))))(previousReference === undefined ? [text] : [text, previousReference]).pipe(Effect.mapError(() => xeroValidationError("Valid invoice references are required")));
|
|
430
575
|
const contactPages = yield* readPages("/Contacts?includeArchived=true", Schema.Struct({ Contacts: Schema.Array(DirectoryContact) }), (page) => page.Contacts.map((contact) => ({ id: contact.ContactID })));
|
|
431
576
|
const where = `Type=="ACCREC"&&(${[...new Set(references)].map((value) => `Reference.Contains("${value.replaceAll('"', '""')}")`).join("||")})`;
|
|
432
577
|
const invoicePages = yield* readPages(`/Invoices?where=${encodeURIComponent(where)}&Statuses=DRAFT,SUBMITTED,AUTHORISED,PAID,VOIDED,DELETED`, Schema.Struct({ Invoices: Schema.Array(DirectoryInvoice) }), (page) => page.Invoices.map((invoice) => ({ id: invoice.InvoiceID })));
|
|
433
578
|
return {
|
|
434
|
-
contacts: contactPages.flatMap((page) => page.Contacts.map(
|
|
435
|
-
contactId: contact.ContactID,
|
|
436
|
-
name: contact.Name,
|
|
437
|
-
active: contact.ContactStatus === "ACTIVE",
|
|
438
|
-
emails: [
|
|
439
|
-
...new Set([
|
|
440
|
-
contact.EmailAddress,
|
|
441
|
-
...(contact.ContactPersons ?? []).map((person) => person.EmailAddress),
|
|
442
|
-
].flatMap((email) => email
|
|
443
|
-
? email.split(/[;,]/).map(normalizeEmail).filter(Boolean)
|
|
444
|
-
: [])),
|
|
445
|
-
],
|
|
446
|
-
invoiceRecipientEmails: enabledInvoiceEmails(contact),
|
|
447
|
-
}))),
|
|
579
|
+
contacts: contactPages.flatMap((page) => page.Contacts.map(invoiceContact)),
|
|
448
580
|
invoices: invoicePages.flatMap((page) => page.Invoices.map((invoice) => ({
|
|
449
581
|
invoiceId: invoice.InvoiceID,
|
|
450
582
|
invoiceNumber: invoice.InvoiceNumber,
|
|
@@ -456,6 +588,55 @@ export const XeroInvoiceLookupLive = Layer.effect(XeroInvoiceLookup, Effect.gen(
|
|
|
456
588
|
});
|
|
457
589
|
return { readDirectory };
|
|
458
590
|
}));
|
|
591
|
+
const SalesItemWire = Schema.Struct({
|
|
592
|
+
Code: Schema.String,
|
|
593
|
+
Description: optionalNullable(Schema.String),
|
|
594
|
+
IsSold: optionalNullable(Schema.Boolean),
|
|
595
|
+
SalesDetails: optionalNullable(Schema.Struct({ UnitPrice: Schema.optional(Schema.Unknown) })),
|
|
596
|
+
});
|
|
597
|
+
export const XeroInvoicePreparationLive = Layer.effect(XeroInvoicePreparation, Effect.gen(function* () {
|
|
598
|
+
const { readPages, httpClient, access } = yield* makeDirectoryReader;
|
|
599
|
+
return {
|
|
600
|
+
read: (codes) => Effect.gen(function* () {
|
|
601
|
+
const contactPages = yield* readPages("/Contacts?includeArchived=true", Schema.Struct({ Contacts: Schema.Array(DirectoryContact) }), (page) => page.Contacts.map((contact) => ({ id: contact.ContactID })));
|
|
602
|
+
const items = yield* Effect.forEach([...new Set(codes)], (code) => Effect.gen(function* () {
|
|
603
|
+
const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `/Items?unitdp=4&where=${encodeURIComponent(`Code=="${code.replaceAll('"', '\\"')}"`)}`, current.accessToken, current.tenantId), "");
|
|
604
|
+
if (result.status !== 200 || result.partial)
|
|
605
|
+
return yield* xeroMalformedResponseError(`Incomplete Xero item response for ${code}`);
|
|
606
|
+
const decoded = yield* decodeJson(Schema.Struct({ Items: Schema.Array(SalesItemWire) }), result.bodyText, `Malformed Xero item response for ${code}`);
|
|
607
|
+
const matches = decoded.Items.filter((item) => item.Code === code);
|
|
608
|
+
const item = matches.length === 1 ? matches[0] : undefined;
|
|
609
|
+
const price = item?.SalesDetails?.UnitPrice;
|
|
610
|
+
const invalid = (problem) => ({
|
|
611
|
+
kind: "invalid",
|
|
612
|
+
code,
|
|
613
|
+
problem: `${code}: ${problem}`,
|
|
614
|
+
});
|
|
615
|
+
if (!item)
|
|
616
|
+
return invalid("item missing or ambiguous in Xero; configure an existing item code");
|
|
617
|
+
if (item.IsSold !== true)
|
|
618
|
+
return invalid("item is not available for sales in Xero");
|
|
619
|
+
if (typeof price !== "number" ||
|
|
620
|
+
!Number.isFinite(price) ||
|
|
621
|
+
price < 0 ||
|
|
622
|
+
!Number.isSafeInteger(Math.round(price * 100)))
|
|
623
|
+
return invalid("set a valid non-negative sales price in Xero (zero is allowed)");
|
|
624
|
+
if (!item.Description?.trim())
|
|
625
|
+
return invalid("set a sales description in Xero");
|
|
626
|
+
return {
|
|
627
|
+
kind: "available",
|
|
628
|
+
code,
|
|
629
|
+
description: item.Description,
|
|
630
|
+
unitAmountCents: BigDecimal.toNumberUnsafe(BigDecimal.multiply(BigDecimal.fromNumberUnsafe(price), BigDecimal.make(100n, 0))),
|
|
631
|
+
};
|
|
632
|
+
}));
|
|
633
|
+
return {
|
|
634
|
+
contacts: contactPages.flatMap((page) => page.Contacts.map(invoiceContact)),
|
|
635
|
+
items,
|
|
636
|
+
};
|
|
637
|
+
}),
|
|
638
|
+
};
|
|
639
|
+
}));
|
|
459
640
|
const CreatedDraftWire = Schema.Struct({
|
|
460
641
|
...DirectoryInvoice.fields,
|
|
461
642
|
Status: Schema.Literal("DRAFT"),
|
|
@@ -480,157 +661,234 @@ const CreatedDraftWire = Schema.Struct({
|
|
|
480
661
|
}))),
|
|
481
662
|
})),
|
|
482
663
|
});
|
|
664
|
+
const CreatedRepeatedDraftWire = Schema.Struct({
|
|
665
|
+
...CreatedDraftWire.fields,
|
|
666
|
+
LineItems: Schema.Array(Schema.Struct({
|
|
667
|
+
Description: Schema.String,
|
|
668
|
+
ItemCode: Schema.optional(Schema.String),
|
|
669
|
+
Quantity: Schema.optional(Schema.Number),
|
|
670
|
+
UnitAmount: Schema.optional(Schema.Number),
|
|
671
|
+
LineAmount: Schema.optional(Schema.Number),
|
|
672
|
+
TaxAmount: Schema.optional(Schema.Number),
|
|
673
|
+
TaxType: Schema.optional(Schema.String),
|
|
674
|
+
AccountCode: Schema.optional(Schema.String),
|
|
675
|
+
Tracking: Schema.optional(Schema.Array(Schema.Struct({ Name: Schema.String, Option: Schema.String }))),
|
|
676
|
+
})),
|
|
677
|
+
});
|
|
483
678
|
const ContactInvoiceWire = Schema.Struct({
|
|
484
679
|
...DirectoryInvoice.fields,
|
|
485
|
-
Reference:
|
|
680
|
+
Reference: optionalNullable(Schema.String),
|
|
486
681
|
});
|
|
487
|
-
export const XeroDraftInvoiceLive = Layer.
|
|
682
|
+
export const XeroDraftInvoiceLive = Layer.effectContext(Effect.gen(function* () {
|
|
488
683
|
const httpClient = yield* HttpClient.HttpClient;
|
|
489
684
|
const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
|
|
490
685
|
const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
|
|
491
|
-
const serial = yield*
|
|
686
|
+
const serial = yield* Semaphore.make(1);
|
|
492
687
|
// Pace the lookup/write pair below the tenant's minute budget. Xero's
|
|
493
688
|
// Retry-After handling still applies when other clients share the tenant.
|
|
494
|
-
const request = (build) => Effect.sleep("2 seconds").pipe(Effect.
|
|
689
|
+
const request = (build) => Effect.sleep("2 seconds").pipe(Effect.andThen(sendAccounting(httpClient, access, build, "").pipe(Effect.timeoutOrElse({
|
|
495
690
|
duration: "30 seconds",
|
|
496
|
-
|
|
691
|
+
orElse: () => Effect.fail(xeroTimeoutError("Xero draft request timed out; reconcile before retry")),
|
|
497
692
|
}))));
|
|
498
|
-
const
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
693
|
+
const create = (input, writeKey) => {
|
|
694
|
+
// The repeated operation constructs this effect once per invocation.
|
|
695
|
+
let writeAttempted = false;
|
|
696
|
+
return serial.withPermits(1)(Effect.gen(function* () {
|
|
697
|
+
const validated = writeKey
|
|
698
|
+
? Schema.decodeUnknownEffect(RepeatedDraftSalesInvoice)(input)
|
|
699
|
+
: Schema.decodeUnknownEffect(DraftSalesInvoice)(input);
|
|
700
|
+
const invoice = yield* validated.pipe(Effect.mapError(() => xeroValidationError("Invalid draft invoice input or inconsistent amounts")));
|
|
701
|
+
const duplicateReference = ("duplicateReference" in invoice
|
|
702
|
+
? invoice.duplicateReference
|
|
703
|
+
: undefined) ?? invoice.reference;
|
|
704
|
+
if (!writeKey) {
|
|
705
|
+
// Read this contact's invoices, not a potentially stale batch snapshot.
|
|
706
|
+
// Filtering references locally also handles whitespace/case and suffixes.
|
|
707
|
+
const matches = [];
|
|
708
|
+
const seen = new Set();
|
|
709
|
+
let complete = false;
|
|
710
|
+
for (let page = 1; page <= 1000; page++) {
|
|
711
|
+
const response = yield* request((current) => accountingRequest("GET", `/Invoices?ContactIDs=${invoice.contactId}&where=${encodeURIComponent('Type=="ACCREC"')}&Statuses=DRAFT,SUBMITTED,AUTHORISED,PAID,VOIDED,DELETED&page=${page}&pageSize=100`, current.accessToken, current.tenantId));
|
|
712
|
+
if (response.status !== 200 || response.partial)
|
|
713
|
+
return yield* xeroMalformedResponseError("Incomplete draft duplicate check");
|
|
714
|
+
const decoded = yield* decodeJson(Schema.Struct({ Invoices: Schema.Array(ContactInvoiceWire) }), response.bodyText, "Malformed draft duplicate check");
|
|
715
|
+
for (const existing of decoded.Invoices) {
|
|
716
|
+
if (seen.has(existing.InvoiceID) ||
|
|
717
|
+
existing.Contact.ContactID !== invoice.contactId)
|
|
718
|
+
return yield* xeroMalformedResponseError("Repeated identity or unrelated contact in draft duplicate check");
|
|
719
|
+
seen.add(existing.InvoiceID);
|
|
720
|
+
if (matchesInvoiceReference(existing.Reference ?? "", duplicateReference))
|
|
721
|
+
matches.push(existing);
|
|
722
|
+
}
|
|
723
|
+
if (decoded.Invoices.length < 100) {
|
|
724
|
+
complete = true;
|
|
725
|
+
break;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
if (!complete)
|
|
729
|
+
return yield* xeroMalformedResponseError("Draft duplicate-check pagination limit exceeded");
|
|
730
|
+
const [first, ...rest] = matches;
|
|
731
|
+
if (first)
|
|
732
|
+
return {
|
|
733
|
+
kind: "skipped-existing",
|
|
734
|
+
existingInvoices: [
|
|
735
|
+
{
|
|
736
|
+
invoiceId: first.InvoiceID,
|
|
737
|
+
invoiceNumber: first.InvoiceNumber,
|
|
738
|
+
status: first.Status,
|
|
739
|
+
},
|
|
740
|
+
...rest.map((value) => ({
|
|
741
|
+
invoiceId: value.InvoiceID,
|
|
742
|
+
invoiceNumber: value.InvoiceNumber,
|
|
743
|
+
status: value.Status,
|
|
744
|
+
})),
|
|
745
|
+
],
|
|
746
|
+
};
|
|
518
747
|
}
|
|
519
|
-
if (
|
|
520
|
-
|
|
521
|
-
|
|
748
|
+
if (!invoice.expectedRecipientEmails?.length)
|
|
749
|
+
return yield* xeroValidationError("Draft recipient intent is missing; prepare the invoice again before creating it");
|
|
750
|
+
const contactResponse = yield* request((current) => accountingRequest("GET", `/Contacts?IDs=${invoice.contactId}`, current.accessToken, current.tenantId));
|
|
751
|
+
if (contactResponse.status !== 200 || contactResponse.partial)
|
|
752
|
+
return yield* xeroMalformedResponseError("Incomplete draft recipient check");
|
|
753
|
+
const decodedContact = yield* decodeJson(Schema.Struct({ Contacts: Schema.Array(DirectoryContact) }), contactResponse.bodyText, "Malformed draft recipient check");
|
|
754
|
+
const contact = decodedContact.Contacts[0];
|
|
755
|
+
if (decodedContact.Contacts.length !== 1 ||
|
|
756
|
+
!contact ||
|
|
757
|
+
contact.ContactID !== invoice.contactId)
|
|
758
|
+
return yield* xeroMalformedResponseError("Unexpected contact in draft recipient check");
|
|
759
|
+
const expectedEmails = new Set(invoice.expectedRecipientEmails.map(normalizeEmail));
|
|
760
|
+
const actualEmails = new Set(enabledInvoiceEmails(contact));
|
|
761
|
+
if (contact.ContactStatus !== "ACTIVE" ||
|
|
762
|
+
expectedEmails.size !== actualEmails.size ||
|
|
763
|
+
[...expectedEmails].some((email) => !actualEmails.has(email))) {
|
|
764
|
+
return yield* xeroValidationError("Xero invoice recipients do not match the bill payers; review the contact before creating a draft");
|
|
522
765
|
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
766
|
+
const currentAccess = yield* access.get();
|
|
767
|
+
const key = writeKey ??
|
|
768
|
+
xeroDraftIdempotencyKey(currentAccess.tenantId, invoice.contactId, duplicateReference);
|
|
769
|
+
writeAttempted = true;
|
|
770
|
+
const response = yield* request((current) => accountingRequest("POST", "/Invoices", current.accessToken, current.tenantId, key).pipe(HttpClientRequest.appendUrlParam("SummarizeErrors", "true"), (request) => writeKey
|
|
771
|
+
? HttpClientRequest.appendUrlParam(request, "unitdp", "4")
|
|
772
|
+
: request, HttpClientRequest.bodyJsonUnsafe({
|
|
773
|
+
Invoices: [
|
|
531
774
|
{
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
775
|
+
Type: "ACCREC",
|
|
776
|
+
Status: "DRAFT",
|
|
777
|
+
Contact: { ContactID: invoice.contactId },
|
|
778
|
+
Reference: invoice.reference,
|
|
779
|
+
Date: invoice.date,
|
|
780
|
+
DueDate: invoice.dueDate,
|
|
781
|
+
CurrencyCode: invoice.currency,
|
|
782
|
+
LineAmountTypes: invoice.lineAmountType,
|
|
783
|
+
LineItems: invoice.lines.map((line) => "itemCode" in line
|
|
784
|
+
? {
|
|
785
|
+
ItemCode: line.itemCode,
|
|
786
|
+
Description: line.description,
|
|
787
|
+
Quantity: line.quantity,
|
|
788
|
+
UnitAmount: line.unitAmountCents / 100,
|
|
789
|
+
LineAmount: line.lineAmountCents / 100,
|
|
790
|
+
TaxAmount: line.taxCents / 100,
|
|
791
|
+
TaxType: line.taxType,
|
|
792
|
+
...("accountCode" in line && {
|
|
793
|
+
AccountCode: line.accountCode,
|
|
794
|
+
}),
|
|
795
|
+
...("tracking" in line &&
|
|
796
|
+
line.tracking && {
|
|
797
|
+
Tracking: line.tracking.map((tracking) => ({
|
|
798
|
+
Name: tracking.category,
|
|
799
|
+
Option: tracking.option,
|
|
800
|
+
})),
|
|
801
|
+
}),
|
|
802
|
+
}
|
|
803
|
+
: { Description: line.description }),
|
|
535
804
|
},
|
|
536
|
-
...rest.map((value) => ({
|
|
537
|
-
invoiceId: value.InvoiceID,
|
|
538
|
-
invoiceNumber: value.InvoiceNumber,
|
|
539
|
-
status: value.Status,
|
|
540
|
-
})),
|
|
541
805
|
],
|
|
806
|
+
}))).pipe(Effect.retry({
|
|
807
|
+
times: writeKey ? 2 : 0,
|
|
808
|
+
while: (error) => error.retryable,
|
|
809
|
+
}));
|
|
810
|
+
const decoded = yield* decodeJson(Schema.Struct({
|
|
811
|
+
Invoices: Schema.Array(writeKey ? CreatedRepeatedDraftWire : CreatedDraftWire),
|
|
812
|
+
}), response.bodyText, "Malformed Xero draft creation response");
|
|
813
|
+
const created = decoded.Invoices[0];
|
|
814
|
+
if (decoded.Invoices.length !== 1 ||
|
|
815
|
+
!created ||
|
|
816
|
+
created.Contact.ContactID !== invoice.contactId ||
|
|
817
|
+
created.Reference !== invoice.reference ||
|
|
818
|
+
created.DateString.slice(0, 10) !== invoice.date ||
|
|
819
|
+
created.DueDateString.slice(0, 10) !== invoice.dueDate ||
|
|
820
|
+
created.Total !== invoice.totalCents / 100 ||
|
|
821
|
+
created.TotalTax !== invoice.taxCents / 100 ||
|
|
822
|
+
created.SubTotal !== invoice.subtotalCents / 100 ||
|
|
823
|
+
created.LineItems.length !== invoice.lines.length ||
|
|
824
|
+
created.LineItems.some((line, index) => {
|
|
825
|
+
const expected = invoice.lines[index];
|
|
826
|
+
if (!expected)
|
|
827
|
+
return true;
|
|
828
|
+
if (!("itemCode" in expected))
|
|
829
|
+
return (line.Description !== expected.description ||
|
|
830
|
+
("ItemCode" in line &&
|
|
831
|
+
line.ItemCode !== undefined &&
|
|
832
|
+
line.ItemCode !== "") ||
|
|
833
|
+
("Quantity" in line &&
|
|
834
|
+
line.Quantity !== undefined &&
|
|
835
|
+
line.Quantity !== 0) ||
|
|
836
|
+
("UnitAmount" in line &&
|
|
837
|
+
line.UnitAmount !== undefined &&
|
|
838
|
+
line.UnitAmount !== 0) ||
|
|
839
|
+
("LineAmount" in line &&
|
|
840
|
+
line.LineAmount !== undefined &&
|
|
841
|
+
line.LineAmount !== 0) ||
|
|
842
|
+
("TaxAmount" in line &&
|
|
843
|
+
line.TaxAmount !== undefined &&
|
|
844
|
+
line.TaxAmount !== 0) ||
|
|
845
|
+
(line.Tracking ?? []).length !== 0);
|
|
846
|
+
const tracking = "tracking" in expected ? (expected.tracking ?? []) : [];
|
|
847
|
+
return (line.ItemCode !== expected.itemCode ||
|
|
848
|
+
line.Description !== expected.description ||
|
|
849
|
+
line.Quantity !== expected.quantity ||
|
|
850
|
+
line.UnitAmount !== expected.unitAmountCents / 100 ||
|
|
851
|
+
line.LineAmount !== expected.lineAmountCents / 100 ||
|
|
852
|
+
line.TaxAmount !== expected.taxCents / 100 ||
|
|
853
|
+
line.TaxType !== expected.taxType ||
|
|
854
|
+
(writeKey &&
|
|
855
|
+
"accountCode" in expected &&
|
|
856
|
+
(!("AccountCode" in line) ||
|
|
857
|
+
line.AccountCode !== expected.accountCode)) ||
|
|
858
|
+
(line.Tracking ?? []).length !== tracking.length ||
|
|
859
|
+
tracking.some((tracking) => !line.Tracking?.some((actual) => actual.Name === tracking.category &&
|
|
860
|
+
actual.Option === tracking.option)));
|
|
861
|
+
}))
|
|
862
|
+
return yield* xeroMalformedResponseError("Created Xero draft does not match the requested invoice identity, lines or amounts");
|
|
863
|
+
yield* Effect.log("Created Xero draft invoice").pipe(Effect.annotateLogs({
|
|
864
|
+
invoiceId: created.InvoiceID,
|
|
865
|
+
invoiceNumber: created.InvoiceNumber,
|
|
866
|
+
contactId: invoice.contactId,
|
|
867
|
+
reference: invoice.reference,
|
|
868
|
+
totalCents: invoice.totalCents,
|
|
869
|
+
}));
|
|
870
|
+
return {
|
|
871
|
+
kind: "created-draft",
|
|
872
|
+
invoiceId: created.InvoiceID,
|
|
873
|
+
invoiceNumber: created.InvoiceNumber,
|
|
874
|
+
status: "DRAFT",
|
|
542
875
|
};
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
return yield* xeroValidationError("Xero invoice recipients do not match the bill payers; review the contact before creating a draft");
|
|
560
|
-
}
|
|
561
|
-
const currentAccess = yield* access.get();
|
|
562
|
-
const key = xeroDraftIdempotencyKey(currentAccess.tenantId, invoice.contactId, duplicateReference);
|
|
563
|
-
const response = yield* request((current) => accountingRequest("POST", "/Invoices", current.accessToken, current.tenantId, key).pipe(HttpClientRequest.appendUrlParam("SummarizeErrors", "true"), HttpClientRequest.bodyUnsafeJson({
|
|
564
|
-
Invoices: [
|
|
565
|
-
{
|
|
566
|
-
Type: "ACCREC",
|
|
567
|
-
Status: "DRAFT",
|
|
568
|
-
Contact: { ContactID: invoice.contactId },
|
|
569
|
-
Reference: invoice.reference,
|
|
570
|
-
Date: invoice.date,
|
|
571
|
-
DueDate: invoice.dueDate,
|
|
572
|
-
CurrencyCode: invoice.currency,
|
|
573
|
-
LineAmountTypes: invoice.lineAmountType,
|
|
574
|
-
LineItems: invoice.lines.map((line) => ({
|
|
575
|
-
ItemCode: line.itemCode,
|
|
576
|
-
Description: line.description,
|
|
577
|
-
Quantity: line.quantity,
|
|
578
|
-
UnitAmount: line.unitAmountCents / 100,
|
|
579
|
-
LineAmount: line.lineAmountCents / 100,
|
|
580
|
-
TaxAmount: line.taxCents / 100,
|
|
581
|
-
TaxType: line.taxType,
|
|
582
|
-
...(line.tracking && {
|
|
583
|
-
Tracking: line.tracking.map((tracking) => ({
|
|
584
|
-
Name: tracking.category,
|
|
585
|
-
Option: tracking.option,
|
|
586
|
-
})),
|
|
587
|
-
}),
|
|
588
|
-
})),
|
|
589
|
-
},
|
|
590
|
-
],
|
|
591
|
-
})));
|
|
592
|
-
const decoded = yield* decodeJson(Schema.Struct({ Invoices: Schema.Array(CreatedDraftWire) }), response.bodyText, "Malformed Xero draft creation response");
|
|
593
|
-
const created = decoded.Invoices[0];
|
|
594
|
-
if (decoded.Invoices.length !== 1 ||
|
|
595
|
-
!created ||
|
|
596
|
-
created.Contact.ContactID !== invoice.contactId ||
|
|
597
|
-
created.Reference !== invoice.reference ||
|
|
598
|
-
created.DateString.slice(0, 10) !== invoice.date ||
|
|
599
|
-
created.DueDateString.slice(0, 10) !== invoice.dueDate ||
|
|
600
|
-
created.Total !== invoice.totalCents / 100 ||
|
|
601
|
-
created.TotalTax !== invoice.taxCents / 100 ||
|
|
602
|
-
created.SubTotal !== invoice.subtotalCents / 100 ||
|
|
603
|
-
created.LineItems.length !== invoice.lines.length ||
|
|
604
|
-
created.LineItems.some((line, index) => {
|
|
605
|
-
const expected = invoice.lines[index];
|
|
606
|
-
return (!expected ||
|
|
607
|
-
line.ItemCode !== expected.itemCode ||
|
|
608
|
-
line.Description !== expected.description ||
|
|
609
|
-
line.Quantity !== expected.quantity ||
|
|
610
|
-
line.UnitAmount !== expected.unitAmountCents / 100 ||
|
|
611
|
-
line.LineAmount !== expected.lineAmountCents / 100 ||
|
|
612
|
-
line.TaxAmount !== expected.taxCents / 100 ||
|
|
613
|
-
line.TaxType !== expected.taxType ||
|
|
614
|
-
(line.Tracking ?? []).length !==
|
|
615
|
-
(expected.tracking ?? []).length ||
|
|
616
|
-
(expected.tracking ?? []).some((tracking) => !line.Tracking?.some((actual) => actual.Name === tracking.category &&
|
|
617
|
-
actual.Option === tracking.option)));
|
|
618
|
-
}))
|
|
619
|
-
return yield* xeroMalformedResponseError("Created Xero draft does not match the requested invoice identity, lines or amounts");
|
|
620
|
-
yield* Effect.log("Created Xero draft invoice").pipe(Effect.annotateLogs({
|
|
621
|
-
invoiceId: created.InvoiceID,
|
|
622
|
-
invoiceNumber: created.InvoiceNumber,
|
|
623
|
-
contactId: invoice.contactId,
|
|
624
|
-
reference: invoice.reference,
|
|
625
|
-
totalCents: invoice.totalCents,
|
|
626
|
-
}));
|
|
627
|
-
return {
|
|
628
|
-
kind: "created-draft",
|
|
629
|
-
invoiceId: created.InvoiceID,
|
|
630
|
-
invoiceNumber: created.InvoiceNumber,
|
|
631
|
-
status: "DRAFT",
|
|
632
|
-
};
|
|
876
|
+
}).pipe(Effect.mapError((error) => writeKey
|
|
877
|
+
? new XeroInvoiceError({
|
|
878
|
+
...error,
|
|
879
|
+
message: error.message,
|
|
880
|
+
draftCreationOutcome: writeAttempted
|
|
881
|
+
? "unconfirmed"
|
|
882
|
+
: "not-created",
|
|
883
|
+
})
|
|
884
|
+
: error)));
|
|
885
|
+
};
|
|
886
|
+
return Context.make(XeroDraftInvoice, {
|
|
887
|
+
createIfAbsent: (invoice) => create(invoice),
|
|
888
|
+
}).pipe(Context.add(XeroRepeatedDraftInvoice, {
|
|
889
|
+
create: (invoice) => Effect.suspend(() => create(invoice, `pf-repeat-draft:${randomUUID()}`)).pipe(Effect.flatMap((result) => Schema.decodeUnknownEffect(CreatedRepeatedDraft)(result)), Effect.mapError((error) => error instanceof Schema.SchemaError
|
|
890
|
+
? xeroMalformedResponseError("Unexpected repeated draft result")
|
|
891
|
+
: error)),
|
|
633
892
|
}));
|
|
634
|
-
return { createIfAbsent };
|
|
635
893
|
}));
|
|
636
894
|
//# sourceMappingURL=xero-invoice-live.js.map
|