@arcforgelabs/flow 2026.10.25 → 2026.10.27

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/README.md +6 -0
  2. package/npm-shrinkwrap.json +627 -2
  3. package/package.json +3 -1
  4. package/server/api/invoicing.js +586 -0
  5. package/server/app.js +38 -1
  6. package/server/auth/people.js +26 -0
  7. package/server/auth/routes.js +13 -0
  8. package/server/core/automations.js +140 -0
  9. package/server/core/invoice-rules.js +224 -0
  10. package/server/core/invoices.js +11 -1
  11. package/server/core/invoicing-rules.js +255 -0
  12. package/server/core/ledger.js +50 -14
  13. package/server/core/links.js +3 -3
  14. package/server/core/monitoring.js +34 -0
  15. package/server/core/pipeline.js +495 -0
  16. package/server/core/sending.js +282 -0
  17. package/server/db/migrations/0008_people_appearance.sql +1 -0
  18. package/server/db/migrations/0009_pipeline_matcher.sql +46 -0
  19. package/server/db/migrations/0010_invoicing_rules.sql +51 -0
  20. package/server/db/migrations/0011_invoice_rules.sql +21 -0
  21. package/server/db/migrations/0012_invoice_sending.sql +9 -0
  22. package/server/db/migrations/meta/0008_snapshot.json +2479 -0
  23. package/server/db/migrations/meta/0009_snapshot.json +2809 -0
  24. package/server/db/migrations/meta/0010_snapshot.json +3158 -0
  25. package/server/db/migrations/meta/0011_snapshot.json +3314 -0
  26. package/server/db/migrations/meta/0012_snapshot.json +3380 -0
  27. package/server/db/migrations/meta/_journal.json +35 -0
  28. package/server/db/schema.js +186 -2
  29. package/server/index.js +20 -3
  30. package/server/integrations/adapters.js +2 -1
  31. package/server/integrations/port.js +8 -0
  32. package/server/integrations/seazona/feed.js +11 -0
  33. package/server/integrations/seazona/index.js +7 -1
  34. package/server/integrations/seazona/ledger.js +4 -0
  35. package/server/integrations/sentry/index.js +105 -0
  36. package/server/integrations/xero/client.js +5 -0
  37. package/server/integrations/xero/drafts.js +123 -16
  38. package/server/integrations/xero/import.js +22 -0
  39. package/server/integrations/xero/index.js +21 -3
  40. package/server/integrations/xero/lookup.js +94 -0
  41. package/server/integrations/xero/migrations/0005_xero_send_modes.sql +10 -0
  42. package/server/integrations/xero/migrations/meta/_journal.json +7 -0
  43. package/server/theme/color-contrast.js +39 -2
  44. package/server/theme/contrast-audit.js +63 -0
  45. package/server/theme/themes.js +10 -2
  46. package/server/ui/app-page.js +6 -10
  47. package/server/ui/app.js +364 -105
  48. package/server/ui/appearance.js +3 -2
  49. package/server/ui/automations.js +96 -0
  50. package/server/ui/clerk-appearance.js +18 -2
  51. package/server/ui/flow.css +334 -22
  52. package/server/ui/invoice-rules.js +237 -0
  53. package/server/ui/invoicing-settings.js +108 -0
  54. package/server/ui/invoicing.js +597 -0
  55. package/server/ui/jobs.js +172 -0
  56. package/server/ui/logos/seazona.svg +1 -0
  57. package/server/ui/logos/sentry.svg +1 -0
  58. package/server/ui/logos/xero.svg +1 -0
  59. package/server/ui/monitoring.js +53 -0
  60. package/server/ui/routes.js +5 -1
@@ -0,0 +1,255 @@
1
+ import { and, eq, inArray, isNull, sql } from 'drizzle-orm';
2
+ import {
3
+ billingObligations, contacts, customerBillingSettings, invoicingSettings, SEND_MODES,
4
+ } from '../db/schema.js';
5
+ import { FlowError, notFound } from './errors.js';
6
+ import { listRules, ruleReasons } from './invoice-rules.js';
7
+ import { draftInvoiceForObligation } from './ledger.js';
8
+
9
+ // Invoicing rules (docs/INVOICING_RULES.md). They are the checks a job that
10
+ // is ready to invoice passes before Flow drafts its invoice, and how a checked
11
+ // draft goes to the accounting system. Each rule is a setting of the
12
+ // organisation; a customer can override some of them. The rules come from
13
+ // the earlier lab app, where they were fixed in its code. When Flow drafts is
14
+ // an automation (automations.js): Flow's own "ready to invoice" stage
15
+ // triggers it, never another system's status.
16
+ //
17
+ // The ledger's own checks (ledger.js, draftBlockers) still guard every draft:
18
+ // the job is not held, every line maps to a price item, it has a customer, the
19
+ // accounting copy holds no invoice for it, and the work system's report is
20
+ // recent. The lab's own checks are invoice rules it builds (invoice-rules.js);
21
+ // the old job limit, practitioner and rush settings here only seed them.
22
+
23
+ export const ACTOR = 'system:rules';
24
+ const DRAFT_BATCH = 200;
25
+
26
+ export const INVOICING_DEFAULTS = Object.freeze({
27
+ sendMode: 'accounting_draft',
28
+ staleDays: 90,
29
+ paymentTermsDays: 30,
30
+ requirePractitioner: false,
31
+ rushItemCode: null,
32
+ rushPercent: 20,
33
+ });
34
+
35
+ const CUSTOMER_DEFAULTS = Object.freeze({
36
+ billable: true, defaultPractitioner: null, autoDraft: null, sendMode: null, paymentTermsDays: null,
37
+ });
38
+
39
+ const pick = (row, keys) => Object.fromEntries(keys.map((k) => [k, row[k]]));
40
+ const SETTING_KEYS = Object.keys(INVOICING_DEFAULTS);
41
+ const CUSTOMER_KEYS = Object.keys(CUSTOMER_DEFAULTS);
42
+
43
+ const invalid = (message) => new FlowError('invalid', message);
44
+
45
+ function wholeNumber(value, name, min, max) {
46
+ if (!Number.isInteger(value) || value < min || value > max) throw invalid(`${name} must be a whole number from ${min} to ${max}`);
47
+ return value;
48
+ }
49
+
50
+ function flag(value, name) {
51
+ if (typeof value !== 'boolean') throw invalid(`${name} must be true or false`);
52
+ return value;
53
+ }
54
+
55
+ function shortText(value, name) {
56
+ if (value === null || value === '') return null;
57
+ if (typeof value !== 'string' || value.length > 200) throw invalid(`${name} must be text of 200 characters at most`);
58
+ return value.trim() || null;
59
+ }
60
+
61
+ function sendMode(value, name) {
62
+ if (!SEND_MODES.includes(value)) throw invalid(`${name} must be one of ${SEND_MODES.join(', ')}`);
63
+ return value;
64
+ }
65
+
66
+ // The organisation's settings as stored, or the defaults.
67
+ export async function readInvoicingSettings(db, organisationId) {
68
+ const [row] = await db.select().from(invoicingSettings).where(eq(invoicingSettings.organisationId, organisationId));
69
+ return row ? pick(row, SETTING_KEYS) : { ...INVOICING_DEFAULTS };
70
+ }
71
+
72
+ function readSettingChanges(changes) {
73
+ if (!changes || typeof changes !== 'object' || Array.isArray(changes)) throw invalid('the settings must be an object');
74
+ const out = {};
75
+ for (const [key, value] of Object.entries(changes)) {
76
+ if (key === 'requirePractitioner') out[key] = flag(value, key);
77
+ else if (key === 'sendMode') out[key] = sendMode(value, key);
78
+ else if (key === 'staleDays') out[key] = wholeNumber(value, key, 1, 3650);
79
+ else if (key === 'paymentTermsDays') out[key] = wholeNumber(value, key, 0, 365);
80
+ else if (key === 'rushPercent') out[key] = wholeNumber(value, key, 0, 100);
81
+ else if (key === 'rushItemCode') out[key] = shortText(value, key);
82
+ else throw invalid(`unknown setting: ${key}`);
83
+ }
84
+ return out;
85
+ }
86
+
87
+ export async function saveInvoicingSettings(db, organisationId, changes, { personId = null } = {}) {
88
+ const fields = readSettingChanges(changes);
89
+ await db.insert(invoicingSettings)
90
+ .values({ organisationId, ...fields, updatedBy: personId })
91
+ .onConflictDoUpdate({ target: invoicingSettings.organisationId, set: { ...fields, updatedBy: personId, updatedAt: sql`now()` } });
92
+ return readInvoicingSettings(db, organisationId);
93
+ }
94
+
95
+ async function requireCustomer(db, organisationId, contactId) {
96
+ const [contact] = await db.select({ id: contacts.id, kind: contacts.kind }).from(contacts)
97
+ .where(and(eq(contacts.organisationId, organisationId), eq(contacts.id, contactId)));
98
+ if (!contact) throw notFound('customer');
99
+ if (contact.kind !== 'customer') throw invalid('invoicing settings are for a customer contact');
100
+ }
101
+
102
+ // One customer's own settings. A null value takes the organisation's setting.
103
+ export async function readCustomerBilling(db, organisationId, contactId) {
104
+ await requireCustomer(db, organisationId, contactId);
105
+ const [row] = await db.select().from(customerBillingSettings)
106
+ .where(and(eq(customerBillingSettings.organisationId, organisationId), eq(customerBillingSettings.contactId, contactId)));
107
+ return row ? pick(row, CUSTOMER_KEYS) : { ...CUSTOMER_DEFAULTS };
108
+ }
109
+
110
+ export async function saveCustomerBilling(db, organisationId, contactId, changes, { personId = null } = {}) {
111
+ if (!changes || typeof changes !== 'object' || Array.isArray(changes)) throw invalid('the settings must be an object');
112
+ await requireCustomer(db, organisationId, contactId);
113
+ const fields = {};
114
+ for (const [key, value] of Object.entries(changes)) {
115
+ if (key === 'billable') fields[key] = flag(value, key);
116
+ else if (key === 'defaultPractitioner') fields[key] = shortText(value, key);
117
+ else if (key === 'autoDraft') fields[key] = value === null ? null : flag(value, key);
118
+ else if (key === 'sendMode') fields[key] = value === null ? null : sendMode(value, key);
119
+ else if (key === 'paymentTermsDays') fields[key] = value === null ? null : wholeNumber(value, key, 0, 365);
120
+ else throw invalid(`unknown setting: ${key}`);
121
+ }
122
+ await db.insert(customerBillingSettings)
123
+ .values({ organisationId, contactId, ...fields, updatedBy: personId })
124
+ .onConflictDoUpdate({
125
+ target: [customerBillingSettings.organisationId, customerBillingSettings.contactId],
126
+ set: { ...fields, updatedBy: personId, updatedAt: sql`now()` },
127
+ });
128
+ return readCustomerBilling(db, organisationId, contactId);
129
+ }
130
+
131
+ // The customers' own settings, by contact id.
132
+ export async function customerBillingByContact(db, organisationId, contactIds) {
133
+ const ids = [...new Set(contactIds.filter(Boolean))];
134
+ if (!ids.length) return new Map();
135
+ const rows = await db.select().from(customerBillingSettings)
136
+ .where(and(eq(customerBillingSettings.organisationId, organisationId), inArray(customerBillingSettings.contactId, ids)));
137
+ return new Map(rows.map((r) => [r.contactId, pick(r, CUSTOMER_KEYS)]));
138
+ }
139
+
140
+ // The settings that apply to one customer: its own, else the organisation's.
141
+ // `autoDraft` is the customer's own switch for the draft automation.
142
+ export function effectiveSettings(settings, customer = CUSTOMER_DEFAULTS) {
143
+ const own = { ...CUSTOMER_DEFAULTS, ...customer };
144
+ return {
145
+ ...settings,
146
+ billable: own.billable,
147
+ defaultPractitioner: own.defaultPractitioner,
148
+ autoDraft: own.autoDraft ?? true,
149
+ sendMode: own.sendMode ?? settings.sendMode,
150
+ paymentTermsDays: own.paymentTermsDays ?? settings.paymentTermsDays,
151
+ };
152
+ }
153
+
154
+ // How one customer's checked drafts go to the accounting system.
155
+ export async function sendModeFor(db, organisationId, contactId) {
156
+ const settings = await readInvoicingSettings(db, organisationId);
157
+ const customers = await customerBillingByContact(db, organisationId, [contactId]);
158
+ return effectiveSettings(settings, customers.get(contactId)).sendMode;
159
+ }
160
+
161
+ // What a job still waits on before Flow drafts it, as reasons a person can
162
+ // read: Flow's own ready stage, then the lab's invoice rules (invoice-rules.js)
163
+ // in their order. An empty list means the job may be drafted. `rules` is the
164
+ // organisation's rules, read once per run with listRules.
165
+ export function ruleBlockers(obligation, effective, { now = new Date(), rules = [] } = {}) {
166
+ const reasons = [];
167
+ if (!obligation.readyAt) reasons.push('the job is not marked ready to invoice');
168
+ return [...reasons, ...ruleReasons(rules, obligation, { customer: effective, now })];
169
+ }
170
+
171
+ function addDays(date, days) {
172
+ const at = new Date(`${date}T00:00:00Z`);
173
+ at.setUTCDate(at.getUTCDate() + days);
174
+ return at.toISOString().slice(0, 10);
175
+ }
176
+
177
+ const isoDay = (at) => `${at.getFullYear()}-${String(at.getMonth() + 1).padStart(2, '0')}-${String(at.getDate()).padStart(2, '0')}`;
178
+
179
+ // The ledger's live check, answered from the accounting system's copy in Flow
180
+ // instead of a call for each job: the copy is complete and was read lately,
181
+ // the matcher checked the job after the copy last changed, and the copy holds
182
+ // no invoice with the job's own invoice number.
183
+ export function copyCheck(accounting, organisationId) {
184
+ return async (obligation) => {
185
+ const { complete, fresh, changedAt, invoices } = await accounting.capabilities.findInvoices({
186
+ organisationId,
187
+ numbers: obligation.sourceInvoiceRef ? [obligation.sourceInvoiceRef] : [],
188
+ });
189
+ if (!complete || !fresh) throw new Error('the accounting copy is not complete or not fresh');
190
+ if (obligation.accountingState !== 'not_found') return { state: obligation.accountingState, matchedBy: 'copy' };
191
+ if (changedAt && (!obligation.accountingCheckedAt || new Date(obligation.accountingCheckedAt) < changedAt)) {
192
+ throw new Error('the accounting copy changed after the job was last matched');
193
+ }
194
+ const sales = invoices.filter((i) => !['voided', 'deleted'].includes(i.state));
195
+ if (sales.length) return { state: sales[0].state, accountingRef: sales[0].id, matchedBy: 'copy' };
196
+ return { state: 'not_found', matchedBy: 'copy' };
197
+ };
198
+ }
199
+
200
+ // Drafts the invoice of each job that is ready to invoice and passes the
201
+ // ledger's checks and every rule, except for customers whose drafting is off.
202
+ // It writes only Flow's own records: the drafts wait in Flow for a person.
203
+ // The draft automation (automations.js) runs it. Answers counts.
204
+ // With `accounting` null no accounting system is connected: Flow's own records
205
+ // are the only check, as for a person's draft (ledger.js, ledgerView).
206
+ export async function autoDraftJobs(db, organisationId, { accounting = null, now = new Date(), limit = DRAFT_BATCH, actor = ACTOR }) {
207
+ const result = { drafted: 0, waiting: 0, off: 0, refused: 0 };
208
+ const settings = await readInvoicingSettings(db, organisationId);
209
+ const rules = await listRules(db, organisationId);
210
+ if (accounting) {
211
+ const mirror = await accounting.capabilities.findInvoices({ organisationId });
212
+ if (!mirror.complete || !mirror.fresh) return { ...result, skipped: 'the accounting copy is not complete or not fresh' };
213
+ }
214
+
215
+ const candidates = await db.select().from(billingObligations).where(and(
216
+ eq(billingObligations.organisationId, organisationId),
217
+ isNull(billingObligations.invoiceId),
218
+ sql`${billingObligations.readyAt} is not null`,
219
+ eq(billingObligations.holdState, 'none'),
220
+ accounting
221
+ ? eq(billingObligations.accountingState, 'not_found')
222
+ : inArray(billingObligations.accountingState, ['not_found', 'unknown']),
223
+ eq(billingObligations.mappingComplete, true),
224
+ sql`${billingObligations.contactId} is not null`,
225
+ // Newest first: a backlog of jobs that wait on a rule never hides new work.
226
+ )).orderBy(sql`${billingObligations.jobDate} desc nulls last`, billingObligations.id).limit(limit);
227
+ const customers = await customerBillingByContact(db, organisationId, candidates.map((o) => o.contactId));
228
+ const liveCheck = accounting ? copyCheck(accounting, organisationId) : null;
229
+ const invoiceDate = isoDay(now);
230
+
231
+ for (const obligation of candidates) {
232
+ const effective = effectiveSettings(settings, customers.get(obligation.contactId));
233
+ if (!effective.autoDraft) {
234
+ result.off += 1;
235
+ continue;
236
+ }
237
+ if (ruleBlockers(obligation, effective, { now, rules }).length) {
238
+ result.waiting += 1;
239
+ continue;
240
+ }
241
+ try {
242
+ await draftInvoiceForObligation(db, organisationId, obligation.id, {
243
+ liveCheck,
244
+ actor,
245
+ now,
246
+ dueDate: addDays(invoiceDate, effective.paymentTermsDays),
247
+ });
248
+ result.drafted += 1;
249
+ } catch (error) {
250
+ if (error.code !== 'not_ready') throw error;
251
+ result.refused += 1;
252
+ }
253
+ }
254
+ return result;
255
+ }
@@ -8,16 +8,18 @@ import { createDraftInvoice } from './invoices.js';
8
8
  import { invoiceTotals, lineTotals } from './money.js';
9
9
 
10
10
  // The billing obligation ledger. One billable job in a work system is one
11
- // obligation. Its view (Ready, Pending, Held, Drafted, Invoiced, Paid, Review
12
- // required) comes only from the evidence stored on it, never from a fresh
11
+ // obligation. Its view (In work, Ready, Pending, Held, Drafted, Invoiced,
12
+ // Paid, Review required) comes only from the evidence stored on it, never from a fresh
13
13
  // guess, and each change of evidence is an event. To make a draft invoice is a
14
14
  // guarded transition that fails closed.
15
15
 
16
16
  // How old the work system's report of a job may be when Flow drafts its invoice.
17
17
  export const SOURCE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
18
18
 
19
- // Ways to tie accounting evidence to a job that are exact, not a guess.
20
- export const EXACT_MATCHES = ['flow_invoice', 'source_invoice_ref', 'accounting_ref'];
19
+ // Ways to tie accounting evidence to a job that are exact, not a guess:
20
+ // `prior_link` is a link the earlier installation held, checked against the
21
+ // accounting mirror; `person` is a link a person chose.
22
+ export const EXACT_MATCHES = ['flow_invoice', 'source_invoice_ref', 'accounting_ref', 'prior_link', 'person'];
21
23
 
22
24
  const LINKED_STATES = ['drafted', 'authorised', 'part_paid', 'paid', 'voided', 'deleted'];
23
25
 
@@ -30,8 +32,11 @@ async function loadObligation(tx, organisationId, obligationId, { lock = false }
30
32
  return row;
31
33
  }
32
34
 
35
+ // clock_timestamp, not now(): events written in one transaction keep their
36
+ // order when they are read back by time.
33
37
  async function addEvent(tx, obligation, kind, actor, evidence = {}) {
34
38
  await tx.insert(obligationEvents).values({
39
+ createdAt: sql`clock_timestamp()`,
35
40
  organisationId: obligation.organisationId,
36
41
  obligationId: obligation.id,
37
42
  kind,
@@ -107,6 +112,8 @@ export async function observeJob(db, organisationId, job) {
107
112
  contactId: job.contactId ?? null,
108
113
  practitioner: job.practitioner ?? null,
109
114
  shippedOn: job.shippedOn ?? null,
115
+ jobDate: job.jobDate ?? null,
116
+ sourceStatus: job.sourceStatus ?? null,
110
117
  lines,
111
118
  lineFingerprint: fingerprint(lines),
112
119
  ...invoiceTotals(lines),
@@ -135,7 +142,9 @@ export async function observeJob(db, organisationId, job) {
135
142
  const changed = ['sourceInvoiceRef', 'caseRef', 'contactId', 'practitioner', 'shippedOn', 'lineFingerprint', 'totalCents']
136
143
  .filter((key) => String(existing[key] ?? '') !== String(facts[key] ?? ''));
137
144
  if (!changed.length) {
138
- return update(tx, existing, { sourceSeenAt: seenAt, mappingComplete: facts.mappingComplete, lines });
145
+ return update(tx, existing, {
146
+ sourceSeenAt: seenAt, mappingComplete: facts.mappingComplete, lines, jobDate: facts.jobDate, sourceStatus: facts.sourceStatus,
147
+ });
139
148
  }
140
149
  const fields = { ...facts, sourceSeenAt: seenAt };
141
150
  if (existing.invoiceId && changed.some((key) => ['lineFingerprint', 'totalCents', 'contactId'].includes(key))) {
@@ -310,6 +319,20 @@ export async function recordWritebackResult(db, organisationId, writebackId, { o
310
319
  });
311
320
  }
312
321
 
322
+ // Marks a job ready to invoice, or back in work. `actor` is a person or the
323
+ // automation that decided. A job with an invoice stays as it is.
324
+ export async function setReady(db, organisationId, obligationId, { ready = true, actor }) {
325
+ requireActor(actor);
326
+ return db.transaction(async (tx) => {
327
+ const obligation = await loadObligation(tx, organisationId, obligationId, { lock: true });
328
+ if (Boolean(obligation.readyAt) === ready) return obligation;
329
+ if (!ready && obligation.invoiceId) throw new FlowError('invalid', 'the job has an invoice already');
330
+ const row = await update(tx, obligation, ready ? { readyAt: sql`now()`, readyBy: actor } : { readyAt: null, readyBy: null });
331
+ await addEvent(tx, row, ready ? 'ready' : 'in_work', actor, {});
332
+ return row;
333
+ });
334
+ }
335
+
313
336
  // Puts an obligation on hold, sends it to review, or releases it.
314
337
  export async function setHold(db, organisationId, obligationId, { holdState, reason = null, actor }) {
315
338
  requireActor(actor);
@@ -326,7 +349,9 @@ export async function setHold(db, organisationId, obligationId, { holdState, rea
326
349
  }
327
350
 
328
351
  // The obligation's view and the reasons for it, from its stored evidence only.
329
- export function ledgerView(obligation, { now = new Date(), sourceMaxAgeMs = SOURCE_MAX_AGE_MS } = {}) {
352
+ // `accounting` is false while no accounting system is connected: Flow's own
353
+ // records are then the only check, so a job nobody checked in one can draft.
354
+ export function ledgerView(obligation, { now = new Date(), sourceMaxAgeMs = SOURCE_MAX_AGE_MS, accounting = true } = {}) {
330
355
  const o = obligation;
331
356
  if (o.holdState === 'review') return { view: 'review_required', reasons: [o.holdReason ?? 'sent to review'] };
332
357
  if (['ambiguous', 'conflict'].includes(o.accountingState)) {
@@ -341,15 +366,20 @@ export function ledgerView(obligation, { now = new Date(), sourceMaxAgeMs = SOUR
341
366
  return { view: 'invoiced', reasons: [`invoice ${o.accountingRef} is ${o.accountingState.replace('_', ' ')}`] };
342
367
  }
343
368
  if (o.invoiceId || o.accountingState === 'drafted') return { view: 'drafted', reasons: ['a draft invoice exists'] };
344
- const reasons = draftBlockers(o, { now, sourceMaxAgeMs });
369
+ const reasons = draftBlockers(o, { now, sourceMaxAgeMs, accounting });
370
+ // Flow's own stage: a job is in work until a person or an automation marks
371
+ // it ready to invoice (setReady).
372
+ if (!o.readyAt) return { view: 'in_work', reasons: ['the job is not marked ready to invoice', ...reasons] };
345
373
  return reasons.length ? { view: 'pending', reasons } : { view: 'ready', reasons: ['all checks pass'] };
346
374
  }
347
375
 
348
- function draftBlockers(o, { now, sourceMaxAgeMs }) {
376
+ function draftBlockers(o, { now, sourceMaxAgeMs, accounting = true }) {
349
377
  const reasons = [];
350
378
  if (o.holdState !== 'none') reasons.push(`the job is ${o.holdState}`);
351
379
  if (o.invoiceId) reasons.push('the job already has an invoice');
352
- if (o.accountingState === 'unknown') reasons.push('the accounting system was not checked');
380
+ if (o.accountingState === 'unknown') {
381
+ if (accounting) reasons.push('the accounting system was not checked');
382
+ }
353
383
  else if (o.accountingState !== 'not_found') reasons.push(`the accounting system reports ${o.accountingState}`);
354
384
  if (!o.mappingComplete) reasons.push('a line does not map to a price item');
355
385
  if (!o.contactId) reasons.push('the job has no customer contact');
@@ -362,15 +392,17 @@ function draftBlockers(o, { now, sourceMaxAgeMs }) {
362
392
  // the write, finds no invoice for the job. Any doubt refuses the draft, and
363
393
  // the refusal is recorded.
364
394
  export async function draftInvoiceForObligation(db, organisationId, obligationId, {
365
- liveCheck, actor, now = new Date(), sourceMaxAgeMs = SOURCE_MAX_AGE_MS,
395
+ liveCheck, actor, now = new Date(), sourceMaxAgeMs = SOURCE_MAX_AGE_MS, dueDate = null,
366
396
  }) {
367
397
  requireActor(actor);
368
- if (typeof liveCheck !== 'function') throw new FlowError('invalid', 'liveCheck is required');
398
+ // A null liveCheck says no accounting system is connected (ledgerView).
399
+ if (liveCheck !== null && typeof liveCheck !== 'function') throw new FlowError('invalid', 'liveCheck must be a function, or null with no accounting system');
400
+ const accounting = liveCheck !== null;
369
401
  const outcome = await db.transaction(async (tx) => {
370
402
  const obligation = await loadObligation(tx, organisationId, obligationId, { lock: true });
371
- const reasons = draftBlockers(obligation, { now, sourceMaxAgeMs });
403
+ const reasons = draftBlockers(obligation, { now, sourceMaxAgeMs, accounting });
372
404
  let live = null;
373
- if (!reasons.length) {
405
+ if (!reasons.length && accounting) {
374
406
  try {
375
407
  live = await liveCheck(obligation);
376
408
  } catch (error) {
@@ -385,11 +417,15 @@ export async function draftInvoiceForObligation(db, organisationId, obligationId
385
417
  const invoice = await createDraftInvoice(tx, organisationId, {
386
418
  contactId: obligation.contactId,
387
419
  reference: obligation.caseRef ?? obligation.sourceJobRef,
420
+ dueDate,
388
421
  lines: obligation.lines.map(({ priceItemId, description, quantity, unitAmountCents, taxCode }) => (
389
422
  { priceItemId, description, quantity, unitAmountCents, taxCode }
390
423
  )),
391
424
  });
392
- const row = await update(tx, obligation, { invoiceId: invoice.id, accountingCheckedAt: now });
425
+ // Drafting the invoice says the job is ready, whoever asked.
426
+ const row = await update(tx, obligation, {
427
+ invoiceId: invoice.id, accountingCheckedAt: now, ...(obligation.readyAt ? {} : { readyAt: now, readyBy: actor }),
428
+ });
393
429
  await addEvent(tx, row, 'drafted', actor, { invoiceId: invoice.id, totalCents: invoice.totalCents, live });
394
430
  return { obligation: row, invoice };
395
431
  });
@@ -8,12 +8,12 @@ import { openReview, resolveReviewFor } from './review.js';
8
8
  // Pushes, imports and the ledger read the link first; matching by name only
9
9
  // ever proposes one.
10
10
  //
11
- // A link is exact when Flow made the external record, or both sides carry the
12
- // same id. A name match is a guess: it stays `proposed` and opens a review item
11
+ // A link is exact when Flow made the external record, both sides carry the
12
+ // same id, or one record on each side has the same name. A looser name match is a guess: it stays `proposed` and opens a review item
13
13
  // until a person confirms it. A link is never deleted; a replaced one is
14
14
  // `superseded`.
15
15
 
16
- const EXACT = new Set(['created_by_flow', 'exact_id', 'imported', 'person']);
16
+ const EXACT = new Set(['created_by_flow', 'exact_id', 'exact_name', 'imported', 'person']);
17
17
 
18
18
  function check({ entity, flowId, system, externalId, matchedBy }) {
19
19
  if (!LINK_ENTITIES.includes(entity)) throw new FlowError('invalid', `unknown link entity: ${entity}`);
@@ -0,0 +1,34 @@
1
+ // The logger every part of Flow writes to. It passes each line to the host's
2
+ // own log first, unchanged, then sends each error to the error services that
3
+ // are on (the `captureError` capability, docs/SENTRY.md). With none on, it is
4
+ // the host's log. A line's leading "[tag]" is its source.
5
+ //
6
+ // `reporters()` answers the adapters to send to; it is read at each error,
7
+ // so an integration turned on or off later is followed. A failure to send is
8
+ // logged as a warning at most once a minute, never sent, so it cannot loop.
9
+ export function createMonitoredLog({ log = console, reporters = () => [], now = Date.now }) {
10
+ let lastFailure = -Infinity;
11
+
12
+ function error(...args) {
13
+ log.error?.(...args);
14
+ const cause = args.find((arg) => arg instanceof Error) ?? null;
15
+ const message = args.map((arg) => (arg instanceof Error ? arg.message : String(arg))).join(' ');
16
+ const source = /^\[([a-z0-9_-]+)\]/i.exec(message)?.[1].toLowerCase() ?? 'server';
17
+ for (const adapter of reporters()) {
18
+ try {
19
+ adapter.capabilities.captureError({ message, source, error: cause });
20
+ } catch (failure) {
21
+ const at = now();
22
+ if (at - lastFailure < 60_000) continue;
23
+ lastFailure = at;
24
+ log.warn?.(`[monitoring] ${adapter.id} could not take an error: ${failure.message}`);
25
+ }
26
+ }
27
+ }
28
+
29
+ return {
30
+ info: (...args) => log.info?.(...args),
31
+ warn: (...args) => log.warn?.(...args),
32
+ error,
33
+ };
34
+ }