@processfocus/plugin-xero 0.1.0-next.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.
Files changed (60) hide show
  1. package/LICENSE.md +28 -0
  2. package/README.md +207 -0
  3. package/dist/index.d.ts +5 -0
  4. package/dist/index.js +6 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/lib/contact-resolution.d.ts +39 -0
  7. package/dist/lib/contact-resolution.js +64 -0
  8. package/dist/lib/contact-resolution.js.map +1 -0
  9. package/dist/lib/errors.d.ts +38 -0
  10. package/dist/lib/errors.js +87 -0
  11. package/dist/lib/errors.js.map +1 -0
  12. package/dist/lib/idempotency.d.ts +15 -0
  13. package/dist/lib/idempotency.js +21 -0
  14. package/dist/lib/idempotency.js.map +1 -0
  15. package/dist/lib/identities.d.ts +63 -0
  16. package/dist/lib/identities.js +48 -0
  17. package/dist/lib/identities.js.map +1 -0
  18. package/dist/lib/invoice-reconciliation.d.ts +34 -0
  19. package/dist/lib/invoice-reconciliation.js +72 -0
  20. package/dist/lib/invoice-reconciliation.js.map +1 -0
  21. package/dist/lib/money.d.ts +6 -0
  22. package/dist/lib/money.js +23 -0
  23. package/dist/lib/money.js.map +1 -0
  24. package/dist/lib/xero-draft-invoice.d.ts +53 -0
  25. package/dist/lib/xero-draft-invoice.js +70 -0
  26. package/dist/lib/xero-draft-invoice.js.map +1 -0
  27. package/dist/lib/xero-http.d.ts +12 -0
  28. package/dist/lib/xero-http.js +55 -0
  29. package/dist/lib/xero-http.js.map +1 -0
  30. package/dist/lib/xero-invoice-live.d.ts +57 -0
  31. package/dist/lib/xero-invoice-live.js +636 -0
  32. package/dist/lib/xero-invoice-live.js.map +1 -0
  33. package/dist/lib/xero-invoice-lookup.d.ts +26 -0
  34. package/dist/lib/xero-invoice-lookup.js +24 -0
  35. package/dist/lib/xero-invoice-lookup.js.map +1 -0
  36. package/dist/lib/xero-invoice-step.d.ts +23 -0
  37. package/dist/lib/xero-invoice-step.js +26 -0
  38. package/dist/lib/xero-invoice-step.js.map +1 -0
  39. package/dist/lib/xero-invoice-test.d.ts +159 -0
  40. package/dist/lib/xero-invoice-test.js +497 -0
  41. package/dist/lib/xero-invoice-test.js.map +1 -0
  42. package/dist/lib/xero-invoice.d.ts +12 -0
  43. package/dist/lib/xero-invoice.js +8 -0
  44. package/dist/lib/xero-invoice.js.map +1 -0
  45. package/dist/lib/xero-token.d.ts +22 -0
  46. package/dist/lib/xero-token.js +68 -0
  47. package/dist/lib/xero-token.js.map +1 -0
  48. package/dist/lib/xero-wire.d.ts +92 -0
  49. package/dist/lib/xero-wire.js +65 -0
  50. package/dist/lib/xero-wire.js.map +1 -0
  51. package/dist/runtime.d.ts +2 -0
  52. package/dist/runtime.js +3 -0
  53. package/dist/runtime.js.map +1 -0
  54. package/dist/test-support.d.ts +1 -0
  55. package/dist/test-support.js +2 -0
  56. package/dist/test-support.js.map +1 -0
  57. package/dist/testing.d.ts +2 -0
  58. package/dist/testing.js +3 -0
  59. package/dist/testing.js.map +1 -0
  60. package/package.json +54 -0
@@ -0,0 +1,636 @@
1
+ import { Headers, HttpClient, HttpClientRequest } from "@effect/platform";
2
+ import { Clock, Config, Context, Effect, Layer, Option, Redacted, Schema, } from "effect";
3
+ import { CurrentStepJobContext } from "processfocus";
4
+ import { isContactNameConflict, resolveInvoiceContact, } from "./contact-resolution.js";
5
+ import { XeroInvoiceError, xeroAuthError, xeroDeploymentError, xeroIdempotencyConflictError, xeroMalformedResponseError, xeroPermissionError, xeroProviderServerError, xeroRateLimitError, xeroTimeoutError, xeroUnknownItemCodeError, xeroUnsupportedOperationError, xeroValidationError, } from "./errors.js";
6
+ import { isXeroIdempotencyConflictMessage, xeroDraftIdempotencyKey, xeroIdempotencyKey, } from "./idempotency.js";
7
+ import { XeroContactId, XeroInvoiceId, XeroInvoiceNumber, normalizeEmail, } from "./identities.js";
8
+ import { decodeIssuedSalesInvoice, reconcileExistingInvoices, wireAmountToMoney, } from "./invoice-reconciliation.js";
9
+ import { DraftSalesInvoice, XeroDraftInvoice, matchesInvoiceReference, } from "./xero-draft-invoice.js";
10
+ import { mapHttpClientError, parseRetryAfterSeconds, waitForRetryAfter, } from "./xero-http.js";
11
+ import { XeroInvoice } from "./xero-invoice.js";
12
+ import { XeroInvoiceLookup } from "./xero-invoice-lookup.js";
13
+ import { makeXeroAccessCache, refreshAfterMsFromExpiresIn, } from "./xero-token.js";
14
+ import { XeroConnectionsResponse, XeroContactsResponse, XeroErrorResponse, XeroInvoicesResponse, XeroTokenErrorResponse, XeroTokenResponse, } from "./xero-wire.js";
15
+ export { XERO_TOKEN_REFRESH_BUFFER_MS } from "./xero-token.js";
16
+ const TOKEN_URL = "https://identity.xero.com/connect/token";
17
+ const CONNECTIONS_URL = "https://api.xero.com/connections";
18
+ const ACCOUNTING_URL = "https://api.xero.com/api.xro/2.0";
19
+ const DEFAULT_SCOPES = "accounting.invoices accounting.contacts";
20
+ export const XERO_DEFAULT_SCOPES = DEFAULT_SCOPES;
21
+ export class XeroInvoiceConfig extends Context.Tag("@processfocus/plugin-xero/XeroInvoiceConfig")() {
22
+ }
23
+ const requireXeroInvoiceConfig = (config) => {
24
+ if (config.clientId.trim() === "" ||
25
+ config.scopes.trim() === "" ||
26
+ Redacted.value(config.clientSecret).trim() === "") {
27
+ return Effect.fail(xeroDeploymentError("Xero Custom Connection configuration is missing or malformed"));
28
+ }
29
+ return Effect.succeed(config);
30
+ };
31
+ export const XeroInvoiceConfigFromEnv = Layer.effect(XeroInvoiceConfig, Effect.gen(function* () {
32
+ return yield* requireXeroInvoiceConfig({
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)));
41
+ const validationMessages = (bodyText) => {
42
+ const decoded = Schema.decodeUnknownOption(Schema.parseJson(XeroErrorResponse))(bodyText);
43
+ return Option.match(decoded, {
44
+ onNone: () => [],
45
+ onSome: (value) => [
46
+ ...(value.Detail !== undefined ? [value.Detail] : []),
47
+ ...(value.Message !== undefined ? [value.Message] : []),
48
+ ...(value.Elements ?? []).flatMap((element) => (element.ValidationErrors ?? []).flatMap((error) => error.Message === undefined ? [] : [error.Message])),
49
+ ],
50
+ });
51
+ };
52
+ const PROVIDER_FIELDS = [
53
+ "ItemCode",
54
+ "ContactID",
55
+ "Contact",
56
+ "Reference",
57
+ "Date",
58
+ "DueDate",
59
+ "CurrencyCode",
60
+ "UnitAmount",
61
+ "Quantity",
62
+ "Type",
63
+ "Status",
64
+ "LineAmountTypes",
65
+ "Name",
66
+ "EmailAddress",
67
+ ];
68
+ const isUnknownItemMessage = (message) => {
69
+ const lower = message.toLowerCase();
70
+ return lower.includes("item code") || lower.includes("itemcode");
71
+ };
72
+ const fieldsFromMessages = (messages) => {
73
+ const lowerMessages = messages.map((message) => message.toLowerCase());
74
+ return PROVIDER_FIELDS.filter((field) => {
75
+ const needle = field.toLowerCase();
76
+ return lowerMessages.some((message) => message.includes(needle) ||
77
+ message.includes(needle.replace("code", " code")));
78
+ });
79
+ };
80
+ const providerFailure = (status, bodyText, productSku) => {
81
+ if (status === 401) {
82
+ return xeroAuthError("Xero Custom Connection authentication failed");
83
+ }
84
+ if (status === 403) {
85
+ return xeroPermissionError("Xero Custom Connection is missing required permissions");
86
+ }
87
+ if (status === 405 || status === 501) {
88
+ return xeroUnsupportedOperationError("Xero operation is not supported");
89
+ }
90
+ if (status >= 500) {
91
+ return xeroProviderServerError(status);
92
+ }
93
+ const messages = validationMessages(bodyText);
94
+ if (messages.some(isXeroIdempotencyConflictMessage)) {
95
+ return xeroIdempotencyConflictError();
96
+ }
97
+ if (messages.some(isUnknownItemMessage)) {
98
+ return xeroUnknownItemCodeError(productSku);
99
+ }
100
+ const contactNameConflict = messages.find(isContactNameConflict);
101
+ if (contactNameConflict !== undefined) {
102
+ return xeroValidationError(contactNameConflict);
103
+ }
104
+ if (messages[0] !== undefined) {
105
+ const fields = fieldsFromMessages(messages);
106
+ return xeroValidationError(messages[0], {
107
+ ...(fields.length > 0 ? { fields } : {}),
108
+ });
109
+ }
110
+ return xeroValidationError(`Xero request was rejected (${String(status)})`);
111
+ };
112
+ const tokenFailure = (status, bodyText) => {
113
+ if (status === 401 || status === 403) {
114
+ return xeroAuthError("Xero Custom Connection authentication failed");
115
+ }
116
+ if (status >= 500) {
117
+ return xeroProviderServerError(status);
118
+ }
119
+ const decoded = Schema.decodeUnknownOption(Schema.parseJson(XeroTokenErrorResponse))(bodyText);
120
+ const description = Option.match(decoded, {
121
+ onNone: () => undefined,
122
+ onSome: (value) => value.error_description,
123
+ });
124
+ return xeroAuthError(description ?? "Xero Custom Connection token request failed");
125
+ };
126
+ const execute = (httpClient, request) => Effect.gen(function* () {
127
+ const response = yield* httpClient
128
+ .execute(request)
129
+ .pipe(Effect.mapError(mapHttpClientError));
130
+ const bodyText = yield* response.text.pipe(Effect.mapError(mapHttpClientError));
131
+ return {
132
+ status: response.status,
133
+ bodyText,
134
+ partial: Option.isSome(Headers.get(response.headers, "content-range")),
135
+ retryAfter: Option.getOrUndefined(Headers.get(response.headers, "retry-after")),
136
+ };
137
+ });
138
+ const failRateLimited = (retryAfter) => Effect.gen(function* () {
139
+ const nowMs = yield* Clock.currentTimeMillis;
140
+ const retryAfterSeconds = parseRetryAfterSeconds(retryAfter, nowMs);
141
+ yield* waitForRetryAfter(retryAfterSeconds);
142
+ return yield* xeroRateLimitError(retryAfterSeconds);
143
+ });
144
+ const interpretXeroResult = (result, productSku) => {
145
+ if (result.status === 429) {
146
+ return failRateLimited(result.retryAfter);
147
+ }
148
+ if (result.status < 200 || result.status >= 300) {
149
+ return Effect.fail(providerFailure(result.status, result.bodyText, productSku));
150
+ }
151
+ return Effect.succeed(result);
152
+ };
153
+ const accountingRequest = (method, path, accessToken, tenantId, idempotencyKey) => {
154
+ const url = `${ACCOUNTING_URL}${path}`;
155
+ const base = method === "GET" ? HttpClientRequest.get(url) : HttpClientRequest.post(url);
156
+ const headers = base.pipe(HttpClientRequest.bearerToken(accessToken), HttpClientRequest.setHeader("Xero-tenant-id", tenantId), HttpClientRequest.setHeader("Accept", "application/json"));
157
+ if (idempotencyKey === undefined) {
158
+ return headers;
159
+ }
160
+ return headers.pipe(HttpClientRequest.setHeader("Idempotency-Key", idempotencyKey));
161
+ };
162
+ const xeroStreetAddress = (shipping) => ({
163
+ AddressType: "STREET",
164
+ AddressLine1: shipping.line1,
165
+ ...(shipping.line2 !== undefined && { AddressLine2: shipping.line2 }),
166
+ City: shipping.city,
167
+ ...(shipping.region !== undefined && { Region: shipping.region }),
168
+ ...(shipping.postalCode !== undefined && {
169
+ PostalCode: shipping.postalCode,
170
+ }),
171
+ ...(shipping.country !== undefined && { Country: shipping.country }),
172
+ });
173
+ export const xeroContactWritePayload = (input, name, contactId) => ({
174
+ Contacts: [
175
+ {
176
+ ...(contactId !== undefined && { ContactID: contactId }),
177
+ Name: name,
178
+ EmailAddress: input.customer.email,
179
+ Addresses: [xeroStreetAddress(input.shippingAddress)],
180
+ },
181
+ ],
182
+ });
183
+ export const xeroInvoiceWritePayload = (contactId, input) => ({
184
+ Invoices: [
185
+ {
186
+ Type: "ACCREC",
187
+ Status: "AUTHORISED",
188
+ Contact: { ContactID: contactId },
189
+ Date: input.date,
190
+ DueDate: input.dueDate,
191
+ LineAmountTypes: "Inclusive",
192
+ CurrencyCode: input.currency,
193
+ Reference: input.reference,
194
+ LineItems: [
195
+ {
196
+ ItemCode: input.productSku,
197
+ Description: input.productSku,
198
+ Quantity: 1,
199
+ UnitAmount: input.agreedPrice,
200
+ },
201
+ ],
202
+ },
203
+ ],
204
+ });
205
+ const xeroWhereEquals = (field, value) => `${field}=="${value.replaceAll('"', '""')}"`;
206
+ const requestAccessToken = (httpClient, config) => Effect.gen(function* () {
207
+ const request = HttpClientRequest.post(TOKEN_URL).pipe(HttpClientRequest.basicAuth(config.clientId, config.clientSecret), HttpClientRequest.bodyUrlParams({
208
+ grant_type: "client_credentials",
209
+ scope: config.scopes,
210
+ }));
211
+ const result = yield* execute(httpClient, request);
212
+ if (result.status === 429) {
213
+ return yield* failRateLimited(result.retryAfter);
214
+ }
215
+ if (result.status < 200 || result.status >= 300) {
216
+ return yield* tokenFailure(result.status, result.bodyText);
217
+ }
218
+ const token = yield* decodeJson(XeroTokenResponse, result.bodyText, "Malformed Xero token response");
219
+ return {
220
+ accessToken: Redacted.make(token.access_token),
221
+ expiresIn: token.expires_in,
222
+ };
223
+ });
224
+ const requestTenantId = (httpClient, accessToken) => Effect.gen(function* () {
225
+ const request = HttpClientRequest.get(CONNECTIONS_URL).pipe(HttpClientRequest.bearerToken(accessToken), HttpClientRequest.setHeader("Accept", "application/json"));
226
+ const result = yield* execute(httpClient, request);
227
+ if (result.status === 429) {
228
+ return yield* failRateLimited(result.retryAfter);
229
+ }
230
+ if (result.status < 200 || result.status >= 300) {
231
+ return yield* providerFailure(result.status, result.bodyText, "");
232
+ }
233
+ const connections = yield* decodeJson(XeroConnectionsResponse, result.bodyText, "Malformed Xero connections response");
234
+ if (connections.length === 0) {
235
+ return yield* xeroAuthError("Xero Custom Connection has no organisation");
236
+ }
237
+ if (connections.length !== 1 || connections[0] === undefined) {
238
+ return yield* xeroAuthError("Xero Custom Connection must be linked to exactly one organisation");
239
+ }
240
+ return connections[0].tenantId;
241
+ });
242
+ const fetchXeroAccess = (httpClient, config) => Effect.gen(function* () {
243
+ const token = yield* requestAccessToken(httpClient, config);
244
+ const tenantId = yield* requestTenantId(httpClient, token.accessToken);
245
+ const nowMs = yield* Clock.currentTimeMillis;
246
+ return {
247
+ accessToken: token.accessToken,
248
+ tenantId,
249
+ refreshAfterMs: refreshAfterMsFromExpiresIn(nowMs, token.expiresIn),
250
+ };
251
+ });
252
+ const sendAccounting = (httpClient, access, build, productSku) => Effect.gen(function* () {
253
+ const firstAccess = yield* access.get();
254
+ const first = yield* execute(httpClient, build(firstAccess));
255
+ if (first.status !== 401) {
256
+ return yield* interpretXeroResult(first, productSku);
257
+ }
258
+ yield* access.invalidate();
259
+ const secondAccess = yield* access.get();
260
+ const second = yield* execute(httpClient, build(secondAccess));
261
+ return yield* interpretXeroResult(second, productSku);
262
+ });
263
+ const findContacts = (httpClient, access, where, matches) => Effect.gen(function* () {
264
+ const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `/Contacts?where=${encodeURIComponent(where)}`, current.accessToken, current.tenantId), "");
265
+ const decoded = yield* decodeJson(XeroContactsResponse, result.bodyText, "Malformed Xero contact response");
266
+ return decoded.Contacts.filter(matches).map((contact) => ({
267
+ contactId: contact.ContactID,
268
+ ...(contact.Name !== undefined && { name: contact.Name }),
269
+ ...(contact.EmailAddress !== undefined && {
270
+ email: contact.EmailAddress,
271
+ }),
272
+ }));
273
+ });
274
+ const writeContact = (httpClient, access, input, name, contactId, idempotencyKey) => Effect.gen(function* () {
275
+ const payload = xeroContactWritePayload(input, name, contactId);
276
+ const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("POST", "/Contacts", current.accessToken, current.tenantId, idempotencyKey).pipe(HttpClientRequest.bodyUnsafeJson(payload)), input.productSku);
277
+ const decoded = yield* decodeJson(XeroContactsResponse, result.bodyText, "Malformed Xero contact response");
278
+ const written = decoded.Contacts[0];
279
+ if (decoded.Contacts.length !== 1 || written === undefined) {
280
+ return yield* xeroMalformedResponseError("Malformed Xero contact response");
281
+ }
282
+ yield* Effect.log(contactId === undefined ? "Created Xero contact" : "Updated Xero contact").pipe(Effect.annotateLogs({
283
+ reference: input.reference,
284
+ contactId: written.ContactID,
285
+ customerName: input.customer.name,
286
+ customerEmail: input.customer.email,
287
+ }));
288
+ return {
289
+ contactId: written.ContactID,
290
+ ...(written.Name !== undefined && { name: written.Name }),
291
+ ...(written.EmailAddress !== undefined && {
292
+ email: written.EmailAddress,
293
+ }),
294
+ };
295
+ });
296
+ const toReconcilableInvoice = (invoice) => {
297
+ const line = invoice.LineItems?.[0];
298
+ return {
299
+ invoiceId: invoice.InvoiceID,
300
+ invoiceNumber: invoice.InvoiceNumber,
301
+ type: invoice.Type ?? "",
302
+ status: invoice.Status,
303
+ currency: invoice.CurrencyCode ?? "",
304
+ date: invoice.Date ?? "",
305
+ dueDate: invoice.DueDate ?? "",
306
+ contactId: invoice.Contact?.ContactID ?? "",
307
+ itemCode: line?.ItemCode ?? "",
308
+ unitAmount: wireAmountToMoney(line?.UnitAmount) ?? "",
309
+ total: wireAmountToMoney(invoice.Total) ?? "",
310
+ lineCount: invoice.LineItems?.length ?? 0,
311
+ };
312
+ };
313
+ const findInvoicesByReference = (httpClient, access, reference) => Effect.gen(function* () {
314
+ const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `/Invoices?where=${encodeURIComponent(xeroWhereEquals("Reference", reference))}`, current.accessToken, current.tenantId), "");
315
+ const decoded = yield* decodeJson(XeroInvoicesResponse, result.bodyText, "Malformed Xero invoice response");
316
+ return decoded.Invoices.filter((invoice) => invoice.Reference === reference).map(toReconcilableInvoice);
317
+ });
318
+ const createInvoice = (httpClient, access, contactId, input, idempotencyKey) => Effect.gen(function* () {
319
+ 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.bodyUnsafeJson(payload)), input.productSku);
321
+ const decoded = yield* decodeJson(XeroInvoicesResponse, result.bodyText, "Malformed Xero invoice response");
322
+ const invoice = decoded.Invoices[0];
323
+ if (decoded.Invoices.length !== 1 || invoice === undefined) {
324
+ return yield* xeroMalformedResponseError("Malformed Xero invoice response");
325
+ }
326
+ if (invoice.Status !== "AUTHORISED") {
327
+ return yield* xeroMalformedResponseError("Xero invoice was not created in AUTHORISED state");
328
+ }
329
+ const issued = yield* decodeIssuedSalesInvoice(invoice.InvoiceID, invoice.InvoiceNumber);
330
+ yield* Effect.log("Issued Xero Sales Invoice").pipe(Effect.annotateLogs({
331
+ reference: input.reference,
332
+ invoiceId: issued.invoiceId,
333
+ invoiceNumber: issued.invoiceNumber,
334
+ customerName: input.customer.name,
335
+ customerEmail: input.customer.email,
336
+ productSku: input.productSku,
337
+ contactId,
338
+ }));
339
+ return issued;
340
+ });
341
+ const logInvoiceFailure = (input, error) => Effect.logWarning("Xero Sales Invoice failed").pipe(Effect.annotateLogs({
342
+ reference: input.reference,
343
+ customerName: input.customer.name,
344
+ customerEmail: input.customer.email,
345
+ code: error.code ?? "unknown",
346
+ retryable: error.retryable,
347
+ }));
348
+ export const XeroInvoiceLive = Layer.effect(XeroInvoice, Effect.gen(function* () {
349
+ const httpClient = yield* HttpClient.HttpClient;
350
+ const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
351
+ const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
352
+ const issueAuthorisedSalesInvoice = Effect.fn("XeroInvoice.issueAuthorisedSalesInvoice")(function* (input) {
353
+ return yield* Effect.gen(function* () {
354
+ const { todoId } = yield* CurrentStepJobContext;
355
+ const contactId = yield* resolveInvoiceContact({
356
+ findByName: (name) => findContacts(httpClient, access, xeroWhereEquals("Name", name), (contact) => contact.Name === name),
357
+ findByEmail: (email) => findContacts(httpClient, access, xeroWhereEquals("EmailAddress", normalizeEmail(email)), (contact) => contact.EmailAddress !== undefined &&
358
+ normalizeEmail(contact.EmailAddress) ===
359
+ normalizeEmail(email)),
360
+ create: (invoiceInput, name, idempotencyKey) => writeContact(httpClient, access, invoiceInput, name, undefined, idempotencyKey),
361
+ update: (contact, invoiceInput, idempotencyKey) => writeContact(httpClient, access, invoiceInput, invoiceInput.customer.name, contact.contactId, idempotencyKey),
362
+ }, input, todoId);
363
+ const existing = yield* findInvoicesByReference(httpClient, access, input.reference);
364
+ const reconciled = yield* reconcileExistingInvoices(existing, input, contactId);
365
+ if (reconciled !== undefined) {
366
+ return reconciled;
367
+ }
368
+ return yield* createInvoice(httpClient, access, contactId, input, xeroIdempotencyKey(todoId, "invoice.create"));
369
+ }).pipe(Effect.tapError((error) => logInvoiceFailure(input, error)));
370
+ });
371
+ return { issueAuthorisedSalesInvoice };
372
+ }));
373
+ const DirectoryContact = Schema.Struct({
374
+ ContactID: XeroContactId,
375
+ Name: Schema.String,
376
+ ContactStatus: Schema.Literal("ACTIVE", "ARCHIVED", "GDPRREQUEST"),
377
+ EmailAddress: Schema.optionalWith(Schema.String, { nullable: true }),
378
+ ContactPersons: Schema.optionalWith(Schema.Array(Schema.Struct({
379
+ EmailAddress: Schema.optionalWith(Schema.String, { nullable: true }),
380
+ IncludeInEmails: Schema.optionalWith(Schema.Boolean, {
381
+ nullable: true,
382
+ }),
383
+ })), { nullable: true }),
384
+ });
385
+ const DirectoryInvoice = Schema.Struct({
386
+ InvoiceID: XeroInvoiceId,
387
+ InvoiceNumber: XeroInvoiceNumber,
388
+ Type: Schema.Literal("ACCREC"),
389
+ Status: Schema.String,
390
+ Contact: Schema.Struct({ ContactID: XeroContactId }),
391
+ Reference: Schema.String,
392
+ });
393
+ const enabledInvoiceEmails = (contact) => [
394
+ ...new Set([
395
+ contact.EmailAddress,
396
+ ...(contact.ContactPersons ?? [])
397
+ .filter((person) => person.IncludeInEmails === true)
398
+ .map((person) => person.EmailAddress),
399
+ ].flatMap((email) => email ? email.split(/[;,]/).map(normalizeEmail).filter(Boolean) : [])),
400
+ ];
401
+ /** Read-only companion: shares authentication/error handling, never writes. */
402
+ export const XeroInvoiceLookupLive = Layer.effect(XeroInvoiceLookup, Effect.gen(function* () {
403
+ const httpClient = yield* HttpClient.HttpClient;
404
+ const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
405
+ const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
406
+ const readPages = (path, schema, rows) => Effect.gen(function* () {
407
+ const pages = [];
408
+ const seen = new Set();
409
+ for (let page = 1; page <= 1000; page++) {
410
+ const result = yield* sendAccounting(httpClient, access, (current) => accountingRequest("GET", `${path}&page=${page}&pageSize=100`, current.accessToken, current.tenantId), "");
411
+ // A partial or malformed response must never imply absence of an invoice.
412
+ if (result.status !== 200 || result.partial)
413
+ return yield* xeroMalformedResponseError("Incomplete Xero invoice directory response");
414
+ const decoded = yield* decodeJson(schema, result.bodyText, "Malformed Xero invoice directory response");
415
+ const items = rows(decoded);
416
+ for (const item of items) {
417
+ if (seen.has(item.id))
418
+ return yield* xeroMalformedResponseError("Repeated Xero directory page or identity");
419
+ seen.add(item.id);
420
+ }
421
+ pages.push(decoded);
422
+ if (items.length < 100)
423
+ return pages;
424
+ }
425
+ return yield* xeroMalformedResponseError("Xero directory pagination limit exceeded");
426
+ });
427
+ const readDirectory = (reference, previousReference) => Effect.gen(function* () {
428
+ const text = yield* Schema.decodeUnknown(Schema.Trim.pipe(Schema.minLength(1)))(reference).pipe(Effect.mapError(() => xeroValidationError("An invoice reference is required")));
429
+ const references = yield* Schema.decodeUnknown(Schema.Array(Schema.Trim.pipe(Schema.minLength(1))))(previousReference === undefined ? [text] : [text, previousReference]).pipe(Effect.mapError(() => xeroValidationError("Valid invoice references are required")));
430
+ const contactPages = yield* readPages("/Contacts?includeArchived=true", Schema.Struct({ Contacts: Schema.Array(DirectoryContact) }), (page) => page.Contacts.map((contact) => ({ id: contact.ContactID })));
431
+ const where = `Type=="ACCREC"&&(${[...new Set(references)].map((value) => `Reference.Contains("${value.replaceAll('"', '""')}")`).join("||")})`;
432
+ 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
+ return {
434
+ contacts: contactPages.flatMap((page) => page.Contacts.map((contact) => ({
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
+ }))),
448
+ invoices: invoicePages.flatMap((page) => page.Invoices.map((invoice) => ({
449
+ invoiceId: invoice.InvoiceID,
450
+ invoiceNumber: invoice.InvoiceNumber,
451
+ contactId: invoice.Contact.ContactID,
452
+ reference: invoice.Reference,
453
+ status: invoice.Status,
454
+ }))),
455
+ };
456
+ });
457
+ return { readDirectory };
458
+ }));
459
+ const CreatedDraftWire = Schema.Struct({
460
+ ...DirectoryInvoice.fields,
461
+ Status: Schema.Literal("DRAFT"),
462
+ CurrencyCode: Schema.Literal("NZD"),
463
+ LineAmountTypes: Schema.Literal("Inclusive"),
464
+ DateString: Schema.String,
465
+ DueDateString: Schema.String,
466
+ Total: Schema.Number,
467
+ TotalTax: Schema.Number,
468
+ SubTotal: Schema.Number,
469
+ LineItems: Schema.Array(Schema.Struct({
470
+ ItemCode: Schema.String,
471
+ Description: Schema.String,
472
+ Quantity: Schema.Number,
473
+ UnitAmount: Schema.Number,
474
+ LineAmount: Schema.Number,
475
+ TaxAmount: Schema.Number,
476
+ TaxType: Schema.String,
477
+ Tracking: Schema.optional(Schema.Array(Schema.Struct({
478
+ Name: Schema.String,
479
+ Option: Schema.String,
480
+ }))),
481
+ })),
482
+ });
483
+ const ContactInvoiceWire = Schema.Struct({
484
+ ...DirectoryInvoice.fields,
485
+ Reference: Schema.optionalWith(Schema.String, { nullable: true }),
486
+ });
487
+ export const XeroDraftInvoiceLive = Layer.effect(XeroDraftInvoice, Effect.gen(function* () {
488
+ const httpClient = yield* HttpClient.HttpClient;
489
+ const config = yield* requireXeroInvoiceConfig(yield* XeroInvoiceConfig);
490
+ const access = yield* makeXeroAccessCache(fetchXeroAccess(httpClient, config));
491
+ const serial = yield* Effect.makeSemaphore(1);
492
+ // Pace the lookup/write pair below the tenant's minute budget. Xero's
493
+ // Retry-After handling still applies when other clients share the tenant.
494
+ const request = (build) => Effect.sleep("2 seconds").pipe(Effect.zipRight(sendAccounting(httpClient, access, build, "").pipe(Effect.timeoutFail({
495
+ duration: "30 seconds",
496
+ onTimeout: () => xeroTimeoutError("Xero draft request timed out; reconcile before retry"),
497
+ }))));
498
+ const createIfAbsent = (input) => serial.withPermits(1)(Effect.gen(function* () {
499
+ const invoice = yield* Schema.decodeUnknown(DraftSalesInvoice)(input).pipe(Effect.mapError(() => xeroValidationError("Invalid draft invoice input or inconsistent amounts")));
500
+ const duplicateReference = invoice.duplicateReference ?? invoice.reference;
501
+ // Read this contact's invoices, not a potentially stale batch snapshot.
502
+ // Filtering references locally also handles whitespace/case and suffixes.
503
+ const matches = [];
504
+ const seen = new Set();
505
+ let complete = false;
506
+ for (let page = 1; page <= 1000; page++) {
507
+ 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));
508
+ if (response.status !== 200 || response.partial)
509
+ return yield* xeroMalformedResponseError("Incomplete draft duplicate check");
510
+ const decoded = yield* decodeJson(Schema.Struct({ Invoices: Schema.Array(ContactInvoiceWire) }), response.bodyText, "Malformed draft duplicate check");
511
+ for (const existing of decoded.Invoices) {
512
+ if (seen.has(existing.InvoiceID) ||
513
+ existing.Contact.ContactID !== invoice.contactId)
514
+ return yield* xeroMalformedResponseError("Repeated identity or unrelated contact in draft duplicate check");
515
+ seen.add(existing.InvoiceID);
516
+ if (matchesInvoiceReference(existing.Reference ?? "", duplicateReference))
517
+ matches.push(existing);
518
+ }
519
+ if (decoded.Invoices.length < 100) {
520
+ complete = true;
521
+ break;
522
+ }
523
+ }
524
+ if (!complete)
525
+ return yield* xeroMalformedResponseError("Draft duplicate-check pagination limit exceeded");
526
+ const [first, ...rest] = matches;
527
+ if (first)
528
+ return {
529
+ kind: "skipped-existing",
530
+ existingInvoices: [
531
+ {
532
+ invoiceId: first.InvoiceID,
533
+ invoiceNumber: first.InvoiceNumber,
534
+ status: first.Status,
535
+ },
536
+ ...rest.map((value) => ({
537
+ invoiceId: value.InvoiceID,
538
+ invoiceNumber: value.InvoiceNumber,
539
+ status: value.Status,
540
+ })),
541
+ ],
542
+ };
543
+ if (!invoice.expectedRecipientEmails?.length)
544
+ return yield* xeroValidationError("Draft recipient intent is missing; prepare the invoice again before creating it");
545
+ const contactResponse = yield* request((current) => accountingRequest("GET", `/Contacts?IDs=${invoice.contactId}`, current.accessToken, current.tenantId));
546
+ if (contactResponse.status !== 200 || contactResponse.partial)
547
+ return yield* xeroMalformedResponseError("Incomplete draft recipient check");
548
+ const decodedContact = yield* decodeJson(Schema.Struct({ Contacts: Schema.Array(DirectoryContact) }), contactResponse.bodyText, "Malformed draft recipient check");
549
+ const contact = decodedContact.Contacts[0];
550
+ if (decodedContact.Contacts.length !== 1 ||
551
+ !contact ||
552
+ contact.ContactID !== invoice.contactId)
553
+ return yield* xeroMalformedResponseError("Unexpected contact in draft recipient check");
554
+ const expectedEmails = new Set(invoice.expectedRecipientEmails.map(normalizeEmail));
555
+ const actualEmails = new Set(enabledInvoiceEmails(contact));
556
+ if (contact.ContactStatus !== "ACTIVE" ||
557
+ expectedEmails.size !== actualEmails.size ||
558
+ [...expectedEmails].some((email) => !actualEmails.has(email))) {
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
+ };
633
+ }));
634
+ return { createIfAbsent };
635
+ }));
636
+ //# sourceMappingURL=xero-invoice-live.js.map