@fire-spark/local 0.29.0 → 0.31.0
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/dist/index.d.ts +118 -6
- package/dist/index.js +1179 -237
- package/package.json +4 -4
package/dist/index.js
CHANGED
|
@@ -8,7 +8,7 @@ import { request } from "node:http";
|
|
|
8
8
|
import { arch, cpus, hostname, platform, totalmem } from "node:os";
|
|
9
9
|
//#region src/constants.ts
|
|
10
10
|
/** Forward-only SQLite schema version (`meta.schema_version`). */
|
|
11
|
-
const LOCAL_SCHEMA_VERSION =
|
|
11
|
+
const LOCAL_SCHEMA_VERSION = 2;
|
|
12
12
|
/** Envelope `schema_version` of every upstream event this runtime writes. */
|
|
13
13
|
const LOCAL_EVENT_SCHEMA_VERSION = 1;
|
|
14
14
|
/** Upstream batch cap (§4.5): whichever of the two is hit first. */
|
|
@@ -47,6 +47,11 @@ const LOCAL_CREDENTIALS_SECTION = "credentials";
|
|
|
47
47
|
const LOCAL_ORIGIN_HEADER = "x-firespark-origin";
|
|
48
48
|
/** Payment methods that work with no internet (cash today). */
|
|
49
49
|
const LOCAL_OFFLINE_PAYMENT_METHODS = ["CASH"];
|
|
50
|
+
/**
|
|
51
|
+
* Charged by the device's own terminal (§5): allowed while the node still
|
|
52
|
+
* reaches the internet, so the pinpad can reach its acquirer.
|
|
53
|
+
*/
|
|
54
|
+
const LOCAL_DEVICE_PAYMENT_METHODS = ["PIN_PAD"];
|
|
50
55
|
const LOCAL_UPSTREAM_EVENT_TYPES = [
|
|
51
56
|
"order.created",
|
|
52
57
|
"order.updated",
|
|
@@ -80,6 +85,17 @@ const LOCAL_MODES = [
|
|
|
80
85
|
* forgotten cart never stops the store.
|
|
81
86
|
*/
|
|
82
87
|
const DRAIN_HOLD_MS = 6e4;
|
|
88
|
+
/**
|
|
89
|
+
* Once DRAINING reaches `drain_max_min`, carts idle this long count as
|
|
90
|
+
* expired too, so only carts someone is still working on keep the node.
|
|
91
|
+
*/
|
|
92
|
+
const DRAIN_CAPPED_CART_IDLE_MS = 300 * 1e3;
|
|
93
|
+
/**
|
|
94
|
+
* Failed cloud answers (retry or rejection) after which an event is
|
|
95
|
+
* quarantined: still retried at the longest backoff, never dropped, but no
|
|
96
|
+
* longer holding the hand-back (§4.3).
|
|
97
|
+
*/
|
|
98
|
+
const LOCAL_QUARANTINE_AFTER_ATTEMPTS = 12;
|
|
83
99
|
/** Modes in which this node serves the storefront itself (§4.6). */
|
|
84
100
|
const LOCAL_SERVING_MODES = [
|
|
85
101
|
"LOCAL",
|
|
@@ -140,7 +156,9 @@ const DEFAULT_LOCAL_SETTINGS = {
|
|
|
140
156
|
degraded_after_failures: 2,
|
|
141
157
|
local_after_failures: 3,
|
|
142
158
|
recover_after_successes: 12,
|
|
143
|
-
p95_threshold_ms: 3e3
|
|
159
|
+
p95_threshold_ms: 3e3,
|
|
160
|
+
local_cart_ttl_min: 60,
|
|
161
|
+
drain_max_min: 15
|
|
144
162
|
},
|
|
145
163
|
heartbeat_interval_s: 30,
|
|
146
164
|
speed_probe_minutes: 15,
|
|
@@ -152,7 +170,7 @@ const DEFAULT_LOCAL_SETTINGS = {
|
|
|
152
170
|
max_cart_staleness_minutes: 30,
|
|
153
171
|
display_number_prefix: "L"
|
|
154
172
|
};
|
|
155
|
-
const isRecord$
|
|
173
|
+
const isRecord$3 = (value) => {
|
|
156
174
|
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
157
175
|
};
|
|
158
176
|
const pick = (value, fallback, check) => {
|
|
@@ -161,15 +179,16 @@ const pick = (value, fallback, check) => {
|
|
|
161
179
|
const isNumber = (value) => {
|
|
162
180
|
return typeof value === "number" && Number.isFinite(value);
|
|
163
181
|
};
|
|
182
|
+
const isPositive = (value) => isNumber(value) && Number(value) > 0;
|
|
164
183
|
const isBoolean = (value) => typeof value === "boolean";
|
|
165
184
|
const isMoneyOrNull = (value) => {
|
|
166
185
|
return value === null || typeof value === "string" && value.length > 0;
|
|
167
186
|
};
|
|
168
187
|
const readFailover = (raw) => {
|
|
169
|
-
const source = isRecord$
|
|
188
|
+
const source = isRecord$3(raw) ? raw : {};
|
|
170
189
|
const base = DEFAULT_LOCAL_SETTINGS.failover;
|
|
171
190
|
const entries = Object.keys(base).map((key) => {
|
|
172
|
-
const check = key === "automatic" ? isBoolean :
|
|
191
|
+
const check = key === "automatic" ? isBoolean : isPositive;
|
|
173
192
|
return [key, pick(source[key], base[key], check)];
|
|
174
193
|
});
|
|
175
194
|
return Object.fromEntries(entries);
|
|
@@ -179,9 +198,9 @@ const readFailover = (raw) => {
|
|
|
179
198
|
* to the defaults instead of failing, so an older node keeps running.
|
|
180
199
|
*/
|
|
181
200
|
const readLocalSettings = (raw) => {
|
|
182
|
-
const source = isRecord$
|
|
201
|
+
const source = isRecord$3(raw) ? raw : {};
|
|
183
202
|
const base = DEFAULT_LOCAL_SETTINGS;
|
|
184
|
-
const limits = isRecord$
|
|
203
|
+
const limits = isRecord$3(source.offline_limits) ? source.offline_limits : {};
|
|
185
204
|
let ids = base.offline_payment_ids;
|
|
186
205
|
if (Array.isArray(source.offline_payment_ids)) ids = source.offline_payment_ids.filter((id) => typeof id === "string");
|
|
187
206
|
const maxOrder = base.offline_limits.max_order_total;
|
|
@@ -310,6 +329,9 @@ create table mode_changes (
|
|
|
310
329
|
actor text null,
|
|
311
330
|
changed_at text not null
|
|
312
331
|
);
|
|
332
|
+
`, `
|
|
333
|
+
alter table events add column quarantined_at text null;
|
|
334
|
+
create index events_quarantined_idx on events (synced, quarantined_at);
|
|
313
335
|
`];
|
|
314
336
|
//#endregion
|
|
315
337
|
//#region src/db/database.ts
|
|
@@ -387,6 +409,9 @@ const setMeta = (db, key, value) => {
|
|
|
387
409
|
insert into meta (key, value) values (?, ?)
|
|
388
410
|
on conflict (key) do update set value = excluded.value`).run(key, value);
|
|
389
411
|
};
|
|
412
|
+
const deleteMeta = (db, key) => {
|
|
413
|
+
db.prepare("delete from meta where key = ?").run(key);
|
|
414
|
+
};
|
|
390
415
|
/** The state version the node runs on, or null before the first load. */
|
|
391
416
|
const readStateRef = (db) => {
|
|
392
417
|
const seq = getMetaNumber(db, "state_seq");
|
|
@@ -402,7 +427,7 @@ const readStateRef = (db) => {
|
|
|
402
427
|
const EVENT_COLUMNS = `seq, event_id, aggregate_type, aggregate_id, type,
|
|
403
428
|
schema_version, occurred_at, connectivity, state_seq, state_root,
|
|
404
429
|
idempotency_key, payload, payload_hash, synced, synced_at, attempts,
|
|
405
|
-
next_attempt_at, last_error, cloud_result`;
|
|
430
|
+
next_attempt_at, last_error, cloud_result, quarantined_at`;
|
|
406
431
|
/** `sha256:<hex>` of a payload's canonical text, as the cloud checks it. */
|
|
407
432
|
const payloadHashOf = (canonical) => {
|
|
408
433
|
return `${STATE_HASH_PREFIX}${sha256HexOfString(canonical)}`;
|
|
@@ -467,12 +492,34 @@ const appendEvent = (db, input, context) => {
|
|
|
467
492
|
created: true
|
|
468
493
|
};
|
|
469
494
|
};
|
|
495
|
+
const BLOCKING_SQL = `select count(*) as n from events e
|
|
496
|
+
where e.synced = 0 and e.quarantined_at is null
|
|
497
|
+
and not exists (select 1 from events q where q.synced = 0
|
|
498
|
+
and q.quarantined_at is not null and q.seq < e.seq
|
|
499
|
+
and q.aggregate_type = e.aggregate_type
|
|
500
|
+
and q.aggregate_id = e.aggregate_id)`;
|
|
501
|
+
const QUARANTINED_SQL = `select count(*) as n from events
|
|
502
|
+
where synced = 0 and quarantined_at is not null`;
|
|
503
|
+
/**
|
|
504
|
+
* Unsynced events. `blocking` leaves out quarantined events and the later
|
|
505
|
+
* events of their aggregates (held behind them by per-aggregate order):
|
|
506
|
+
* those keep retrying but no longer hold DRAINING → ONLINE.
|
|
507
|
+
*/
|
|
470
508
|
const countUnsyncedEvents = (db) => {
|
|
471
509
|
const row = db.prepare(`select count(*) as n, min(occurred_at) as oldest from events where synced = 0`).get();
|
|
472
|
-
|
|
510
|
+
const count = (query) => {
|
|
511
|
+
return db.prepare(query).get().n;
|
|
512
|
+
};
|
|
513
|
+
const b1 = {
|
|
473
514
|
pending: row.n,
|
|
474
515
|
oldestPendingAt: row.oldest
|
|
475
516
|
};
|
|
517
|
+
const b2 = { blocking: count(BLOCKING_SQL) };
|
|
518
|
+
return {
|
|
519
|
+
...b1,
|
|
520
|
+
...b2,
|
|
521
|
+
quarantined: count(QUARANTINED_SQL)
|
|
522
|
+
};
|
|
476
523
|
};
|
|
477
524
|
const listEvents = (db) => {
|
|
478
525
|
const sql = `select ${EVENT_COLUMNS} from events order by seq`;
|
|
@@ -1491,6 +1538,8 @@ const onBoot = (state, input) => {
|
|
|
1491
1538
|
if (!input.integrityOk) return move(state, "BLOCKED", "DB_INTEGRITY");
|
|
1492
1539
|
if (!input.snapshotVerified) return move(state, "BLOCKED", "NO_SNAPSHOT");
|
|
1493
1540
|
if (state.override === "LOCAL") return move(state, "LOCAL", "OVERRIDE");
|
|
1541
|
+
const previous = input.previousMode ?? null;
|
|
1542
|
+
if (input.cloudReachable && previous && isServingMode(previous)) return move(state, "DRAINING", "BOOTED_DRAINING");
|
|
1494
1543
|
if (input.cloudReachable) return move(state, "ONLINE", "BOOTED_ONLINE");
|
|
1495
1544
|
return move(state, "LOCAL", "BOOTED_OFFLINE");
|
|
1496
1545
|
};
|
|
@@ -1544,6 +1593,14 @@ const readOverride$1 = (db) => {
|
|
|
1544
1593
|
if (parsed.override === "LOCAL" || parsed.override === "ONLINE") return parsed.override;
|
|
1545
1594
|
return null;
|
|
1546
1595
|
};
|
|
1596
|
+
const MODES = LOCAL_MODES;
|
|
1597
|
+
/** The mode written before the last shutdown (null on a fresh node). */
|
|
1598
|
+
const readPersistedMode = (db) => {
|
|
1599
|
+
const value = getMeta(db, "mode");
|
|
1600
|
+
const mode = (value ? JSON.parse(value) : {}).mode;
|
|
1601
|
+
if (typeof mode !== "string" || !MODES.includes(mode)) return null;
|
|
1602
|
+
return mode;
|
|
1603
|
+
};
|
|
1547
1604
|
const listModeChanges = (db) => {
|
|
1548
1605
|
return db.prepare("select * from mode_changes order by id").all();
|
|
1549
1606
|
};
|
|
@@ -1602,7 +1659,7 @@ const createModeController = (db, settings, now = () => /* @__PURE__ */ new Date
|
|
|
1602
1659
|
const SELECT_UNSYNCED = `select seq, event_id, aggregate_type, aggregate_id,
|
|
1603
1660
|
type, schema_version, occurred_at, connectivity, state_seq, state_root,
|
|
1604
1661
|
idempotency_key, payload, payload_hash, synced, synced_at, attempts,
|
|
1605
|
-
next_attempt_at, last_error, cloud_result
|
|
1662
|
+
next_attempt_at, last_error, cloud_result, quarantined_at
|
|
1606
1663
|
from events where synced = 0 order by seq`;
|
|
1607
1664
|
/**
|
|
1608
1665
|
* One envelope as JSON text. The payload is spliced in as the stored
|
|
@@ -1723,6 +1780,24 @@ const scheduleRetry = (db, event, code, now, random) => {
|
|
|
1723
1780
|
const next = new Date(now.getTime() + delay).toISOString();
|
|
1724
1781
|
db.prepare(`update events set attempts = ?, next_attempt_at = ?,
|
|
1725
1782
|
last_error = ? where seq = ? and synced = 0`).run(attempts, next, code, event.seq);
|
|
1783
|
+
if (!(attempts >= 12) || event.quarantined_at !== null) return null;
|
|
1784
|
+
db.prepare(`update events set quarantined_at = ?
|
|
1785
|
+
where seq = ? and synced = 0 and quarantined_at is null`).run(now.toISOString(), event.seq);
|
|
1786
|
+
const aggregate = {
|
|
1787
|
+
type: event.aggregate_type,
|
|
1788
|
+
id: event.aggregate_id
|
|
1789
|
+
};
|
|
1790
|
+
return {
|
|
1791
|
+
event_id: event.event_id,
|
|
1792
|
+
seq: event.seq,
|
|
1793
|
+
type: event.type,
|
|
1794
|
+
aggregate,
|
|
1795
|
+
attempts,
|
|
1796
|
+
code
|
|
1797
|
+
};
|
|
1798
|
+
};
|
|
1799
|
+
const report = (options, quarantined) => {
|
|
1800
|
+
for (const event of quarantined) if (event) options.onQuarantine?.(event);
|
|
1726
1801
|
};
|
|
1727
1802
|
/** Every event with seq ≤ cursor is synced; it never moves backwards. */
|
|
1728
1803
|
const advanceCursor = (db) => {
|
|
@@ -1745,11 +1820,12 @@ const markOrdersSynced = (db, ids, nowIso) => {
|
|
|
1745
1820
|
* duplicate and needs_review become synced; retry (or a missing result)
|
|
1746
1821
|
* backs off that event only.
|
|
1747
1822
|
*/
|
|
1748
|
-
const applyBatchResults = (db, batch, response, now, random = Math.random) => {
|
|
1823
|
+
const applyBatchResults = (db, batch, response, now, random = Math.random, options = {}) => {
|
|
1749
1824
|
const byId = new Map(response.results.map((r) => [r.event_id, r]));
|
|
1750
1825
|
const nowIso = now.toISOString();
|
|
1751
1826
|
let synced = 0;
|
|
1752
1827
|
let retried = 0;
|
|
1828
|
+
const quarantined = [];
|
|
1753
1829
|
inTransaction(db, () => {
|
|
1754
1830
|
const orderIds = /* @__PURE__ */ new Set();
|
|
1755
1831
|
for (const event of batch.events) {
|
|
@@ -1761,29 +1837,33 @@ const applyBatchResults = (db, batch, response, now, random = Math.random) => {
|
|
|
1761
1837
|
continue;
|
|
1762
1838
|
}
|
|
1763
1839
|
const code = result?.code ?? (result ? "RETRY" : "RESULT_MISSING");
|
|
1764
|
-
scheduleRetry(db, event, code, now, random);
|
|
1840
|
+
quarantined.push(scheduleRetry(db, event, code, now, random));
|
|
1765
1841
|
retried += 1;
|
|
1766
1842
|
}
|
|
1767
1843
|
markOrdersSynced(db, [...orderIds], nowIso);
|
|
1768
1844
|
advanceCursor(db);
|
|
1769
1845
|
});
|
|
1846
|
+
report(options, quarantined);
|
|
1770
1847
|
return {
|
|
1771
1848
|
synced,
|
|
1772
1849
|
retried
|
|
1773
1850
|
};
|
|
1774
1851
|
};
|
|
1775
1852
|
/** Backs off the given events (all of the batch when `seqs` is empty). */
|
|
1776
|
-
const backOffEvents = (db, batch, code, seqs, now,
|
|
1853
|
+
const backOffEvents = (db, batch, code, seqs, now, options) => {
|
|
1854
|
+
const random = options.random ?? Math.random;
|
|
1777
1855
|
const targets = new Set(seqs);
|
|
1778
1856
|
const all = targets.size === 0;
|
|
1779
1857
|
let retried = 0;
|
|
1858
|
+
const quarantined = [];
|
|
1780
1859
|
inTransaction(db, () => {
|
|
1781
1860
|
for (const event of batch.events) {
|
|
1782
1861
|
if (!all && !targets.has(event.seq)) continue;
|
|
1783
|
-
scheduleRetry(db, event, code, now, random);
|
|
1862
|
+
quarantined.push(scheduleRetry(db, event, code, now, random));
|
|
1784
1863
|
retried += 1;
|
|
1785
1864
|
}
|
|
1786
1865
|
});
|
|
1866
|
+
report(options, quarantined);
|
|
1787
1867
|
return retried;
|
|
1788
1868
|
};
|
|
1789
1869
|
const errorMessage = (error) => {
|
|
@@ -1815,10 +1895,17 @@ const sendNextBatch = async (db, client, options = {}) => {
|
|
|
1815
1895
|
};
|
|
1816
1896
|
}
|
|
1817
1897
|
if (response.ok) {
|
|
1818
|
-
const
|
|
1898
|
+
const r1 = [
|
|
1899
|
+
db,
|
|
1900
|
+
batch,
|
|
1901
|
+
(await response.json()).data,
|
|
1902
|
+
now(),
|
|
1903
|
+
random,
|
|
1904
|
+
options
|
|
1905
|
+
];
|
|
1819
1906
|
return {
|
|
1820
1907
|
status: "sent",
|
|
1821
|
-
...applyBatchResults(
|
|
1908
|
+
...applyBatchResults(...r1),
|
|
1822
1909
|
batch
|
|
1823
1910
|
};
|
|
1824
1911
|
}
|
|
@@ -1833,11 +1920,13 @@ const sendNextBatch = async (db, client, options = {}) => {
|
|
|
1833
1920
|
};
|
|
1834
1921
|
const code = error.code ?? `HTTP_${error.status}`;
|
|
1835
1922
|
const seqs = readSeqs(error.details);
|
|
1836
|
-
const retried = backOffEvents(db, batch, code, seqs, now(),
|
|
1923
|
+
const retried = backOffEvents(db, batch, code, seqs, now(), options);
|
|
1924
|
+
const rest = batch.events.length - retried;
|
|
1837
1925
|
return {
|
|
1838
1926
|
status: "rejected",
|
|
1839
1927
|
code: error.code,
|
|
1840
|
-
retried
|
|
1928
|
+
retried,
|
|
1929
|
+
rest
|
|
1841
1930
|
};
|
|
1842
1931
|
};
|
|
1843
1932
|
const countPending = (db) => {
|
|
@@ -1852,6 +1941,7 @@ const drainUpstream = async (db, client, options = {}) => {
|
|
|
1852
1941
|
let sent = 0;
|
|
1853
1942
|
for (;;) {
|
|
1854
1943
|
const outcome = await sendNextBatch(db, client, options);
|
|
1944
|
+
if (outcome.status === "rejected" && outcome.retried > 0 && outcome.rest > 0) continue;
|
|
1855
1945
|
if (outcome.status !== "sent") return {
|
|
1856
1946
|
sent,
|
|
1857
1947
|
outcome
|
|
@@ -2064,10 +2154,21 @@ const listPendingOrders = (db, input = {}) => {
|
|
|
2064
2154
|
order by occurred_at desc limit ${limit}`;
|
|
2065
2155
|
return db.prepare(sql).all(...args);
|
|
2066
2156
|
};
|
|
2067
|
-
/**
|
|
2068
|
-
|
|
2157
|
+
/**
|
|
2158
|
+
* Local orders not placed yet that block DRAINING → ONLINE: open carts
|
|
2159
|
+
* touched at or after `cartsSince` and orders locked for a pinpad result
|
|
2160
|
+
* touched at or after `paymentsSince` (ISO). Older ones never count.
|
|
2161
|
+
*/
|
|
2162
|
+
const countOpenLocalOrders = (db, cartsSince = "", paymentsSince = cartsSince) => {
|
|
2069
2163
|
return db.prepare(`select count(*) as n from pending_orders
|
|
2070
|
-
where origin = 'local' and
|
|
2164
|
+
where origin = 'local' and placed is null
|
|
2165
|
+
and ((status = 'OPEN' and updated_at >= ?)
|
|
2166
|
+
or (status <> 'OPEN' and updated_at >= ?))`).get(cartsSince, paymentsSince).n;
|
|
2167
|
+
};
|
|
2168
|
+
/** An open, unpaid local cart nobody touched within `idleLimitMs`. */
|
|
2169
|
+
const isExpiredCart = (row, now, idleLimitMs) => {
|
|
2170
|
+
if (row.origin !== "local" || row.status !== "OPEN" || row.placed) return false;
|
|
2171
|
+
return now.getTime() - Date.parse(row.updated_at) > idleLimitMs;
|
|
2071
2172
|
};
|
|
2072
2173
|
//#endregion
|
|
2073
2174
|
//#region src/sync/downstreamHandlers.ts
|
|
@@ -2726,7 +2827,12 @@ const checkoutIssues = (order, state, at) => {
|
|
|
2726
2827
|
* and its schedule, prices, fees and checkout rules at this state version.
|
|
2727
2828
|
* Exact Big.js comparisons; nothing is rounded.
|
|
2728
2829
|
*/
|
|
2729
|
-
|
|
2830
|
+
/**
|
|
2831
|
+
* `checkout: false` skips customer/shipping/billing fields, like the
|
|
2832
|
+
* cloud's `orders/validate` for a body without the customer (the SDK's
|
|
2833
|
+
* `validateOrder`); place always checks them on the stored cart.
|
|
2834
|
+
*/
|
|
2835
|
+
const checkOrder = (order, state, at, options = {}) => {
|
|
2730
2836
|
const entry = state.menu.find((item) => {
|
|
2731
2837
|
return item.channel_id === order.channel_id && item.fulfillment_id === order.fulfillment_id;
|
|
2732
2838
|
});
|
|
@@ -2760,7 +2866,7 @@ const checkOrder = (order, state, at) => {
|
|
|
2760
2866
|
...v4
|
|
2761
2867
|
});
|
|
2762
2868
|
const issues = result.ok ? [] : [...result.issues];
|
|
2763
|
-
issues.push(...checkoutIssues(order, state, at));
|
|
2869
|
+
if (options.checkout !== false) issues.push(...checkoutIssues(order, state, at));
|
|
2764
2870
|
const lineIssues = result.ok ? {} : result.lines;
|
|
2765
2871
|
return {
|
|
2766
2872
|
ok: issues.length === 0 && Object.keys(lineIssues).length === 0,
|
|
@@ -2791,10 +2897,241 @@ const nextDisplayNumber = (db, prefix, issuer) => {
|
|
|
2791
2897
|
return formatDisplayNumber(prefix, value);
|
|
2792
2898
|
};
|
|
2793
2899
|
//#endregion
|
|
2900
|
+
//#region src/orders/intents.ts
|
|
2901
|
+
const COLLECT_POINTS = [
|
|
2902
|
+
"COUNTER",
|
|
2903
|
+
"DEVICE",
|
|
2904
|
+
"DOOR",
|
|
2905
|
+
"KIOSK",
|
|
2906
|
+
"OTHER"
|
|
2907
|
+
];
|
|
2908
|
+
const isRecord$2 = (value) => {
|
|
2909
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2910
|
+
};
|
|
2911
|
+
const refuse$2 = (code, status, details = {}) => {
|
|
2912
|
+
return new LocalRuntimeError(code, status, details);
|
|
2913
|
+
};
|
|
2914
|
+
const textOf = (value) => {
|
|
2915
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
2916
|
+
};
|
|
2917
|
+
/**
|
|
2918
|
+
* Reads the intent body. A local node charges one real tender: mixed
|
|
2919
|
+
* payments and redemptions need the cloud.
|
|
2920
|
+
*/
|
|
2921
|
+
const readTenderInput = (body) => {
|
|
2922
|
+
const tenders = Array.isArray(body.tenders) ? body.tenders : [];
|
|
2923
|
+
if (tenders.length === 0) throw refuse$2("VALIDATION_ERROR", 400, { field: "tenders" });
|
|
2924
|
+
if (tenders.map((item) => isRecord$2(item) ? item.method : null).includes("REDEMPTION")) throw refuse$2("LOCAL_REDEMPTION_UNAVAILABLE", 422);
|
|
2925
|
+
if (tenders.length > 1) throw refuse$2("LOCAL_MIXED_PAYMENT_UNAVAILABLE", 422);
|
|
2926
|
+
const tender = tenders[0];
|
|
2927
|
+
const paymentId = textOf(tender.payment_id);
|
|
2928
|
+
if (!paymentId) throw refuse$2("VALIDATION_ERROR", 400, { field: "payment_id" });
|
|
2929
|
+
const method = textOf(tender.method);
|
|
2930
|
+
if (!method) throw refuse$2("VALIDATION_ERROR", 400, { field: "method" });
|
|
2931
|
+
const collect = textOf(tender.collect_at) ?? "COUNTER";
|
|
2932
|
+
if (!COLLECT_POINTS.includes(collect)) throw refuse$2("VALIDATION_ERROR", 400, { field: "collect_at" });
|
|
2933
|
+
const b1 = {
|
|
2934
|
+
paymentId,
|
|
2935
|
+
method,
|
|
2936
|
+
provider: textOf(tender.provider)
|
|
2937
|
+
};
|
|
2938
|
+
const b2 = {
|
|
2939
|
+
collectAt: collect,
|
|
2940
|
+
details: isRecord$2(tender.details) ? tender.details : null,
|
|
2941
|
+
metadata: isRecord$2(tender.metadata) ? tender.metadata : null
|
|
2942
|
+
};
|
|
2943
|
+
return {
|
|
2944
|
+
...b1,
|
|
2945
|
+
...b2
|
|
2946
|
+
};
|
|
2947
|
+
};
|
|
2948
|
+
/** One-tender intent for the whole total (amounts as the cloud stores). */
|
|
2949
|
+
const buildIntent = (input) => {
|
|
2950
|
+
const { order, payment, id } = input;
|
|
2951
|
+
const total = new Big(String(order.totals.total));
|
|
2952
|
+
const placedAt = input.placedAt ?? null;
|
|
2953
|
+
const t1 = {
|
|
2954
|
+
id: `tnd_${id}`,
|
|
2955
|
+
sequence: 0
|
|
2956
|
+
};
|
|
2957
|
+
const t2 = { attempt_reference: `att_${id}` };
|
|
2958
|
+
const t3 = {
|
|
2959
|
+
previous_attempt_references: [],
|
|
2960
|
+
method: payment.method
|
|
2961
|
+
};
|
|
2962
|
+
const t4 = {
|
|
2963
|
+
provider: payment.provider,
|
|
2964
|
+
collect_at: input.collectAt
|
|
2965
|
+
};
|
|
2966
|
+
const t5 = {
|
|
2967
|
+
payment_id: payment.id,
|
|
2968
|
+
status: input.status
|
|
2969
|
+
};
|
|
2970
|
+
const t6 = {
|
|
2971
|
+
amount: {
|
|
2972
|
+
currency: order.totals.currency,
|
|
2973
|
+
total: total.toNumber()
|
|
2974
|
+
},
|
|
2975
|
+
refunded_total: 0,
|
|
2976
|
+
allocation: null
|
|
2977
|
+
};
|
|
2978
|
+
const metadata = {
|
|
2979
|
+
...input.metadata,
|
|
2980
|
+
origin: "local"
|
|
2981
|
+
};
|
|
2982
|
+
const t7 = {
|
|
2983
|
+
details: input.details ?? null,
|
|
2984
|
+
placed_at: placedAt,
|
|
2985
|
+
metadata
|
|
2986
|
+
};
|
|
2987
|
+
const tender = {
|
|
2988
|
+
...t1,
|
|
2989
|
+
...t2,
|
|
2990
|
+
...t3,
|
|
2991
|
+
...t4,
|
|
2992
|
+
...t5,
|
|
2993
|
+
...t6,
|
|
2994
|
+
...t7
|
|
2995
|
+
};
|
|
2996
|
+
const i1 = {
|
|
2997
|
+
id: `pi_${id}`,
|
|
2998
|
+
totals: order.totals,
|
|
2999
|
+
is_mixed: false
|
|
3000
|
+
};
|
|
3001
|
+
const i2 = {
|
|
3002
|
+
rules_snapshot: null,
|
|
3003
|
+
primary_tender_id: tender.id
|
|
3004
|
+
};
|
|
3005
|
+
const i3 = {
|
|
3006
|
+
placed_at: placedAt,
|
|
3007
|
+
metadata: {},
|
|
3008
|
+
status: "DRAFT"
|
|
3009
|
+
};
|
|
3010
|
+
const tenders = [tender];
|
|
3011
|
+
return {
|
|
3012
|
+
...i1,
|
|
3013
|
+
...i2,
|
|
3014
|
+
...i3,
|
|
3015
|
+
tenders
|
|
3016
|
+
};
|
|
3017
|
+
};
|
|
3018
|
+
/** Intent status that follows from its tenders (COMPLETED once paid). */
|
|
3019
|
+
const settleIntent = (intent) => {
|
|
3020
|
+
const status = nextIntentStatus(intent, derivePaymentStatus(intent));
|
|
3021
|
+
return {
|
|
3022
|
+
...intent,
|
|
3023
|
+
status
|
|
3024
|
+
};
|
|
3025
|
+
};
|
|
3026
|
+
/** The intent for the order's current total (the cart may have changed). */
|
|
3027
|
+
const refreshIntent = (intent, order) => {
|
|
3028
|
+
const total = new Big(String(order.totals.total)).toNumber();
|
|
3029
|
+
const amount = {
|
|
3030
|
+
currency: order.totals.currency,
|
|
3031
|
+
total
|
|
3032
|
+
};
|
|
3033
|
+
const tenders = intent.tenders.map((tender) => ({
|
|
3034
|
+
...tender,
|
|
3035
|
+
amount
|
|
3036
|
+
}));
|
|
3037
|
+
return {
|
|
3038
|
+
...intent,
|
|
3039
|
+
totals: order.totals,
|
|
3040
|
+
tenders
|
|
3041
|
+
};
|
|
3042
|
+
};
|
|
3043
|
+
const lockIntent = (intent, placedAt) => {
|
|
3044
|
+
const b1 = {
|
|
3045
|
+
status: "LOCKED",
|
|
3046
|
+
placed_at: placedAt,
|
|
3047
|
+
tenders: intent.tenders.map((tender) => {
|
|
3048
|
+
return {
|
|
3049
|
+
...tender,
|
|
3050
|
+
placed_at: placedAt
|
|
3051
|
+
};
|
|
3052
|
+
})
|
|
3053
|
+
};
|
|
3054
|
+
return {
|
|
3055
|
+
...intent,
|
|
3056
|
+
...b1
|
|
3057
|
+
};
|
|
3058
|
+
};
|
|
3059
|
+
const activeLocalIntent = (order) => {
|
|
3060
|
+
return (order.payment_intents ?? []).find((intent) => intent.status !== "ABANDONED") ?? null;
|
|
3061
|
+
};
|
|
3062
|
+
const RECORDABLE = [
|
|
3063
|
+
"PENDING",
|
|
3064
|
+
"PAID",
|
|
3065
|
+
"FAILED"
|
|
3066
|
+
];
|
|
3067
|
+
const readRecordPayment = (body) => {
|
|
3068
|
+
const tenderId = textOf(body.tender_id);
|
|
3069
|
+
if (!tenderId) throw refuse$2("VALIDATION_ERROR", 400, { field: "tender_id" });
|
|
3070
|
+
const attempt = textOf(body.attempt_reference);
|
|
3071
|
+
if (!attempt) throw refuse$2("VALIDATION_ERROR", 400, { field: "attempt_reference" });
|
|
3072
|
+
const status = textOf(body.status) ?? "";
|
|
3073
|
+
if (!RECORDABLE.includes(status)) throw refuse$2("LOCAL_MODE_UNAVAILABLE", 503, { status });
|
|
3074
|
+
const b1 = {
|
|
3075
|
+
tender_id: tenderId,
|
|
3076
|
+
attempt_reference: attempt
|
|
3077
|
+
};
|
|
3078
|
+
const b2 = { status };
|
|
3079
|
+
const b3 = { details: isRecord$2(body.details) ? body.details : null };
|
|
3080
|
+
const b4 = { provider_reference: textOf(body.provider_reference) };
|
|
3081
|
+
const b5 = { error_message: textOf(body.error_message) };
|
|
3082
|
+
const b6 = { metadata: isRecord$2(body.metadata) ? body.metadata : null };
|
|
3083
|
+
return {
|
|
3084
|
+
...b1,
|
|
3085
|
+
...b2,
|
|
3086
|
+
...b3,
|
|
3087
|
+
...b4,
|
|
3088
|
+
...b5,
|
|
3089
|
+
...b6
|
|
3090
|
+
};
|
|
3091
|
+
};
|
|
3092
|
+
const matchAttempt = (tender, attempt) => {
|
|
3093
|
+
if (tender.attempt_reference === attempt) return "current";
|
|
3094
|
+
if (tender.previous_attempt_references.includes(attempt)) return "stale";
|
|
3095
|
+
if (tender.status === "FAILED") return "retry";
|
|
3096
|
+
return "mismatch";
|
|
3097
|
+
};
|
|
3098
|
+
/** The tender after one attempt result (a retry gets the new reference). */
|
|
3099
|
+
const applyAttempt = (tender, body, at) => {
|
|
3100
|
+
let next = { ...tender };
|
|
3101
|
+
if (tender.attempt_reference !== body.attempt_reference) {
|
|
3102
|
+
const previous = [...tender.previous_attempt_references, tender.attempt_reference];
|
|
3103
|
+
const b1 = { attempt_reference: body.attempt_reference };
|
|
3104
|
+
next = {
|
|
3105
|
+
...next,
|
|
3106
|
+
...b1,
|
|
3107
|
+
previous_attempt_references: previous
|
|
3108
|
+
};
|
|
3109
|
+
}
|
|
3110
|
+
const metadata = {
|
|
3111
|
+
...next.metadata,
|
|
3112
|
+
...body.metadata
|
|
3113
|
+
};
|
|
3114
|
+
if (body.provider_reference) metadata.provider_reference = body.provider_reference;
|
|
3115
|
+
const details = body.details ?? next.details;
|
|
3116
|
+
const b2 = {
|
|
3117
|
+
status: body.status,
|
|
3118
|
+
metadata,
|
|
3119
|
+
details
|
|
3120
|
+
};
|
|
3121
|
+
const error = body.error_message ? { error_message: body.error_message } : {};
|
|
3122
|
+
const ended = body.status === "PENDING" ? {} : { resolved_at: at };
|
|
3123
|
+
return {
|
|
3124
|
+
...next,
|
|
3125
|
+
...b2,
|
|
3126
|
+
...error,
|
|
3127
|
+
...ended
|
|
3128
|
+
};
|
|
3129
|
+
};
|
|
3130
|
+
//#endregion
|
|
2794
3131
|
//#region src/orders/orderService.ts
|
|
2795
3132
|
/** Fulfillment status of an order placed on the node. */
|
|
2796
3133
|
const LOCAL_PLACED_FULFILLMENT_STATUS = "ORDER_PLACED";
|
|
2797
|
-
const refuse = (code, status, details = {}) => {
|
|
3134
|
+
const refuse$1 = (code, status, details = {}) => {
|
|
2798
3135
|
return new LocalRuntimeError(code, status, details);
|
|
2799
3136
|
};
|
|
2800
3137
|
const zeroTotals = (currency) => {
|
|
@@ -2814,7 +3151,7 @@ const zeroTotals = (currency) => {
|
|
|
2814
3151
|
currency
|
|
2815
3152
|
};
|
|
2816
3153
|
};
|
|
2817
|
-
const isRecord = (value) => {
|
|
3154
|
+
const isRecord$1 = (value) => {
|
|
2818
3155
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
2819
3156
|
};
|
|
2820
3157
|
/** The `order.created` / `order.updated` payload (§4.4). */
|
|
@@ -2843,7 +3180,13 @@ const documentPayload = (order, rev, createdAt) => {
|
|
|
2843
3180
|
const paymentMethodOf = (row) => {
|
|
2844
3181
|
const method = row.payment_method;
|
|
2845
3182
|
if (typeof method === "string") return method;
|
|
2846
|
-
if (isRecord(method) && typeof method.method === "string") return method.method;
|
|
3183
|
+
if (isRecord$1(method) && typeof method.method === "string") return method.method;
|
|
3184
|
+
return null;
|
|
3185
|
+
};
|
|
3186
|
+
const providerOf = (row) => {
|
|
3187
|
+
const provider = row.payment_provider;
|
|
3188
|
+
if (typeof provider === "string") return provider;
|
|
3189
|
+
if (isRecord$1(provider) && typeof provider.provider_id === "string") return provider.provider_id;
|
|
2847
3190
|
return null;
|
|
2848
3191
|
};
|
|
2849
3192
|
/**
|
|
@@ -2862,24 +3205,38 @@ const createOrderService = (options) => {
|
|
|
2862
3205
|
};
|
|
2863
3206
|
const stateRef = () => {
|
|
2864
3207
|
const ref = readStateRef(db);
|
|
2865
|
-
if (!ref) throw refuse("STATE_NOT_LOADED", 503);
|
|
3208
|
+
if (!ref) throw refuse$1("STATE_NOT_LOADED", 503);
|
|
2866
3209
|
return ref;
|
|
2867
3210
|
};
|
|
2868
3211
|
const assertScope = (storeId, channelId) => {
|
|
2869
|
-
if (storeId !== options.storeId) throw refuse("LOCAL_SCOPE_MISMATCH", 403, { field: "store_id" });
|
|
2870
|
-
if (!options.servedChannelIds().includes(channelId)) throw refuse("LOCAL_SCOPE_MISMATCH", 403, { field: "channel_id" });
|
|
3212
|
+
if (storeId !== options.storeId) throw refuse$1("LOCAL_SCOPE_MISMATCH", 403, { field: "store_id" });
|
|
3213
|
+
if (!options.servedChannelIds().includes(channelId)) throw refuse$1("LOCAL_SCOPE_MISMATCH", 403, { field: "channel_id" });
|
|
2871
3214
|
};
|
|
2872
3215
|
const assertFulfillment = (state, fulfillmentId) => {
|
|
2873
|
-
if (!state.fulfillment.some((row) => row.id === fulfillmentId)) throw refuse("FULFILLMENT_NOT_FOUND", 404);
|
|
3216
|
+
if (!state.fulfillment.some((row) => row.id === fulfillmentId)) throw refuse$1("FULFILLMENT_NOT_FOUND", 404);
|
|
2874
3217
|
};
|
|
2875
3218
|
const assertDiskAccepts = () => {
|
|
2876
|
-
if (options.disk?.() === "critical") throw refuse("LOCAL_DISK_FULL", 507);
|
|
3219
|
+
if (options.disk?.() === "critical") throw refuse$1("LOCAL_DISK_FULL", 507);
|
|
2877
3220
|
};
|
|
2878
3221
|
const load = (orderId) => {
|
|
2879
3222
|
const row = readPendingOrder(db, orderId);
|
|
2880
|
-
if (!row) throw refuse("LOCAL_ORDER_UNKNOWN", 409, { order_id: orderId });
|
|
3223
|
+
if (!row) throw refuse$1("LOCAL_ORDER_UNKNOWN", 409, { order_id: orderId });
|
|
2881
3224
|
return row;
|
|
2882
3225
|
};
|
|
3226
|
+
/**
|
|
3227
|
+
* An expired cart answers 409 `LOCAL_CART_EXPIRED`: the device starts a
|
|
3228
|
+
* new cart (new id) with the same lines. It was never paid, so nothing
|
|
3229
|
+
* is lost, and it can no longer be placed here.
|
|
3230
|
+
*/
|
|
3231
|
+
const assertNotExpired = (row) => {
|
|
3232
|
+
const limit = options.cartIdleLimitMs?.();
|
|
3233
|
+
if (limit === void 0 || !isExpiredCart(row, now(), limit)) return;
|
|
3234
|
+
const details = {
|
|
3235
|
+
order_id: row.order_id,
|
|
3236
|
+
expired_after_ms: limit
|
|
3237
|
+
};
|
|
3238
|
+
throw refuse$1("LOCAL_CART_EXPIRED", 409, details);
|
|
3239
|
+
};
|
|
2883
3240
|
const committed = (fn) => {
|
|
2884
3241
|
const result = inTransaction(db, fn);
|
|
2885
3242
|
options.onWrite?.();
|
|
@@ -2916,10 +3273,13 @@ const createOrderService = (options) => {
|
|
|
2916
3273
|
const get = (orderId) => documentOf(load(orderId));
|
|
2917
3274
|
const create = (body, actor) => {
|
|
2918
3275
|
assertDiskAccepts();
|
|
2919
|
-
if (!body?.id) throw refuse("VALIDATION_ERROR", 400, { field: "id" });
|
|
3276
|
+
if (!body?.id) throw refuse$1("VALIDATION_ERROR", 400, { field: "id" });
|
|
2920
3277
|
const existing = readPendingOrder(db, body.id);
|
|
2921
|
-
if (existing)
|
|
2922
|
-
|
|
3278
|
+
if (existing) {
|
|
3279
|
+
assertNotExpired(existing);
|
|
3280
|
+
return documentOf(existing);
|
|
3281
|
+
}
|
|
3282
|
+
if (options.admitsNewOrders?.() === false) throw refuse$1("LOCAL_NODE_DRAINING", 503, { order_id: body.id });
|
|
2923
3283
|
assertScope(body.store_id, body.channel_id);
|
|
2924
3284
|
const state = readOrderState(db);
|
|
2925
3285
|
assertFulfillment(state, body.fulfillment_id);
|
|
@@ -2974,7 +3334,8 @@ const createOrderService = (options) => {
|
|
|
2974
3334
|
return committed(() => {
|
|
2975
3335
|
const row = load(orderId);
|
|
2976
3336
|
const current = documentOf(row);
|
|
2977
|
-
if (row.origin !== "local" || current.status !== "OPEN") throw refuse("ORDER_NOT_EDITABLE", 409, { status: current.status });
|
|
3337
|
+
if (row.origin !== "local" || current.status !== "OPEN") throw refuse$1("ORDER_NOT_EDITABLE", 409, { status: current.status });
|
|
3338
|
+
assertNotExpired(row);
|
|
2978
3339
|
const next = { ...current };
|
|
2979
3340
|
const fields = [
|
|
2980
3341
|
"brand_id",
|
|
@@ -3016,20 +3377,38 @@ const createOrderService = (options) => {
|
|
|
3016
3377
|
const validate = (orderId) => {
|
|
3017
3378
|
return checkOrder(get(orderId), readOrderState(db), now());
|
|
3018
3379
|
};
|
|
3019
|
-
const
|
|
3380
|
+
const activePayments = () => {
|
|
3381
|
+
return readSectionRows(db, "payments").filter((row) => {
|
|
3382
|
+
return row.status === void 0 || row.status === "ACTIVE";
|
|
3383
|
+
});
|
|
3384
|
+
};
|
|
3385
|
+
/**
|
|
3386
|
+
* The payment row a tender may use here: cash (within
|
|
3387
|
+
* `offline_payment_ids`) always; a device pinpad only while the node
|
|
3388
|
+
* reaches the internet. Anything else needs the cloud.
|
|
3389
|
+
*/
|
|
3390
|
+
const localPayment = (paymentId, method = "CASH") => {
|
|
3391
|
+
const cash = LOCAL_OFFLINE_PAYMENT_METHODS;
|
|
3392
|
+
const device = LOCAL_DEVICE_PAYMENT_METHODS;
|
|
3020
3393
|
const allowed = options.settings().offline_payment_ids;
|
|
3021
|
-
const
|
|
3022
|
-
const rows =
|
|
3023
|
-
|
|
3024
|
-
|
|
3025
|
-
if (
|
|
3394
|
+
const online = options.internetReachable?.() ?? false;
|
|
3395
|
+
const rows = activePayments().filter((row) => {
|
|
3396
|
+
const rowMethod = paymentMethodOf(row);
|
|
3397
|
+
if (!rowMethod || rowMethod !== method) return false;
|
|
3398
|
+
if (device.includes(rowMethod)) return online;
|
|
3399
|
+
if (!cash.includes(rowMethod)) return false;
|
|
3026
3400
|
return allowed.length === 0 || allowed.includes(String(row.id));
|
|
3027
3401
|
});
|
|
3028
3402
|
const row = paymentId ? rows.find((item) => item.id === paymentId) : rows[0];
|
|
3029
|
-
if (!row) throw refuse("PAYMENT_NOT_OFFLINE_CAPABLE", 422, {
|
|
3403
|
+
if (!row) throw refuse$1("PAYMENT_NOT_OFFLINE_CAPABLE", 422, {
|
|
3404
|
+
payment_id: paymentId ?? null,
|
|
3405
|
+
method
|
|
3406
|
+
});
|
|
3407
|
+
const provider = providerOf(row) ?? "firespark";
|
|
3030
3408
|
return {
|
|
3031
3409
|
id: String(row.id),
|
|
3032
|
-
method
|
|
3410
|
+
method,
|
|
3411
|
+
provider
|
|
3033
3412
|
};
|
|
3034
3413
|
};
|
|
3035
3414
|
const outageTotal = () => {
|
|
@@ -3048,7 +3427,7 @@ const createOrderService = (options) => {
|
|
|
3048
3427
|
limit: maxOrder,
|
|
3049
3428
|
actual: total.toFixed()
|
|
3050
3429
|
};
|
|
3051
|
-
throw refuse("OFFLINE_LIMIT_EXCEEDED", 422, details);
|
|
3430
|
+
throw refuse$1("OFFLINE_LIMIT_EXCEEDED", 422, details);
|
|
3052
3431
|
}
|
|
3053
3432
|
const maxOutage = limits.max_outage_total;
|
|
3054
3433
|
if (maxOutage === null) return;
|
|
@@ -3058,198 +3437,347 @@ const createOrderService = (options) => {
|
|
|
3058
3437
|
limit: maxOutage,
|
|
3059
3438
|
actual: after.toFixed()
|
|
3060
3439
|
};
|
|
3061
|
-
throw refuse("OFFLINE_OUTAGE_LIMIT_EXCEEDED", 422, details);
|
|
3440
|
+
throw refuse$1("OFFLINE_OUTAGE_LIMIT_EXCEEDED", 422, details);
|
|
3062
3441
|
}
|
|
3063
3442
|
};
|
|
3064
3443
|
const cashIntent = (input) => {
|
|
3065
3444
|
const { order, placedAt } = input;
|
|
3066
3445
|
const total = new Big(String(order.totals.total));
|
|
3067
|
-
const change = input.tendered.minus(total);
|
|
3446
|
+
const change = input.tendered.minus(total).toFixed();
|
|
3447
|
+
const details = {
|
|
3448
|
+
method: "CASH",
|
|
3449
|
+
tendered: input.tendered.toFixed(),
|
|
3450
|
+
change
|
|
3451
|
+
};
|
|
3068
3452
|
const id = uuidv7(now().getTime());
|
|
3069
|
-
const
|
|
3070
|
-
|
|
3071
|
-
|
|
3453
|
+
const b1 = {
|
|
3454
|
+
order,
|
|
3455
|
+
payment: input.payment,
|
|
3456
|
+
collectAt: input.collectAt
|
|
3072
3457
|
};
|
|
3073
|
-
const
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3458
|
+
const b2 = {
|
|
3459
|
+
status: "PAID",
|
|
3460
|
+
id,
|
|
3461
|
+
details,
|
|
3462
|
+
placedAt
|
|
3077
3463
|
};
|
|
3078
|
-
|
|
3079
|
-
|
|
3080
|
-
|
|
3464
|
+
return settleIntent(lockIntent(buildIntent({
|
|
3465
|
+
...b1,
|
|
3466
|
+
...b2
|
|
3467
|
+
}), placedAt));
|
|
3468
|
+
};
|
|
3469
|
+
const placedResult = (orderId) => {
|
|
3470
|
+
const row = load(orderId);
|
|
3471
|
+
return {
|
|
3472
|
+
order: documentOf(row),
|
|
3473
|
+
display_number: row.display_number ?? "",
|
|
3474
|
+
created: false
|
|
3081
3475
|
};
|
|
3082
|
-
|
|
3083
|
-
|
|
3084
|
-
|
|
3476
|
+
};
|
|
3477
|
+
const assertOpenLocal = (row) => {
|
|
3478
|
+
const current = documentOf(row);
|
|
3479
|
+
if (row.origin !== "local" || current.status !== "OPEN") throw refuse$1("ORDER_NOT_EDITABLE", 409, { status: current.status });
|
|
3480
|
+
assertNotExpired(row);
|
|
3481
|
+
return current;
|
|
3482
|
+
};
|
|
3483
|
+
/** The order priced and checked exactly as the cloud's import will. */
|
|
3484
|
+
const checkedForPlace = (row) => {
|
|
3485
|
+
const current = assertOpenLocal(row);
|
|
3486
|
+
if (current.lines.length === 0) throw refuse$1("ORDER_EMPTY", 422);
|
|
3487
|
+
if ((current.redeem ?? []).length > 0) throw refuse$1("LOCAL_REDEMPTION_UNAVAILABLE", 422);
|
|
3488
|
+
const state = readOrderState(db);
|
|
3489
|
+
const order = priceOrder(current, state);
|
|
3490
|
+
const check = checkOrder(order, state, now());
|
|
3491
|
+
if (!check.ok) {
|
|
3492
|
+
const details = {
|
|
3493
|
+
issues: check.issues,
|
|
3494
|
+
lines: check.lines
|
|
3495
|
+
};
|
|
3496
|
+
throw refuse$1("ORDER_VALIDATION_FAILED", 422, details);
|
|
3497
|
+
}
|
|
3498
|
+
const total = new Big(String(order.totals.total));
|
|
3499
|
+
assertOfflineLimits(total);
|
|
3500
|
+
return {
|
|
3501
|
+
order,
|
|
3502
|
+
total
|
|
3085
3503
|
};
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3504
|
+
};
|
|
3505
|
+
/** Paid in full: display number, CLOSED and `order.placed` (§4.4). */
|
|
3506
|
+
const finalize = (input) => {
|
|
3507
|
+
const { row, order, intent, placedAt } = input;
|
|
3508
|
+
const prefix = options.settings().display_number_prefix;
|
|
3509
|
+
const displayNumber = nextDisplayNumber(db, prefix, options.nodeUid);
|
|
3510
|
+
const fulfillment = LOCAL_PLACED_FULFILLMENT_STATUS;
|
|
3511
|
+
const placedOrder = {
|
|
3512
|
+
...order,
|
|
3513
|
+
payment_intents: [intent],
|
|
3514
|
+
payment_status: derivePaymentStatus(intent),
|
|
3515
|
+
status: "CLOSED",
|
|
3516
|
+
fulfillment_status: fulfillment,
|
|
3517
|
+
device_id: input.deviceId ?? order.device_id ?? null,
|
|
3518
|
+
metadata: {
|
|
3519
|
+
...order.metadata,
|
|
3520
|
+
display_number: displayNumber
|
|
3521
|
+
}
|
|
3093
3522
|
};
|
|
3094
|
-
const
|
|
3095
|
-
|
|
3096
|
-
|
|
3097
|
-
|
|
3098
|
-
|
|
3099
|
-
},
|
|
3523
|
+
const rev = row.rev + 1;
|
|
3524
|
+
const createdAt = String(order.issued_at ?? placedAt);
|
|
3525
|
+
const payload = {
|
|
3526
|
+
order: documentPayload(placedOrder, rev, createdAt),
|
|
3527
|
+
payment_intents: JSON.parse(JSON.stringify([intent])),
|
|
3100
3528
|
placed_at: placedAt,
|
|
3101
|
-
|
|
3102
|
-
|
|
3103
|
-
const tender = {
|
|
3104
|
-
...t1,
|
|
3105
|
-
...t2,
|
|
3106
|
-
...t3,
|
|
3107
|
-
...t4,
|
|
3108
|
-
...t5,
|
|
3109
|
-
...t6,
|
|
3110
|
-
...t7
|
|
3111
|
-
};
|
|
3112
|
-
const i1 = {
|
|
3113
|
-
id: `pi_${id}`,
|
|
3114
|
-
totals: order.totals,
|
|
3115
|
-
is_mixed: false
|
|
3529
|
+
display_number: displayNumber,
|
|
3530
|
+
fulfillment_status: fulfillment
|
|
3116
3531
|
};
|
|
3117
|
-
const
|
|
3118
|
-
|
|
3119
|
-
|
|
3532
|
+
const ref = stateRef();
|
|
3533
|
+
const b1 = {
|
|
3534
|
+
order: placedOrder,
|
|
3535
|
+
origin: "local",
|
|
3536
|
+
rev
|
|
3120
3537
|
};
|
|
3121
|
-
const
|
|
3122
|
-
|
|
3123
|
-
|
|
3124
|
-
|
|
3538
|
+
const b2 = {
|
|
3539
|
+
displayNumber,
|
|
3540
|
+
placed: payload,
|
|
3541
|
+
state: ref,
|
|
3542
|
+
now: placedAt
|
|
3125
3543
|
};
|
|
3126
|
-
|
|
3127
|
-
|
|
3128
|
-
...
|
|
3129
|
-
|
|
3130
|
-
|
|
3131
|
-
|
|
3544
|
+
savePendingOrder(db, {
|
|
3545
|
+
...b1,
|
|
3546
|
+
...b2
|
|
3547
|
+
});
|
|
3548
|
+
const event = {
|
|
3549
|
+
type: "order.placed",
|
|
3550
|
+
aggregate: {
|
|
3551
|
+
type: "order",
|
|
3552
|
+
id: order.id
|
|
3553
|
+
},
|
|
3554
|
+
payload
|
|
3132
3555
|
};
|
|
3133
|
-
const
|
|
3556
|
+
const key = `order.placed:${order.id}`;
|
|
3557
|
+
appendEvent(db, {
|
|
3558
|
+
...event,
|
|
3559
|
+
idempotencyKey: key
|
|
3560
|
+
}, context());
|
|
3134
3561
|
return {
|
|
3135
|
-
|
|
3136
|
-
|
|
3562
|
+
order: placedOrder,
|
|
3563
|
+
display_number: displayNumber,
|
|
3564
|
+
created: true
|
|
3137
3565
|
};
|
|
3138
3566
|
};
|
|
3139
|
-
const
|
|
3140
|
-
const
|
|
3141
|
-
|
|
3142
|
-
order
|
|
3143
|
-
|
|
3144
|
-
|
|
3567
|
+
const saveDocument = (row, order) => {
|
|
3568
|
+
const at = now().toISOString();
|
|
3569
|
+
const b1 = {
|
|
3570
|
+
order,
|
|
3571
|
+
origin: row.origin,
|
|
3572
|
+
rev: row.rev
|
|
3145
3573
|
};
|
|
3574
|
+
savePendingOrder(db, {
|
|
3575
|
+
...b1,
|
|
3576
|
+
state: stateRef(),
|
|
3577
|
+
now: at
|
|
3578
|
+
});
|
|
3579
|
+
return order;
|
|
3146
3580
|
};
|
|
3147
3581
|
/**
|
|
3148
|
-
*
|
|
3149
|
-
*
|
|
3150
|
-
* Placing the same order again returns the first result.
|
|
3582
|
+
* `PUT orders/:id/payment-intent`: a DRAFT intent with one tender for the
|
|
3583
|
+
* whole total. Replaces an earlier DRAFT; a LOCKED one cannot change.
|
|
3151
3584
|
*/
|
|
3152
|
-
const
|
|
3585
|
+
const putIntent = (orderId, body) => {
|
|
3153
3586
|
assertDiskAccepts();
|
|
3154
3587
|
return committed(() => {
|
|
3155
3588
|
const row = load(orderId);
|
|
3156
|
-
if (row.placed) return placedResult(orderId);
|
|
3157
3589
|
const current = documentOf(row);
|
|
3158
|
-
if (
|
|
3159
|
-
|
|
3160
|
-
|
|
3161
|
-
const
|
|
3162
|
-
|
|
3163
|
-
const at = now();
|
|
3164
|
-
const check = checkOrder(order, state, at);
|
|
3165
|
-
if (!check.ok) {
|
|
3590
|
+
if (activeLocalIntent(current)?.status === "LOCKED") throw refuse$1("PAYMENT_INTENT_LOCKED", 409);
|
|
3591
|
+
assertOpenLocal(row);
|
|
3592
|
+
const input = readTenderInput(body);
|
|
3593
|
+
const payment = localPayment(input.paymentId, input.method);
|
|
3594
|
+
if (LOCAL_DEVICE_PAYMENT_METHODS.includes(payment.method) && input.collectAt !== "DEVICE") {
|
|
3166
3595
|
const details = {
|
|
3167
|
-
|
|
3168
|
-
|
|
3596
|
+
method: payment.method,
|
|
3597
|
+
collect_at: input.collectAt
|
|
3169
3598
|
};
|
|
3170
|
-
throw refuse("
|
|
3599
|
+
throw refuse$1("PAYMENT_NOT_OFFLINE_CAPABLE", 422, details);
|
|
3171
3600
|
}
|
|
3172
|
-
const
|
|
3173
|
-
|
|
3174
|
-
const
|
|
3175
|
-
const tendered = new Big(body.tendered ?? total.toFixed());
|
|
3176
|
-
if (tendered.lt(total)) {
|
|
3177
|
-
const details = {
|
|
3178
|
-
total: total.toFixed(),
|
|
3179
|
-
tendered: tendered.toFixed()
|
|
3180
|
-
};
|
|
3181
|
-
throw refuse("CASH_TENDERED_INSUFFICIENT", 422, details);
|
|
3182
|
-
}
|
|
3183
|
-
const placedAt = at.toISOString();
|
|
3184
|
-
const collectAt = body.collect_at ?? "COUNTER";
|
|
3185
|
-
const p1 = {
|
|
3601
|
+
const order = priceOrder(current, readOrderState(db));
|
|
3602
|
+
const id = uuidv7(now().getTime());
|
|
3603
|
+
const b1 = {
|
|
3186
3604
|
order,
|
|
3187
|
-
|
|
3188
|
-
|
|
3189
|
-
|
|
3605
|
+
payment,
|
|
3606
|
+
collectAt: input.collectAt,
|
|
3607
|
+
id
|
|
3190
3608
|
};
|
|
3191
|
-
const
|
|
3192
|
-
|
|
3193
|
-
|
|
3609
|
+
const b2 = {
|
|
3610
|
+
details: input.details,
|
|
3611
|
+
metadata: input.metadata
|
|
3612
|
+
};
|
|
3613
|
+
const intent = buildIntent({
|
|
3614
|
+
...b1,
|
|
3615
|
+
...b2,
|
|
3616
|
+
status: "IDLE"
|
|
3194
3617
|
});
|
|
3195
|
-
|
|
3196
|
-
const displayNumber = nextDisplayNumber(db, prefix, options.nodeUid);
|
|
3197
|
-
const fulfillment = LOCAL_PLACED_FULFILLMENT_STATUS;
|
|
3198
|
-
const placedOrder = {
|
|
3618
|
+
return saveDocument(row, {
|
|
3199
3619
|
...order,
|
|
3200
|
-
payment_intents: [intent]
|
|
3201
|
-
|
|
3202
|
-
|
|
3203
|
-
|
|
3204
|
-
|
|
3205
|
-
|
|
3206
|
-
|
|
3207
|
-
|
|
3208
|
-
|
|
3620
|
+
payment_intents: [intent]
|
|
3621
|
+
});
|
|
3622
|
+
});
|
|
3623
|
+
};
|
|
3624
|
+
const deleteIntent = (orderId) => {
|
|
3625
|
+
return committed(() => {
|
|
3626
|
+
const row = load(orderId);
|
|
3627
|
+
const current = documentOf(row);
|
|
3628
|
+
const intent = activeLocalIntent(current);
|
|
3629
|
+
if (!intent) return current;
|
|
3630
|
+
if (intent.status !== "DRAFT") throw refuse$1("PAYMENT_INTENT_LOCKED", 409);
|
|
3631
|
+
assertOpenLocal(row);
|
|
3632
|
+
return saveDocument(row, {
|
|
3633
|
+
...current,
|
|
3634
|
+
payment_intents: []
|
|
3635
|
+
});
|
|
3636
|
+
});
|
|
3637
|
+
};
|
|
3638
|
+
/** Cash in full now; a device pinpad locks and waits for its result. */
|
|
3639
|
+
const placeWithIntent = (row, intentId, body, deviceId) => {
|
|
3640
|
+
const intent = activeLocalIntent(documentOf(row));
|
|
3641
|
+
if (!intent || intent.id !== intentId || intent.status !== "DRAFT") throw refuse$1("PAYMENT_INTENT_NOT_FOUND", 409, { intent_id: intentId });
|
|
3642
|
+
const tender = intent.tenders[0];
|
|
3643
|
+
if (!tender) throw refuse$1("PAYMENT_INTENT_NOT_FOUND", 409);
|
|
3644
|
+
const { order, total } = checkedForPlace(row);
|
|
3645
|
+
const payment = localPayment(tender.payment_id, tender.method);
|
|
3646
|
+
const placedAt = now().toISOString();
|
|
3647
|
+
if (payment.method === "CASH") {
|
|
3648
|
+
const b1 = {
|
|
3649
|
+
order,
|
|
3650
|
+
payment,
|
|
3651
|
+
tendered: cashTendered(body.tendered, total),
|
|
3652
|
+
collectAt: tender.collect_at === "DEVICE" ? "COUNTER" : tender.collect_at,
|
|
3653
|
+
placedAt
|
|
3209
3654
|
};
|
|
3210
|
-
const
|
|
3211
|
-
|
|
3212
|
-
|
|
3213
|
-
order
|
|
3214
|
-
|
|
3215
|
-
|
|
3216
|
-
|
|
3217
|
-
|
|
3655
|
+
const paid = cashIntent(b1);
|
|
3656
|
+
return finalize({
|
|
3657
|
+
row,
|
|
3658
|
+
order,
|
|
3659
|
+
intent: paid,
|
|
3660
|
+
deviceId,
|
|
3661
|
+
placedAt
|
|
3662
|
+
});
|
|
3663
|
+
}
|
|
3664
|
+
const locked = lockIntent(refreshIntent(intent, order), placedAt);
|
|
3665
|
+
const lockedOrder = {
|
|
3666
|
+
...order,
|
|
3667
|
+
payment_intents: [locked],
|
|
3668
|
+
status: "CLOSED",
|
|
3669
|
+
device_id: deviceId ?? order.device_id ?? null
|
|
3670
|
+
};
|
|
3671
|
+
saveDocument(row, lockedOrder);
|
|
3672
|
+
return {
|
|
3673
|
+
order: lockedOrder,
|
|
3674
|
+
display_number: "",
|
|
3675
|
+
created: true
|
|
3676
|
+
};
|
|
3677
|
+
};
|
|
3678
|
+
const cashTendered = (raw, total) => {
|
|
3679
|
+
const tendered = new Big(raw ?? total.toFixed());
|
|
3680
|
+
if (tendered.lt(total)) {
|
|
3681
|
+
const details = {
|
|
3682
|
+
total: total.toFixed(),
|
|
3683
|
+
tendered: tendered.toFixed()
|
|
3218
3684
|
};
|
|
3219
|
-
|
|
3220
|
-
|
|
3221
|
-
|
|
3222
|
-
|
|
3223
|
-
|
|
3685
|
+
throw refuse$1("CASH_TENDERED_INSUFFICIENT", 422, details);
|
|
3686
|
+
}
|
|
3687
|
+
return tendered;
|
|
3688
|
+
};
|
|
3689
|
+
/**
|
|
3690
|
+
* Places the order. Cash is charged and closed at once; with an
|
|
3691
|
+
* `intent_id` for a device pinpad the order locks until the device
|
|
3692
|
+
* reports the charge. It is checked first exactly as the cloud will
|
|
3693
|
+
* check it on import; a refusal changes nothing. Placing the same order
|
|
3694
|
+
* again returns the first result.
|
|
3695
|
+
*/
|
|
3696
|
+
const place = (orderId, body = {}, deviceId = null) => {
|
|
3697
|
+
assertDiskAccepts();
|
|
3698
|
+
return committed(() => {
|
|
3699
|
+
const row = load(orderId);
|
|
3700
|
+
if (row.placed) return placedResult(orderId);
|
|
3701
|
+
const current = documentOf(row);
|
|
3702
|
+
if (activeLocalIntent(current)?.status === "LOCKED") return {
|
|
3703
|
+
order: current,
|
|
3704
|
+
display_number: "",
|
|
3705
|
+
created: false
|
|
3224
3706
|
};
|
|
3225
|
-
|
|
3226
|
-
|
|
3227
|
-
|
|
3228
|
-
|
|
3229
|
-
|
|
3707
|
+
if (body.intent_id) return placeWithIntent(row, body.intent_id, body, deviceId);
|
|
3708
|
+
const { order, total } = checkedForPlace(row);
|
|
3709
|
+
const payment = localPayment(body.payment_id);
|
|
3710
|
+
const tendered = cashTendered(body.tendered, total);
|
|
3711
|
+
const placedAt = now().toISOString();
|
|
3712
|
+
const b1 = {
|
|
3713
|
+
order,
|
|
3714
|
+
payment,
|
|
3715
|
+
tendered,
|
|
3716
|
+
collectAt: body.collect_at ?? "COUNTER",
|
|
3717
|
+
placedAt
|
|
3230
3718
|
};
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3719
|
+
const intent = cashIntent(b1);
|
|
3720
|
+
return finalize({
|
|
3721
|
+
row,
|
|
3722
|
+
order,
|
|
3723
|
+
intent,
|
|
3724
|
+
deviceId,
|
|
3725
|
+
placedAt
|
|
3234
3726
|
});
|
|
3235
|
-
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
3241
|
-
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3727
|
+
});
|
|
3728
|
+
};
|
|
3729
|
+
/**
|
|
3730
|
+
* `POST orders/:id/payments`: the device reports one pinpad attempt.
|
|
3731
|
+
* PAID places the order (display number, `order.placed`); FAILED keeps
|
|
3732
|
+
* it locked for a retry with a new attempt reference. A repeated result
|
|
3733
|
+
* changes nothing.
|
|
3734
|
+
*/
|
|
3735
|
+
const recordPayment = (orderId, raw) => {
|
|
3736
|
+
const body = readRecordPayment(raw);
|
|
3737
|
+
return committed(() => {
|
|
3738
|
+
const row = load(orderId);
|
|
3739
|
+
const current = documentOf(row);
|
|
3740
|
+
const intent = activeLocalIntent(current);
|
|
3741
|
+
const tender = intent?.tenders.find((item) => item.id === body.tender_id);
|
|
3742
|
+
if (!intent || !tender) {
|
|
3743
|
+
const details = { tender_id: body.tender_id };
|
|
3744
|
+
throw refuse$1("TENDER_NOT_FOUND", 404, details);
|
|
3745
|
+
}
|
|
3746
|
+
if (row.placed || tender.status === "PAID") return current;
|
|
3747
|
+
if (intent.status !== "LOCKED") throw refuse$1("ORDER_NOT_PLACED", 409);
|
|
3748
|
+
const match = matchAttempt(tender, body.attempt_reference);
|
|
3749
|
+
if (match === "stale") return current;
|
|
3750
|
+
if (match === "mismatch") {
|
|
3751
|
+
const details = { attempt_reference: tender.attempt_reference };
|
|
3752
|
+
throw refuse$1("ATTEMPT_REFERENCE_MISMATCH", 409, details);
|
|
3753
|
+
}
|
|
3754
|
+
const at = now().toISOString();
|
|
3755
|
+
const nextTender = applyAttempt(tender, body, at);
|
|
3756
|
+
const tenders = intent.tenders.map((item) => {
|
|
3757
|
+
return item.id === tender.id ? nextTender : item;
|
|
3758
|
+
});
|
|
3759
|
+
const nextIntent = settleIntent({
|
|
3760
|
+
...intent,
|
|
3761
|
+
tenders
|
|
3762
|
+
});
|
|
3763
|
+
const order = {
|
|
3764
|
+
...current,
|
|
3765
|
+
payment_intents: [nextIntent]
|
|
3252
3766
|
};
|
|
3767
|
+
if (body.status !== "PAID") {
|
|
3768
|
+
const status = derivePaymentStatus(nextIntent);
|
|
3769
|
+
return saveDocument(row, {
|
|
3770
|
+
...order,
|
|
3771
|
+
payment_status: status
|
|
3772
|
+
});
|
|
3773
|
+
}
|
|
3774
|
+
return finalize({
|
|
3775
|
+
row,
|
|
3776
|
+
order,
|
|
3777
|
+
intent: nextIntent,
|
|
3778
|
+
placedAt: at,
|
|
3779
|
+
deviceId: current.device_id ?? null
|
|
3780
|
+
}).order;
|
|
3253
3781
|
});
|
|
3254
3782
|
};
|
|
3255
3783
|
/**
|
|
@@ -3259,10 +3787,10 @@ const createOrderService = (options) => {
|
|
|
3259
3787
|
*/
|
|
3260
3788
|
const changeFulfillment = (orderId, to, actor = {}) => {
|
|
3261
3789
|
const target = to.trim().toUpperCase();
|
|
3262
|
-
if (!target) throw refuse("VALIDATION_ERROR", 400, { field: "status" });
|
|
3790
|
+
if (!target) throw refuse$1("VALIDATION_ERROR", 400, { field: "status" });
|
|
3263
3791
|
return committed(() => {
|
|
3264
3792
|
const row = load(orderId);
|
|
3265
|
-
if (!row.placed) throw refuse("ORDER_NOT_PLACED", 409);
|
|
3793
|
+
if (!row.placed) throw refuse$1("ORDER_NOT_PLACED", 409);
|
|
3266
3794
|
const order = documentOf(row);
|
|
3267
3795
|
const from = order.fulfillment_status;
|
|
3268
3796
|
if (from === target) return order;
|
|
@@ -3307,7 +3835,10 @@ const createOrderService = (options) => {
|
|
|
3307
3835
|
update,
|
|
3308
3836
|
validate,
|
|
3309
3837
|
place,
|
|
3310
|
-
changeFulfillment
|
|
3838
|
+
changeFulfillment,
|
|
3839
|
+
putIntent,
|
|
3840
|
+
deleteIntent,
|
|
3841
|
+
recordPayment
|
|
3311
3842
|
};
|
|
3312
3843
|
};
|
|
3313
3844
|
//#endregion
|
|
@@ -3324,11 +3855,11 @@ const publicRow = (row) => {
|
|
|
3324
3855
|
return out;
|
|
3325
3856
|
};
|
|
3326
3857
|
const notFound = (code) => new LocalRuntimeError(code, 404);
|
|
3327
|
-
const isActive = (row) => {
|
|
3858
|
+
const isActive$1 = (row) => {
|
|
3328
3859
|
return row.status === void 0 || row.status === "ACTIVE";
|
|
3329
3860
|
};
|
|
3330
3861
|
const rowsOf = (db, section) => {
|
|
3331
|
-
return readSectionRows(db, section).filter(isActive).map(publicRow);
|
|
3862
|
+
return readSectionRows(db, section).filter(isActive$1).map(publicRow);
|
|
3332
3863
|
};
|
|
3333
3864
|
const findById = (rows, id, code) => {
|
|
3334
3865
|
const row = rows.find((item) => item.id === id);
|
|
@@ -3427,14 +3958,23 @@ const toMerchantPayment = (row) => {
|
|
|
3427
3958
|
...b6
|
|
3428
3959
|
};
|
|
3429
3960
|
};
|
|
3430
|
-
/**
|
|
3431
|
-
|
|
3432
|
-
|
|
3433
|
-
|
|
3434
|
-
|
|
3435
|
-
|
|
3961
|
+
/**
|
|
3962
|
+
* Payments that work on this node, in scope: cash (within
|
|
3963
|
+
* `offlinePaymentIds`) always, device pinpads only while the node reaches
|
|
3964
|
+
* the internet.
|
|
3965
|
+
*/
|
|
3966
|
+
const listLocalPayments = (db, scope, offlinePaymentIds, internetReachable = false) => {
|
|
3967
|
+
const cash = LOCAL_OFFLINE_PAYMENT_METHODS;
|
|
3968
|
+
const device = LOCAL_DEVICE_PAYMENT_METHODS;
|
|
3969
|
+
const usable = (row) => {
|
|
3970
|
+
const method = String(row.payment_method);
|
|
3971
|
+
if (device.includes(method)) return internetReachable;
|
|
3972
|
+
if (!cash.includes(method)) return false;
|
|
3436
3973
|
const allowed = offlinePaymentIds;
|
|
3437
|
-
|
|
3974
|
+
return allowed.length === 0 || allowed.includes(String(row.id));
|
|
3975
|
+
};
|
|
3976
|
+
return readSectionRows(db, "payments").filter((row) => {
|
|
3977
|
+
if (!isActive$1(row) || !usable(row)) return false;
|
|
3438
3978
|
const s1 = inScope(row.store_ids, row.store_label_ids, scope.store_id);
|
|
3439
3979
|
const c = [row.channel_ids, row.channel_label_ids];
|
|
3440
3980
|
const s2 = inScope(...c, scope.channel_id);
|
|
@@ -3446,6 +3986,52 @@ const listLocalPayments = (db, scope, offlinePaymentIds) => {
|
|
|
3446
3986
|
}).map(toMerchantPayment);
|
|
3447
3987
|
};
|
|
3448
3988
|
//#endregion
|
|
3989
|
+
//#region src/handlers/fulfillment.ts
|
|
3990
|
+
/**
|
|
3991
|
+
* `GET orders/:id/fulfillment` on the node: the fields the SDK reads to
|
|
3992
|
+
* follow an order by polling (realtime is cloud only). A placed, paid
|
|
3993
|
+
* order is released; one still waiting for its pinpad is pending.
|
|
3994
|
+
*/
|
|
3995
|
+
const fulfillmentSnapshot = (order) => {
|
|
3996
|
+
const status = String(order.fulfillment_status ?? "IDLE");
|
|
3997
|
+
const released = order.payment_status === "PAID" && order.status !== "OPEN";
|
|
3998
|
+
const nodeId = `local:${status}`;
|
|
3999
|
+
const workflow = {
|
|
4000
|
+
nodes: [{
|
|
4001
|
+
id: nodeId,
|
|
4002
|
+
type: "status",
|
|
4003
|
+
data: { mappedStatus: status }
|
|
4004
|
+
}],
|
|
4005
|
+
edges: []
|
|
4006
|
+
};
|
|
4007
|
+
const b1 = {
|
|
4008
|
+
id: order.id,
|
|
4009
|
+
order_id: order.id
|
|
4010
|
+
};
|
|
4011
|
+
const b2 = { status: released ? "SUCCESS" : "WAITING" };
|
|
4012
|
+
const b3 = { checkout_state: released ? "released" : "pending" };
|
|
4013
|
+
const b4 = {
|
|
4014
|
+
current_node_ids: [nodeId],
|
|
4015
|
+
workflow,
|
|
4016
|
+
error: null
|
|
4017
|
+
};
|
|
4018
|
+
const b5 = { customer_id: order.customer_id ?? "" };
|
|
4019
|
+
const b6 = { payment_status: order.payment_status };
|
|
4020
|
+
const b7 = {
|
|
4021
|
+
fulfillment_status: status,
|
|
4022
|
+
origin: "local"
|
|
4023
|
+
};
|
|
4024
|
+
return {
|
|
4025
|
+
...b1,
|
|
4026
|
+
...b2,
|
|
4027
|
+
...b3,
|
|
4028
|
+
...b4,
|
|
4029
|
+
...b5,
|
|
4030
|
+
...b6,
|
|
4031
|
+
...b7
|
|
4032
|
+
};
|
|
4033
|
+
};
|
|
4034
|
+
//#endregion
|
|
3449
4035
|
//#region src/handlers/messages.ts
|
|
3450
4036
|
const MESSAGES = {
|
|
3451
4037
|
LOCAL_MODE_UNAVAILABLE: {
|
|
@@ -3463,6 +4049,11 @@ const MESSAGES = {
|
|
|
3463
4049
|
"en-US": "This order is not on the local device. Create it again here.",
|
|
3464
4050
|
"pt-BR": "Este pedido não está no equipamento local. Crie-o novamente aqui."
|
|
3465
4051
|
},
|
|
4052
|
+
LOCAL_CART_EXPIRED: {
|
|
4053
|
+
es: "Este carrito venció por inactividad. Empieza un pedido nuevo.",
|
|
4054
|
+
"en-US": "This cart expired after inactivity. Start a new order.",
|
|
4055
|
+
"pt-BR": "Este carrinho expirou por inatividade. Comece um novo pedido."
|
|
4056
|
+
},
|
|
3466
4057
|
LOCAL_NODE_DRAINING: {
|
|
3467
4058
|
es: "Estamos volviendo a la nube. Tu pedido sigue en unos segundos.",
|
|
3468
4059
|
"en-US": "Switching back to the cloud. Your order continues in seconds.",
|
|
@@ -3512,6 +4103,21 @@ const MESSAGES = {
|
|
|
3512
4103
|
es: "Los canjes y recompensas no están disponibles sin conexión.",
|
|
3513
4104
|
"en-US": "Rewards and redemptions are not available offline.",
|
|
3514
4105
|
"pt-BR": "Resgates e recompensas não estão disponíveis offline."
|
|
4106
|
+
},
|
|
4107
|
+
LOCAL_MIXED_PAYMENT_UNAVAILABLE: {
|
|
4108
|
+
es: "En modo local se paga con un solo medio de pago.",
|
|
4109
|
+
"en-US": "In local mode an order is paid with one payment method.",
|
|
4110
|
+
"pt-BR": "No modo local, o pedido é pago com um só meio de pagamento."
|
|
4111
|
+
},
|
|
4112
|
+
PAYMENT_INTENT_NOT_FOUND: {
|
|
4113
|
+
es: "No encontramos el pago de este pedido. Elige el medio de pago otra vez.",
|
|
4114
|
+
"en-US": "We could not find this order's payment. Choose a method again.",
|
|
4115
|
+
"pt-BR": "Não encontramos o pagamento deste pedido. Escolha o meio de pagamento de novo."
|
|
4116
|
+
},
|
|
4117
|
+
PAYMENT_INTENT_LOCKED: {
|
|
4118
|
+
es: "Este pago ya está en curso y no se puede cambiar.",
|
|
4119
|
+
"en-US": "This payment is already in progress and cannot change.",
|
|
4120
|
+
"pt-BR": "Este pagamento já está em andamento e não pode mudar."
|
|
3515
4121
|
}
|
|
3516
4122
|
};
|
|
3517
4123
|
/** Best match of an `Accept-Language` header; Spanish by default. */
|
|
@@ -3587,6 +4193,191 @@ const bearerOf = (request) => {
|
|
|
3587
4193
|
if (scheme?.toLowerCase() !== "bearer" || !token) return null;
|
|
3588
4194
|
return token.trim();
|
|
3589
4195
|
};
|
|
4196
|
+
//#endregion
|
|
4197
|
+
//#region src/handlers/pos.ts
|
|
4198
|
+
const refuse = (code, status, details = {}) => {
|
|
4199
|
+
return new LocalRuntimeError(code, status, details);
|
|
4200
|
+
};
|
|
4201
|
+
const text = (body, field) => {
|
|
4202
|
+
const value = body[field];
|
|
4203
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
4204
|
+
throw refuse("VALIDATION_ERROR", 400, { field });
|
|
4205
|
+
};
|
|
4206
|
+
const optionalText = (value) => {
|
|
4207
|
+
return typeof value === "string" && value.trim() ? value.trim() : null;
|
|
4208
|
+
};
|
|
4209
|
+
const isRecord = (value) => {
|
|
4210
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
4211
|
+
};
|
|
4212
|
+
const isActive = (row) => {
|
|
4213
|
+
return row.status === void 0 || row.status === "ACTIVE";
|
|
4214
|
+
};
|
|
4215
|
+
/** Same id as the cloud (`POS-<client_id>`), so a replay finds the sale. */
|
|
4216
|
+
const posOrderId = (clientId) => `POS-${clientId}`;
|
|
4217
|
+
/** Same walk-in customer as the cloud: one per register. */
|
|
4218
|
+
const posWalkInCustomerId = (deviceUid) => {
|
|
4219
|
+
return `pos-walkin-${deviceUid}`;
|
|
4220
|
+
};
|
|
4221
|
+
const walkInCustomer = (name) => {
|
|
4222
|
+
const display_name = name.trim() || "POS";
|
|
4223
|
+
return { customer_info: {
|
|
4224
|
+
display_name,
|
|
4225
|
+
first_name: display_name,
|
|
4226
|
+
last_name: display_name,
|
|
4227
|
+
email: "unknown@example.com",
|
|
4228
|
+
phone: "+10000000000"
|
|
4229
|
+
} };
|
|
4230
|
+
};
|
|
4231
|
+
const decimalText = (value) => {
|
|
4232
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
4233
|
+
return optionalText(value);
|
|
4234
|
+
};
|
|
4235
|
+
/**
|
|
4236
|
+
* The register's routes served by the node (§4.6): catalog, operators and
|
|
4237
|
+
* cash sales. Device uid + secret in the body, like the cloud. Cash
|
|
4238
|
+
* sessions stay on the register's outbox until the cloud is back.
|
|
4239
|
+
*/
|
|
4240
|
+
const createPosHandlers = (options) => {
|
|
4241
|
+
const { db, auth, orders } = options;
|
|
4242
|
+
const posDevice = async (body) => {
|
|
4243
|
+
const uid = text(body, "device_uid");
|
|
4244
|
+
const secret = text(body, "device_secret");
|
|
4245
|
+
const entry = await auth.authenticateDevice(uid, secret);
|
|
4246
|
+
if (entry.kind !== "POS") throw refuse("DEVICE_NOT_POS", 403);
|
|
4247
|
+
return entry.device;
|
|
4248
|
+
};
|
|
4249
|
+
/** `POST pos/catalog`: menus, fulfillment and preferences of the node. */
|
|
4250
|
+
const catalog = async (body) => {
|
|
4251
|
+
const channel = (await posDevice(body)).channel_id;
|
|
4252
|
+
const fulfillments = listLocalFulfillment(db);
|
|
4253
|
+
const seen = /* @__PURE__ */ new Set();
|
|
4254
|
+
const menus = [];
|
|
4255
|
+
for (const row of fulfillments) {
|
|
4256
|
+
const scope = {
|
|
4257
|
+
channel_id: channel,
|
|
4258
|
+
fulfillment_id: String(row.id)
|
|
4259
|
+
};
|
|
4260
|
+
for (const menu of listLocalMenus(db, scope)) {
|
|
4261
|
+
const id = String(menu.id);
|
|
4262
|
+
if (seen.has(id)) continue;
|
|
4263
|
+
seen.add(id);
|
|
4264
|
+
menus.push(menu);
|
|
4265
|
+
}
|
|
4266
|
+
}
|
|
4267
|
+
return {
|
|
4268
|
+
menus,
|
|
4269
|
+
fulfillments,
|
|
4270
|
+
preferences: getLocalPreferences(db),
|
|
4271
|
+
fetched_at: options.now().toISOString()
|
|
4272
|
+
};
|
|
4273
|
+
};
|
|
4274
|
+
/** `POST pos/operators`: active operators cached for this store. */
|
|
4275
|
+
const operators = async (body) => {
|
|
4276
|
+
await posDevice(body);
|
|
4277
|
+
return readSectionRows(db, "pos_operators").filter(isActive);
|
|
4278
|
+
};
|
|
4279
|
+
const findOperator = (operatorId) => {
|
|
4280
|
+
const operator = readSectionRows(db, "pos_operators").filter(isActive).find((row) => row.id === operatorId);
|
|
4281
|
+
if (!operator) throw refuse("OPERATOR_NOT_ASSIGNED", 403);
|
|
4282
|
+
return operator;
|
|
4283
|
+
};
|
|
4284
|
+
/**
|
|
4285
|
+
* `POST pos/orders`: a cash sale, created and placed in one call.
|
|
4286
|
+
* Idempotent by `client_id`: a replay returns the same order.
|
|
4287
|
+
*/
|
|
4288
|
+
const createOrder = async (body) => {
|
|
4289
|
+
const device = await posDevice(body);
|
|
4290
|
+
const clientId = text(body, "client_id");
|
|
4291
|
+
const orderId = posOrderId(clientId);
|
|
4292
|
+
if ((Array.isArray(body.tenders) ? body.tenders : []).length > 1) throw refuse("LOCAL_MIXED_PAYMENT_UNAVAILABLE", 422);
|
|
4293
|
+
const payment = isRecord(body.payment) ? body.payment : {};
|
|
4294
|
+
const paymentId = text(payment, "payment_id");
|
|
4295
|
+
const operator = findOperator(text(body, "operator_id"));
|
|
4296
|
+
if (!readPendingOrder(db, orderId)) {
|
|
4297
|
+
const name = optionalText(body.customer_name) ?? device.alias ?? "";
|
|
4298
|
+
let customer = walkInCustomer(name);
|
|
4299
|
+
if (isRecord(body.customer)) customer = body.customer;
|
|
4300
|
+
const m1 = {
|
|
4301
|
+
device_uid: device.uid,
|
|
4302
|
+
device_id: device.id
|
|
4303
|
+
};
|
|
4304
|
+
const m2 = {
|
|
4305
|
+
operator_uid: operator.uid,
|
|
4306
|
+
operator_id: operator.id
|
|
4307
|
+
};
|
|
4308
|
+
const m3 = {
|
|
4309
|
+
client_id: clientId,
|
|
4310
|
+
session_uid: null
|
|
4311
|
+
};
|
|
4312
|
+
const m4 = { tendered: decimalText(payment.tendered) };
|
|
4313
|
+
const m5 = { change: decimalText(payment.change) };
|
|
4314
|
+
const m6 = { occurred_at: optionalText(body.occurred_at) };
|
|
4315
|
+
const m7 = { notes: optionalText(body.notes) };
|
|
4316
|
+
const pos = {
|
|
4317
|
+
...m1,
|
|
4318
|
+
...m2,
|
|
4319
|
+
...m3,
|
|
4320
|
+
...m4,
|
|
4321
|
+
...m5,
|
|
4322
|
+
...m6,
|
|
4323
|
+
...m7
|
|
4324
|
+
};
|
|
4325
|
+
const c1 = {
|
|
4326
|
+
id: orderId,
|
|
4327
|
+
store_id: device.store_id
|
|
4328
|
+
};
|
|
4329
|
+
const c2 = { channel_id: device.channel_id };
|
|
4330
|
+
const c3 = { fulfillment_id: text(body, "fulfillment_id") };
|
|
4331
|
+
const c4 = {
|
|
4332
|
+
brand_id: optionalText(body.brand_id),
|
|
4333
|
+
is_anonymous: true,
|
|
4334
|
+
customer
|
|
4335
|
+
};
|
|
4336
|
+
const c5 = { lines: Array.isArray(body.lines) ? body.lines : [] };
|
|
4337
|
+
const c6 = { metadata: {
|
|
4338
|
+
source: "POS",
|
|
4339
|
+
pos
|
|
4340
|
+
} };
|
|
4341
|
+
const create = {
|
|
4342
|
+
...c1,
|
|
4343
|
+
...c2,
|
|
4344
|
+
...c3,
|
|
4345
|
+
...c4,
|
|
4346
|
+
...c5,
|
|
4347
|
+
...c6
|
|
4348
|
+
};
|
|
4349
|
+
const actor = {
|
|
4350
|
+
customerId: posWalkInCustomerId(device.uid),
|
|
4351
|
+
deviceId: device.id,
|
|
4352
|
+
subject: device.uid
|
|
4353
|
+
};
|
|
4354
|
+
orders.create(create, actor);
|
|
4355
|
+
}
|
|
4356
|
+
const tendered = decimalText(payment.tendered) ?? void 0;
|
|
4357
|
+
const place = {
|
|
4358
|
+
payment_id: paymentId,
|
|
4359
|
+
collect_at: "COUNTER"
|
|
4360
|
+
};
|
|
4361
|
+
return {
|
|
4362
|
+
order: orders.place(orderId, {
|
|
4363
|
+
...place,
|
|
4364
|
+
tendered
|
|
4365
|
+
}, device.id).order,
|
|
4366
|
+
session: null
|
|
4367
|
+
};
|
|
4368
|
+
};
|
|
4369
|
+
return {
|
|
4370
|
+
catalog,
|
|
4371
|
+
operators,
|
|
4372
|
+
createOrder
|
|
4373
|
+
};
|
|
4374
|
+
};
|
|
4375
|
+
/** Register routes authenticated by device uid + secret in the body. */
|
|
4376
|
+
const POS_ROUTES = {
|
|
4377
|
+
"/pos/catalog": "catalog",
|
|
4378
|
+
"/pos/operators": "operators",
|
|
4379
|
+
"/pos/orders": "createOrder"
|
|
4380
|
+
};
|
|
3590
4381
|
const unavailable = (code = "LOCAL_MODE_UNAVAILABLE") => {
|
|
3591
4382
|
return new LocalRuntimeError(code, 503);
|
|
3592
4383
|
};
|
|
@@ -3604,6 +4395,11 @@ const actorOf = (principal) => {
|
|
|
3604
4395
|
};
|
|
3605
4396
|
};
|
|
3606
4397
|
const toPlaceBody = (body) => {
|
|
4398
|
+
if (typeof body.intent_id === "string" && body.intent_id) {
|
|
4399
|
+
const intent = { intent_id: body.intent_id };
|
|
4400
|
+
if (typeof body.tendered === "string") intent.tendered = body.tendered;
|
|
4401
|
+
return intent;
|
|
4402
|
+
}
|
|
3607
4403
|
const payment = body.payment ?? {};
|
|
3608
4404
|
const type = payment.type;
|
|
3609
4405
|
if (type !== void 0 && type !== "CASH") throw new LocalRuntimeError("PAYMENT_NOT_OFFLINE_CAPABLE", 422, { method: type });
|
|
@@ -3623,6 +4419,12 @@ const toPlaceBody = (body) => {
|
|
|
3623
4419
|
const createStorefrontHandler = (options) => {
|
|
3624
4420
|
const { db, auth, orders } = options;
|
|
3625
4421
|
const now = options.now ?? (() => /* @__PURE__ */ new Date());
|
|
4422
|
+
const pos = createPosHandlers({
|
|
4423
|
+
db,
|
|
4424
|
+
auth,
|
|
4425
|
+
orders,
|
|
4426
|
+
now
|
|
4427
|
+
});
|
|
3626
4428
|
const verifyDevice = async (body) => {
|
|
3627
4429
|
const device = body.device;
|
|
3628
4430
|
if (!device) return null;
|
|
@@ -3652,12 +4454,14 @@ const createStorefrontHandler = (options) => {
|
|
|
3652
4454
|
const validateBody = (body) => {
|
|
3653
4455
|
const order = body;
|
|
3654
4456
|
const lines = Array.isArray(order.lines) ? order.lines : [];
|
|
3655
|
-
const
|
|
4457
|
+
const input = {
|
|
3656
4458
|
...order,
|
|
3657
4459
|
lines,
|
|
3658
4460
|
redeem: order.redeem ?? [],
|
|
3659
4461
|
redemption_steps: order.redemption_steps ?? []
|
|
3660
|
-
}
|
|
4462
|
+
};
|
|
4463
|
+
const checkout = { checkout: body.customer !== void 0 };
|
|
4464
|
+
const result = checkOrder(input, readOrderState(db), now(), checkout);
|
|
3661
4465
|
if (result.ok) return jsonData({ ok: true });
|
|
3662
4466
|
throw new LocalRuntimeError("ORDER_VALIDATION_FAILED", 422, {
|
|
3663
4467
|
issues: result.issues,
|
|
@@ -3730,7 +4534,8 @@ const createStorefrontHandler = (options) => {
|
|
|
3730
4534
|
brand_id: query(url, "brand_id")
|
|
3731
4535
|
};
|
|
3732
4536
|
const ids = options.settings().offline_payment_ids;
|
|
3733
|
-
|
|
4537
|
+
const online = options.internetReachable?.() ?? false;
|
|
4538
|
+
return jsonData(listLocalPayments(db, scope, ids, online));
|
|
3734
4539
|
}
|
|
3735
4540
|
},
|
|
3736
4541
|
{
|
|
@@ -3781,6 +4586,34 @@ const createStorefrontHandler = (options) => {
|
|
|
3781
4586
|
});
|
|
3782
4587
|
}
|
|
3783
4588
|
},
|
|
4589
|
+
{
|
|
4590
|
+
method: "PUT",
|
|
4591
|
+
pattern: /^\/orders\/([^/]+)\/payment-intent$/,
|
|
4592
|
+
handler: async ({ request, params }) => {
|
|
4593
|
+
const body = await readJsonBody(request);
|
|
4594
|
+
return jsonData(orders.putIntent(params[0] ?? "", body));
|
|
4595
|
+
}
|
|
4596
|
+
},
|
|
4597
|
+
{
|
|
4598
|
+
method: "DELETE",
|
|
4599
|
+
pattern: /^\/orders\/([^/]+)\/payment-intent$/,
|
|
4600
|
+
handler: ({ params }) => jsonData(orders.deleteIntent(params[0] ?? ""))
|
|
4601
|
+
},
|
|
4602
|
+
{
|
|
4603
|
+
method: "POST",
|
|
4604
|
+
pattern: /^\/orders\/([^/]+)\/payments$/,
|
|
4605
|
+
handler: async ({ request, params }) => {
|
|
4606
|
+
const body = await readJsonBody(request);
|
|
4607
|
+
return jsonData(orders.recordPayment(params[0] ?? "", body));
|
|
4608
|
+
}
|
|
4609
|
+
},
|
|
4610
|
+
{
|
|
4611
|
+
method: "GET",
|
|
4612
|
+
pattern: /^\/orders\/([^/]+)\/fulfillment$/,
|
|
4613
|
+
handler: ({ params }) => {
|
|
4614
|
+
return jsonData(fulfillmentSnapshot(orders.get(params[0] ?? "")));
|
|
4615
|
+
}
|
|
4616
|
+
},
|
|
3784
4617
|
{
|
|
3785
4618
|
method: "POST",
|
|
3786
4619
|
pattern: /^\/orders\/([^/]+)\/fulfillment\/status$/,
|
|
@@ -3833,6 +4666,11 @@ const createStorefrontHandler = (options) => {
|
|
|
3833
4666
|
if (!isServingMode(options.mode())) throw new LocalRuntimeError("LOCAL_NOT_SERVING", 503);
|
|
3834
4667
|
if (method === "POST" && path === "/local/device-token") return issueToken(request);
|
|
3835
4668
|
if (method === "POST" && path === "/pos/operators/verify") return verifyOperator(await readJsonBody(request));
|
|
4669
|
+
const posRoute = method === "POST" ? POS_ROUTES[path] : void 0;
|
|
4670
|
+
if (posRoute) {
|
|
4671
|
+
const body = await readJsonBody(request);
|
|
4672
|
+
return jsonData(await pos[posRoute](body));
|
|
4673
|
+
}
|
|
3836
4674
|
for (const route of routes) {
|
|
3837
4675
|
if (route.method !== method) continue;
|
|
3838
4676
|
const match = route.pattern.exec(path);
|
|
@@ -3962,14 +4800,23 @@ const readNetworkInfo = (sources = {}) => {
|
|
|
3962
4800
|
};
|
|
3963
4801
|
/** SQLite figures for the heartbeat (§7). */
|
|
3964
4802
|
const readSyncCounts = (db) => {
|
|
3965
|
-
const { pending, oldestPendingAt } = countUnsyncedEvents(db);
|
|
3966
|
-
|
|
4803
|
+
const { pending, oldestPendingAt, quarantined } = countUnsyncedEvents(db);
|
|
4804
|
+
const orders = db.prepare(`select count(*) as n from pending_orders
|
|
4805
|
+
where origin = 'local' and synced = 0`).get().n;
|
|
4806
|
+
const review = db.prepare(`select count(*) as n from pending_orders
|
|
4807
|
+
where cloud_status = 'needs_review'`).get().n;
|
|
4808
|
+
const b1 = {
|
|
3967
4809
|
pending_events: pending,
|
|
3968
|
-
oldest_pending_at: oldestPendingAt
|
|
3969
|
-
|
|
3970
|
-
|
|
3971
|
-
|
|
3972
|
-
|
|
4810
|
+
oldest_pending_at: oldestPendingAt
|
|
4811
|
+
};
|
|
4812
|
+
const b2 = {
|
|
4813
|
+
pending_orders: orders,
|
|
4814
|
+
needs_review_local: review
|
|
4815
|
+
};
|
|
4816
|
+
return {
|
|
4817
|
+
...b1,
|
|
4818
|
+
...b2,
|
|
4819
|
+
quarantined_events: quarantined
|
|
3973
4820
|
};
|
|
3974
4821
|
};
|
|
3975
4822
|
/** One heartbeat sample, shaped as `POST /api/nodes/v1/heartbeat` wants. */
|
|
@@ -4053,6 +4900,75 @@ const runDueJobs = async (db, handlers, now = () => /* @__PURE__ */ new Date())
|
|
|
4053
4900
|
};
|
|
4054
4901
|
};
|
|
4055
4902
|
//#endregion
|
|
4903
|
+
//#region src/mode/drain.ts
|
|
4904
|
+
const minutes = (value) => Math.max(1, value) * 6e4;
|
|
4905
|
+
/**
|
|
4906
|
+
* DRAINING timing (§4.3, drain-stall fix). `draining_since` lives in
|
|
4907
|
+
* SQLite, so a restart during DRAINING keeps the hold and the cap where
|
|
4908
|
+
* they were. Phases, from the first DRAINING:
|
|
4909
|
+
*
|
|
4910
|
+
* - hold (`DRAIN_HOLD_MS`): new carts get 503 `LOCAL_NODE_DRAINING` so the
|
|
4911
|
+
* open ones can close and devices move to the cloud;
|
|
4912
|
+
* - then new carts are taken locally again, so a store whose devices
|
|
4913
|
+
* cannot reach the cloud keeps selling;
|
|
4914
|
+
* - cap (`drain_max_min`): no new local carts at all, and open carts idle
|
|
4915
|
+
* for `DRAIN_CAPPED_CART_IDLE_MS` expire (they were never paid), so the
|
|
4916
|
+
* node hands back as soon as its events are synced.
|
|
4917
|
+
*
|
|
4918
|
+
* Placed orders and their events are never expired or dropped.
|
|
4919
|
+
*/
|
|
4920
|
+
const createDrainTracker = (options) => {
|
|
4921
|
+
const { db, now } = options;
|
|
4922
|
+
const since = () => getMetaNumber(db, "draining_since");
|
|
4923
|
+
const onTransition = (transition) => {
|
|
4924
|
+
const { from, to } = transition;
|
|
4925
|
+
if (to === "DRAINING" && since() === null) {
|
|
4926
|
+
setMeta(db, "draining_since", String(now().getTime()));
|
|
4927
|
+
return;
|
|
4928
|
+
}
|
|
4929
|
+
if (to === "ONLINE" || to === "LOCAL" && from !== "BOOTING") deleteMeta(db, "draining_since");
|
|
4930
|
+
};
|
|
4931
|
+
/** Milliseconds spent in DRAINING, or null when not draining. */
|
|
4932
|
+
const drainingFor = () => {
|
|
4933
|
+
if (options.mode() !== "DRAINING") return null;
|
|
4934
|
+
const start = since();
|
|
4935
|
+
if (start === null) return null;
|
|
4936
|
+
return Math.max(0, now().getTime() - start);
|
|
4937
|
+
};
|
|
4938
|
+
const capped = () => {
|
|
4939
|
+
const elapsed = drainingFor();
|
|
4940
|
+
if (elapsed === null) return false;
|
|
4941
|
+
return elapsed >= minutes(options.settings().drain_max_min);
|
|
4942
|
+
};
|
|
4943
|
+
const admitsNewOrders = () => {
|
|
4944
|
+
const elapsed = drainingFor();
|
|
4945
|
+
if (elapsed === null) return true;
|
|
4946
|
+
if (capped()) return false;
|
|
4947
|
+
return elapsed >= DRAIN_HOLD_MS;
|
|
4948
|
+
};
|
|
4949
|
+
/** Idle time after which an open local cart is expired. */
|
|
4950
|
+
const cartIdleLimitMs = () => {
|
|
4951
|
+
const ttl = minutes(options.settings().local_cart_ttl_min);
|
|
4952
|
+
if (!capped()) return ttl;
|
|
4953
|
+
return Math.min(ttl, DRAIN_CAPPED_CART_IDLE_MS);
|
|
4954
|
+
};
|
|
4955
|
+
/**
|
|
4956
|
+
* An order waiting for its pinpad result blocks the hand-back for the
|
|
4957
|
+
* whole cart TTL, even past the cap: the device may be charging it.
|
|
4958
|
+
*/
|
|
4959
|
+
const paymentIdleLimitMs = () => {
|
|
4960
|
+
return minutes(options.settings().local_cart_ttl_min);
|
|
4961
|
+
};
|
|
4962
|
+
return {
|
|
4963
|
+
onTransition,
|
|
4964
|
+
drainingFor,
|
|
4965
|
+
capped,
|
|
4966
|
+
admitsNewOrders,
|
|
4967
|
+
cartIdleLimitMs,
|
|
4968
|
+
paymentIdleLimitMs
|
|
4969
|
+
};
|
|
4970
|
+
};
|
|
4971
|
+
//#endregion
|
|
4056
4972
|
//#region src/runtime.ts
|
|
4057
4973
|
const PING_PATH = "/api/nodes/v1/ping";
|
|
4058
4974
|
const errorText = (error) => {
|
|
@@ -4076,6 +4992,7 @@ const createLocalRuntime = (options) => {
|
|
|
4076
4992
|
let servedChannelIds = [...identity.served_channel_ids];
|
|
4077
4993
|
let settings = readLocalSettings(JSON.parse(getMeta(db, "settings") ?? "{}"));
|
|
4078
4994
|
let cloudReachable = false;
|
|
4995
|
+
let internetUp = false;
|
|
4079
4996
|
const client = createCloudClient({
|
|
4080
4997
|
baseUrl: options.cloudUrl,
|
|
4081
4998
|
nodeUid: identity.node_uid,
|
|
@@ -4100,19 +5017,29 @@ const createLocalRuntime = (options) => {
|
|
|
4100
5017
|
env: identity.env,
|
|
4101
5018
|
now
|
|
4102
5019
|
});
|
|
5020
|
+
const log = options.log ?? (() => void 0);
|
|
5021
|
+
const previousMode = readPersistedMode(db);
|
|
4103
5022
|
const mode = createModeController(db, () => settings.failover, now);
|
|
4104
|
-
const
|
|
4105
|
-
|
|
4106
|
-
mode.onChange((transition) => {
|
|
4107
|
-
drainingSince = transition.to === "DRAINING" ? now().getTime() : null;
|
|
4108
|
-
});
|
|
4109
|
-
const admitsNewOrders = () => {
|
|
4110
|
-
if (drainingSince === null) return true;
|
|
4111
|
-
return now().getTime() - drainingSince >= DRAIN_HOLD_MS;
|
|
5023
|
+
const onQuarantine = (event) => {
|
|
5024
|
+
log("sync.event_quarantined", { ...event });
|
|
4112
5025
|
};
|
|
5026
|
+
const upstream = createUpstreamSync(db, client, {
|
|
5027
|
+
now,
|
|
5028
|
+
onQuarantine
|
|
5029
|
+
});
|
|
5030
|
+
const drain = createDrainTracker({
|
|
5031
|
+
db,
|
|
5032
|
+
mode: mode.mode,
|
|
5033
|
+
settings: () => settings.failover,
|
|
5034
|
+
now
|
|
5035
|
+
});
|
|
5036
|
+
mode.onChange(drain.onTransition);
|
|
5037
|
+
const admitsNewOrders = drain.admitsNewOrders;
|
|
4113
5038
|
const connectivity = () => {
|
|
4114
5039
|
return cloudReachable ? "online" : "offline";
|
|
4115
5040
|
};
|
|
5041
|
+
/** Any HTTP answer from the cloud host means the store has internet. */
|
|
5042
|
+
const internetReachable = () => cloudReachable || internetUp;
|
|
4116
5043
|
const disk = () => {
|
|
4117
5044
|
return readDiskStatus(options.dataDir, options.statfs);
|
|
4118
5045
|
};
|
|
@@ -4126,6 +5053,8 @@ const createLocalRuntime = (options) => {
|
|
|
4126
5053
|
now,
|
|
4127
5054
|
disk: () => disk().level,
|
|
4128
5055
|
admitsNewOrders,
|
|
5056
|
+
cartIdleLimitMs: drain.cartIdleLimitMs,
|
|
5057
|
+
internetReachable,
|
|
4129
5058
|
onWrite: () => {
|
|
4130
5059
|
if (cloudReachable) upstream.trigger();
|
|
4131
5060
|
}
|
|
@@ -4136,7 +5065,8 @@ const createLocalRuntime = (options) => {
|
|
|
4136
5065
|
orders,
|
|
4137
5066
|
mode: mode.mode,
|
|
4138
5067
|
settings: () => settings,
|
|
4139
|
-
now
|
|
5068
|
+
now,
|
|
5069
|
+
internetReachable
|
|
4140
5070
|
});
|
|
4141
5071
|
const heartbeat = async () => {
|
|
4142
5072
|
const d = disk();
|
|
@@ -4200,7 +5130,8 @@ const createLocalRuntime = (options) => {
|
|
|
4200
5130
|
const snapshot = verifyCachedSnapshot(db);
|
|
4201
5131
|
const b5 = {
|
|
4202
5132
|
integrityOk: integrity.ok,
|
|
4203
|
-
cloudReachable
|
|
5133
|
+
cloudReachable,
|
|
5134
|
+
previousMode
|
|
4204
5135
|
};
|
|
4205
5136
|
const input = {
|
|
4206
5137
|
type: "boot",
|
|
@@ -4223,8 +5154,9 @@ const createLocalRuntime = (options) => {
|
|
|
4223
5154
|
try {
|
|
4224
5155
|
await client.json("GET", PING_PATH);
|
|
4225
5156
|
ok = true;
|
|
4226
|
-
} catch {
|
|
5157
|
+
} catch (error) {
|
|
4227
5158
|
ok = false;
|
|
5159
|
+
internetUp = error instanceof CloudHttpError;
|
|
4228
5160
|
}
|
|
4229
5161
|
cloudReachable = ok;
|
|
4230
5162
|
const latencyMs = Date.now() - started;
|
|
@@ -4247,15 +5179,23 @@ const createLocalRuntime = (options) => {
|
|
|
4247
5179
|
const state = await syncState().catch(failed);
|
|
4248
5180
|
const down = await pullDownstream(db, client, handlers, { now });
|
|
4249
5181
|
const up = await upstream.trigger();
|
|
4250
|
-
const pending = countUnsyncedEvents(db).
|
|
4251
|
-
const
|
|
4252
|
-
const
|
|
5182
|
+
const pending = countUnsyncedEvents(db).blocking;
|
|
5183
|
+
const since = (ms) => new Date(now().getTime() - ms).toISOString();
|
|
5184
|
+
const carts = since(drain.cartIdleLimitMs());
|
|
5185
|
+
const payments = since(drain.paymentIdleLimitMs());
|
|
5186
|
+
const openLocalOrders = countOpenLocalOrders(db, carts, payments);
|
|
5187
|
+
const input = {
|
|
4253
5188
|
type: "drain_status",
|
|
4254
5189
|
pendingEvents: pending
|
|
4255
5190
|
};
|
|
4256
|
-
|
|
4257
|
-
|
|
5191
|
+
const drainedAfterMs = drain.drainingFor();
|
|
5192
|
+
const capped = drain.capped();
|
|
5193
|
+
if (mode.dispatch({
|
|
5194
|
+
...input,
|
|
4258
5195
|
openLocalOrders
|
|
5196
|
+
}).reason === "DRAINED") log("mode.drained", {
|
|
5197
|
+
capped,
|
|
5198
|
+
drained_after_ms: drainedAfterMs
|
|
4259
5199
|
});
|
|
4260
5200
|
return {
|
|
4261
5201
|
skipped: false,
|
|
@@ -4303,6 +5243,7 @@ const createLocalRuntime = (options) => {
|
|
|
4303
5243
|
start,
|
|
4304
5244
|
stop,
|
|
4305
5245
|
close,
|
|
5246
|
+
drain,
|
|
4306
5247
|
settings: () => settings
|
|
4307
5248
|
};
|
|
4308
5249
|
};
|
|
@@ -4987,7 +5928,8 @@ const createLocalNode = (options) => {
|
|
|
4987
5928
|
...b1,
|
|
4988
5929
|
...b2,
|
|
4989
5930
|
...b3,
|
|
4990
|
-
image
|
|
5931
|
+
image,
|
|
5932
|
+
log
|
|
4991
5933
|
});
|
|
4992
5934
|
runtime = opened;
|
|
4993
5935
|
opened.mode.onChange((transition) => {
|
|
@@ -5177,4 +6119,4 @@ const startLocalNodeFromEnv = (env = process.env) => {
|
|
|
5177
6119
|
return node;
|
|
5178
6120
|
};
|
|
5179
6121
|
//#endregion
|
|
5180
|
-
export { CLOUD_STOREFRONT_AUDIENCE, CREDENTIALS_PATH, CloudHttpError, DEFAULT_CLOUD_URL, DEFAULT_LOCAL_SETTINGS, DEFAULT_TLS_DOMAIN, DRAIN_HOLD_MS, ENROLL_PATH, GATEWAY_CERTIFICATE_TAG, GATEWAY_ROUTE_ID, GATEWAY_TARGET_VAR, LOCAL_BACKUP_INTERVAL_MS, LOCAL_BACKUP_KEEP, LOCAL_BATCH_MAX_BYTES, LOCAL_BATCH_MAX_EVENTS, LOCAL_BATCH_OVERHEAD_BYTES, LOCAL_CREDENTIALS_INFO, LOCAL_CREDENTIALS_SECTION, LOCAL_DEVICE_TOKEN_AUDIENCE, LOCAL_DEVICE_TOKEN_TTL_SECONDS, LOCAL_DISK_CRITICAL_RATIO, LOCAL_DISK_WARNING_RATIO, LOCAL_DOWNSTREAM_PAGE, LOCAL_EVENT_MAX_PAYLOAD_BYTES, LOCAL_EVENT_SCHEMA_VERSION, LOCAL_MODES, LOCAL_NODE_GLOBAL, LOCAL_OFFLINE_PAYMENT_METHODS, LOCAL_ORIGIN_HEADER, LOCAL_PLACED_FULFILLMENT_STATUS, LOCAL_RELAY_HEADER, LOCAL_RETRY_MAX_MS, LOCAL_RETRY_MIN_MS, LOCAL_SCHEMA_VERSION, LOCAL_SERVING_MODES, LOCAL_SYNC_INTERVAL_MS, LOCAL_UPSTREAM_EVENT_TYPES, LocalRuntimeError, NODE_ASSERTION_AUDIENCE_PATH, NODE_ASSERTION_TTL_SECONDS, TLS_CERTIFICATE_PATH, TLS_CSR_PATH, appendEvent, applyBatchResults, applyInbox, applySnapshot, backupDatabase, buildNodeCsr, caddyAdminRequest, cancelJob, checkIntegrity, checkOrder, collectHealthSample, countUnsyncedEvents, createCloudClient, createCloudRelay, createCredentialStore, createDeviceAuth, createDownstreamHandlers, createGatewaySwitch, createLocalNode, createLocalRuntime, createModeController, createNodeTls, createOrderService, createStorefrontHandler, createUpstreamSync, decodeJwt, diskLevel, drainUpstream, enrollNode, enrollmentCodeHash, enrollmentJwks, findEventByIdempotencyKey, formatDisplayNumber, gatewayTargetFor, generateNodeKeys, getMeta, hashDeviceSecret, importSigningKey, importVerifyKey, inTransaction, initialModeState, isDeviceRevoked, isLocalRuntimeError, isNodeHostname, isServingMode, jwkThumbprint, listBackups, listEvents, listModeChanges, listPendingOrders, loadOrCreateControlToken, loadOrCreateNodeKeys, localMessage, localNodeOptionsFromEnv, matchesControlToken, migrateLocalDatabase, nextDisplayNumber, nextMode, openCredentials, openLocalDatabase, payloadHashOf, pickLocale, pinLookupHash, priceOrder, publicJwkOf, publishedLocalNode, pullDownstream, readDiskStatus, readLocalSettings, readNetworkInfo, readNodeIdentity, readOrderState, readPendingOrder, readStateRef, retryDelayMs, revokeDevice, runDueJobs, saveNodeIdentity, scheduleJob, selectBatch, sendNextBatch, setMeta, signEs256, startLocalNodeFromEnv, syncSnapshot, targetOfRoute, uuidv7, verifyBlob, verifyCachedSnapshot, verifyEs256, verifyManifest, verifyPinHash };
|
|
6122
|
+
export { CLOUD_STOREFRONT_AUDIENCE, CREDENTIALS_PATH, CloudHttpError, DEFAULT_CLOUD_URL, DEFAULT_LOCAL_SETTINGS, DEFAULT_TLS_DOMAIN, DRAIN_CAPPED_CART_IDLE_MS, DRAIN_HOLD_MS, ENROLL_PATH, GATEWAY_CERTIFICATE_TAG, GATEWAY_ROUTE_ID, GATEWAY_TARGET_VAR, LOCAL_BACKUP_INTERVAL_MS, LOCAL_BACKUP_KEEP, LOCAL_BATCH_MAX_BYTES, LOCAL_BATCH_MAX_EVENTS, LOCAL_BATCH_OVERHEAD_BYTES, LOCAL_CREDENTIALS_INFO, LOCAL_CREDENTIALS_SECTION, LOCAL_DEVICE_PAYMENT_METHODS, LOCAL_DEVICE_TOKEN_AUDIENCE, LOCAL_DEVICE_TOKEN_TTL_SECONDS, LOCAL_DISK_CRITICAL_RATIO, LOCAL_DISK_WARNING_RATIO, LOCAL_DOWNSTREAM_PAGE, LOCAL_EVENT_MAX_PAYLOAD_BYTES, LOCAL_EVENT_SCHEMA_VERSION, LOCAL_MODES, LOCAL_NODE_GLOBAL, LOCAL_OFFLINE_PAYMENT_METHODS, LOCAL_ORIGIN_HEADER, LOCAL_PLACED_FULFILLMENT_STATUS, LOCAL_QUARANTINE_AFTER_ATTEMPTS, LOCAL_RELAY_HEADER, LOCAL_RETRY_MAX_MS, LOCAL_RETRY_MIN_MS, LOCAL_SCHEMA_VERSION, LOCAL_SERVING_MODES, LOCAL_SYNC_INTERVAL_MS, LOCAL_UPSTREAM_EVENT_TYPES, LocalRuntimeError, NODE_ASSERTION_AUDIENCE_PATH, NODE_ASSERTION_TTL_SECONDS, TLS_CERTIFICATE_PATH, TLS_CSR_PATH, appendEvent, applyBatchResults, applyInbox, applySnapshot, backupDatabase, buildNodeCsr, caddyAdminRequest, cancelJob, checkIntegrity, checkOrder, collectHealthSample, countUnsyncedEvents, createCloudClient, createCloudRelay, createCredentialStore, createDeviceAuth, createDownstreamHandlers, createGatewaySwitch, createLocalNode, createLocalRuntime, createModeController, createNodeTls, createOrderService, createStorefrontHandler, createUpstreamSync, decodeJwt, diskLevel, drainUpstream, enrollNode, enrollmentCodeHash, enrollmentJwks, findEventByIdempotencyKey, formatDisplayNumber, gatewayTargetFor, generateNodeKeys, getMeta, hashDeviceSecret, importSigningKey, importVerifyKey, inTransaction, initialModeState, isDeviceRevoked, isLocalRuntimeError, isNodeHostname, isServingMode, jwkThumbprint, listBackups, listEvents, listModeChanges, listPendingOrders, loadOrCreateControlToken, loadOrCreateNodeKeys, localMessage, localNodeOptionsFromEnv, matchesControlToken, migrateLocalDatabase, nextDisplayNumber, nextMode, openCredentials, openLocalDatabase, payloadHashOf, pickLocale, pinLookupHash, priceOrder, publicJwkOf, publishedLocalNode, pullDownstream, readDiskStatus, readLocalSettings, readNetworkInfo, readNodeIdentity, readOrderState, readPendingOrder, readStateRef, retryDelayMs, revokeDevice, runDueJobs, saveNodeIdentity, scheduleJob, selectBatch, sendNextBatch, setMeta, signEs256, startLocalNodeFromEnv, syncSnapshot, targetOfRoute, uuidv7, verifyBlob, verifyCachedSnapshot, verifyEs256, verifyManifest, verifyPinHash };
|