@arcforgelabs/flow 2026.10.30 → 2026.10.32
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 +2 -0
- package/npm-shrinkwrap.json +188 -2
- package/package.json +2 -1
- package/server/api/alerts.js +49 -0
- package/server/api/invoicing.js +125 -7
- package/server/app.js +29 -2
- package/server/core/alerts.js +157 -0
- package/server/core/automations.js +17 -3
- package/server/core/history.js +65 -0
- package/server/core/invoice-pdf.js +266 -0
- package/server/core/invoices.js +2 -2
- package/server/core/invoicing-rules.js +26 -1
- package/server/core/job-board.js +25 -3
- package/server/core/ledger.js +3 -2
- package/server/core/line-mapping.js +36 -10
- package/server/core/pipeline.js +76 -4
- package/server/core/price-list.js +348 -0
- package/server/core/references.js +99 -0
- package/server/core/sending.js +11 -5
- package/server/db/commands.js +42 -0
- package/server/db/doctor.js +168 -0
- package/server/db/migrations/0014_price_list.sql +34 -0
- package/server/db/migrations/0015_alert_dismissals.sql +17 -0
- package/server/db/migrations/0016_invoice_reference.sql +1 -0
- package/server/db/migrations/meta/0014_snapshot.json +3773 -0
- package/server/db/migrations/meta/0015_snapshot.json +3854 -0
- package/server/db/migrations/meta/0016_snapshot.json +3861 -0
- package/server/db/migrations/meta/_journal.json +21 -0
- package/server/db/schema.js +46 -0
- package/server/flow-server.js +20 -1
- package/server/index.js +2 -1
- package/server/integrations/call-guard.js +362 -0
- package/server/integrations/port.js +21 -1
- package/server/integrations/seazona/feed.js +31 -2
- package/server/integrations/seazona/governor.js +50 -122
- package/server/integrations/seazona/history/backfill.js +208 -0
- package/server/integrations/seazona/history/csv.js +65 -0
- package/server/integrations/seazona/history/index.js +584 -0
- package/server/integrations/seazona/history/read.js +196 -0
- package/server/integrations/seazona/index.js +46 -1
- package/server/integrations/seazona/lanes.js +187 -51
- package/server/integrations/seazona/migrations/0003_call_guard.sql +2 -0
- package/server/integrations/seazona/migrations/0004_history_import.sql +68 -0
- package/server/integrations/seazona/migrations/meta/0003_snapshot.json +895 -0
- package/server/integrations/seazona/migrations/meta/0004_snapshot.json +1323 -0
- package/server/integrations/seazona/migrations/meta/_journal.json +14 -0
- package/server/integrations/seazona/patients.js +30 -0
- package/server/integrations/seazona/routes.js +145 -0
- package/server/integrations/seazona/schema.js +94 -0
- package/server/integrations/seazona/settings.js +14 -3
- package/server/integrations/seazona/sync-once.js +1 -1
- package/server/integrations/seazona/tables.js +4 -0
- package/server/integrations/xero/client.js +39 -7
- package/server/integrations/xero/drafts.js +46 -8
- package/server/integrations/xero/import.js +131 -17
- package/server/integrations/xero/index.js +38 -7
- package/server/integrations/xero/lookup.js +26 -0
- package/server/integrations/xero/migrations/0006_xero_call_guard.sql +26 -0
- package/server/integrations/xero/migrations/0007_xero_webhooks.sql +30 -0
- package/server/integrations/xero/migrations/meta/_journal.json +14 -0
- package/server/integrations/xero/mirror.js +27 -10
- package/server/integrations/xero/oauth.js +4 -1
- package/server/integrations/xero/reconcile.js +173 -0
- package/server/integrations/xero/routes.js +55 -0
- package/server/integrations/xero/runtime.js +45 -4
- package/server/integrations/xero/settings.js +3 -0
- package/server/integrations/xero/webhooks.js +311 -0
- package/server/release-channel.js +3 -3
- package/server/ui/alerts.js +77 -0
- package/server/ui/app-page.js +1 -1
- package/server/ui/app.js +63 -21
- package/server/ui/clerk-appearance.js +42 -9
- package/server/ui/flow.css +78 -9
- package/server/ui/invoice-notes.js +26 -0
- package/server/ui/invoicing-settings.js +4 -2
- package/server/ui/invoicing.js +241 -49
- package/server/ui/line-mappings.js +3 -2
- package/server/ui/price-list.js +247 -0
- package/server/ui/routes.js +1 -1
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { sql } from 'drizzle-orm';
|
|
3
|
-
import { enqueueJob, runNextJob } from '../../core/queue.js';
|
|
3
|
+
import { deadHoldSince, deadSince, enqueueJob, runNextJob } from '../../core/queue.js';
|
|
4
|
+
import { isCallsStopped } from '../call-guard.js';
|
|
4
5
|
import { lastSync, syncCatalogue } from './catalogue.js';
|
|
6
|
+
import { mirrorState } from './lookup.js';
|
|
5
7
|
import { MIRROR_RESOURCES, mirrorXero } from './mirror.js';
|
|
8
|
+
import { checkSentInvoices } from './reconcile.js';
|
|
9
|
+
import { runWebhookWork, WEBHOOK_REFRESH_MS, webhooksActive } from './webhooks.js';
|
|
6
10
|
|
|
7
|
-
// The history import. When an owner connects Xero,
|
|
8
|
-
// organisation's invoices, credit notes and payments into the
|
|
9
|
-
// (mirror.js) as a background job, so nobody runs a script by hand. The
|
|
10
|
-
// reads in slices; a slice that stops at the day's budget or its page
|
|
11
|
-
// queues the next slice.
|
|
11
|
+
// The history import, then the reads of changes. When an owner connects Xero,
|
|
12
|
+
// Flow copies the organisation's invoices, credit notes and payments into the
|
|
13
|
+
// mirror (mirror.js) as a background job, so nobody runs a script by hand. The
|
|
14
|
+
// job reads in slices; a slice that stops at the day's budget or its page
|
|
15
|
+
// limit queues the next slice. When every resource is read to its end, the
|
|
16
|
+
// same job is queued again for REFRESH_MS later and reads only what changed
|
|
17
|
+
// since its cursor (issue #131), so the copy stays fresh (lookup.js). While
|
|
18
|
+
// Xero's webhooks arrive (webhooks.js), it waits WEBHOOK_REFRESH_MS instead.
|
|
19
|
+
// It only reads from Xero.
|
|
12
20
|
|
|
13
21
|
export const IMPORT_KIND = 'xero.import';
|
|
14
22
|
const IMPORT_KEY = 'history';
|
|
@@ -18,6 +26,10 @@ const LEASE_MS = 30 * 60 * 1000;
|
|
|
18
26
|
// Xero's day limit resets on a rolling day; an hour is a cheap re-check.
|
|
19
27
|
const BUDGET_WAIT_MS = 60 * 60 * 1000;
|
|
20
28
|
const IDLE_MS = 30 * 1000;
|
|
29
|
+
// How often a finished copy reads Xero's changes again. Each read costs about
|
|
30
|
+
// one call per resource when little changed: 96 a day for each of invoices and
|
|
31
|
+
// credit notes, inside the reserve the mirror leaves (XERO_MIRROR_RESERVE_FRACTION).
|
|
32
|
+
export const REFRESH_MS = 15 * 60 * 1000;
|
|
21
33
|
// Contacts and items are read again once a day, so the matcher can link each
|
|
22
34
|
// customer (server/core/pipeline.js) without a person pressing Sync.
|
|
23
35
|
const CATALOGUE_EVERY_MS = 24 * 60 * 60 * 1000;
|
|
@@ -44,12 +56,33 @@ export async function organisationsToImport(db, mode) {
|
|
|
44
56
|
return rows.map((r) => r.organisation_id);
|
|
45
57
|
}
|
|
46
58
|
|
|
59
|
+
// The next read for one organisation: queued now unless one is open already.
|
|
60
|
+
export async function queueChangesRead(db, organisationId, { runAfter = null } = {}) {
|
|
61
|
+
return queueHistoryImport(db, organisationId, { reason: 'changes', runAfter });
|
|
62
|
+
}
|
|
63
|
+
|
|
47
64
|
// One slice of the import for one job. Answers what it read and whether more
|
|
48
65
|
// remains (`more`: 'budget' or 'max_pages').
|
|
66
|
+
// While the call guard stops Xero calls the slice does not fail, so it does
|
|
67
|
+
// not spend the job's attempts: it answers `more: 'stopped'` with the wait,
|
|
68
|
+
// or no wait for a stop only a person clears (connecting queues the import).
|
|
49
69
|
export async function runImportSlice(db, runtime, job, { maxPages = SLICE_PAGES } = {}) {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
70
|
+
let results;
|
|
71
|
+
try {
|
|
72
|
+
results = await mirrorXero(db, runtime, job.organisationId, { maxPages });
|
|
73
|
+
} catch (error) {
|
|
74
|
+
if (!isCallsStopped(error)) throw error;
|
|
75
|
+
return { results: [], more: error.retryAfterMs === null ? null : 'stopped', retryAfterMs: error.retryAfterMs, stoppedBy: error.code };
|
|
76
|
+
}
|
|
77
|
+
// A refused resource waits for a person; it never queues another slice.
|
|
78
|
+
const stopped = results.find((r) => !['done', 'refused'].includes(r.stopped))?.stopped ?? null;
|
|
79
|
+
// Each invoice Flow sent, against what the copy now holds (issue #132):
|
|
80
|
+
// an edit, void or delete in Xero opens a review item. No Xero calls.
|
|
81
|
+
const invoices = results.find((r) => r.resource === 'invoices');
|
|
82
|
+
const sent = invoices && (invoices.inserted || invoices.changed || job.payload?.reason !== 'changes')
|
|
83
|
+
? await checkSentInvoices(db, runtime, job.organisationId)
|
|
84
|
+
: null;
|
|
85
|
+
return { results, more: stopped, ...(sent ? { sent } : {}) };
|
|
53
86
|
}
|
|
54
87
|
|
|
55
88
|
// Claims and runs one due import job, then queues the next slice when one is
|
|
@@ -61,33 +94,109 @@ export async function runImportOnce(db, runtime, { workerId = `xero-import-${ran
|
|
|
61
94
|
handlers: { [IMPORT_KIND]: (job) => runImportSlice(db, runtime, job, { maxPages }) },
|
|
62
95
|
});
|
|
63
96
|
if (ran?.outcome === 'succeeded' && ran.job.result?.more) {
|
|
64
|
-
const
|
|
97
|
+
const { more, retryAfterMs } = ran.job.result;
|
|
98
|
+
const wait = more === 'budget' ? BUDGET_WAIT_MS : more === 'stopped' ? Math.max(IDLE_MS, Number(retryAfterMs) || BUDGET_WAIT_MS) : 0;
|
|
65
99
|
await queueHistoryImport(db, ran.job.organisationId, { reason: ran.job.result.more, runAfter: new Date(Number(now()) + wait) });
|
|
100
|
+
} else if (ran?.outcome === 'succeeded' && !ran.job.result?.stoppedBy) {
|
|
101
|
+
// Read to the end: read the changes again later. A stop only a person
|
|
102
|
+
// clears queues nothing; connecting or saving the settings queues it.
|
|
103
|
+
// While Xero's webhooks arrive, the poll is only the safety net (issue #45).
|
|
104
|
+
const every = await webhooksActive(db, runtime, ran.job.organisationId, { now: Number(now()) }) ? WEBHOOK_REFRESH_MS : REFRESH_MS;
|
|
105
|
+
await queueChangesRead(db, ran.job.organisationId, { runAfter: new Date(Number(now()) + every) });
|
|
66
106
|
}
|
|
67
107
|
return ran;
|
|
68
108
|
}
|
|
69
109
|
|
|
110
|
+
// Failed catalogue reads in a row since the last good one, and the newest
|
|
111
|
+
// failure's code.
|
|
112
|
+
async function failuresInARow(db, organisationId) {
|
|
113
|
+
const { rows } = await db.execute(sql`
|
|
114
|
+
select count(*)::int as failures,
|
|
115
|
+
(array_agg(error_code order by started_at desc))[1] as last_code
|
|
116
|
+
from xero_sync_runs
|
|
117
|
+
where organisation_id = ${organisationId} and status = 'failed'
|
|
118
|
+
and started_at > coalesce((select max(started_at) from xero_sync_runs
|
|
119
|
+
where organisation_id = ${organisationId} and status = 'succeeded'), 'epoch')`);
|
|
120
|
+
return { failures: rows[0]?.failures ?? 0, lastCode: rows[0]?.last_code ?? null };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// The wait after `failures` failed reads in a row: an hour, doubling, at most
|
|
124
|
+
// a day (issue #111: never every hour for ever).
|
|
125
|
+
export function catalogueRetryMs(failures) {
|
|
126
|
+
return Math.min(CATALOGUE_EVERY_MS, BUDGET_WAIT_MS * 2 ** Math.max(0, failures - 1));
|
|
127
|
+
}
|
|
128
|
+
|
|
70
129
|
// Reads the contacts and items of each connected organisation whose last good
|
|
71
|
-
// read is older than a day. A
|
|
130
|
+
// read is older than a day. A failed read waits longer each time (above). A
|
|
131
|
+
// failure is reported once with log.error; the same failure again is a
|
|
132
|
+
// warning. While the call guard stops Xero calls, no read is tried.
|
|
72
133
|
export async function refreshStaleCatalogues(db, runtime, { now = Date.now, log = console } = {}) {
|
|
73
|
-
const { rows } = await db.execute(sql`select organisation_id from xero_connections where mode = ${runtime.settings.mode}`);
|
|
74
|
-
for (const { organisation_id: organisationId } of rows) {
|
|
134
|
+
const { rows } = await db.execute(sql`select organisation_id, tenant_id from xero_connections where mode = ${runtime.settings.mode}`);
|
|
135
|
+
for (const { organisation_id: organisationId, tenant_id: tenantId } of rows) {
|
|
75
136
|
const last = await lastSync(db, organisationId);
|
|
76
137
|
const at = last?.finishedAt ?? last?.startedAt;
|
|
77
|
-
|
|
138
|
+
const { failures, lastCode } = last?.status === 'failed' ? await failuresInARow(db, organisationId) : { failures: 0, lastCode: null };
|
|
139
|
+
if (last && at && Number(now()) - new Date(at) < (last.status === 'succeeded' ? CATALOGUE_EVERY_MS : catalogueRetryMs(failures))) continue;
|
|
140
|
+
try {
|
|
141
|
+
await runtime.guardFor(db).check(tenantId);
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (isCallsStopped(error)) continue;
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
78
146
|
try {
|
|
79
147
|
const run = await syncCatalogue(db, runtime, organisationId);
|
|
80
148
|
log.info?.(`[xero] contacts and items read for organisation ${organisationId}: ${run.contactCount} contacts, ${run.itemCount} items`);
|
|
81
149
|
} catch (error) {
|
|
82
|
-
|
|
150
|
+
const code = error?.code ?? 'error';
|
|
151
|
+
const line = `[xero] reading contacts and items for organisation ${organisationId} failed: ${code}; next try in ${Math.round(catalogueRetryMs(failures + 1) / 60_000)} minutes`;
|
|
152
|
+
// The guard reported a stop already; a repeat of the same failure is a warning.
|
|
153
|
+
if (isCallsStopped(error) || (failures > 0 && code === lastCode)) log.warn?.(line);
|
|
154
|
+
else log.error?.(line);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Keeps a read queued for each connected organisation. A read that gave up
|
|
160
|
+
// (dead) waits for a person, a restart or the next day (issue #101), and
|
|
161
|
+
// while the call guard stops Xero calls no read is queued.
|
|
162
|
+
export async function keepReadsQueued(db, runtime, { startedAtMs = Date.now(), now = Date.now } = {}) {
|
|
163
|
+
const { rows } = await db.execute(sql`select organisation_id, tenant_id from xero_connections where mode = ${runtime.settings.mode}`);
|
|
164
|
+
for (const { organisation_id: organisationId, tenant_id: tenantId } of rows) {
|
|
165
|
+
if (await deadSince(db, organisationId, { kind: IMPORT_KIND, dedupeKey: IMPORT_KEY, since: deadHoldSince(startedAtMs, Number(now())) })) continue;
|
|
166
|
+
try {
|
|
167
|
+
await runtime.guardFor(db).check(tenantId);
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (isCallsStopped(error)) continue;
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
await queueChangesRead(db, organisationId);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
// Reports a copy that went stale once with log.error, and its recovery with
|
|
177
|
+
// log.info. `stale` is the set of organisations already reported.
|
|
178
|
+
export async function reportStaleCopies(db, runtime, { stale = new Set(), now = Date.now, log = console } = {}) {
|
|
179
|
+
const { rows } = await db.execute(sql`select organisation_id from xero_connections where mode = ${runtime.settings.mode}`);
|
|
180
|
+
for (const { organisation_id: organisationId } of rows) {
|
|
181
|
+
const state = await mirrorState(db, organisationId, { now: new Date(Number(now())) });
|
|
182
|
+
if (!state.complete) continue;
|
|
183
|
+
if (!state.fresh && !stale.has(organisationId)) {
|
|
184
|
+
stale.add(organisationId);
|
|
185
|
+
log.error?.(`[xero] the copy of Xero for organisation ${organisationId} is out of date (last full read ${state.lastPassAt?.toISOString() ?? 'never'}); drafts by rule wait until it is read again`);
|
|
186
|
+
} else if (state.fresh && stale.delete(organisationId)) {
|
|
187
|
+
log.info?.(`[xero] the copy of Xero for organisation ${organisationId} is up to date again`);
|
|
83
188
|
}
|
|
84
189
|
}
|
|
190
|
+
return stale;
|
|
85
191
|
}
|
|
86
192
|
|
|
87
193
|
// The background worker: runs due slices one at a time, then waits. Started
|
|
88
194
|
// by the adapter outside replay mode; stop() waits for a slice in flight.
|
|
89
195
|
export function createImportWorker({ db, runtime, log = console, timers = { setTimeout, clearTimeout }, firstDelayMs = 10_000 }) {
|
|
90
196
|
const workerId = `xero-import-${randomUUID()}`;
|
|
197
|
+
const startedAtMs = Date.now();
|
|
198
|
+
const stale = new Set();
|
|
199
|
+
const holds = new Map();
|
|
91
200
|
let timer = null;
|
|
92
201
|
let running = null;
|
|
93
202
|
let stopped = true;
|
|
@@ -105,12 +214,15 @@ export function createImportWorker({ db, runtime, log = console, timers = { setT
|
|
|
105
214
|
running = (async () => {
|
|
106
215
|
try {
|
|
107
216
|
await refreshStaleCatalogues(db, runtime, { log });
|
|
217
|
+
await keepReadsQueued(db, runtime, { startedAtMs });
|
|
218
|
+
await reportStaleCopies(db, runtime, { stale, log });
|
|
219
|
+
await runWebhookWork(db, runtime, { log, holds });
|
|
108
220
|
const ran = await runImportOnce(db, runtime, { workerId });
|
|
109
221
|
if (ran) {
|
|
110
222
|
busy = true;
|
|
111
223
|
const read = (ran.job.result?.results ?? []).map((r) => `${r.resource} ${r.read}`).join(', ');
|
|
112
|
-
if (ran.outcome === 'dead') log.error?.('[xero]
|
|
113
|
-
log.info?.(`[xero]
|
|
224
|
+
if (ran.outcome === 'dead') log.error?.('[xero] reading Xero gave up after its last attempt');
|
|
225
|
+
log.info?.(`[xero] read ${ran.outcome} for organisation ${ran.job.organisationId}${read ? `: ${read}` : ''}${ran.job.result?.more ? `; more (${ran.job.result.more})` : ''}`);
|
|
114
226
|
}
|
|
115
227
|
} catch (error) {
|
|
116
228
|
log.error?.(`[xero] import worker: ${error?.code ?? 'error'}: ${error?.message ?? error}`);
|
|
@@ -127,6 +239,8 @@ export function createImportWorker({ db, runtime, log = console, timers = { setT
|
|
|
127
239
|
for (const organisationId of await organisationsToImport(db, runtime.settings.mode)) {
|
|
128
240
|
await queueHistoryImport(db, organisationId, { reason: 'start' });
|
|
129
241
|
}
|
|
242
|
+
// A finished copy reads its changes again from the first tick on
|
|
243
|
+
// (keepReadsQueued), so an upgrade or a restart needs no step.
|
|
130
244
|
schedule(firstDelayMs);
|
|
131
245
|
},
|
|
132
246
|
async stop() {
|
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
import { fileURLToPath } from 'node:url';
|
|
2
2
|
import { sql } from 'drizzle-orm';
|
|
3
|
-
import {
|
|
3
|
+
import { guardAlerts } from '../call-guard.js';
|
|
4
|
+
import { checkDrafts, documentFacts, pushInvoice, pushInvoices } from './drafts.js';
|
|
4
5
|
import { readConnection } from './connections.js';
|
|
5
6
|
import { createImportWorker } from './import.js';
|
|
6
7
|
import { readPayments, xeroLiveCheck } from './ledger.js';
|
|
7
|
-
import { findInvoices, listCustomers } from './lookup.js';
|
|
8
|
+
import { findInvoices, listCustomers, listPriceItems, mirrorState } from './lookup.js';
|
|
8
9
|
import { createXeroRouter } from './routes.js';
|
|
9
|
-
import { createXeroRuntime, requireXeroSettings } from './runtime.js';
|
|
10
|
+
import { createXeroRuntime, requireXeroSettings, XERO_CALL_GUARD } from './runtime.js';
|
|
10
11
|
import { writesAllowed } from './settings.js';
|
|
11
12
|
|
|
12
13
|
// The Xero adapter (docs/XERO.md). FLOW_INTEGRATIONS=xero turns it on and
|
|
13
14
|
// XERO_MODE says which Xero it acts on. Its tables are created only while it
|
|
14
15
|
// is on (docs/INTEGRATIONS.md).
|
|
15
16
|
|
|
16
|
-
export const XERO_TABLES = Object.freeze(['xero_connections', 'xero_contacts', 'xero_items', 'xero_sync_runs', 'xero_invoice_pushes', 'xero_payment_cursors', 'xero_invoices', 'xero_credit_notes', 'xero_payments', 'xero_mirror_cursors']);
|
|
17
|
+
export const XERO_TABLES = Object.freeze(['xero_connections', 'xero_contacts', 'xero_items', 'xero_sync_runs', 'xero_invoice_pushes', 'xero_payment_cursors', 'xero_invoices', 'xero_credit_notes', 'xero_payments', 'xero_mirror_cursors', 'xero_call_guard', 'xero_calls', 'xero_webhook_events', 'xero_daily_checks']);
|
|
17
18
|
|
|
18
19
|
// What an owner enters in Settings, Integrations (server/integrations/setup.js).
|
|
19
20
|
// The refresh token's key comes from Flow's secrets key.
|
|
@@ -28,6 +29,7 @@ export const XERO_SETUP = {
|
|
|
28
29
|
'Redirect URI: copy it from below, exactly.',
|
|
29
30
|
'Open the app\'s Configuration. Copy the client id. Generate a secret and copy it: Xero shows it once.',
|
|
30
31
|
'Paste both below, choose the mode, name your Xero organisation, and turn Xero on.',
|
|
32
|
+
'Optional, for changes in seconds: open the app\'s Webhooks page. Delivery URL: this installation\'s address plus /api/xero/webhooks. Tick Contacts and Invoices, and Credit notes when Xero offers it. Copy the webhook key into "Webhook key" below and save, then press Send "Intent to receive" in Xero.',
|
|
31
33
|
],
|
|
32
34
|
},
|
|
33
35
|
fields: [
|
|
@@ -37,6 +39,7 @@ export const XERO_SETUP = {
|
|
|
37
39
|
{ name: 'XERO_CLIENT_SECRET', label: 'Client secret', secret: true, help: 'Stored encrypted. Flow never shows it again.' },
|
|
38
40
|
{ name: 'XERO_TENANT_NAME', label: 'Xero organisation name', help: 'Live mode connects only the organisation with this exact name.' },
|
|
39
41
|
{ name: 'XERO_ALLOW_LIVE_WRITES', label: 'Create draft invoices in live Xero', kind: 'onoff', help: 'Off: Flow only reads from Xero.' },
|
|
42
|
+
{ name: 'XERO_WEBHOOK_KEY', label: 'Webhook key', secret: true, help: 'From the Xero app\'s Webhooks page. Empty: Flow reads Xero\'s changes every 15 minutes instead.' },
|
|
40
43
|
],
|
|
41
44
|
derivedKeys: ['XERO_TOKEN_KEY'],
|
|
42
45
|
};
|
|
@@ -61,10 +64,16 @@ export function createXeroAdapter({ runtime: given = null } = {}) {
|
|
|
61
64
|
tables: [...XERO_TABLES],
|
|
62
65
|
},
|
|
63
66
|
setup: XERO_SETUP,
|
|
64
|
-
|
|
67
|
+
// Every Xero call goes through this call guard (docs/INTEGRATIONS.md,
|
|
68
|
+
// "Outbound calls").
|
|
69
|
+
callGuard: XERO_CALL_GUARD,
|
|
70
|
+
// `reconfigured` is true when a person saved the settings or turned Xero
|
|
71
|
+
// on: that clears a halt, stopped resources and an open circuit.
|
|
72
|
+
async start({ db, log, env, reconfigured = false }) {
|
|
65
73
|
database = db;
|
|
66
74
|
if (!given) runtime = createXeroRuntime({ settings: requireXeroSettings(env ?? process.env) });
|
|
67
75
|
const { settings } = current();
|
|
76
|
+
if (reconfigured) await current().guardFor(db).resume();
|
|
68
77
|
log.info?.(`[xero] mode ${settings.mode}; writes ${writesAllowed(settings) ? 'on' : 'off (XERO_ALLOW_LIVE_WRITES)'}; redirect URI ${settings.redirectUri ?? 'not set (FLOW_PUBLIC_ORIGIN)'}`);
|
|
69
78
|
// The history import (import.js) runs in the background outside replay
|
|
70
79
|
// mode. Replay tests run its slices directly.
|
|
@@ -81,8 +90,25 @@ export function createXeroAdapter({ runtime: given = null } = {}) {
|
|
|
81
90
|
capabilities: {
|
|
82
91
|
async health() {
|
|
83
92
|
const { settings } = current();
|
|
84
|
-
const { rows } = await database.execute(sql`select
|
|
85
|
-
|
|
93
|
+
const { rows } = await database.execute(sql`select organisation_id, tenant_id from xero_connections where mode = ${settings.mode}`);
|
|
94
|
+
const guard = current().guardFor(database);
|
|
95
|
+
const calls = await Promise.all(rows.map(async (r) => ({ tenantId: r.tenant_id, ...await guard.status(r.tenant_id) })));
|
|
96
|
+
const stopped = calls.some((c) => c.circuit !== 'closed' || c.stoppedResources.length || c.failedToday >= c.dailyFailureBudget);
|
|
97
|
+
// How fresh each copy of Xero is (lookup.js): a complete copy that is
|
|
98
|
+
// not fresh stops drafts by rule (issue #131).
|
|
99
|
+
const copies = await Promise.all(rows.map(async (r) => {
|
|
100
|
+
const { complete, fresh, lastPassAt } = await mirrorState(database, r.organisation_id);
|
|
101
|
+
return { tenantId: r.tenant_id, complete, fresh, lastPassAt };
|
|
102
|
+
}));
|
|
103
|
+
const stale = copies.some((c) => c.complete && !c.fresh);
|
|
104
|
+
return { ok: !stopped && !stale, mode: settings.mode, writesAllowed: writesAllowed(settings), connected: rows.length, calls, copies };
|
|
105
|
+
},
|
|
106
|
+
// What only a person can clear, for the Integrations page
|
|
107
|
+
// (server/core/alerts.js): a refused connection stops calls.
|
|
108
|
+
async alerts({ organisationId }) {
|
|
109
|
+
const connection = await readConnection(database, organisationId);
|
|
110
|
+
if (!connection || connection.mode !== current().settings.mode) return [];
|
|
111
|
+
return guardAlerts('Xero', await current().guardFor(database).status(connection.tenantId));
|
|
86
112
|
},
|
|
87
113
|
// One issued invoice to a Xero draft (drafts.js). The Flow invoice id
|
|
88
114
|
// and version are the idempotency key.
|
|
@@ -96,6 +122,9 @@ export function createXeroAdapter({ runtime: given = null } = {}) {
|
|
|
96
122
|
const connection = await readConnection(database, organisationId);
|
|
97
123
|
return { connected: Boolean(connection && connection.mode === settings.mode), writesAllowed: writesAllowed(settings) };
|
|
98
124
|
},
|
|
125
|
+
// What the customer's Xero copy of a Flow invoice version says, from
|
|
126
|
+
// Flow's copy of Xero (drafts.js; no calls). The invoice PDF uses it.
|
|
127
|
+
documentFacts: ({ organisationId, invoiceId, version = null }) => documentFacts(database, current(), { organisationId, invoiceId, version }),
|
|
99
128
|
// Sales invoice payments changed since `since` (ledger.js). The answer's
|
|
100
129
|
// cursor is the next `since`.
|
|
101
130
|
pullPayments: ({ organisationId, since }) => readPayments(database, current(), organisationId, { since: new Date(since) }),
|
|
@@ -106,6 +135,8 @@ export function createXeroAdapter({ runtime: given = null } = {}) {
|
|
|
106
135
|
listCustomers: ({ organisationId }) => listCustomers(database, organisationId),
|
|
107
136
|
// Sales invoices from the mirror, with the mirror's state (lookup.js).
|
|
108
137
|
findInvoices: ({ organisationId, ...query }) => findInvoices(database, organisationId, query),
|
|
138
|
+
// Xero items, from Flow's copy, for the price list (lookup.js).
|
|
139
|
+
listPriceItems: ({ organisationId }) => listPriceItems(database, organisationId, { taxTypes: current().settings.taxTypes }),
|
|
109
140
|
},
|
|
110
141
|
routes: ({ db, personAuth, log, messagePage }) => createXeroRouter({ db, personAuth, runtime: current(), log, messagePage }),
|
|
111
142
|
};
|
|
@@ -22,6 +22,32 @@ export async function listCustomers(db, organisationId) {
|
|
|
22
22
|
return rows.map((r) => ({ id: r.xero_contact_id, name: r.name }));
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
// Xero's items, from Flow's copy (catalogue.js, read on each sync), for the
|
|
26
|
+
// price list's links and price check (server/core/price-list.js). A tax type
|
|
27
|
+
// that charges GST reads as GST; any other set type reads as GST free.
|
|
28
|
+
const GST_TAX_TYPES = new Set(['OUTPUT', 'OUTPUT2']);
|
|
29
|
+
export async function listPriceItems(db, organisationId, { taxTypes = {} } = {}) {
|
|
30
|
+
const { rows } = await db.execute(sql`
|
|
31
|
+
select xero_item_id, code, name, description, is_sold, sales_unit_amount_cents, sales_tax_type, synced_at
|
|
32
|
+
from xero_items where organisation_id = ${organisationId} order by code`);
|
|
33
|
+
const taxOf = (type) => {
|
|
34
|
+
if (!type) return null;
|
|
35
|
+
return type === taxTypes.GST || GST_TAX_TYPES.has(type) ? 'GST' : 'GST_FREE';
|
|
36
|
+
};
|
|
37
|
+
return {
|
|
38
|
+
kind: 'accounting',
|
|
39
|
+
syncedAt: rows.reduce((at, r) => (!at || r.synced_at > at ? r.synced_at : at), null),
|
|
40
|
+
items: rows.map((r) => ({
|
|
41
|
+
id: r.xero_item_id,
|
|
42
|
+
code: r.code,
|
|
43
|
+
name: r.name || r.description || r.code,
|
|
44
|
+
unitAmountCents: r.sales_unit_amount_cents,
|
|
45
|
+
taxCode: taxOf(r.sales_tax_type),
|
|
46
|
+
sold: r.is_sold,
|
|
47
|
+
})),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
25
51
|
// Whether the mirror holds the whole history and was read lately. Until then a
|
|
26
52
|
// search that finds nothing proves nothing.
|
|
27
53
|
export async function mirrorState(db, organisationId, { now = new Date() } = {}) {
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
-- The call guard's state and telemetry (server/integrations/call-guard.js,
|
|
2
|
+
-- issue 111): one row per Xero organisation (tenant) with the circuit, a halt
|
|
3
|
+
-- and the resources Xero refused, and one row per call sent. A call row keeps
|
|
4
|
+
-- the resource and path, never the host, the query, a token or a response.
|
|
5
|
+
CREATE TABLE IF NOT EXISTS "xero_call_guard" (
|
|
6
|
+
"key" text PRIMARY KEY NOT NULL,
|
|
7
|
+
"circuit_open_until" timestamp with time zone DEFAULT 'epoch' NOT NULL,
|
|
8
|
+
"circuit_opens" integer DEFAULT 0 NOT NULL,
|
|
9
|
+
"halted_reason" text,
|
|
10
|
+
"halted_at" timestamp with time zone,
|
|
11
|
+
"stopped_resources" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
|
12
|
+
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
|
13
|
+
);
|
|
14
|
+
--> statement-breakpoint
|
|
15
|
+
CREATE TABLE IF NOT EXISTS "xero_calls" (
|
|
16
|
+
"id" bigserial PRIMARY KEY NOT NULL,
|
|
17
|
+
"key" text NOT NULL,
|
|
18
|
+
"at" timestamp with time zone NOT NULL,
|
|
19
|
+
"resource" text,
|
|
20
|
+
"request_path" text,
|
|
21
|
+
"status_code" integer,
|
|
22
|
+
"failure_kind" text,
|
|
23
|
+
"duration_ms" integer
|
|
24
|
+
);
|
|
25
|
+
--> statement-breakpoint
|
|
26
|
+
CREATE INDEX IF NOT EXISTS "xero_calls_window" ON "xero_calls" USING btree ("key","at");
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
-- Xero's webhooks and the daily check (issue #45). Each event Xero pushes, and
|
|
2
|
+
-- each record the daily check finds out of step, waits here until Flow reads
|
|
3
|
+
-- that record by id into its copy. One row per record: a second event for the
|
|
4
|
+
-- same record before it is read only marks it pending again.
|
|
5
|
+
CREATE TABLE IF NOT EXISTS "xero_webhook_events" (
|
|
6
|
+
"organisation_id" uuid NOT NULL REFERENCES "organisations"("id"),
|
|
7
|
+
"resource" text NOT NULL,
|
|
8
|
+
"resource_id" text NOT NULL,
|
|
9
|
+
"event_type" text,
|
|
10
|
+
"source" text NOT NULL,
|
|
11
|
+
"event_at" timestamp with time zone,
|
|
12
|
+
"received_at" timestamp with time zone DEFAULT now() NOT NULL,
|
|
13
|
+
"pending" boolean DEFAULT true NOT NULL,
|
|
14
|
+
"read_at" timestamp with time zone,
|
|
15
|
+
CONSTRAINT "xero_webhook_events_pk" PRIMARY KEY("organisation_id", "resource", "resource_id")
|
|
16
|
+
);
|
|
17
|
+
--> statement-breakpoint
|
|
18
|
+
CREATE INDEX IF NOT EXISTS "xero_webhook_events_pending" ON "xero_webhook_events" ("organisation_id", "resource") WHERE "pending";
|
|
19
|
+
--> statement-breakpoint
|
|
20
|
+
CREATE INDEX IF NOT EXISTS "xero_webhook_events_received" ON "xero_webhook_events" ("organisation_id", "source", "received_at");
|
|
21
|
+
--> statement-breakpoint
|
|
22
|
+
-- One full summary read of the invoices a day for each organisation.
|
|
23
|
+
CREATE TABLE IF NOT EXISTS "xero_daily_checks" (
|
|
24
|
+
"organisation_id" uuid PRIMARY KEY NOT NULL REFERENCES "organisations"("id"),
|
|
25
|
+
"last_started_at" timestamp with time zone,
|
|
26
|
+
"last_finished_at" timestamp with time zone,
|
|
27
|
+
"last_read" integer,
|
|
28
|
+
"last_flagged" integer,
|
|
29
|
+
"last_error" text
|
|
30
|
+
);
|
|
@@ -43,6 +43,20 @@
|
|
|
43
43
|
"when": 1792406000000,
|
|
44
44
|
"tag": "0005_xero_send_modes",
|
|
45
45
|
"breakpoints": true
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
"idx": 6,
|
|
49
|
+
"version": "7",
|
|
50
|
+
"when": 1792490000000,
|
|
51
|
+
"tag": "0006_xero_call_guard",
|
|
52
|
+
"breakpoints": true
|
|
53
|
+
},
|
|
54
|
+
{
|
|
55
|
+
"idx": 7,
|
|
56
|
+
"version": "7",
|
|
57
|
+
"when": 1792500000000,
|
|
58
|
+
"tag": "0007_xero_webhooks",
|
|
59
|
+
"breakpoints": true
|
|
46
60
|
}
|
|
47
61
|
]
|
|
48
62
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto';
|
|
2
2
|
import { sql } from 'drizzle-orm';
|
|
3
|
+
import { isCallsStopped } from '../call-guard.js';
|
|
3
4
|
import { parseXeroDate } from './catalogue.js';
|
|
4
5
|
import { withXeroLane } from './governor.js';
|
|
5
6
|
|
|
@@ -181,6 +182,20 @@ const UPSERT = {
|
|
|
181
182
|
const MAPPERS = { invoices: mapInvoice, credit_notes: mapCreditNote, payments: mapPayment };
|
|
182
183
|
const ID_OF = { invoices: 'xeroInvoiceId', credit_notes: 'xeroCreditNoteId', payments: 'xeroPaymentId' };
|
|
183
184
|
|
|
185
|
+
// Xero records as the copy's rows.
|
|
186
|
+
export const mapRecords = (resource, raw, settings) => raw.map((record) => MAPPERS[resource](record, settings)).filter((r) => r[ID_OF[resource]]);
|
|
187
|
+
|
|
188
|
+
// Writes each mapped row to the copy. `tx` is a transaction or the database.
|
|
189
|
+
// Adds to `counts` (inserted, changed, unchanged).
|
|
190
|
+
export async function storeRows(tx, organisationId, resource, rows, counts) {
|
|
191
|
+
for (const row of rows) {
|
|
192
|
+
const { rows: written } = await tx.execute(UPSERT[resource](organisationId, row, hashOf(row)));
|
|
193
|
+
if (!written.length) counts.unchanged += 1;
|
|
194
|
+
else if (written[0].inserted) counts.inserted += 1;
|
|
195
|
+
else counts.changed += 1;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
184
199
|
async function readCursor(db, organisationId, resource) {
|
|
185
200
|
await db.execute(sql`insert into xero_mirror_cursors (organisation_id, resource) values (${organisationId}, ${resource})
|
|
186
201
|
on conflict do nothing`);
|
|
@@ -212,7 +227,6 @@ export function nextPosition({ modifiedSince, page }, rows, pageSize) {
|
|
|
212
227
|
export async function mirrorResource(db, runtime, organisationId, resource, { maxPages = 50 } = {}) {
|
|
213
228
|
if (!MIRROR_RESOURCES.includes(resource)) throw new TypeError(`unknown Xero mirror resource: ${resource}`);
|
|
214
229
|
const { settings } = runtime;
|
|
215
|
-
const map = MAPPERS[resource];
|
|
216
230
|
const pageSize = settings.mirrorPageSize;
|
|
217
231
|
const counts = { pages: 0, read: 0, inserted: 0, changed: 0, unchanged: 0 };
|
|
218
232
|
return withXeroLane('sync', async () => {
|
|
@@ -232,15 +246,10 @@ export async function mirrorResource(db, runtime, organisationId, resource, { ma
|
|
|
232
246
|
where organisation_id = ${organisationId} and resource = ${resource}`);
|
|
233
247
|
throw error;
|
|
234
248
|
}
|
|
235
|
-
const rows =
|
|
249
|
+
const rows = mapRecords(resource, raw, settings);
|
|
236
250
|
const next = nextPosition(position, rows, pageSize);
|
|
237
251
|
await db.transaction(async (tx) => {
|
|
238
|
-
|
|
239
|
-
const { rows: written } = await tx.execute(UPSERT[resource](organisationId, row, hashOf(row)));
|
|
240
|
-
if (!written.length) counts.unchanged += 1;
|
|
241
|
-
else if (written[0].inserted) counts.inserted += 1;
|
|
242
|
-
else counts.changed += 1;
|
|
243
|
-
}
|
|
252
|
+
await storeRows(tx, organisationId, resource, rows, counts);
|
|
244
253
|
await tx.execute(sql`update xero_mirror_cursors set
|
|
245
254
|
modified_since = ${next.modifiedSince}, page = ${next.page}, rows_read = rows_read + ${raw.length},
|
|
246
255
|
last_read_at = now(), last_error = null,
|
|
@@ -257,12 +266,20 @@ export async function mirrorResource(db, runtime, organisationId, resource, { ma
|
|
|
257
266
|
}
|
|
258
267
|
|
|
259
268
|
// Reads each resource in turn, one organisation at a time with any other Xero
|
|
260
|
-
// work for it (runtime.serial).
|
|
269
|
+
// work for it (runtime.serial). A resource Xero refused (the call guard
|
|
270
|
+
// stopped it: the connection lacks its scope) is skipped as `refused`, so
|
|
271
|
+
// the others still read.
|
|
261
272
|
export async function mirrorXero(db, runtime, organisationId, { resources = MIRROR_RESOURCES, maxPages } = {}) {
|
|
262
273
|
return runtime.serial(organisationId, async () => {
|
|
263
274
|
const results = [];
|
|
264
275
|
for (const resource of resources) {
|
|
265
|
-
|
|
276
|
+
let result;
|
|
277
|
+
try {
|
|
278
|
+
result = await mirrorResource(db, runtime, organisationId, resource, { maxPages });
|
|
279
|
+
} catch (error) {
|
|
280
|
+
if (!isCallsStopped(error) || error.reason !== 'resource_stopped') throw error;
|
|
281
|
+
result = { resource, pages: 0, read: 0, inserted: 0, changed: 0, unchanged: 0, stopped: 'refused' };
|
|
282
|
+
}
|
|
266
283
|
results.push(result);
|
|
267
284
|
if (result.stopped === 'budget') break;
|
|
268
285
|
}
|
|
@@ -53,7 +53,10 @@ async function tokenRequest(settings, fetchImpl, form, what) {
|
|
|
53
53
|
if (body?.error === 'invalid_grant') {
|
|
54
54
|
throw xeroError('xero_reconnect_needed', 'Xero no longer accepts this connection. An owner must connect Xero again.', { status: 409 });
|
|
55
55
|
}
|
|
56
|
-
throw xeroError('xero_token_failed', `Xero refused ${what} (${response.status}${body?.error ? `, ${body.error}` : ''}).`, {
|
|
56
|
+
throw xeroError('xero_token_failed', `Xero refused ${what} (${response.status}${body?.error ? `, ${body.error}` : ''}).`, {
|
|
57
|
+
status: 502,
|
|
58
|
+
oauthError: typeof body?.error === 'string' ? body.error.slice(0, 40) : null,
|
|
59
|
+
});
|
|
57
60
|
}
|
|
58
61
|
if (!body?.access_token || !body?.refresh_token) {
|
|
59
62
|
throw xeroError('xero_token_failed', `Xero's answer to ${what} had no tokens.`, { status: 502 });
|