@burdenoff/microfe-healthybowl 2026.902.31 → 2026.902.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/healthybowl/offline/OfflineSyncProvider.js +153 -130
- package/dist/healthybowl/offline/OfflineSyncProvider.js.map +1 -1
- package/dist/healthybowl/offline/captureCache.js +30 -0
- package/dist/healthybowl/offline/captureCache.js.map +1 -0
- package/dist/healthybowl/offline/store.js +1 -1
- package/package.json +1 -1
|
@@ -1,128 +1,152 @@
|
|
|
1
1
|
import { useHealthyBowl as e } from "../context/HealthyBowlContext.js";
|
|
2
2
|
import { getNetworkState as t, isCellular as n, subscribeNetwork as r } from "./network.js";
|
|
3
3
|
import { useToast as i } from "../hooks/useToast.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
4
|
+
import { downscaleImage as a } from "../utils/imageDownscale.js";
|
|
5
|
+
import { DEFAULT_SETTINGS as o } from "./types.js";
|
|
6
|
+
import { deleteObservation as s, deletePendingMutation as c, getAllObservations as l, getAllPendingMutations as u, getHistory as d, getMeta as f, getObservation as ee, getPendingMutation as te, getPhotosFor as ne, loadSettings as re, saveObservation as p, savePendingMutation as ie, savePhoto as ae, saveSettings as oe, setMeta as m } from "./store.js";
|
|
7
|
+
import { CAPTURE_DATA_META as h, CAPTURE_PHOTO_MAX_DIM as se, CAPTURE_PHOTO_QUALITY as ce, autoResolutionFor as le, conflictsToAutoResolve as g, isUsableCaptureCache as ue, shouldCompressPhotos as de, toCachedCaptureData as fe } from "./captureCache.js";
|
|
8
|
+
import { fetchFieldCaptureData as pe, resolveConflict as me } from "./graphql.js";
|
|
9
|
+
import { drainQueue as he } from "./syncEngine.js";
|
|
10
|
+
import { describeDrain as ge } from "./syncOutcome.js";
|
|
11
|
+
import { createContext as _, useCallback as v, useContext as y, useEffect as b, useMemo as x, useRef as S, useState as C } from "react";
|
|
12
|
+
import { jsx as _e } from "react/jsx-runtime";
|
|
13
|
+
import { useSaveToFiles as ve } from "@burdenoff/fe-libs/storage";
|
|
12
14
|
//#region src/healthybowl/offline/OfflineSyncProvider.tsx
|
|
13
|
-
var
|
|
14
|
-
function
|
|
15
|
-
let e =
|
|
15
|
+
var w = _(null);
|
|
16
|
+
function T() {
|
|
17
|
+
let e = y(w);
|
|
16
18
|
if (!e) throw Error("useOfflineSync must be used within an OfflineSyncProvider");
|
|
17
19
|
return e;
|
|
18
20
|
}
|
|
19
|
-
var
|
|
20
|
-
function
|
|
21
|
+
var E = "lastSyncedAt";
|
|
22
|
+
function D() {
|
|
21
23
|
return (/* @__PURE__ */ new Date()).toISOString();
|
|
22
24
|
}
|
|
23
|
-
function
|
|
25
|
+
function O(e) {
|
|
24
26
|
return `${e}-${typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.round(Math.random() * 1e9)}`}`;
|
|
25
27
|
}
|
|
26
|
-
var
|
|
27
|
-
let { workspaceId:
|
|
28
|
-
|
|
29
|
-
let
|
|
28
|
+
var k = ({ children: _ }) => {
|
|
29
|
+
let { workspaceId: y } = e(), { save: T } = ve(), { toast: k } = i(), [ye, be] = C(!1), [A, xe] = C(() => t()), [Se, j] = C(!1), [M, N] = C([]), [P, F] = C([]), [Ce, I] = C([]), [L, R] = C(o), [we, z] = C(null), [B, V] = C(null), [Te, H] = C(!1), U = S(L), W = S(A), G = S(!1), K = S(T), q = S(y), J = S(() => Promise.resolve());
|
|
30
|
+
U.current = L, W.current = A, K.current = T, q.current = y;
|
|
31
|
+
let Y = v(async () => {
|
|
30
32
|
let [e, t, n] = await Promise.all([
|
|
31
|
-
s(),
|
|
32
33
|
l(),
|
|
33
|
-
|
|
34
|
+
d(),
|
|
35
|
+
u()
|
|
34
36
|
]);
|
|
35
|
-
|
|
36
|
-
}, []),
|
|
37
|
-
if (!(!
|
|
38
|
-
|
|
37
|
+
N(e), I(t), F(n);
|
|
38
|
+
}, []), X = v(async () => {
|
|
39
|
+
if (!(!q.current || !W.current.online)) {
|
|
40
|
+
H(!0);
|
|
39
41
|
try {
|
|
40
|
-
let e = await
|
|
41
|
-
e && fe(e);
|
|
42
|
+
let e = await pe({ workspaceId: q.current });
|
|
43
|
+
e && (V(e), await m(h, fe(e, q.current, Date.now())).catch(() => void 0));
|
|
42
44
|
} finally {
|
|
43
|
-
|
|
45
|
+
H(!1);
|
|
44
46
|
}
|
|
45
47
|
}
|
|
46
48
|
}, []);
|
|
47
|
-
|
|
49
|
+
b(() => {
|
|
48
50
|
let e = !1;
|
|
49
51
|
return (async () => {
|
|
50
|
-
let [t, n, r, i, a] = await Promise.all([
|
|
51
|
-
s(),
|
|
52
|
+
let [t, n, r, i, a, o] = await Promise.all([
|
|
52
53
|
l(),
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
54
|
+
d(),
|
|
55
|
+
re(),
|
|
56
|
+
f(E),
|
|
57
|
+
u(),
|
|
58
|
+
f(h)
|
|
56
59
|
]);
|
|
57
|
-
e || (
|
|
60
|
+
e || (N(t), I(n), R(r), z(i ?? null), F(a), ue(o, q.current, Date.now()) && V(o.data), be(!0));
|
|
58
61
|
})(), () => {
|
|
59
62
|
e = !0;
|
|
60
63
|
};
|
|
61
|
-
}, []),
|
|
62
|
-
|
|
63
|
-
}, [
|
|
64
|
-
let
|
|
65
|
-
if (
|
|
66
|
-
let t =
|
|
67
|
-
if (!(!t || !r.online) && !(!e?.manual && !
|
|
68
|
-
|
|
64
|
+
}, []), b(() => {
|
|
65
|
+
X();
|
|
66
|
+
}, [X, y]);
|
|
67
|
+
let Z = v(async (e) => {
|
|
68
|
+
if (G.current) return;
|
|
69
|
+
let t = q.current, r = W.current;
|
|
70
|
+
if (!(!t || !r.online) && !(!e?.manual && !U.current.syncOverMobileData && n(r))) {
|
|
71
|
+
G.current = !0, j(!0);
|
|
69
72
|
try {
|
|
70
|
-
let n = await
|
|
73
|
+
let n = await he({
|
|
71
74
|
workspaceId: t,
|
|
72
|
-
saveToFiles:
|
|
73
|
-
settings:
|
|
75
|
+
saveToFiles: K.current,
|
|
76
|
+
settings: U.current,
|
|
74
77
|
network: r
|
|
75
78
|
}), i = Date.now();
|
|
76
|
-
|
|
77
|
-
let a =
|
|
78
|
-
a &&
|
|
79
|
+
z(i), await m(E, i), await Y(), X();
|
|
80
|
+
let a = le(U.current.conflictHandling), o = n.conflict;
|
|
81
|
+
if (a && n.conflict > 0) {
|
|
82
|
+
let e = g(await l(), t), r = 0;
|
|
83
|
+
for (let t of e) await J.current(t.clientId, a, void 0, { silent: !0 }).then(() => !0, () => !1) && (r += 1);
|
|
84
|
+
o = Math.max(0, n.conflict - r), r > 0 && (await Y(), k({
|
|
85
|
+
title: `${r} conflict${r > 1 ? "s" : ""} resolved`,
|
|
86
|
+
description: a === "KEEP_MINE" ? "Your offline version was kept, as set in Offline Settings." : "The server version was kept, as set in Offline Settings.",
|
|
87
|
+
variant: "info"
|
|
88
|
+
}));
|
|
89
|
+
}
|
|
90
|
+
let s = ge({
|
|
91
|
+
...n,
|
|
92
|
+
conflict: o
|
|
93
|
+
}, { manual: e?.manual });
|
|
94
|
+
s && k(s);
|
|
79
95
|
} catch {
|
|
80
|
-
e?.manual &&
|
|
96
|
+
e?.manual && k({
|
|
81
97
|
title: "Sync failed",
|
|
82
98
|
description: "Please try again.",
|
|
83
99
|
variant: "error"
|
|
84
100
|
});
|
|
85
101
|
} finally {
|
|
86
|
-
|
|
102
|
+
G.current = !1, j(!1);
|
|
87
103
|
}
|
|
88
104
|
}
|
|
89
105
|
}, [
|
|
106
|
+
Y,
|
|
90
107
|
X,
|
|
91
|
-
|
|
92
|
-
A
|
|
108
|
+
k
|
|
93
109
|
]);
|
|
94
|
-
|
|
95
|
-
let e =
|
|
110
|
+
b(() => {
|
|
111
|
+
let e = W.current.online;
|
|
96
112
|
return r((t) => {
|
|
97
|
-
|
|
113
|
+
xe(t);
|
|
98
114
|
let n = !e && t.online;
|
|
99
|
-
e = t.online, n &&
|
|
115
|
+
e = t.online, n && U.current.autoSyncOnReconnect && Z();
|
|
100
116
|
});
|
|
101
|
-
}, [
|
|
102
|
-
if (!
|
|
117
|
+
}, [Z]), b(() => {
|
|
118
|
+
if (!L.autoSyncOnReconnect || L.syncFrequencyMs <= 0) return;
|
|
103
119
|
let e = window.setInterval(() => {
|
|
104
|
-
|
|
105
|
-
},
|
|
120
|
+
W.current.online && Z();
|
|
121
|
+
}, L.syncFrequencyMs);
|
|
106
122
|
return () => window.clearInterval(e);
|
|
107
123
|
}, [
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
124
|
+
L.autoSyncOnReconnect,
|
|
125
|
+
L.syncFrequencyMs,
|
|
126
|
+
Z
|
|
111
127
|
]);
|
|
112
|
-
let
|
|
113
|
-
let t =
|
|
114
|
-
for (let
|
|
115
|
-
let e =
|
|
116
|
-
|
|
128
|
+
let Ee = v(async (e) => {
|
|
129
|
+
let t = O("obs"), n = [], r = de(U.current);
|
|
130
|
+
for (let i of e.photos ?? []) {
|
|
131
|
+
let e = O("photo"), o = i, s = i.name || `photo-${e}.jpg`, c = i.type || "image/jpeg";
|
|
132
|
+
if (r) try {
|
|
133
|
+
let e = await a(i, {
|
|
134
|
+
maxDim: se,
|
|
135
|
+
quality: ce,
|
|
136
|
+
encodeFallback: !1
|
|
137
|
+
});
|
|
138
|
+
e.downscaled && e.blob && (o = e.blob, s = e.filename ?? s, c = e.mimeType ?? "image/jpeg");
|
|
139
|
+
} catch {}
|
|
140
|
+
await ae({
|
|
117
141
|
id: e,
|
|
118
142
|
clientId: t,
|
|
119
|
-
blob:
|
|
120
|
-
filename:
|
|
121
|
-
mimeType:
|
|
143
|
+
blob: o,
|
|
144
|
+
filename: s,
|
|
145
|
+
mimeType: c,
|
|
122
146
|
createdAt: Date.now()
|
|
123
147
|
}), n.push(e);
|
|
124
148
|
}
|
|
125
|
-
let
|
|
149
|
+
let i = {
|
|
126
150
|
clientId: t,
|
|
127
151
|
observationType: e.observationType,
|
|
128
152
|
fieldId: e.fieldId ?? null,
|
|
@@ -138,23 +162,23 @@ var A = ({ children: g }) => {
|
|
|
138
162
|
gpsAccuracy: e.gpsAccuracy ?? null,
|
|
139
163
|
photoLocalIds: n,
|
|
140
164
|
photoFileIds: [],
|
|
141
|
-
capturedAt:
|
|
142
|
-
capturedOffline: !
|
|
165
|
+
capturedAt: D(),
|
|
166
|
+
capturedOffline: !W.current.online,
|
|
143
167
|
status: "QUEUED",
|
|
144
168
|
baseVersion: null,
|
|
145
169
|
attempts: 0,
|
|
146
170
|
createdAt: Date.now(),
|
|
147
171
|
updatedAt: Date.now(),
|
|
148
|
-
workspaceId:
|
|
172
|
+
workspaceId: q.current
|
|
149
173
|
};
|
|
150
|
-
return await
|
|
151
|
-
}, [
|
|
152
|
-
let
|
|
174
|
+
return await p(i), await Y(), W.current.online && U.current.autoSyncOnReconnect && Z(), i;
|
|
175
|
+
}, [Y, Z]), Q = v(async (e, t, n, r) => {
|
|
176
|
+
let i = await ee(e), a = i?.serverVersion?.version ?? i?.baseVersion ?? 0;
|
|
153
177
|
try {
|
|
154
|
-
let
|
|
178
|
+
let o = await me({ workspaceId: q.current }, {
|
|
155
179
|
clientId: e,
|
|
156
180
|
resolution: t,
|
|
157
|
-
baseVersion:
|
|
181
|
+
baseVersion: a,
|
|
158
182
|
fieldId: n?.fieldId,
|
|
159
183
|
note: n?.note,
|
|
160
184
|
severity: n?.severity,
|
|
@@ -166,24 +190,21 @@ var A = ({ children: g }) => {
|
|
|
166
190
|
longitude: n?.longitude,
|
|
167
191
|
photoFileIds: n?.photoFileIds
|
|
168
192
|
});
|
|
169
|
-
|
|
193
|
+
i && (i.status = "SYNCED", i.serverVersion = null, i.baseVersion = o.version, i.serverId = o.id, i.syncedAt = D(), i.message = null, i.note = o.note ?? i.note, i.severity = o.severity ?? i.severity, i.updatedAt = Date.now(), await p(i)), await Y(), r?.silent || k({
|
|
170
194
|
title: "Conflict resolved",
|
|
171
195
|
variant: "success"
|
|
172
196
|
});
|
|
173
197
|
} catch (e) {
|
|
174
|
-
|
|
198
|
+
let t = e instanceof Error ? e.message : "Could not resolve the conflict";
|
|
199
|
+
throw r?.silent || k({
|
|
175
200
|
title: "Resolve failed",
|
|
176
|
-
description:
|
|
201
|
+
description: t,
|
|
177
202
|
variant: "error"
|
|
178
203
|
}), e;
|
|
179
204
|
}
|
|
180
|
-
}, [
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
A
|
|
184
|
-
]), ge = _(async (e, t) => {
|
|
185
|
-
let n = k("scheme");
|
|
186
|
-
if (await h({
|
|
205
|
+
}, [Y, k]), De = v(async (e, t) => {
|
|
206
|
+
let n = O("scheme");
|
|
207
|
+
if (await ie({
|
|
187
208
|
clientId: n,
|
|
188
209
|
kind: "SCHEME_APPLICATION",
|
|
189
210
|
payload: e,
|
|
@@ -192,63 +213,65 @@ var A = ({ children: g }) => {
|
|
|
192
213
|
attempts: 0,
|
|
193
214
|
createdAt: Date.now(),
|
|
194
215
|
updatedAt: Date.now(),
|
|
195
|
-
workspaceId:
|
|
196
|
-
}), await
|
|
197
|
-
await
|
|
198
|
-
let r = await
|
|
199
|
-
return await
|
|
216
|
+
workspaceId: q.current
|
|
217
|
+
}), await Y(), !W.current.online) return { status: "QUEUED" };
|
|
218
|
+
await Z();
|
|
219
|
+
let r = await te(n);
|
|
220
|
+
return await Y(), r?.status === "SYNCED" && r.serverId ? {
|
|
200
221
|
status: "SYNCED",
|
|
201
222
|
serverId: r.serverId
|
|
202
223
|
} : r?.status === "FAILED" ? {
|
|
203
224
|
status: "FAILED",
|
|
204
225
|
message: r.message ?? "The server rejected this application."
|
|
205
226
|
} : { status: "QUEUED" };
|
|
206
|
-
}, [
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
await
|
|
210
|
-
}, [
|
|
211
|
-
|
|
227
|
+
}, [Y, Z]);
|
|
228
|
+
J.current = Q;
|
|
229
|
+
let $ = v(async (e) => {
|
|
230
|
+
await c(e), await Y();
|
|
231
|
+
}, [Y]), Oe = v(async (e) => {
|
|
232
|
+
await s(e), await Y();
|
|
233
|
+
}, [Y]), ke = v(async (e) => {
|
|
234
|
+
R((t) => {
|
|
212
235
|
let n = {
|
|
213
236
|
...t,
|
|
214
237
|
...e
|
|
215
238
|
};
|
|
216
|
-
return
|
|
239
|
+
return oe(n), n;
|
|
217
240
|
});
|
|
218
|
-
}, []),
|
|
219
|
-
ready:
|
|
220
|
-
online:
|
|
221
|
-
connectionType:
|
|
222
|
-
syncing:
|
|
223
|
-
lastSyncedAt:
|
|
224
|
-
observations:
|
|
225
|
-
pendingMutations:
|
|
226
|
-
queuedCount:
|
|
227
|
-
conflictCount:
|
|
228
|
-
history:
|
|
229
|
-
settings:
|
|
230
|
-
fields:
|
|
231
|
-
serverRecent:
|
|
232
|
-
stats:
|
|
233
|
-
loadingCaptureData:
|
|
234
|
-
capture:
|
|
235
|
-
queueSchemeApplication:
|
|
241
|
+
}, []), Ae = v((e) => ne(e), []), je = x(() => M.filter((e) => e.status === "QUEUED" || e.status === "UPLOADING" || e.status === "FAILED").length + P.filter((e) => e.status === "QUEUED" || e.status === "UPLOADING" || e.status === "FAILED").length, [M, P]), Me = x(() => M.filter((e) => e.status === "CONFLICT").length, [M]), Ne = {
|
|
242
|
+
ready: ye,
|
|
243
|
+
online: A.online,
|
|
244
|
+
connectionType: A.connectionType,
|
|
245
|
+
syncing: Se,
|
|
246
|
+
lastSyncedAt: we,
|
|
247
|
+
observations: M,
|
|
248
|
+
pendingMutations: P,
|
|
249
|
+
queuedCount: je,
|
|
250
|
+
conflictCount: Me,
|
|
251
|
+
history: Ce,
|
|
252
|
+
settings: L,
|
|
253
|
+
fields: B?.fields ?? [],
|
|
254
|
+
serverRecent: B?.recentObservations ?? [],
|
|
255
|
+
stats: B?.stats ?? null,
|
|
256
|
+
loadingCaptureData: Te,
|
|
257
|
+
capture: Ee,
|
|
258
|
+
queueSchemeApplication: De,
|
|
236
259
|
discardPendingMutation: $,
|
|
237
|
-
syncNow:
|
|
238
|
-
resolve:
|
|
239
|
-
remove:
|
|
240
|
-
updateSettings:
|
|
260
|
+
syncNow: Z,
|
|
261
|
+
resolve: Q,
|
|
262
|
+
remove: Oe,
|
|
263
|
+
updateSettings: ke,
|
|
241
264
|
refresh: async () => {
|
|
242
|
-
await
|
|
265
|
+
await Y(), await X();
|
|
243
266
|
},
|
|
244
|
-
loadLocalPhotos:
|
|
267
|
+
loadLocalPhotos: Ae
|
|
245
268
|
};
|
|
246
|
-
return /* @__PURE__ */
|
|
247
|
-
value:
|
|
248
|
-
children:
|
|
269
|
+
return /* @__PURE__ */ _e(w.Provider, {
|
|
270
|
+
value: Ne,
|
|
271
|
+
children: _
|
|
249
272
|
});
|
|
250
273
|
};
|
|
251
274
|
//#endregion
|
|
252
|
-
export {
|
|
275
|
+
export { k as OfflineSyncProvider, T as useOfflineSync };
|
|
253
276
|
|
|
254
277
|
//# sourceMappingURL=OfflineSyncProvider.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OfflineSyncProvider.js","names":[],"sources":["../../../src/healthybowl/offline/OfflineSyncProvider.tsx"],"sourcesContent":["/**\n * OfflineSyncProvider (BOFF-2883).\n *\n * The single owner of the offline capture + sync lifecycle for the HealthyBowl\n * MFE. Holds the outbox + history + settings, watches connectivity, auto-drains\n * the queue on reconnect (and on an interval), and exposes capture / sync /\n * resolve / delete actions to the Field Capture screens.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport { useToast } from '../hooks/useToast';\nimport type {\n LocalObservation,\n LocalPhoto,\n ObservationType,\n OfflineSettings,\n PendingMutation,\n SchemeApplicationPayload,\n SyncHistoryEntry,\n ServerObservation,\n} from './types';\nimport { DEFAULT_SETTINGS } from './types';\nimport {\n getAllObservations,\n saveObservation,\n deleteObservation as storeDeleteObservation,\n getAllPendingMutations,\n savePendingMutation,\n getPendingMutation,\n deletePendingMutation,\n savePhoto,\n getPhotosFor,\n getHistory,\n loadSettings,\n saveSettings,\n getMeta,\n setMeta,\n} from './store';\nimport { subscribeNetwork, getNetworkState, isCellular } from './network';\nimport { drainQueue, type SaveToFiles } from './syncEngine';\nimport { describeDrain } from './syncOutcome';\nimport { resolveConflict as resolveConflictGql, fetchFieldCaptureData, type FieldCaptureData } from './graphql';\nimport type { NetworkState } from './types';\n\nexport interface CaptureInput {\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n /** Freshly-captured photo files (blobs stored locally, uploaded on sync). */\n photos?: File[];\n}\n\nexport interface ResolveValues {\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\n/**\n * What actually happened to a queued write (BOFF-6179).\n *\n * Returned so the caller can tell the farmer the truth rather than an optimistic\n * guess: a government application is close to a legal submission, and reporting\n * \"Submitted\" for a request that never reached the server is the exact failure\n * this board keeps finding.\n */\nexport type QueueOutcome =\n { status: 'SYNCED'; serverId: string } | { status: 'QUEUED' } | { status: 'FAILED'; message: string };\n\ninterface OfflineSyncContextValue {\n ready: boolean;\n online: boolean;\n connectionType: string;\n syncing: boolean;\n lastSyncedAt: number | null;\n observations: LocalObservation[];\n /** Queued non-observation writes (currently scheme applications). */\n pendingMutations: PendingMutation[];\n queuedCount: number;\n conflictCount: number;\n history: SyncHistoryEntry[];\n settings: OfflineSettings;\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n serverRecent: ServerObservation[];\n stats: FieldCaptureData['stats'] | null;\n loadingCaptureData: boolean;\n capture: (input: CaptureInput) => Promise<LocalObservation>;\n /**\n * Queue a scheme application. Online, this drains immediately and reports the\n * real server outcome; offline it returns QUEUED and drains on reconnect.\n */\n queueSchemeApplication: (payload: SchemeApplicationPayload, label: string) => Promise<QueueOutcome>;\n /** Drop a queued application before it drains. */\n discardPendingMutation: (clientId: string) => Promise<void>;\n syncNow: (opts?: { manual?: boolean }) => Promise<void>;\n resolve: (\n clientId: string,\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE',\n values?: ResolveValues\n ) => Promise<void>;\n remove: (clientId: string) => Promise<void>;\n updateSettings: (patch: Partial<OfflineSettings>) => Promise<void>;\n refresh: () => Promise<void>;\n loadLocalPhotos: (clientId: string) => Promise<LocalPhoto[]>;\n}\n\nconst OfflineSyncContext = createContext<OfflineSyncContextValue | null>(null);\n\nexport function useOfflineSync(): OfflineSyncContextValue {\n const ctx = useContext(OfflineSyncContext);\n if (!ctx) throw new Error('useOfflineSync must be used within an OfflineSyncProvider');\n return ctx;\n}\n\nconst LAST_SYNCED_META = 'lastSyncedAt';\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\nfunction uid(prefix: string): string {\n const rand =\n typeof crypto !== 'undefined' && crypto.randomUUID\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n return `${prefix}-${rand}`;\n}\n\nexport const OfflineSyncProvider: FC<PropsWithChildren> = ({ children }) => {\n const { workspaceId } = useHealthyBowl();\n const { save: saveToFiles } = useSaveToFiles();\n const { toast } = useToast();\n\n const [ready, setReady] = useState(false);\n const [network, setNetwork] = useState<NetworkState>(() => getNetworkState());\n const [syncing, setSyncing] = useState(false);\n const [observations, setObservations] = useState<LocalObservation[]>([]);\n const [pendingMutations, setPendingMutations] = useState<PendingMutation[]>([]);\n const [history, setHistory] = useState<SyncHistoryEntry[]>([]);\n const [settings, setSettings] = useState<OfflineSettings>(DEFAULT_SETTINGS);\n const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);\n const [captureData, setCaptureData] = useState<FieldCaptureData | null>(null);\n const [loadingCaptureData, setLoadingCaptureData] = useState(false);\n\n // Refs mirror the latest values for use inside listeners / intervals (avoids stale closures).\n const settingsRef = useRef(settings);\n const networkRef = useRef(network);\n const syncingRef = useRef(false);\n const saveToFilesRef = useRef<SaveToFiles>(saveToFiles as unknown as SaveToFiles);\n const workspaceRef = useRef(workspaceId);\n settingsRef.current = settings;\n networkRef.current = network;\n saveToFilesRef.current = saveToFiles as unknown as SaveToFiles;\n workspaceRef.current = workspaceId;\n\n const reload = useCallback(async () => {\n const [obs, hist, mutations] = await Promise.all([getAllObservations(), getHistory(), getAllPendingMutations()]);\n setObservations(obs);\n setHistory(hist);\n setPendingMutations(mutations);\n }, []);\n\n const refreshCaptureData = useCallback(async () => {\n if (!workspaceRef.current || !networkRef.current.online) return;\n setLoadingCaptureData(true);\n try {\n const data = await fetchFieldCaptureData({ workspaceId: workspaceRef.current });\n if (data) setCaptureData(data);\n } finally {\n setLoadingCaptureData(false);\n }\n }, []);\n\n // Initial load.\n useEffect(() => {\n let cancelled = false;\n void (async () => {\n const [obs, hist, s, last, mutations] = await Promise.all([\n getAllObservations(),\n getHistory(),\n loadSettings(),\n getMeta<number>(LAST_SYNCED_META),\n // Must be read on mount, not just in reload(): a queued application has\n // to be visible in Pending Sync straight after a browser restart, before\n // any network returns or any other action triggers a refresh.\n getAllPendingMutations(),\n ]);\n if (cancelled) return;\n setObservations(obs);\n setHistory(hist);\n setSettings(s);\n setLastSyncedAt(last ?? null);\n setPendingMutations(mutations);\n setReady(true);\n })();\n return () => {\n cancelled = true;\n };\n }, []);\n\n useEffect(() => {\n void refreshCaptureData();\n }, [refreshCaptureData, workspaceId]);\n\n const syncNow = useCallback(\n async (opts?: { manual?: boolean }) => {\n if (syncingRef.current) return;\n const ws = workspaceRef.current;\n const net = networkRef.current;\n if (!ws || !net.online) return;\n // Respect \"sync over mobile data\" — a manual tap always syncs.\n if (!opts?.manual && !settingsRef.current.syncOverMobileData && isCellular(net)) return;\n\n syncingRef.current = true;\n setSyncing(true);\n try {\n const summary = await drainQueue({\n workspaceId: ws,\n saveToFiles: saveToFilesRef.current,\n settings: settingsRef.current,\n network: net,\n });\n const ts = Date.now();\n setLastSyncedAt(ts);\n await setMeta(LAST_SYNCED_META, ts);\n await reload();\n void refreshCaptureData();\n // Every outcome the drain produced decides the message — including records that\n // failed or were deferred without ever entering the upload batch (BOFF-6364).\n const outcome = describeDrain(summary, { manual: opts?.manual });\n if (outcome) toast(outcome);\n } catch {\n if (opts?.manual) toast({ title: 'Sync failed', description: 'Please try again.', variant: 'error' });\n } finally {\n syncingRef.current = false;\n setSyncing(false);\n }\n },\n [reload, refreshCaptureData, toast]\n );\n\n // Connectivity: subscribe and auto-sync on the offline→online transition.\n useEffect(() => {\n let prevOnline = networkRef.current.online;\n const unsub = subscribeNetwork((state) => {\n setNetwork(state);\n const cameOnline = !prevOnline && state.online;\n prevOnline = state.online;\n if (cameOnline && settingsRef.current.autoSyncOnReconnect) {\n void syncNow();\n }\n });\n return unsub;\n }, [syncNow]);\n\n // Periodic auto-sync while online (configurable frequency; 0 disables).\n useEffect(() => {\n if (!settings.autoSyncOnReconnect || settings.syncFrequencyMs <= 0) return;\n const id = window.setInterval(() => {\n if (networkRef.current.online) void syncNow();\n }, settings.syncFrequencyMs);\n return () => window.clearInterval(id);\n }, [settings.autoSyncOnReconnect, settings.syncFrequencyMs, syncNow]);\n\n const capture = useCallback(\n async (input: CaptureInput): Promise<LocalObservation> => {\n const clientId = uid('obs');\n const photoLocalIds: string[] = [];\n for (const file of input.photos ?? []) {\n const pid = uid('photo');\n await savePhoto({\n id: pid,\n clientId,\n blob: file,\n filename: file.name || `photo-${pid}.jpg`,\n mimeType: file.type || 'image/jpeg',\n createdAt: Date.now(),\n });\n photoLocalIds.push(pid);\n }\n const obs: LocalObservation = {\n clientId,\n observationType: input.observationType,\n fieldId: input.fieldId ?? null,\n fieldName: input.fieldName ?? null,\n note: input.note ?? null,\n severity: input.severity ?? null,\n quantity: input.quantity ?? null,\n unit: input.unit ?? null,\n cropName: input.cropName ?? null,\n animalTag: input.animalTag ?? null,\n latitude: input.latitude ?? null,\n longitude: input.longitude ?? null,\n gpsAccuracy: input.gpsAccuracy ?? null,\n photoLocalIds,\n photoFileIds: [],\n capturedAt: nowIso(),\n capturedOffline: !networkRef.current.online,\n status: 'QUEUED',\n baseVersion: null,\n attempts: 0,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n workspaceId: workspaceRef.current,\n };\n await saveObservation(obs);\n await reload();\n // Kick a sync immediately if we're online and auto-sync is on.\n if (networkRef.current.online && settingsRef.current.autoSyncOnReconnect) void syncNow();\n return obs;\n },\n [reload, syncNow]\n );\n\n const resolve = useCallback(\n async (clientId: string, resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE', values?: ResolveValues) => {\n const obs = observations.find((o) => o.clientId === clientId);\n const baseVersion = obs?.serverVersion?.version ?? obs?.baseVersion ?? 0;\n try {\n const server = await resolveConflictGql(\n { workspaceId: workspaceRef.current },\n {\n clientId,\n resolution,\n baseVersion,\n fieldId: values?.fieldId,\n note: values?.note,\n severity: values?.severity,\n quantity: values?.quantity,\n unit: values?.unit,\n cropName: values?.cropName,\n animalTag: values?.animalTag,\n latitude: values?.latitude,\n longitude: values?.longitude,\n photoFileIds: values?.photoFileIds,\n }\n );\n if (obs) {\n obs.status = 'SYNCED';\n obs.serverVersion = null;\n obs.baseVersion = server.version;\n obs.serverId = server.id;\n obs.syncedAt = nowIso();\n obs.message = null;\n // Reflect the resolved values locally so the queue shows the merged truth.\n if (resolution !== 'KEEP_SERVER') {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n } else {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n await reload();\n toast({ title: 'Conflict resolved', variant: 'success' });\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Could not resolve the conflict';\n toast({ title: 'Resolve failed', description: message, variant: 'error' });\n throw err;\n }\n },\n [observations, reload, toast]\n );\n\n /**\n * Queue a scheme application, and — when online — tell the caller what really\n * happened rather than assuming success.\n *\n * The write ALWAYS goes through the outbox, online or not. That single path is\n * what makes the server's idempotency key meaningful: a submission that is\n * retried after a dropped connection returns the original application instead\n * of lodging a second one.\n */\n const queueSchemeApplication = useCallback(\n async (payload: SchemeApplicationPayload, label: string): Promise<QueueOutcome> => {\n // 'scheme-' + a uuid is 43 chars, inside the column's 64.\n const clientId = uid('scheme');\n const mutation: PendingMutation = {\n clientId,\n kind: 'SCHEME_APPLICATION',\n payload,\n label,\n status: 'QUEUED',\n attempts: 0,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n workspaceId: workspaceRef.current,\n };\n await savePendingMutation(mutation);\n await reload();\n\n if (!networkRef.current.online) return { status: 'QUEUED' };\n\n await syncNow();\n const after = await getPendingMutation(clientId);\n await reload();\n if (after?.status === 'SYNCED' && after.serverId) {\n return { status: 'SYNCED', serverId: after.serverId };\n }\n if (after?.status === 'FAILED') {\n return { status: 'FAILED', message: after.message ?? 'The server rejected this application.' };\n }\n // Still queued — e.g. a drain was already in flight, or the connection\n // dropped between the click and the request. It retries automatically.\n return { status: 'QUEUED' };\n },\n [reload, syncNow]\n );\n\n const discardPendingMutation = useCallback(\n async (clientId: string) => {\n await deletePendingMutation(clientId);\n await reload();\n },\n [reload]\n );\n\n const remove = useCallback(\n async (clientId: string) => {\n await storeDeleteObservation(clientId);\n await reload();\n },\n [reload]\n );\n\n const updateSettings = useCallback(async (patch: Partial<OfflineSettings>) => {\n setSettings((prev) => {\n const next = { ...prev, ...patch };\n void saveSettings(next);\n return next;\n });\n }, []);\n\n const loadLocalPhotos = useCallback((clientId: string) => getPhotosFor(clientId), []);\n\n const queuedCount = useMemo(\n () =>\n observations.filter((o) => o.status === 'QUEUED' || o.status === 'UPLOADING' || o.status === 'FAILED').length +\n // Queued applications count too, or the offline pill under-reports what is\n // actually waiting to reach the server.\n pendingMutations.filter((m) => m.status === 'QUEUED' || m.status === 'UPLOADING' || m.status === 'FAILED').length,\n [observations, pendingMutations]\n );\n const conflictCount = useMemo(() => observations.filter((o) => o.status === 'CONFLICT').length, [observations]);\n\n const value: OfflineSyncContextValue = {\n ready,\n online: network.online,\n connectionType: network.connectionType,\n syncing,\n lastSyncedAt,\n observations,\n pendingMutations,\n queuedCount,\n conflictCount,\n history,\n settings,\n fields: captureData?.fields ?? [],\n serverRecent: captureData?.recentObservations ?? [],\n stats: captureData?.stats ?? null,\n loadingCaptureData,\n capture,\n queueSchemeApplication,\n discardPendingMutation,\n syncNow,\n resolve,\n remove,\n updateSettings,\n refresh: async () => {\n await reload();\n await refreshCaptureData();\n },\n loadLocalPhotos,\n };\n\n return <OfflineSyncContext.Provider value={value}>{children}</OfflineSyncContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;AAqIA,IAAM,IAAqB,EAA8C,IAAI;AAE7E,SAAgB,IAA0C;CACxD,IAAM,IAAM,EAAW,CAAkB;CACzC,IAAI,CAAC,GAAK,MAAU,MAAM,2DAA2D;CACrF,OAAO;AACT;AAEA,IAAM,IAAmB;AAEzB,SAAS,IAAiB;CACxB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AACA,SAAS,EAAI,GAAwB;CAKnC,OAAO,GAAG,EAAO,GAHf,OAAO,SAAW,OAAe,OAAO,aACpC,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAEvD;AAEA,IAAa,KAA8C,EAAE,kBAAe;CAC1E,IAAM,EAAE,mBAAgB,EAAe,GACjC,EAAE,MAAM,MAAgB,EAAe,GACvC,EAAE,aAAU,EAAS,GAErB,CAAC,IAAO,MAAY,EAAS,EAAK,GAClC,CAAC,GAAS,MAAc,QAA6B,EAA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O,GAAa,SAAS;EAC7B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,YAAY;GAEnB,AADA,MAAM,EAAO,GACb,MAAM,EAAmB;EAC3B;EACA;CACF;CAEA,OAAO,kBAAC,EAAmB,UAApB;EAAoC;EAAQ;CAAsC,CAAA;AAC3F"}
|
|
1
|
+
{"version":3,"file":"OfflineSyncProvider.js","names":[],"sources":["../../../src/healthybowl/offline/OfflineSyncProvider.tsx"],"sourcesContent":["/**\n * OfflineSyncProvider (BOFF-2883).\n *\n * The single owner of the offline capture + sync lifecycle for the HealthyBowl\n * MFE. Holds the outbox + history + settings, watches connectivity, auto-drains\n * the queue on reconnect (and on an interval), and exposes capture / sync /\n * resolve / delete actions to the Field Capture screens.\n */\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type FC,\n type PropsWithChildren,\n} from 'react';\nimport { useSaveToFiles } from '@burdenoff/fe-libs/storage';\nimport { useHealthyBowl } from '../context/HealthyBowlContext';\nimport { useToast } from '../hooks/useToast';\nimport type {\n LocalObservation,\n LocalPhoto,\n ObservationType,\n OfflineSettings,\n PendingMutation,\n SchemeApplicationPayload,\n SyncHistoryEntry,\n ServerObservation,\n} from './types';\nimport { DEFAULT_SETTINGS } from './types';\nimport {\n getAllObservations,\n getObservation,\n saveObservation,\n deleteObservation as storeDeleteObservation,\n getAllPendingMutations,\n savePendingMutation,\n getPendingMutation,\n deletePendingMutation,\n savePhoto,\n getPhotosFor,\n getHistory,\n loadSettings,\n saveSettings,\n getMeta,\n setMeta,\n} from './store';\nimport { subscribeNetwork, getNetworkState, isCellular } from './network';\nimport {\n CAPTURE_DATA_META,\n CAPTURE_PHOTO_MAX_DIM,\n CAPTURE_PHOTO_QUALITY,\n autoResolutionFor,\n conflictsToAutoResolve,\n isUsableCaptureCache,\n shouldCompressPhotos,\n toCachedCaptureData,\n type CachedCaptureData,\n} from './captureCache';\nimport { downscaleImage } from '../utils/imageDownscale';\nimport { drainQueue, type SaveToFiles } from './syncEngine';\nimport { describeDrain } from './syncOutcome';\nimport { resolveConflict as resolveConflictGql, fetchFieldCaptureData, type FieldCaptureData } from './graphql';\nimport type { NetworkState } from './types';\n\nexport interface CaptureInput {\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n gpsAccuracy?: number | null;\n /** Freshly-captured photo files (blobs stored locally, uploaded on sync). */\n photos?: File[];\n}\n\nexport interface ResolveValues {\n fieldId?: string | null;\n note?: string | null;\n severity?: string | null;\n quantity?: number | null;\n unit?: string | null;\n cropName?: string | null;\n animalTag?: string | null;\n latitude?: number | null;\n longitude?: number | null;\n photoFileIds?: string[];\n}\n\n/**\n * What actually happened to a queued write (BOFF-6179).\n *\n * Returned so the caller can tell the farmer the truth rather than an optimistic\n * guess: a government application is close to a legal submission, and reporting\n * \"Submitted\" for a request that never reached the server is the exact failure\n * this board keeps finding.\n */\nexport type QueueOutcome =\n { status: 'SYNCED'; serverId: string } | { status: 'QUEUED' } | { status: 'FAILED'; message: string };\n\ninterface OfflineSyncContextValue {\n ready: boolean;\n online: boolean;\n connectionType: string;\n syncing: boolean;\n lastSyncedAt: number | null;\n observations: LocalObservation[];\n /** Queued non-observation writes (currently scheme applications). */\n pendingMutations: PendingMutation[];\n queuedCount: number;\n conflictCount: number;\n history: SyncHistoryEntry[];\n settings: OfflineSettings;\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n serverRecent: ServerObservation[];\n stats: FieldCaptureData['stats'] | null;\n loadingCaptureData: boolean;\n capture: (input: CaptureInput) => Promise<LocalObservation>;\n /**\n * Queue a scheme application. Online, this drains immediately and reports the\n * real server outcome; offline it returns QUEUED and drains on reconnect.\n */\n queueSchemeApplication: (payload: SchemeApplicationPayload, label: string) => Promise<QueueOutcome>;\n /** Drop a queued application before it drains. */\n discardPendingMutation: (clientId: string) => Promise<void>;\n syncNow: (opts?: { manual?: boolean }) => Promise<void>;\n resolve: (\n clientId: string,\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE',\n values?: ResolveValues\n ) => Promise<void>;\n remove: (clientId: string) => Promise<void>;\n updateSettings: (patch: Partial<OfflineSettings>) => Promise<void>;\n refresh: () => Promise<void>;\n loadLocalPhotos: (clientId: string) => Promise<LocalPhoto[]>;\n}\n\nconst OfflineSyncContext = createContext<OfflineSyncContextValue | null>(null);\n\nexport function useOfflineSync(): OfflineSyncContextValue {\n const ctx = useContext(OfflineSyncContext);\n if (!ctx) throw new Error('useOfflineSync must be used within an OfflineSyncProvider');\n return ctx;\n}\n\nconst LAST_SYNCED_META = 'lastSyncedAt';\n\nfunction nowIso(): string {\n return new Date().toISOString();\n}\nfunction uid(prefix: string): string {\n const rand =\n typeof crypto !== 'undefined' && crypto.randomUUID\n ? crypto.randomUUID()\n : `${Date.now()}-${Math.round(Math.random() * 1e9)}`;\n return `${prefix}-${rand}`;\n}\n\nexport const OfflineSyncProvider: FC<PropsWithChildren> = ({ children }) => {\n const { workspaceId } = useHealthyBowl();\n const { save: saveToFiles } = useSaveToFiles();\n const { toast } = useToast();\n\n const [ready, setReady] = useState(false);\n const [network, setNetwork] = useState<NetworkState>(() => getNetworkState());\n const [syncing, setSyncing] = useState(false);\n const [observations, setObservations] = useState<LocalObservation[]>([]);\n const [pendingMutations, setPendingMutations] = useState<PendingMutation[]>([]);\n const [history, setHistory] = useState<SyncHistoryEntry[]>([]);\n const [settings, setSettings] = useState<OfflineSettings>(DEFAULT_SETTINGS);\n const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);\n const [captureData, setCaptureData] = useState<FieldCaptureData | null>(null);\n const [loadingCaptureData, setLoadingCaptureData] = useState(false);\n\n // Refs mirror the latest values for use inside listeners / intervals (avoids stale closures).\n const settingsRef = useRef(settings);\n const networkRef = useRef(network);\n const syncingRef = useRef(false);\n const saveToFilesRef = useRef<SaveToFiles>(saveToFiles as unknown as SaveToFiles);\n const workspaceRef = useRef(workspaceId);\n /**\n * `resolve` is declared below `syncNow`, so the auto-resolution step cannot call it directly\n * without a temporal-dead-zone error. A ref defers the lookup to call time, which is also what\n * keeps `syncNow` off `resolve`'s dependency list — `resolve` depends on `syncNow`, so a direct\n * dependency would be a cycle.\n */\n const resolveRef = useRef<\n (\n clientId: string,\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE',\n values?: undefined,\n opts?: { silent?: boolean }\n ) => Promise<unknown>\n >(() => Promise.resolve());\n settingsRef.current = settings;\n networkRef.current = network;\n saveToFilesRef.current = saveToFiles as unknown as SaveToFiles;\n workspaceRef.current = workspaceId;\n\n const reload = useCallback(async () => {\n const [obs, hist, mutations] = await Promise.all([getAllObservations(), getHistory(), getAllPendingMutations()]);\n setObservations(obs);\n setHistory(hist);\n setPendingMutations(mutations);\n }, []);\n\n const refreshCaptureData = useCallback(async () => {\n if (!workspaceRef.current || !networkRef.current.online) return;\n setLoadingCaptureData(true);\n try {\n const data = await fetchFieldCaptureData({ workspaceId: workspaceRef.current });\n if (data) {\n setCaptureData(data);\n // Persisted so the field list survives a restart. Without it, an offline cold start left\n // `fields` empty, the capture form showed only its disabled \"No fields yet\" item, and the\n // observation saved with fieldId: null — unattributable to any field, forever. A photo of a\n // pest outbreak nobody can locate is not evidence.\n await setMeta(CAPTURE_DATA_META, toCachedCaptureData(data, workspaceRef.current, Date.now())).catch(\n () => undefined\n );\n }\n } finally {\n setLoadingCaptureData(false);\n }\n }, []);\n\n // Initial load.\n useEffect(() => {\n let cancelled = false;\n void (async () => {\n const [obs, hist, s, last, mutations, cachedCapture] = await Promise.all([\n getAllObservations(),\n getHistory(),\n loadSettings(),\n getMeta<number>(LAST_SYNCED_META),\n // Must be read on mount, not just in reload(): a queued application has\n // to be visible in Pending Sync straight after a browser restart, before\n // any network returns or any other action triggers a refresh.\n getAllPendingMutations(),\n getMeta<CachedCaptureData>(CAPTURE_DATA_META),\n ]);\n if (cancelled) return;\n setObservations(obs);\n setHistory(hist);\n setSettings(s);\n setLastSyncedAt(last ?? null);\n setPendingMutations(mutations);\n // Hydrate the field list before any network is available. refreshCaptureData() overwrites this\n // as soon as one is, so a stale list is only ever shown while genuinely offline. A workspace\n // mismatch is discarded rather than displayed — offering another farm's fields would be worse\n // than offering none.\n if (isUsableCaptureCache(cachedCapture, workspaceRef.current, Date.now())) {\n setCaptureData(cachedCapture!.data);\n }\n setReady(true);\n })();\n return () => {\n cancelled = true;\n };\n }, []);\n\n useEffect(() => {\n void refreshCaptureData();\n }, [refreshCaptureData, workspaceId]);\n\n const syncNow = useCallback(\n async (opts?: { manual?: boolean }) => {\n if (syncingRef.current) return;\n const ws = workspaceRef.current;\n const net = networkRef.current;\n if (!ws || !net.online) return;\n // Respect \"sync over mobile data\" — a manual tap always syncs.\n if (!opts?.manual && !settingsRef.current.syncOverMobileData && isCellular(net)) return;\n\n syncingRef.current = true;\n setSyncing(true);\n try {\n const summary = await drainQueue({\n workspaceId: ws,\n saveToFiles: saveToFilesRef.current,\n settings: settingsRef.current,\n network: net,\n });\n const ts = Date.now();\n setLastSyncedAt(ts);\n await setMeta(LAST_SYNCED_META, ts);\n await reload();\n void refreshCaptureData();\n // `conflictHandling` offers review / keepMine / keepServer and was read by nothing —\n // applyOutcome always parked a conflict for review, so two of the three choices did\n // nothing at all. Resolution runs here rather than inside drainQueue() because it is a\n // separate mutation against a record the drain has just finished writing.\n //\n // Records are re-read from the store rather than taken from `observations`: this callback\n // closes over the state as it was when the sync started, which is before drainQueue marked\n // anything CONFLICT.\n const autoResolution = autoResolutionFor(settingsRef.current.conflictHandling);\n // Conflicts the farmer still has to look at. Starts at what the drain reported and is\n // reduced only by resolutions that actually succeeded — a record whose resolution failed is\n // still sitting in CONFLICT, and she has to be told so.\n let conflictsNeedingReview = summary.conflict;\n if (autoResolution && summary.conflict > 0) {\n const conflicted = conflictsToAutoResolve(await getAllObservations(), ws);\n let resolved = 0;\n for (const record of conflicted) {\n // Sequential, not parallel: each resolution is a write against the same workspace, and\n // a burst of them on a reconnecting rural connection is exactly the wrong shape.\n //\n // Counted rather than swallowed. Reporting `conflicted.length` regardless would tell a\n // farmer \"3 conflicts resolved\" when the connection died after the first — and she\n // would stop checking, which is the setting lying in the very way this ticket exists to\n // stop. The same connection that produced the conflicts is the one resolving them.\n const ok = await resolveRef\n .current(record.clientId, autoResolution, undefined, {\n silent: true,\n })\n .then(\n () => true,\n () => false\n );\n if (ok) resolved += 1;\n }\n conflictsNeedingReview = Math.max(0, summary.conflict - resolved);\n if (resolved > 0) {\n await reload();\n toast({\n title: `${resolved} conflict${resolved > 1 ? 's' : ''} resolved`,\n description:\n autoResolution === 'KEEP_MINE'\n ? 'Your offline version was kept, as set in Offline Settings.'\n : 'The server version was kept, as set in Offline Settings.',\n variant: 'info',\n });\n }\n }\n\n // Every outcome the drain produced decides the message — including records that\n // failed or were deferred without ever entering the upload batch (BOFF-6364). A\n // successfully auto-resolved conflict is no longer actionable, so omit only those\n // records from the generic summary rather than telling the farmer to review them.\n const outcome = describeDrain({ ...summary, conflict: conflictsNeedingReview }, { manual: opts?.manual });\n if (outcome) toast(outcome);\n } catch {\n if (opts?.manual) toast({ title: 'Sync failed', description: 'Please try again.', variant: 'error' });\n } finally {\n syncingRef.current = false;\n setSyncing(false);\n }\n },\n [reload, refreshCaptureData, toast]\n );\n\n // Connectivity: subscribe and auto-sync on the offline→online transition.\n useEffect(() => {\n let prevOnline = networkRef.current.online;\n const unsub = subscribeNetwork((state) => {\n setNetwork(state);\n const cameOnline = !prevOnline && state.online;\n prevOnline = state.online;\n if (cameOnline && settingsRef.current.autoSyncOnReconnect) {\n void syncNow();\n }\n });\n return unsub;\n }, [syncNow]);\n\n // Periodic auto-sync while online (configurable frequency; 0 disables).\n useEffect(() => {\n if (!settings.autoSyncOnReconnect || settings.syncFrequencyMs <= 0) return;\n const id = window.setInterval(() => {\n if (networkRef.current.online) void syncNow();\n }, settings.syncFrequencyMs);\n return () => window.clearInterval(id);\n }, [settings.autoSyncOnReconnect, settings.syncFrequencyMs, syncNow]);\n\n const capture = useCallback(\n async (input: CaptureInput): Promise<LocalObservation> => {\n const clientId = uid('obs');\n const photoLocalIds: string[] = [];\n const compress = shouldCompressPhotos(settingsRef.current);\n for (const file of input.photos ?? []) {\n const pid = uid('photo');\n // `photoQuality` is set to \"compressed\" by default and was read by nothing. A 12MP phone\n // photo is several megabytes; a few of them exhaust a cheap Android's storage quota, the\n // IndexedDB write fails, and the observation is lost — the exact failure offline capture\n // exists to prevent.\n let blob: Blob = file;\n let filename = file.name || `photo-${pid}.jpg`;\n let mimeType = file.type || 'image/jpeg';\n if (compress) {\n try {\n const downscaled = await downscaleImage(file, {\n maxDim: CAPTURE_PHOTO_MAX_DIM,\n quality: CAPTURE_PHOTO_QUALITY,\n // Only `blob` is used here. On the un-rasterisable fallback path the file has NOT\n // been shrunk, so base64 would cost ~1.37x of the ORIGINAL in strings — a 12MB HEIC\n // becoming ~16MB of memory on the device least able to spare it.\n encodeFallback: false,\n });\n if (downscaled.downscaled && downscaled.blob) {\n blob = downscaled.blob;\n filename = downscaled.filename ?? filename;\n mimeType = downscaled.mimeType ?? 'image/jpeg';\n }\n } catch {\n // Keep the original. A photo too large to compress is still better evidence than no\n // photo, and this runs on the capture path where a throw would lose the observation.\n }\n }\n await savePhoto({\n id: pid,\n clientId,\n blob,\n filename,\n mimeType,\n createdAt: Date.now(),\n });\n photoLocalIds.push(pid);\n }\n const obs: LocalObservation = {\n clientId,\n observationType: input.observationType,\n fieldId: input.fieldId ?? null,\n fieldName: input.fieldName ?? null,\n note: input.note ?? null,\n severity: input.severity ?? null,\n quantity: input.quantity ?? null,\n unit: input.unit ?? null,\n cropName: input.cropName ?? null,\n animalTag: input.animalTag ?? null,\n latitude: input.latitude ?? null,\n longitude: input.longitude ?? null,\n gpsAccuracy: input.gpsAccuracy ?? null,\n photoLocalIds,\n photoFileIds: [],\n capturedAt: nowIso(),\n capturedOffline: !networkRef.current.online,\n status: 'QUEUED',\n baseVersion: null,\n attempts: 0,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n workspaceId: workspaceRef.current,\n };\n await saveObservation(obs);\n await reload();\n // Kick a sync immediately if we're online and auto-sync is on.\n if (networkRef.current.online && settingsRef.current.autoSyncOnReconnect) void syncNow();\n return obs;\n },\n [reload, syncNow]\n );\n\n const resolve = useCallback(\n async (\n clientId: string,\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE',\n values?: ResolveValues,\n opts?: { silent?: boolean }\n ) => {\n // Read from IndexedDB, not from the `observations` render state.\n //\n // The state copy can be a whole drain out of date. drainQueue writes CONFLICT and the\n // serverVersion straight to the store; `reload()` calls setObservations, but React has not\n // re-rendered by the time an auto-resolution runs, so a closure over `observations` still\n // holds the pre-drain record. Two things go wrong with it, and the second is the dangerous\n // one:\n //\n // · `serverVersion` is absent, so baseVersion silently falls back to 0 and the server\n // rejects the resolution — auto-resolution would do nothing, quietly, forever;\n // · the success path mutates that stale object and saves it back, overwriting everything\n // drainQueue had just enriched.\n //\n // The store is the single source of truth for a record's state, so read it there.\n const obs = await getObservation(clientId);\n const baseVersion = obs?.serverVersion?.version ?? obs?.baseVersion ?? 0;\n try {\n const server = await resolveConflictGql(\n { workspaceId: workspaceRef.current },\n {\n clientId,\n resolution,\n baseVersion,\n fieldId: values?.fieldId,\n note: values?.note,\n severity: values?.severity,\n quantity: values?.quantity,\n unit: values?.unit,\n cropName: values?.cropName,\n animalTag: values?.animalTag,\n latitude: values?.latitude,\n longitude: values?.longitude,\n photoFileIds: values?.photoFileIds,\n }\n );\n if (obs) {\n obs.status = 'SYNCED';\n obs.serverVersion = null;\n obs.baseVersion = server.version;\n obs.serverId = server.id;\n obs.syncedAt = nowIso();\n obs.message = null;\n // Reflect the resolved values locally so the queue shows the merged truth.\n if (resolution !== 'KEEP_SERVER') {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n } else {\n obs.note = server.note ?? obs.note;\n obs.severity = server.severity ?? obs.severity;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n await reload();\n // Silent on the automatic path: N records would otherwise stack N toasts on top of the one\n // summary toast that already says what happened.\n if (!opts?.silent) toast({ title: 'Conflict resolved', variant: 'success' });\n } catch (err) {\n const message = err instanceof Error ? err.message : 'Could not resolve the conflict';\n if (!opts?.silent) toast({ title: 'Resolve failed', description: message, variant: 'error' });\n throw err;\n }\n },\n [reload, toast]\n );\n\n /**\n * Queue a scheme application, and — when online — tell the caller what really\n * happened rather than assuming success.\n *\n * The write ALWAYS goes through the outbox, online or not. That single path is\n * what makes the server's idempotency key meaningful: a submission that is\n * retried after a dropped connection returns the original application instead\n * of lodging a second one.\n */\n const queueSchemeApplication = useCallback(\n async (payload: SchemeApplicationPayload, label: string): Promise<QueueOutcome> => {\n // 'scheme-' + a uuid is 43 chars, inside the column's 64.\n const clientId = uid('scheme');\n const mutation: PendingMutation = {\n clientId,\n kind: 'SCHEME_APPLICATION',\n payload,\n label,\n status: 'QUEUED',\n attempts: 0,\n createdAt: Date.now(),\n updatedAt: Date.now(),\n workspaceId: workspaceRef.current,\n };\n await savePendingMutation(mutation);\n await reload();\n\n if (!networkRef.current.online) return { status: 'QUEUED' };\n\n await syncNow();\n const after = await getPendingMutation(clientId);\n await reload();\n if (after?.status === 'SYNCED' && after.serverId) {\n return { status: 'SYNCED', serverId: after.serverId };\n }\n if (after?.status === 'FAILED') {\n return { status: 'FAILED', message: after.message ?? 'The server rejected this application.' };\n }\n // Still queued — e.g. a drain was already in flight, or the connection\n // dropped between the click and the request. It retries automatically.\n return { status: 'QUEUED' };\n },\n [reload, syncNow]\n );\n resolveRef.current = resolve;\n\n const discardPendingMutation = useCallback(\n async (clientId: string) => {\n await deletePendingMutation(clientId);\n await reload();\n },\n [reload]\n );\n\n const remove = useCallback(\n async (clientId: string) => {\n await storeDeleteObservation(clientId);\n await reload();\n },\n [reload]\n );\n\n const updateSettings = useCallback(async (patch: Partial<OfflineSettings>) => {\n setSettings((prev) => {\n const next = { ...prev, ...patch };\n void saveSettings(next);\n return next;\n });\n }, []);\n\n const loadLocalPhotos = useCallback((clientId: string) => getPhotosFor(clientId), []);\n\n const queuedCount = useMemo(\n () =>\n observations.filter((o) => o.status === 'QUEUED' || o.status === 'UPLOADING' || o.status === 'FAILED').length +\n // Queued applications count too, or the offline pill under-reports what is\n // actually waiting to reach the server.\n pendingMutations.filter((m) => m.status === 'QUEUED' || m.status === 'UPLOADING' || m.status === 'FAILED').length,\n [observations, pendingMutations]\n );\n const conflictCount = useMemo(() => observations.filter((o) => o.status === 'CONFLICT').length, [observations]);\n\n const value: OfflineSyncContextValue = {\n ready,\n online: network.online,\n connectionType: network.connectionType,\n syncing,\n lastSyncedAt,\n observations,\n pendingMutations,\n queuedCount,\n conflictCount,\n history,\n settings,\n fields: captureData?.fields ?? [],\n serverRecent: captureData?.recentObservations ?? [],\n stats: captureData?.stats ?? null,\n loadingCaptureData,\n capture,\n queueSchemeApplication,\n discardPendingMutation,\n syncNow,\n resolve,\n remove,\n updateSettings,\n refresh: async () => {\n await reload();\n await refreshCaptureData();\n },\n loadLocalPhotos,\n };\n\n return <OfflineSyncContext.Provider value={value}>{children}</OfflineSyncContext.Provider>;\n};\n"],"mappings":";;;;;;;;;;;;;;AAkJA,IAAM,IAAqB,EAA8C,IAAI;AAE7E,SAAgB,IAA0C;CACxD,IAAM,IAAM,EAAW,CAAkB;CACzC,IAAI,CAAC,GAAK,MAAU,MAAM,2DAA2D;CACrF,OAAO;AACT;AAEA,IAAM,IAAmB;AAEzB,SAAS,IAAiB;CACxB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AACA,SAAS,EAAI,GAAwB;CAKnC,OAAO,GAAG,EAAO,GAHf,OAAO,SAAW,OAAe,OAAO,aACpC,OAAO,WAAW,IAClB,GAAG,KAAK,IAAI,EAAE,GAAG,KAAK,MAAM,KAAK,OAAO,IAAI,GAAG;AAEvD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QAAQ,GAAa,UAAU,CAAC;EAChC,cAAc,GAAa,sBAAsB,CAAC;EAClD,OAAO,GAAa,SAAS;EAC7B;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,SAAS,YAAY;GAEnB,AADA,MAAM,EAAO,GACb,MAAM,EAAmB;EAC3B;EACA;CACF;CAEA,OAAO,mBAAC,EAAmB,UAApB;EAAoC;EAAQ;CAAsC,CAAA;AAC3F"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
//#region src/healthybowl/offline/captureCache.ts
|
|
2
|
+
var e = "captureData", t = 720 * 60 * 60 * 1e3;
|
|
3
|
+
function n(e, n, r) {
|
|
4
|
+
return !e || !n || e.workspaceId !== n || !e.data || !Number.isFinite(e.cachedAt) ? !1 : r - e.cachedAt <= t;
|
|
5
|
+
}
|
|
6
|
+
function r(e, t, n) {
|
|
7
|
+
return {
|
|
8
|
+
workspaceId: t,
|
|
9
|
+
cachedAt: n,
|
|
10
|
+
data: e
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
function i(e) {
|
|
14
|
+
return e.photoQuality === "compressed";
|
|
15
|
+
}
|
|
16
|
+
var a = 1600, o = .8;
|
|
17
|
+
function s(e) {
|
|
18
|
+
switch (e) {
|
|
19
|
+
case "keepMine": return "KEEP_MINE";
|
|
20
|
+
case "keepServer": return "KEEP_SERVER";
|
|
21
|
+
default: return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function c(e, t) {
|
|
25
|
+
return t ? e.filter((e) => e.status === "CONFLICT" && e.workspaceId === t) : [];
|
|
26
|
+
}
|
|
27
|
+
//#endregion
|
|
28
|
+
export { e as CAPTURE_DATA_META, a as CAPTURE_PHOTO_MAX_DIM, o as CAPTURE_PHOTO_QUALITY, s as autoResolutionFor, c as conflictsToAutoResolve, n as isUsableCaptureCache, i as shouldCompressPhotos, r as toCachedCaptureData };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=captureCache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"captureCache.js","names":[],"sources":["../../../src/healthybowl/offline/captureCache.ts"],"sourcesContent":["/**\n * Offline capture support: cached field list, photo compression, auto conflict resolution\n * (BOFF-4670) — pure, so it unit-tests without IndexedDB or a network.\n *\n * Three settings that the Offline Settings screen writes and nothing read. A setting that saves and\n * then does nothing is worse than no setting: the farmer believes they have configured something,\n * and behaves accordingly.\n *\n * @module healthybowl\n */\nimport type { LocalObservation, OfflineSettings } from './types';\nimport type { FieldCaptureData } from './graphql';\n\n/** Meta key for the cached capture data. Read on mount, written on every successful fetch. */\nexport const CAPTURE_DATA_META = 'captureData';\n\n/**\n * How long a cached field list stays usable.\n *\n * Long, deliberately. The cache exists precisely for the farmer who has been offline for days, and\n * a stale field name attached to a real observation is recoverable — an observation saved with\n * `fieldId: null` is not, because nothing afterwards can say which field it came from.\n */\nexport const CAPTURE_CACHE_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;\n\nexport interface CachedCaptureData {\n workspaceId: string;\n cachedAt: number;\n data: FieldCaptureData;\n}\n\n/**\n * Is a cached payload safe to hydrate from?\n *\n * The workspace check is the important one: hydrating another workspace's field list would offer the\n * farmer fields that are not theirs and attribute an observation to a field in someone else's farm.\n * Wrong data is worse than no data here, so a mismatch is discarded rather than shown.\n */\nexport function isUsableCaptureCache(\n cached: CachedCaptureData | null | undefined,\n workspaceId: string | null | undefined,\n now: number\n): boolean {\n if (!cached || !workspaceId) return false;\n if (cached.workspaceId !== workspaceId) return false;\n if (!cached.data) return false;\n if (!Number.isFinite(cached.cachedAt)) return false;\n return now - cached.cachedAt <= CAPTURE_CACHE_MAX_AGE_MS;\n}\n\n/** Wraps a freshly fetched payload for storage, stamping the workspace and time. */\nexport function toCachedCaptureData(data: FieldCaptureData, workspaceId: string, now: number): CachedCaptureData {\n return { workspaceId, cachedAt: now, data };\n}\n\n/**\n * Should this capture's photos be downscaled before they go into IndexedDB?\n *\n * `compressed` is the default, so this is what the overwhelming majority of captures get — which is\n * the point. A 12MP phone photo is several megabytes, and a handful of them will exhaust a cheap\n * Android's storage quota, at which point the write fails and the observation is lost.\n */\nexport function shouldCompressPhotos(settings: Pick<OfflineSettings, 'photoQuality'>): boolean {\n return settings.photoQuality === 'compressed';\n}\n\n/**\n * Downscale target for a queued field photo.\n *\n * Larger than the AI-detection path's default: these are evidence photos a reviewer may zoom into,\n * so legibility matters more than the last few hundred kilobytes. Still an order of magnitude\n * smaller than the original.\n */\nexport const CAPTURE_PHOTO_MAX_DIM = 1600;\nexport const CAPTURE_PHOTO_QUALITY = 0.8;\n\n/** The automatic resolution a conflict-handling setting implies, or null to leave it for review. */\nexport function autoResolutionFor(setting: OfflineSettings['conflictHandling']): 'KEEP_MINE' | 'KEEP_SERVER' | null {\n switch (setting) {\n case 'keepMine':\n return 'KEEP_MINE';\n case 'keepServer':\n return 'KEEP_SERVER';\n case 'review':\n default:\n // Unknown values fall through to review rather than guessing. Picking a side automatically on\n // a setting this code does not understand would silently discard someone's data.\n return null;\n }\n}\n\n/**\n * Conflicted records to resolve automatically.\n *\n * Scoped to the current workspace so a stale record captured under another workspace is never\n * silently overwritten by this workspace's preference.\n */\nexport function conflictsToAutoResolve(\n observations: readonly LocalObservation[],\n workspaceId: string | null | undefined\n): LocalObservation[] {\n if (!workspaceId) return [];\n return observations.filter((obs) => obs.status === 'CONFLICT' && obs.workspaceId === workspaceId);\n}\n"],"mappings":";AAcA,IAAa,IAAoB,eASpB,IAA2B,MAAU,KAAK,KAAK;AAe5D,SAAgB,EACd,GACA,GACA,GACS;CAKT,OAJI,CAAC,KAAU,CAAC,KACZ,EAAO,gBAAgB,KACvB,CAAC,EAAO,QACR,CAAC,OAAO,SAAS,EAAO,QAAQ,IAAU,KACvC,IAAM,EAAO,YAAY;AAClC;AAGA,SAAgB,EAAoB,GAAwB,GAAqB,GAAgC;CAC/G,OAAO;EAAE;EAAa,UAAU;EAAK;CAAK;AAC5C;AASA,SAAgB,EAAqB,GAA0D;CAC7F,OAAO,EAAS,iBAAiB;AACnC;AASA,IAAa,IAAwB,MACxB,IAAwB;AAGrC,SAAgB,EAAkB,GAAkF;CAClH,QAAQ,GAAR;EACE,KAAK,YACH,OAAO;EACT,KAAK,cACH,OAAO;EAET,SAGE,OAAO;CACX;AACF;AAQA,SAAgB,EACd,GACA,GACoB;CAEpB,OADK,IACE,EAAa,QAAQ,MAAQ,EAAI,WAAW,cAAc,EAAI,gBAAgB,CAAW,IADvE,CAAC;AAE5B"}
|
|
@@ -174,6 +174,6 @@ async function z(e, t) {
|
|
|
174
174
|
await g(o, t, e);
|
|
175
175
|
}
|
|
176
176
|
//#endregion
|
|
177
|
-
export { P as addHistoryEntry, N as clearSyncedPhotoBlobs, C as deleteObservation, D as deletePendingMutation, M as estimateLocalUsage, S as getAllObservations, E as getAllPendingMutations, F as getHistory, R as getMeta, T as getPendingMutation, k as getPhoto, A as getPhotosFor, I as loadSettings, b as saveObservation, w as savePendingMutation, O as savePhoto, L as saveSettings, z as setMeta };
|
|
177
|
+
export { P as addHistoryEntry, N as clearSyncedPhotoBlobs, C as deleteObservation, D as deletePendingMutation, M as estimateLocalUsage, S as getAllObservations, E as getAllPendingMutations, F as getHistory, R as getMeta, x as getObservation, T as getPendingMutation, k as getPhoto, A as getPhotosFor, I as loadSettings, b as saveObservation, w as savePendingMutation, O as savePhoto, L as saveSettings, z as setMeta };
|
|
178
178
|
|
|
179
179
|
//# sourceMappingURL=store.js.map
|
package/package.json
CHANGED