@burdenoff/microfe-healthybowl 2026.710.20 → 2026.710.21
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/HealthyBowlRoot.js +99 -82
- package/dist/healthybowl/HealthyBowlRoot.js.map +1 -1
- package/dist/healthybowl/HealthyBowlRoutes.js +100 -80
- package/dist/healthybowl/HealthyBowlRoutes.js.map +1 -1
- package/dist/healthybowl/offline/OfflineStatusPill.js +30 -0
- package/dist/healthybowl/offline/OfflineStatusPill.js.map +1 -0
- package/dist/healthybowl/offline/OfflineSyncProvider.js +235 -0
- package/dist/healthybowl/offline/OfflineSyncProvider.js.map +1 -0
- package/dist/healthybowl/offline/geolocation.js +31 -0
- package/dist/healthybowl/offline/geolocation.js.map +1 -0
- package/dist/healthybowl/offline/graphql.js +89 -0
- package/dist/healthybowl/offline/graphql.js.map +1 -0
- package/dist/healthybowl/offline/network.js +43 -0
- package/dist/healthybowl/offline/network.js.map +1 -0
- package/dist/healthybowl/offline/observationMeta.js +107 -0
- package/dist/healthybowl/offline/observationMeta.js.map +1 -0
- package/dist/healthybowl/offline/store.js +120 -0
- package/dist/healthybowl/offline/store.js.map +1 -0
- package/dist/healthybowl/offline/syncEngine.js +141 -0
- package/dist/healthybowl/offline/syncEngine.js.map +1 -0
- package/dist/healthybowl/offline/types.js +15 -0
- package/dist/healthybowl/offline/types.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/CaptureObservationForm.js +272 -0
- package/dist/healthybowl/pages/field-capture/CaptureObservationForm.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/ConflictReviewPage.js +200 -0
- package/dist/healthybowl/pages/field-capture/ConflictReviewPage.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/FieldCapturePage.js +60 -0
- package/dist/healthybowl/pages/field-capture/FieldCapturePage.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/OfflineSettingsPage.js +217 -0
- package/dist/healthybowl/pages/field-capture/OfflineSettingsPage.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/PendingSyncPage.js +80 -0
- package/dist/healthybowl/pages/field-capture/PendingSyncPage.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/SyncHistoryPage.js +130 -0
- package/dist/healthybowl/pages/field-capture/SyncHistoryPage.js.map +1 -0
- package/dist/healthybowl/pages/field-capture/SyncQueuePanel.js +112 -0
- package/dist/healthybowl/pages/field-capture/SyncQueuePanel.js.map +1 -0
- package/package.json +1 -1
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { graphqlFetch as e } from "@burdenoff/fe-libs/shared/graphql";
|
|
2
|
+
//#region src/healthybowl/offline/graphql.ts
|
|
3
|
+
var t = class extends Error {
|
|
4
|
+
code;
|
|
5
|
+
constructor(e, t) {
|
|
6
|
+
super(e), this.name = "SyncGraphQLError", this.code = t;
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
function n(e) {
|
|
10
|
+
if (!e || e.length === 0) return null;
|
|
11
|
+
let n = e[0];
|
|
12
|
+
return new t(n.extensions?.userMessage ?? n.message, n.extensions?.code ?? "INTERNAL_SERVER_ERROR");
|
|
13
|
+
}
|
|
14
|
+
var r = "\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n", i = `
|
|
15
|
+
mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {
|
|
16
|
+
syncHealthyBowlFieldObservations(input: $input) {
|
|
17
|
+
syncedCount duplicateCount conflictCount failedCount
|
|
18
|
+
items {
|
|
19
|
+
clientId outcome message
|
|
20
|
+
observation { ${r} }
|
|
21
|
+
serverVersion { ${r} }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
`;
|
|
26
|
+
async function a(r, a) {
|
|
27
|
+
let o = await e({
|
|
28
|
+
gateway: "workspace",
|
|
29
|
+
query: i,
|
|
30
|
+
variables: { input: {
|
|
31
|
+
context: r,
|
|
32
|
+
observations: a
|
|
33
|
+
} },
|
|
34
|
+
workspaceToken: !0,
|
|
35
|
+
workspaceId: r.workspaceId,
|
|
36
|
+
suppressGlobalErrorEvent: !0
|
|
37
|
+
}), s = n(o.errors);
|
|
38
|
+
if (s) throw s;
|
|
39
|
+
let c = o.data?.syncHealthyBowlFieldObservations;
|
|
40
|
+
if (!c) throw new t("Empty sync response", "INTERNAL_SERVER_ERROR");
|
|
41
|
+
return c;
|
|
42
|
+
}
|
|
43
|
+
var o = `
|
|
44
|
+
mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {
|
|
45
|
+
resolveHealthyBowlFieldObservationConflict(input: $input) { ${r} }
|
|
46
|
+
}
|
|
47
|
+
`;
|
|
48
|
+
async function s(r, i) {
|
|
49
|
+
let a = await e({
|
|
50
|
+
gateway: "workspace",
|
|
51
|
+
query: o,
|
|
52
|
+
variables: { input: {
|
|
53
|
+
...i,
|
|
54
|
+
context: r
|
|
55
|
+
} },
|
|
56
|
+
workspaceToken: !0,
|
|
57
|
+
workspaceId: r.workspaceId,
|
|
58
|
+
suppressGlobalErrorEvent: !0
|
|
59
|
+
}), s = n(a.errors);
|
|
60
|
+
if (s) throw s;
|
|
61
|
+
let c = a.data?.resolveHealthyBowlFieldObservationConflict;
|
|
62
|
+
if (!c) throw new t("Empty resolve response", "INTERNAL_SERVER_ERROR");
|
|
63
|
+
return c;
|
|
64
|
+
}
|
|
65
|
+
var c = `
|
|
66
|
+
query FieldCaptureData($context: ContextInput!) {
|
|
67
|
+
getHealthyBowlFieldCaptureData(context: $context) {
|
|
68
|
+
fields { id name cropNames }
|
|
69
|
+
recentObservations { ${r} }
|
|
70
|
+
stats { totalObservations observationsToday byType { observationType count } }
|
|
71
|
+
updatedAt
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
`;
|
|
75
|
+
async function l(t) {
|
|
76
|
+
let n = await e({
|
|
77
|
+
gateway: "workspace",
|
|
78
|
+
query: c,
|
|
79
|
+
variables: { context: t },
|
|
80
|
+
workspaceToken: !0,
|
|
81
|
+
workspaceId: t.workspaceId,
|
|
82
|
+
suppressGlobalErrorEvent: !0
|
|
83
|
+
});
|
|
84
|
+
return n.errors && n.errors.length ? null : n.data?.getHealthyBowlFieldCaptureData ?? null;
|
|
85
|
+
}
|
|
86
|
+
//#endregion
|
|
87
|
+
export { l as fetchFieldCaptureData, s as resolveConflict, a as syncObservations };
|
|
88
|
+
|
|
89
|
+
//# sourceMappingURL=graphql.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graphql.js","names":[],"sources":["../../../src/healthybowl/offline/graphql.ts"],"sourcesContent":["/**\n * GraphQL operations for the offline sync engine (BOFF-2883).\n *\n * These replay through fe-libs `graphqlFetch` (gateway: 'workspace'), which\n * re-derives auth (bearer + workspace dual-token + context headers) from\n * profile storage on every call — so the outbox never freezes a rotating token.\n * The workspaces public gateway enforces the `@rbac` directives.\n */\nimport { graphqlFetch } from '@burdenoff/fe-libs/shared/graphql';\nimport type { ServerObservation } from './types';\n\ninterface GqlError {\n message: string;\n extensions?: { code?: string; userMessage?: string };\n}\n\n/** Thrown when the gateway returns GraphQL errors (vs a transport failure). */\nexport class SyncGraphQLError extends Error {\n code: string;\n constructor(message: string, code: string) {\n super(message);\n this.name = 'SyncGraphQLError';\n this.code = code;\n }\n}\n\nfunction firstError(errors: GqlError[] | undefined): SyncGraphQLError | null {\n if (!errors || errors.length === 0) return null;\n const e = errors[0];\n return new SyncGraphQLError(e.extensions?.userMessage ?? e.message, e.extensions?.code ?? 'INTERNAL_SERVER_ERROR');\n}\n\ntype Ctx = { workspaceId: string };\n\nconst OBSERVATION_FIELDS = `\n id clientId fieldId fieldName observationType title note severity quantity unit\n cropName animalTag latitude longitude gpsAccuracy photoFileIds capturedAt\n capturedOffline syncedAt version createdBy createdAt updatedAt\n`;\n\nexport interface SyncInputItem {\n clientId: string;\n observationType: string;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: 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 photoFileIds?: string[];\n capturedAt: string;\n capturedOffline?: boolean;\n baseVersion?: number | null;\n}\n\nexport interface SyncResultItem {\n clientId: string;\n outcome: 'SYNCED' | 'DUPLICATE' | 'CONFLICT' | 'FAILED';\n observation: ServerObservation | null;\n serverVersion: ServerObservation | null;\n message: string | null;\n}\n\nexport interface SyncResult {\n items: SyncResultItem[];\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n}\n\nconst SYNC_MUTATION = `\n mutation SyncFieldObservations($input: SyncFieldObservationsInput!) {\n syncHealthyBowlFieldObservations(input: $input) {\n syncedCount duplicateCount conflictCount failedCount\n items {\n clientId outcome message\n observation { ${OBSERVATION_FIELDS} }\n serverVersion { ${OBSERVATION_FIELDS} }\n }\n }\n }\n`;\n\nexport async function syncObservations(ctx: Ctx, observations: SyncInputItem[]): Promise<SyncResult> {\n const res = await graphqlFetch<{ syncHealthyBowlFieldObservations: SyncResult }>({\n gateway: 'workspace',\n query: SYNC_MUTATION,\n variables: { input: { context: ctx, observations } },\n // The workspaces gateway enforces @rbac(scopeType:\"wspace\"); attach the workspace\n // dual-token + x-workspace-id so the call is authorized for this workspace.\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.syncHealthyBowlFieldObservations;\n if (!data) throw new SyncGraphQLError('Empty sync response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface ResolveInput {\n clientId: string;\n resolution: 'KEEP_MINE' | 'KEEP_SERVER' | 'MERGE';\n baseVersion: number;\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\nconst RESOLVE_MUTATION = `\n mutation ResolveFieldObservationConflict($input: ResolveFieldObservationConflictInput!) {\n resolveHealthyBowlFieldObservationConflict(input: $input) { ${OBSERVATION_FIELDS} }\n }\n`;\n\nexport async function resolveConflict(ctx: Ctx, input: ResolveInput): Promise<ServerObservation> {\n const res = await graphqlFetch<{ resolveHealthyBowlFieldObservationConflict: ServerObservation }>({\n gateway: 'workspace',\n query: RESOLVE_MUTATION,\n variables: { input: { ...input, context: ctx } },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n const err = firstError(res.errors as GqlError[] | undefined);\n if (err) throw err;\n const data = res.data?.resolveHealthyBowlFieldObservationConflict;\n if (!data) throw new SyncGraphQLError('Empty resolve response', 'INTERNAL_SERVER_ERROR');\n return data;\n}\n\nexport interface FieldCaptureData {\n fields: Array<{ id: string; name: string; cropNames: string[] }>;\n recentObservations: ServerObservation[];\n stats: {\n totalObservations: number;\n observationsToday: number;\n byType: Array<{ observationType: string; count: number }>;\n };\n updatedAt: string;\n}\n\nconst CAPTURE_DATA_QUERY = `\n query FieldCaptureData($context: ContextInput!) {\n getHealthyBowlFieldCaptureData(context: $context) {\n fields { id name cropNames }\n recentObservations { ${OBSERVATION_FIELDS} }\n stats { totalObservations observationsToday byType { observationType count } }\n updatedAt\n }\n }\n`;\n\nexport async function fetchFieldCaptureData(ctx: Ctx): Promise<FieldCaptureData | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldCaptureData: FieldCaptureData }>({\n gateway: 'workspace',\n query: CAPTURE_DATA_QUERY,\n variables: { context: ctx },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldCaptureData ?? null;\n}\n\nconst DOWNLOAD_URL_QUERY = `\n query HealthyBowlObservationPhotoUrl($id: ID!) {\n getFileDownloadUrl(id: $id, expiresIn: 21600)\n }\n`;\n\n/** Presigned URL for a synced photo (6h TTL, well under the S3 7-day cap). */\nexport async function fetchPhotoUrl(id: string): Promise<string | null> {\n try {\n const res = await graphqlFetch<{ getFileDownloadUrl: string | null }>({\n gateway: 'workspace',\n query: DOWNLOAD_URL_QUERY,\n variables: { id },\n workspaceToken: true,\n workspaceId: true,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getFileDownloadUrl ?? null;\n } catch {\n return null;\n }\n}\n"],"mappings":";;AAiBA,IAAa,IAAb,cAAsC,MAAM;CAC1C;CACA,YAAY,GAAiB,GAAc;AAGzC,EAFA,MAAM,EAAQ,EACd,KAAK,OAAO,oBACZ,KAAK,OAAO;;;AAIhB,SAAS,EAAW,GAAyD;AAC3E,KAAI,CAAC,KAAU,EAAO,WAAW,EAAG,QAAO;CAC3C,IAAM,IAAI,EAAO;AACjB,QAAO,IAAI,EAAiB,EAAE,YAAY,eAAe,EAAE,SAAS,EAAE,YAAY,QAAQ,wBAAwB;;AAKpH,IAAM,IAAqB,wOA2CrB,IAAgB;;;;;;wBAME,EAAmB;0BACjB,EAAmB;;;;;AAM7C,eAAsB,EAAiB,GAAU,GAAoD;CACnG,IAAM,IAAM,MAAM,EAA+D;EAC/E,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,SAAS;GAAK;GAAc,EAAE;EAGpD,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;EAC3B,CAAC,EACI,IAAM,EAAW,EAAI,OAAiC;AAC5D,KAAI,EAAK,OAAM;CACf,IAAM,IAAO,EAAI,MAAM;AACvB,KAAI,CAAC,EAAM,OAAM,IAAI,EAAiB,uBAAuB,wBAAwB;AACrF,QAAO;;AAmBT,IAAM,IAAmB;;kEAEyC,EAAmB;;;AAIrF,eAAsB,EAAgB,GAAU,GAAiD;CAC/F,IAAM,IAAM,MAAM,EAAgF;EAChG,SAAS;EACT,OAAO;EACP,WAAW,EAAE,OAAO;GAAE,GAAG;GAAO,SAAS;GAAK,EAAE;EAChD,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;EAC3B,CAAC,EACI,IAAM,EAAW,EAAI,OAAiC;AAC5D,KAAI,EAAK,OAAM;CACf,IAAM,IAAO,EAAI,MAAM;AACvB,KAAI,CAAC,EAAM,OAAM,IAAI,EAAiB,0BAA0B,wBAAwB;AACxF,QAAO;;AAcT,IAAM,IAAqB;;;;6BAIE,EAAmB;;;;;;AAOhD,eAAsB,EAAsB,GAA4C;CACtF,IAAM,IAAM,MAAM,EAAmE;EACnF,SAAS;EACT,OAAO;EACP,WAAW,EAAE,SAAS,GAAK;EAC3B,gBAAgB;EAChB,aAAa,EAAI;EACjB,0BAA0B;EAC3B,CAAC;AAEF,QADI,EAAI,UAAU,EAAI,OAAO,SAAe,OACrC,EAAI,MAAM,kCAAkC"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import "react";
|
|
2
|
+
//#region src/healthybowl/offline/network.ts
|
|
3
|
+
var e = "burdenoff:connection-status", t = "burdenoff:networkStatusChange", n = "unknown", r = null;
|
|
4
|
+
function i() {
|
|
5
|
+
try {
|
|
6
|
+
return typeof navigator > "u" || navigator.onLine !== !1;
|
|
7
|
+
} catch {
|
|
8
|
+
return !0;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
function a() {
|
|
12
|
+
return {
|
|
13
|
+
online: i() && r !== !1,
|
|
14
|
+
connectionType: n
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
var o = /* @__PURE__ */ new Set(), s = !1;
|
|
18
|
+
function c() {
|
|
19
|
+
let e = a();
|
|
20
|
+
for (let t of o) t(e);
|
|
21
|
+
}
|
|
22
|
+
function l() {
|
|
23
|
+
s || typeof window > "u" || (s = !0, window.addEventListener("online", c), window.addEventListener("offline", c), window.addEventListener(e, (e) => {
|
|
24
|
+
let t = e.detail;
|
|
25
|
+
t && typeof t.online == "boolean" && (r = t.online), c();
|
|
26
|
+
}), window.addEventListener(t, (e) => {
|
|
27
|
+
let t = e.detail;
|
|
28
|
+
t && (typeof t.connectionType == "string" && (n = t.connectionType), t.connected === !0 && (r = r === !1 ? null : r), t.connected === !1 && (r = !1)), c();
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
function u(e) {
|
|
32
|
+
return l(), o.add(e), () => o.delete(e);
|
|
33
|
+
}
|
|
34
|
+
function d(e) {
|
|
35
|
+
return e.connectionType === "cellular" || e.connectionType === "cell";
|
|
36
|
+
}
|
|
37
|
+
function f(e) {
|
|
38
|
+
return e.connectionType === "wifi" || e.connectionType === "unknown" || e.connectionType === "ethernet";
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
export { a as getNetworkState, d as isCellular, f as isWifi, u as subscribeNetwork };
|
|
42
|
+
|
|
43
|
+
//# sourceMappingURL=network.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"network.js","names":[],"sources":["../../../src/healthybowl/offline/network.ts"],"sourcesContent":["/**\n * Connectivity detection (BOFF-2883).\n *\n * A single honest \"are we online\" signal built from every source the platform\n * already exposes — so the offline pill and the sync engine agree with reality:\n * - `navigator.onLine` + window `online`/`offline` events (browser)\n * - fe-libs `burdenoff:connection-status` (transport health: a gateway call\n * failed / recovered — catches \"connected to Wi-Fi but backend unreachable\")\n * - `burdenoff:networkStatusChange` dispatched by the app shell's\n * `@capacitor/network` listener (native connectionType: wifi/cellular/none)\n */\nimport { useEffect, useState } from 'react';\nimport type { NetworkState } from './types';\n\nconst CONNECTION_STATUS_EVENT = 'burdenoff:connection-status';\nconst NATIVE_NETWORK_EVENT = 'burdenoff:networkStatusChange';\n\nlet connectionType = 'unknown';\n/** Last transport-health signal (from fe-libs). null = unknown. */\nlet transportOnline: boolean | null = null;\n\nfunction browserOnline(): boolean {\n try {\n return typeof navigator === 'undefined' || navigator.onLine !== false;\n } catch {\n return true;\n }\n}\n\n/** Current best-effort connectivity snapshot (safe to call outside React). */\nexport function getNetworkState(): NetworkState {\n const online = browserOnline() && transportOnline !== false;\n return { online, connectionType };\n}\n\ntype Listener = (state: NetworkState) => void;\nconst listeners = new Set<Listener>();\nlet wired = false;\n\nfunction emit(): void {\n const state = getNetworkState();\n for (const l of listeners) l(state);\n}\n\nfunction wire(): void {\n if (wired || typeof window === 'undefined') return;\n wired = true;\n\n window.addEventListener('online', emit);\n window.addEventListener('offline', emit);\n\n window.addEventListener(CONNECTION_STATUS_EVENT, (e: Event) => {\n const detail = (e as CustomEvent<{ online?: boolean }>).detail;\n if (detail && typeof detail.online === 'boolean') transportOnline = detail.online;\n emit();\n });\n\n window.addEventListener(NATIVE_NETWORK_EVENT, (e: Event) => {\n const detail = (e as CustomEvent<{ connected?: boolean; connectionType?: string }>).detail;\n if (detail) {\n if (typeof detail.connectionType === 'string') connectionType = detail.connectionType;\n // Native \"connected\" is a strong signal; let it clear a stale transport-offline flag.\n if (detail.connected === true) transportOnline = transportOnline === false ? null : transportOnline;\n if (detail.connected === false) transportOnline = false;\n }\n emit();\n });\n}\n\n/** Subscribe to connectivity changes. Returns an unsubscribe fn. */\nexport function subscribeNetwork(listener: Listener): () => void {\n wire();\n listeners.add(listener);\n return () => listeners.delete(listener);\n}\n\n/** React hook: live connectivity state. */\nexport function useNetworkStatus(): NetworkState {\n const [state, setState] = useState<NetworkState>(() => getNetworkState());\n useEffect(() => {\n setState(getNetworkState());\n return subscribeNetwork(setState);\n }, []);\n return state;\n}\n\n/** True when the current connection is metered cellular (best-effort). */\nexport function isCellular(state: NetworkState): boolean {\n return state.connectionType === 'cellular' || state.connectionType === 'cell';\n}\n\n/** True when we're confident we're on Wi-Fi (for \"upload photos on Wi-Fi only\"). */\nexport function isWifi(state: NetworkState): boolean {\n // Only 'wifi' is a positive Wi-Fi signal; 'unknown' (desktop browser) counts as\n // unmetered so photo upload isn't blocked on a normal broadband connection.\n return state.connectionType === 'wifi' || state.connectionType === 'unknown' || state.connectionType === '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from "lucide-react";
|
|
2
|
+
import { jsx as o } from "react/jsx-runtime";
|
|
3
|
+
//#region src/healthybowl/offline/observationMeta.tsx
|
|
4
|
+
var s = {
|
|
5
|
+
PEST: {
|
|
6
|
+
label: "Pest Sighting",
|
|
7
|
+
short: "Pest",
|
|
8
|
+
icon: e,
|
|
9
|
+
chip: "bg-status-warning-bgSubtle text-status-warning-text"
|
|
10
|
+
},
|
|
11
|
+
CROP_HEALTH: {
|
|
12
|
+
label: "Crop Health",
|
|
13
|
+
short: "Crop",
|
|
14
|
+
icon: i,
|
|
15
|
+
chip: "bg-status-success-bgSubtle text-status-success-text"
|
|
16
|
+
},
|
|
17
|
+
SOIL: {
|
|
18
|
+
label: "Soil Note",
|
|
19
|
+
short: "Soil",
|
|
20
|
+
icon: t,
|
|
21
|
+
chip: "bg-status-info-bgSubtle text-status-info-text"
|
|
22
|
+
},
|
|
23
|
+
HARVEST: {
|
|
24
|
+
label: "Harvest Count",
|
|
25
|
+
short: "Harvest",
|
|
26
|
+
icon: a,
|
|
27
|
+
chip: "bg-status-success-bgSubtle text-status-success-text"
|
|
28
|
+
},
|
|
29
|
+
LIVESTOCK: {
|
|
30
|
+
label: "Livestock Health",
|
|
31
|
+
short: "Livestock",
|
|
32
|
+
icon: r,
|
|
33
|
+
chip: "bg-bg-sunken text-text-secondary"
|
|
34
|
+
}
|
|
35
|
+
}, c = {
|
|
36
|
+
label: "Observation",
|
|
37
|
+
short: "Note",
|
|
38
|
+
icon: n,
|
|
39
|
+
chip: "bg-bg-sunken text-text-secondary"
|
|
40
|
+
};
|
|
41
|
+
function l(e) {
|
|
42
|
+
return s[e] ?? c;
|
|
43
|
+
}
|
|
44
|
+
var u = [
|
|
45
|
+
"PEST",
|
|
46
|
+
"CROP_HEALTH",
|
|
47
|
+
"SOIL",
|
|
48
|
+
"HARVEST",
|
|
49
|
+
"LIVESTOCK"
|
|
50
|
+
], d = ({ type: e, className: t }) => {
|
|
51
|
+
let n = l(e), r = n.icon;
|
|
52
|
+
return /* @__PURE__ */ o("span", {
|
|
53
|
+
className: `flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${n.chip} ${t ?? ""}`,
|
|
54
|
+
children: /* @__PURE__ */ o(r, {
|
|
55
|
+
className: "h-4.5 w-4.5",
|
|
56
|
+
size: 18
|
|
57
|
+
})
|
|
58
|
+
});
|
|
59
|
+
};
|
|
60
|
+
function f(e) {
|
|
61
|
+
switch (e) {
|
|
62
|
+
case "QUEUED": return {
|
|
63
|
+
label: "Queued",
|
|
64
|
+
className: "text-status-warning-text",
|
|
65
|
+
dot: "bg-status-warning-text"
|
|
66
|
+
};
|
|
67
|
+
case "UPLOADING": return {
|
|
68
|
+
label: "Uploading…",
|
|
69
|
+
className: "text-status-info-text",
|
|
70
|
+
dot: "bg-status-info-text"
|
|
71
|
+
};
|
|
72
|
+
case "SYNCED": return {
|
|
73
|
+
label: "Synced",
|
|
74
|
+
className: "text-status-success-text",
|
|
75
|
+
dot: "bg-status-success-text"
|
|
76
|
+
};
|
|
77
|
+
case "CONFLICT": return {
|
|
78
|
+
label: "Conflict — review",
|
|
79
|
+
className: "text-status-error-text",
|
|
80
|
+
dot: "bg-status-error-text"
|
|
81
|
+
};
|
|
82
|
+
case "FAILED": return {
|
|
83
|
+
label: "Retrying…",
|
|
84
|
+
className: "text-status-warning-text",
|
|
85
|
+
dot: "bg-status-warning-text"
|
|
86
|
+
};
|
|
87
|
+
default: return {
|
|
88
|
+
label: e,
|
|
89
|
+
className: "text-text-secondary",
|
|
90
|
+
dot: "bg-text-secondary"
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
function p(e) {
|
|
95
|
+
let t = Date.now() - e, n = Math.round(t / 1e3);
|
|
96
|
+
if (n < 60) return "just now";
|
|
97
|
+
let r = Math.round(n / 60);
|
|
98
|
+
if (r < 60) return `${r} min ago`;
|
|
99
|
+
let i = Math.round(r / 60);
|
|
100
|
+
if (i < 24) return `${i} hr ago`;
|
|
101
|
+
let a = Math.round(i / 24);
|
|
102
|
+
return a === 1 ? "yesterday" : `${a} days ago`;
|
|
103
|
+
}
|
|
104
|
+
//#endregion
|
|
105
|
+
export { u as OBSERVATION_TYPES, d as TypeIcon, p as relativeTime, f as statusMeta, l as typeMeta };
|
|
106
|
+
|
|
107
|
+
//# sourceMappingURL=observationMeta.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"observationMeta.js","names":[],"sources":["../../../src/healthybowl/offline/observationMeta.tsx"],"sourcesContent":["/**\n * Presentation metadata for the five observation types + sync statuses (BOFF-2883).\n * Icons and semantic-token classes only — no raw colors.\n */\nimport type { FC } from 'react';\nimport { Bug, Sprout, Droplets, Wheat, PawPrint, HelpCircle, type LucideIcon } from 'lucide-react';\nimport type { ObservationType, SyncStatus } from './types';\n\ninterface TypeMeta {\n label: string;\n short: string;\n icon: LucideIcon;\n /** Tinted icon-chip classes (subtle background + accent text). */\n chip: string;\n}\n\nconst TYPE_META: Record<ObservationType, TypeMeta> = {\n PEST: {\n label: 'Pest Sighting',\n short: 'Pest',\n icon: Bug,\n chip: 'bg-status-warning-bgSubtle text-status-warning-text',\n },\n CROP_HEALTH: {\n label: 'Crop Health',\n short: 'Crop',\n icon: Sprout,\n chip: 'bg-status-success-bgSubtle text-status-success-text',\n },\n SOIL: { label: 'Soil Note', short: 'Soil', icon: Droplets, chip: 'bg-status-info-bgSubtle text-status-info-text' },\n HARVEST: {\n label: 'Harvest Count',\n short: 'Harvest',\n icon: Wheat,\n chip: 'bg-status-success-bgSubtle text-status-success-text',\n },\n LIVESTOCK: {\n label: 'Livestock Health',\n short: 'Livestock',\n icon: PawPrint,\n chip: 'bg-bg-sunken text-text-secondary',\n },\n};\n\nconst FALLBACK: TypeMeta = {\n label: 'Observation',\n short: 'Note',\n icon: HelpCircle,\n chip: 'bg-bg-sunken text-text-secondary',\n};\n\nexport function typeMeta(type: string): TypeMeta {\n return TYPE_META[type as ObservationType] ?? FALLBACK;\n}\n\nexport const OBSERVATION_TYPES: ObservationType[] = ['PEST', 'CROP_HEALTH', 'SOIL', 'HARVEST', 'LIVESTOCK'];\n\n/** A tinted, icon-badged tile for an observation type. */\nexport const TypeIcon: FC<{ type: string; className?: string }> = ({ type, className }) => {\n const meta = typeMeta(type);\n const Icon = meta.icon;\n return (\n <span className={`flex h-9 w-9 shrink-0 items-center justify-center rounded-lg ${meta.chip} ${className ?? ''}`}>\n <Icon className=\"h-4.5 w-4.5\" size={18} />\n </span>\n );\n};\n\ninterface StatusMeta {\n label: string;\n className: string;\n dot: string;\n}\n\nexport function statusMeta(status: SyncStatus): StatusMeta {\n switch (status) {\n case 'QUEUED':\n return { label: 'Queued', className: 'text-status-warning-text', dot: 'bg-status-warning-text' };\n case 'UPLOADING':\n return { label: 'Uploading…', className: 'text-status-info-text', dot: 'bg-status-info-text' };\n case 'SYNCED':\n return { label: 'Synced', className: 'text-status-success-text', dot: 'bg-status-success-text' };\n case 'CONFLICT':\n return { label: 'Conflict — review', className: 'text-status-error-text', dot: 'bg-status-error-text' };\n case 'FAILED':\n return { label: 'Retrying…', className: 'text-status-warning-text', dot: 'bg-status-warning-text' };\n default:\n return { label: status, className: 'text-text-secondary', dot: 'bg-text-secondary' };\n }\n}\n\n/** \"2 min ago\" style relative time. */\nexport function relativeTime(ms: number): string {\n const diff = Date.now() - ms;\n const s = Math.round(diff / 1000);\n if (s < 60) return 'just now';\n const m = Math.round(s / 60);\n if (m < 60) return `${m} min ago`;\n const h = Math.round(m / 60);\n if (h < 24) return `${h} hr ago`;\n const d = Math.round(h / 24);\n if (d === 1) return 'yesterday';\n return `${d} days ago`;\n}\n\nexport function formatClock(ms: number | null): string {\n if (!ms) return '—';\n try {\n return new Date(ms).toLocaleString(undefined, {\n hour: '2-digit',\n minute: '2-digit',\n month: 'short',\n day: 'numeric',\n });\n } catch {\n return '—';\n }\n}\n"],"mappings":";;;AAgBA,IAAM,IAA+C;CACnD,MAAM;EACJ,OAAO;EACP,OAAO;EACP,MA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AAI,QAAO;CACnB,IAAM,IAAI,KAAK,MAAM,IAAI,GAAG;AAC5B,KAAI,IAAI,GAAI,QAAO,GAAG,EAAE;CACxB,IAAM,IAAI,KAAK,MAAM,IAAI,GAAG;AAC5B,KAAI,IAAI,GAAI,QAAO,GAAG,EAAE;CACxB,IAAM,IAAI,KAAK,MAAM,IAAI,GAAG;AAE5B,QADI,MAAM,IAAU,cACb,GAAG,EAAE"}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { DEFAULT_SETTINGS as e } from "./types.js";
|
|
2
|
+
//#region src/healthybowl/offline/store.ts
|
|
3
|
+
var t = "healthybowl-offline", n = 1, r = "observations", i = "photos", a = "history", o = "meta", s = "settings", c = null, l = {
|
|
4
|
+
[r]: /* @__PURE__ */ new Map(),
|
|
5
|
+
[i]: /* @__PURE__ */ new Map(),
|
|
6
|
+
[a]: /* @__PURE__ */ new Map(),
|
|
7
|
+
[o]: /* @__PURE__ */ new Map()
|
|
8
|
+
};
|
|
9
|
+
function u() {
|
|
10
|
+
try {
|
|
11
|
+
return typeof indexedDB < "u" && indexedDB !== null;
|
|
12
|
+
} catch {
|
|
13
|
+
return !1;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function d() {
|
|
17
|
+
return c || (c = new Promise((e, s) => {
|
|
18
|
+
let c = indexedDB.open(t, n);
|
|
19
|
+
c.onupgradeneeded = () => {
|
|
20
|
+
let e = c.result;
|
|
21
|
+
e.objectStoreNames.contains(r) || e.createObjectStore(r, { keyPath: "clientId" }), e.objectStoreNames.contains(i) || e.createObjectStore(i, { keyPath: "id" }), e.objectStoreNames.contains(a) || e.createObjectStore(a, { keyPath: "id" }), e.objectStoreNames.contains(o) || e.createObjectStore(o);
|
|
22
|
+
}, c.onsuccess = () => e(c.result), c.onerror = () => s(c.error);
|
|
23
|
+
}), c);
|
|
24
|
+
}
|
|
25
|
+
function f(e, t, n) {
|
|
26
|
+
return d().then((r) => new Promise((i, a) => {
|
|
27
|
+
let o = n(r.transaction(e, t).objectStore(e));
|
|
28
|
+
o.onsuccess = () => i(o.result), o.onerror = () => a(o.error);
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
async function p(e, t, n) {
|
|
32
|
+
if (!u()) {
|
|
33
|
+
let r = n ?? t.clientId ?? t.id;
|
|
34
|
+
l[e].set(String(r), t);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
await f(e, "readwrite", (e) => n === void 0 ? e.put(t) : e.put(t, n));
|
|
38
|
+
}
|
|
39
|
+
async function m(e, t) {
|
|
40
|
+
return u() ? f(e, "readonly", (e) => e.get(t)) : l[e].get(String(t));
|
|
41
|
+
}
|
|
42
|
+
async function h(e) {
|
|
43
|
+
return u() ? f(e, "readonly", (e) => e.getAll()) : Array.from(l[e].values());
|
|
44
|
+
}
|
|
45
|
+
async function g(e, t) {
|
|
46
|
+
if (!u()) {
|
|
47
|
+
l[e].delete(String(t));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
await f(e, "readwrite", (e) => e.delete(t));
|
|
51
|
+
}
|
|
52
|
+
async function _(e) {
|
|
53
|
+
await p(r, e);
|
|
54
|
+
}
|
|
55
|
+
async function v(e) {
|
|
56
|
+
return m(r, e);
|
|
57
|
+
}
|
|
58
|
+
async function y() {
|
|
59
|
+
return (await h(r)).sort((e, t) => t.createdAt - e.createdAt);
|
|
60
|
+
}
|
|
61
|
+
async function b(e) {
|
|
62
|
+
let t = await v(e);
|
|
63
|
+
if (t) for (let e of t.photoLocalIds) await w(e);
|
|
64
|
+
await g(r, e);
|
|
65
|
+
}
|
|
66
|
+
async function x(e) {
|
|
67
|
+
await p(i, e);
|
|
68
|
+
}
|
|
69
|
+
async function S(e) {
|
|
70
|
+
return m(i, e);
|
|
71
|
+
}
|
|
72
|
+
async function C(e) {
|
|
73
|
+
return (await h(i)).filter((t) => t.clientId === e).sort((e, t) => e.createdAt - t.createdAt);
|
|
74
|
+
}
|
|
75
|
+
async function w(e) {
|
|
76
|
+
await g(i, e);
|
|
77
|
+
}
|
|
78
|
+
async function T() {
|
|
79
|
+
let [e, t] = await Promise.all([y(), h(i)]);
|
|
80
|
+
return {
|
|
81
|
+
bytes: t.reduce((e, t) => e + (t.blob?.size ?? 0), 0),
|
|
82
|
+
queued: e.filter((e) => e.status === "QUEUED" || e.status === "UPLOADING" || e.status === "FAILED").length,
|
|
83
|
+
photos: t.length
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function E() {
|
|
87
|
+
let e = await y(), t = new Set(e.filter((e) => e.status === "SYNCED").map((e) => e.clientId)), n = await h(i);
|
|
88
|
+
for (let e of n) e.fileId && t.has(e.clientId) && await w(e.id);
|
|
89
|
+
}
|
|
90
|
+
async function D(e) {
|
|
91
|
+
await p(a, e);
|
|
92
|
+
let t = await h(a);
|
|
93
|
+
if (t.length > 200) {
|
|
94
|
+
let e = t.sort((e, t) => e.at - t.at).slice(0, t.length - 200);
|
|
95
|
+
for (let t of e) await g(a, t.id);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function O() {
|
|
99
|
+
return (await h(a)).sort((e, t) => t.at - e.at);
|
|
100
|
+
}
|
|
101
|
+
async function k() {
|
|
102
|
+
let t = await m(o, s);
|
|
103
|
+
return {
|
|
104
|
+
...e,
|
|
105
|
+
...t ?? {}
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
async function A(e) {
|
|
109
|
+
await p(o, e, s);
|
|
110
|
+
}
|
|
111
|
+
async function j(e) {
|
|
112
|
+
return m(o, e);
|
|
113
|
+
}
|
|
114
|
+
async function M(e, t) {
|
|
115
|
+
await p(o, t, e);
|
|
116
|
+
}
|
|
117
|
+
//#endregion
|
|
118
|
+
export { D as addHistoryEntry, E as clearSyncedPhotoBlobs, b as deleteObservation, T as estimateLocalUsage, y as getAllObservations, O as getHistory, j as getMeta, S as getPhoto, C as getPhotosFor, k as loadSettings, _ as saveObservation, x as savePhoto, A as saveSettings, M as setMeta };
|
|
119
|
+
|
|
120
|
+
//# sourceMappingURL=store.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"store.js","names":[],"sources":["../../../src/healthybowl/offline/store.ts"],"sourcesContent":["/**\n * Durable offline store (BOFF-2883).\n *\n * A small, dependency-free IndexedDB wrapper holding the outbox of captured\n * observations, their photo blobs, the device-local sync history, and user\n * settings. IndexedDB (not localStorage) is used so photo blobs and a large\n * queue survive an app restart and never block the main thread.\n *\n * Everything degrades gracefully: if IndexedDB is unavailable (private mode,\n * SSR), the helpers fall back to an in-memory map so the UI still functions for\n * the session.\n */\nimport type { LocalObservation, LocalPhoto, SyncHistoryEntry, OfflineSettings } from './types';\nimport { DEFAULT_SETTINGS } from './types';\n\nconst DB_NAME = 'healthybowl-offline';\nconst DB_VERSION = 1;\nconst STORE_OBS = 'observations';\nconst STORE_PHOTOS = 'photos';\nconst STORE_HISTORY = 'history';\nconst STORE_META = 'meta';\nconst SETTINGS_KEY = 'settings';\n\ntype StoreName = typeof STORE_OBS | typeof STORE_PHOTOS | typeof STORE_HISTORY | typeof STORE_META;\n\nlet dbPromise: Promise<IDBDatabase> | null = null;\n\n/** In-memory fallback when IndexedDB is unavailable. */\nconst memory = {\n [STORE_OBS]: new Map<string, unknown>(),\n [STORE_PHOTOS]: new Map<string, unknown>(),\n [STORE_HISTORY]: new Map<string, unknown>(),\n [STORE_META]: new Map<string, unknown>(),\n} as Record<StoreName, Map<string, unknown>>;\n\nfunction idbAvailable(): boolean {\n try {\n return typeof indexedDB !== 'undefined' && indexedDB !== null;\n } catch {\n return false;\n }\n}\n\nfunction openDb(): Promise<IDBDatabase> {\n if (dbPromise) return dbPromise;\n dbPromise = new Promise<IDBDatabase>((resolve, reject) => {\n const req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onupgradeneeded = () => {\n const db = req.result;\n if (!db.objectStoreNames.contains(STORE_OBS)) db.createObjectStore(STORE_OBS, { keyPath: 'clientId' });\n if (!db.objectStoreNames.contains(STORE_PHOTOS)) db.createObjectStore(STORE_PHOTOS, { keyPath: 'id' });\n if (!db.objectStoreNames.contains(STORE_HISTORY)) db.createObjectStore(STORE_HISTORY, { keyPath: 'id' });\n if (!db.objectStoreNames.contains(STORE_META)) db.createObjectStore(STORE_META);\n };\n req.onsuccess = () => resolve(req.result);\n req.onerror = () => reject(req.error);\n });\n return dbPromise;\n}\n\nfunction tx<T>(store: StoreName, mode: IDBTransactionMode, fn: (s: IDBObjectStore) => IDBRequest): Promise<T> {\n return openDb().then(\n (db) =>\n new Promise<T>((resolve, reject) => {\n const transaction = db.transaction(store, mode);\n const request = fn(transaction.objectStore(store));\n request.onsuccess = () => resolve(request.result as T);\n request.onerror = () => reject(request.error);\n })\n );\n}\n\nasync function put(store: StoreName, value: unknown, key?: IDBValidKey): Promise<void> {\n if (!idbAvailable()) {\n const k = key ?? (value as { clientId?: string; id?: string }).clientId ?? (value as { id?: string }).id;\n memory[store].set(String(k), value);\n return;\n }\n await tx<IDBValidKey>(store, 'readwrite', (s) => (key !== undefined ? s.put(value, key) : s.put(value)));\n}\n\nasync function get<T>(store: StoreName, key: IDBValidKey): Promise<T | undefined> {\n if (!idbAvailable()) return memory[store].get(String(key)) as T | undefined;\n return tx<T | undefined>(store, 'readonly', (s) => s.get(key));\n}\n\nasync function getAll<T>(store: StoreName): Promise<T[]> {\n if (!idbAvailable()) return Array.from(memory[store].values()) as T[];\n return tx<T[]>(store, 'readonly', (s) => s.getAll());\n}\n\nasync function del(store: StoreName, key: IDBValidKey): Promise<void> {\n if (!idbAvailable()) {\n memory[store].delete(String(key));\n return;\n }\n await tx(store, 'readwrite', (s) => s.delete(key));\n}\n\n// ── Observations (the outbox) ────────────────────────────────────────────────\n\nexport async function saveObservation(obs: LocalObservation): Promise<void> {\n await put(STORE_OBS, obs);\n}\n\nexport async function getObservation(clientId: string): Promise<LocalObservation | undefined> {\n return get<LocalObservation>(STORE_OBS, clientId);\n}\n\nexport async function getAllObservations(): Promise<LocalObservation[]> {\n const all = await getAll<LocalObservation>(STORE_OBS);\n return all.sort((a, b) => b.createdAt - a.createdAt);\n}\n\nexport async function deleteObservation(clientId: string): Promise<void> {\n const obs = await getObservation(clientId);\n if (obs) {\n for (const pid of obs.photoLocalIds) await deletePhoto(pid);\n }\n await del(STORE_OBS, clientId);\n}\n\n// ── Photos ───────────────────────────────────────────────────────────────────\n\nexport async function savePhoto(photo: LocalPhoto): Promise<void> {\n await put(STORE_PHOTOS, photo);\n}\n\nexport async function getPhoto(id: string): Promise<LocalPhoto | undefined> {\n return get<LocalPhoto>(STORE_PHOTOS, id);\n}\n\nexport async function getPhotosFor(clientId: string): Promise<LocalPhoto[]> {\n const all = await getAll<LocalPhoto>(STORE_PHOTOS);\n return all.filter((p) => p.clientId === clientId).sort((a, b) => a.createdAt - b.createdAt);\n}\n\nexport async function deletePhoto(id: string): Promise<void> {\n await del(STORE_PHOTOS, id);\n}\n\n/** Approximate local storage footprint (bytes) — for the settings \"Local Storage\" meter. */\nexport async function estimateLocalUsage(): Promise<{ bytes: number; queued: number; photos: number }> {\n const [obs, photos] = await Promise.all([getAllObservations(), getAll<LocalPhoto>(STORE_PHOTOS)]);\n const bytes = photos.reduce((sum, p) => sum + (p.blob?.size ?? 0), 0);\n const queued = obs.filter((o) => o.status === 'QUEUED' || o.status === 'UPLOADING' || o.status === 'FAILED').length;\n return { bytes, queued, photos: photos.length };\n}\n\n/** Drop already-synced photo blobs to reclaim space (keeps the fileId reference on the record). */\nexport async function clearSyncedPhotoBlobs(): Promise<void> {\n const obs = await getAllObservations();\n const syncedClientIds = new Set(obs.filter((o) => o.status === 'SYNCED').map((o) => o.clientId));\n const photos = await getAll<LocalPhoto>(STORE_PHOTOS);\n for (const p of photos) {\n if (p.fileId && syncedClientIds.has(p.clientId)) await deletePhoto(p.id);\n }\n}\n\n// ── Sync history ──────────────────────────────────────────────────────────────\n\nexport async function addHistoryEntry(entry: SyncHistoryEntry): Promise<void> {\n await put(STORE_HISTORY, entry);\n // Cap the timeline at 200 entries.\n const all = await getAll<SyncHistoryEntry>(STORE_HISTORY);\n if (all.length > 200) {\n const oldest = all.sort((a, b) => a.at - b.at).slice(0, all.length - 200);\n for (const e of oldest) await del(STORE_HISTORY, e.id);\n }\n}\n\nexport async function getHistory(): Promise<SyncHistoryEntry[]> {\n const all = await getAll<SyncHistoryEntry>(STORE_HISTORY);\n return all.sort((a, b) => b.at - a.at);\n}\n\n// ── Settings + meta ───────────────────────────────────────────────────────────\n\nexport async function loadSettings(): Promise<OfflineSettings> {\n const stored = await get<OfflineSettings>(STORE_META, SETTINGS_KEY);\n return { ...DEFAULT_SETTINGS, ...(stored ?? {}) };\n}\n\nexport async function saveSettings(settings: OfflineSettings): Promise<void> {\n await put(STORE_META, settings, SETTINGS_KEY);\n}\n\nexport async function getMeta<T>(key: string): Promise<T | undefined> {\n return get<T>(STORE_META, key);\n}\n\nexport async function setMeta(key: string, value: unknown): Promise<void> {\n await put(STORE_META, value, key);\n}\n"],"mappings":";;AAeA,IAAM,IAAU,uBACV,IAAa,GACb,IAAY,gBACZ,IAAe,UACf,IAAgB,WAChB,IAAa,QACb,IAAe,YAIjB,IAAyC,MAGvC,IAAS;EACZ,oBAAY,IAAI,KAAsB;EACtC,oBAAe,IAAI,KAAsB;EACzC,oBAAgB,IAAI,KAAsB;EAC1C,oBAAa,IAAI,KAAsB;CACzC;AAED,SAAS,IAAwB;AAC/B,KAAI;AACF,SAAO,OAAO,YAAc,OAAe,cAAc;SACnD;AACN,SAAO;;;AAIX,SAAS,IAA+B;AActC,QAbI,MACJ,IAAY,IAAI,SAAsB,GAAS,MAAW;EACxD,IAAM,IAAM,UAAU,KAAK,GAAS,EAAW;AAS/C,EARA,EAAI,wBAAwB;GAC1B,IAAM,IAAK,EAAI;AAIf,GAHK,EAAG,iBAAiB,SAAS,EAAU,IAAE,EAAG,kBAAkB,GAAW,EAAE,SAAS,YAAY,CAAC,EACjG,EAAG,iBAAiB,SAAS,EAAa,IAAE,EAAG,kBAAkB,GAAc,EA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AC,EAC1F,IAAS,MAAM,EAAmB,EAAa;AACrD,MAAK,IAAM,KAAK,EACd,CAAI,EAAE,UAAU,EAAgB,IAAI,EAAE,SAAS,IAAE,MAAM,EAAY,EAAE,GAAG;;AAM5E,eAAsB,EAAgB,GAAwC;AAC5E,OAAM,EAAI,GAAe,EAAM;CAE/B,IAAM,IAAM,MAAM,EAAyB,EAAc;AACzD,KAAI,EAAI,SAAS,KAAK;EACpB,IAAM,IAAS,EAAI,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,GAAG,CAAC,MAAM,GAAG,EAAI,SAAS,IAAI;AACzE,OAAK,IAAM,KAAK,EAAQ,OAAM,EAAI,GAAe,EAAE,GAAG;;;AAI1D,eAAsB,IAA0C;AAE9D,SADY,MAAM,EAAyB,EAAc,EAC9C,MAAM,GAAG,MAAM,EAAE,KAAK,EAAE,GAAG;;AAKxC,eAAsB,IAAyC;CAC7D,IAAM,IAAS,MAAM,EAAqB,GAAY,EAAa;AACnE,QAAO;EAAE,GAAG;EAAkB,GAAI,KAAU,EAAE;EAAG;;AAGnD,eAAsB,EAAa,GAA0C;AAC3E,OAAM,EAAI,GAAY,GAAU,EAAa;;AAG/C,eAAsB,EAAW,GAAqC;AACpE,QAAO,EAAO,GAAY,EAAI;;AAGhC,eAAsB,EAAQ,GAAa,GAA+B;AACxE,OAAM,EAAI,GAAY,GAAO,EAAI"}
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { addHistoryEntry as e, getAllObservations as t, getPhoto as n, saveObservation as r, savePhoto as i } from "./store.js";
|
|
2
|
+
import { isWifi as a } from "./network.js";
|
|
3
|
+
import { syncObservations as o } from "./graphql.js";
|
|
4
|
+
//#region src/healthybowl/offline/syncEngine.ts
|
|
5
|
+
var s = "/HealthyBowl/FieldObservation", c = 8;
|
|
6
|
+
function l() {
|
|
7
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
8
|
+
}
|
|
9
|
+
function u(e) {
|
|
10
|
+
return `${e}-${typeof crypto < "u" && crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.round(Math.random() * 1e9)}`}`;
|
|
11
|
+
}
|
|
12
|
+
function d(e) {
|
|
13
|
+
return (e.status === "QUEUED" || e.status === "FAILED") && e.attempts < c;
|
|
14
|
+
}
|
|
15
|
+
async function f(e, t) {
|
|
16
|
+
let r = [];
|
|
17
|
+
for (let t of e.photoLocalIds) {
|
|
18
|
+
let e = await n(t);
|
|
19
|
+
e && r.push(e);
|
|
20
|
+
}
|
|
21
|
+
if (r.some((e) => !e.fileId) && t.settings.uploadPhotosOnWifiOnly && !a(t.network)) return null;
|
|
22
|
+
let o = 0, c = [];
|
|
23
|
+
for (let e of r) {
|
|
24
|
+
if (e.fileId) {
|
|
25
|
+
c.push(e.fileId);
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
let n = await t.saveToFiles({
|
|
29
|
+
source: {
|
|
30
|
+
kind: "blob",
|
|
31
|
+
filename: e.filename,
|
|
32
|
+
mimeType: e.mimeType,
|
|
33
|
+
getBlob: async () => ({
|
|
34
|
+
blob: e.blob,
|
|
35
|
+
filename: e.filename,
|
|
36
|
+
mimeType: e.mimeType
|
|
37
|
+
})
|
|
38
|
+
},
|
|
39
|
+
folderPath: s
|
|
40
|
+
});
|
|
41
|
+
e.fileId = n.id, await i(e), c.push(n.id), o += 1;
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
fileIds: c,
|
|
45
|
+
uploaded: o
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
function p(e, t) {
|
|
49
|
+
return {
|
|
50
|
+
clientId: e.clientId,
|
|
51
|
+
observationType: e.observationType,
|
|
52
|
+
fieldId: e.fieldId ?? null,
|
|
53
|
+
fieldName: e.fieldName ?? null,
|
|
54
|
+
title: e.title ?? null,
|
|
55
|
+
note: e.note ?? null,
|
|
56
|
+
severity: e.severity ?? null,
|
|
57
|
+
quantity: e.quantity ?? null,
|
|
58
|
+
unit: e.unit ?? null,
|
|
59
|
+
cropName: e.cropName ?? null,
|
|
60
|
+
animalTag: e.animalTag ?? null,
|
|
61
|
+
latitude: e.latitude ?? null,
|
|
62
|
+
longitude: e.longitude ?? null,
|
|
63
|
+
gpsAccuracy: e.gpsAccuracy ?? null,
|
|
64
|
+
photoFileIds: t,
|
|
65
|
+
capturedAt: e.capturedAt,
|
|
66
|
+
capturedOffline: e.capturedOffline,
|
|
67
|
+
baseVersion: e.baseVersion
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
async function m(e, t) {
|
|
71
|
+
let n = l();
|
|
72
|
+
t ? t.outcome === "SYNCED" || t.outcome === "DUPLICATE" ? (e.status = "SYNCED", e.serverId = t.observation?.id ?? e.serverId ?? null, e.baseVersion = t.observation?.version ?? e.baseVersion, e.syncedAt = t.observation?.syncedAt ?? n, e.serverVersion = null, e.message = null) : t.outcome === "CONFLICT" ? (e.status = "CONFLICT", e.serverVersion = t.serverVersion ?? t.observation ?? null, e.message = t.message ?? "Record changed since capture — review") : (e.status = "FAILED", e.message = t.message ?? "Sync failed", e.attempts += 1) : (e.status = "FAILED", e.message = "No result returned for this record", e.attempts += 1), e.updatedAt = Date.now(), await r(e);
|
|
73
|
+
}
|
|
74
|
+
async function h(e) {
|
|
75
|
+
let n = {
|
|
76
|
+
attempted: 0,
|
|
77
|
+
synced: 0,
|
|
78
|
+
duplicate: 0,
|
|
79
|
+
conflict: 0,
|
|
80
|
+
failed: 0,
|
|
81
|
+
skipped: 0,
|
|
82
|
+
photosUploaded: 0
|
|
83
|
+
};
|
|
84
|
+
if (!e.network.online || !e.workspaceId) return n;
|
|
85
|
+
let i = await t();
|
|
86
|
+
for (let e of i) e.status === "UPLOADING" && (e.status = "QUEUED", e.updatedAt = Date.now(), await r(e));
|
|
87
|
+
let a = (await t()).filter(d);
|
|
88
|
+
if (a.length === 0) return n;
|
|
89
|
+
let s = [];
|
|
90
|
+
for (let t of a) {
|
|
91
|
+
let i;
|
|
92
|
+
try {
|
|
93
|
+
i = await f(t, e);
|
|
94
|
+
} catch (e) {
|
|
95
|
+
t.attempts += 1, t.status = t.attempts >= c ? "FAILED" : "QUEUED", t.message = e instanceof Error ? e.message : "Photo upload failed", t.updatedAt = Date.now(), await r(t), n.failed += 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
if (!i) {
|
|
99
|
+
n.skipped += 1;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
n.photosUploaded += i.uploaded, t.photoFileIds = i.fileIds, t.status = "UPLOADING", t.updatedAt = Date.now(), await r(t), s.push({
|
|
103
|
+
obs: t,
|
|
104
|
+
input: p(t, i.fileIds)
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
if (s.length === 0) return n;
|
|
108
|
+
n.attempted = s.length;
|
|
109
|
+
try {
|
|
110
|
+
let t = await o({ workspaceId: e.workspaceId }, s.map((e) => e.input)), r = new Map(t.items.map((e) => [e.clientId, e]));
|
|
111
|
+
for (let { obs: e } of s) {
|
|
112
|
+
let t = r.get(e.clientId);
|
|
113
|
+
await m(e, t), t?.outcome === "SYNCED" ? n.synced += 1 : t?.outcome === "DUPLICATE" ? n.duplicate += 1 : t?.outcome === "CONFLICT" ? n.conflict += 1 : n.failed += 1;
|
|
114
|
+
}
|
|
115
|
+
await g(e, n, "complete");
|
|
116
|
+
} catch (t) {
|
|
117
|
+
let i = t instanceof Error ? t.message : "Sync failed";
|
|
118
|
+
for (let { obs: e } of s) e.attempts += 1, e.status = e.attempts >= c ? "FAILED" : "QUEUED", e.message = i, e.updatedAt = Date.now(), await r(e), n.failed += 1;
|
|
119
|
+
await g(e, n, "failed", i);
|
|
120
|
+
}
|
|
121
|
+
return n;
|
|
122
|
+
}
|
|
123
|
+
async function g(n, r, i, a) {
|
|
124
|
+
let o = (await t()).filter((e) => e.updatedAt >= Date.now() - 5e3), s = Array.from(new Set(o.map((e) => e.observationType)));
|
|
125
|
+
await e({
|
|
126
|
+
id: u("hist"),
|
|
127
|
+
at: Date.now(),
|
|
128
|
+
kind: i === "failed" ? "SYNC_FAILED" : r.conflict > 0 ? "CONFLICT" : "SYNC_COMPLETE",
|
|
129
|
+
syncedCount: r.synced + r.duplicate,
|
|
130
|
+
duplicateCount: r.duplicate,
|
|
131
|
+
conflictCount: r.conflict,
|
|
132
|
+
failedCount: r.failed,
|
|
133
|
+
photoCount: r.photosUploaded,
|
|
134
|
+
message: i === "failed" ? `Sync failed${a ? ` — ${a}` : ""} · ${r.failed} record(s) still queued` : `${r.synced + r.duplicate} record(s) synced` + (r.photosUploaded ? `, ${r.photosUploaded} photo(s) uploaded` : "") + (r.conflict ? `, ${r.conflict} conflict(s)` : ""),
|
|
135
|
+
types: s
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
//#endregion
|
|
139
|
+
export { h as drainQueue };
|
|
140
|
+
|
|
141
|
+
//# sourceMappingURL=syncEngine.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"syncEngine.js","names":[],"sources":["../../../src/healthybowl/offline/syncEngine.ts"],"sourcesContent":["/**\n * Sync engine (BOFF-2883).\n *\n * Drains the local outbox when connectivity returns: uploads any offline-captured\n * photo blobs to files-svc, then replays the queued observations through the\n * idempotent `syncHealthyBowlFieldObservations` mutation and reconciles each\n * record's local status from the per-item outcome (Synced / Conflict / Failed).\n *\n * The engine is dependency-injected (workspace id, the fe-libs file-upload\n * function, current settings + network state) so it stays pure and testable and\n * can be driven from the OfflineSyncProvider.\n */\nimport type { LocalObservation, LocalPhoto, OfflineSettings, NetworkState, SyncHistoryEntry } from './types';\nimport { getAllObservations, saveObservation, getPhoto, savePhoto, addHistoryEntry } from './store';\nimport { syncObservations, type SyncInputItem, type SyncResultItem } from './graphql';\nimport { isWifi } from './network';\n\n/** fe-libs `useSaveToFiles().save` shape — uploads a blob, returns its files-svc id. */\nexport type SaveToFiles = (args: {\n source: {\n kind: 'blob';\n filename: string;\n mimeType: string;\n getBlob: () => Promise<{ blob: Blob; filename: string; mimeType: string }>;\n };\n folderPath: string;\n}) => Promise<{ id: string }>;\n\nexport interface SyncDeps {\n workspaceId: string;\n saveToFiles: SaveToFiles;\n settings: OfflineSettings;\n network: NetworkState;\n}\n\nexport interface DrainSummary {\n attempted: number;\n synced: number;\n duplicate: number;\n conflict: number;\n failed: number;\n skipped: number;\n photosUploaded: number;\n}\n\nconst PHOTO_FOLDER = '/HealthyBowl/FieldObservation';\nconst MAX_ATTEMPTS = 8;\n\nfunction now(): string {\n return new Date().toISOString();\n}\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\n/** Records eligible to sync now (queued or previously-failed, under the retry cap). */\nfunction isSyncable(o: LocalObservation): boolean {\n return (o.status === 'QUEUED' || o.status === 'FAILED') && o.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Upload any not-yet-uploaded photo blobs for a record and return the resolved\n * files-svc ids. Honors the \"upload photos on Wi-Fi only\" setting by signalling\n * a defer (returns null) when the record still has local blobs and we're metered.\n */\nasync function resolvePhotoFileIds(\n obs: LocalObservation,\n deps: SyncDeps\n): Promise<{ fileIds: string[]; uploaded: number } | null> {\n // Rebuild the fileId list from the AUTHORITATIVE per-photo records (in capture\n // order), not from the possibly-stale obs.photoFileIds snapshot. A prior partial\n // upload persists each photo's fileId on its own record, so already-uploaded\n // photos are never dropped on retry.\n const photos: LocalPhoto[] = [];\n for (const pid of obs.photoLocalIds) {\n const p = await getPhoto(pid);\n if (p) photos.push(p);\n }\n const needsUpload = photos.some((p) => !p.fileId);\n\n // Metered connection + Wi-Fi-only preference → defer the whole record so its\n // photos and observation reach the server together on Wi-Fi.\n if (needsUpload && deps.settings.uploadPhotosOnWifiOnly && !isWifi(deps.network)) {\n return null;\n }\n\n let uploaded = 0;\n const fileIds: string[] = [];\n for (const photo of photos) {\n if (photo.fileId) {\n fileIds.push(photo.fileId);\n continue;\n }\n const saved = await deps.saveToFiles({\n source: {\n kind: 'blob',\n filename: photo.filename,\n mimeType: photo.mimeType,\n getBlob: async () => ({ blob: photo.blob, filename: photo.filename, mimeType: photo.mimeType }),\n },\n folderPath: PHOTO_FOLDER,\n });\n // Persist the fileId immediately so a later failure in this loop never re-uploads\n // this photo or loses its id.\n photo.fileId = saved.id;\n await savePhoto(photo);\n fileIds.push(saved.id);\n uploaded += 1;\n }\n return { fileIds, uploaded };\n}\n\nfunction toSyncInput(obs: LocalObservation, photoFileIds: string[]): SyncInputItem {\n return {\n clientId: obs.clientId,\n observationType: obs.observationType,\n fieldId: obs.fieldId ?? null,\n fieldName: obs.fieldName ?? null,\n title: obs.title ?? null,\n note: obs.note ?? null,\n severity: obs.severity ?? null,\n quantity: obs.quantity ?? null,\n unit: obs.unit ?? null,\n cropName: obs.cropName ?? null,\n animalTag: obs.animalTag ?? null,\n latitude: obs.latitude ?? null,\n longitude: obs.longitude ?? null,\n gpsAccuracy: obs.gpsAccuracy ?? null,\n photoFileIds,\n capturedAt: obs.capturedAt,\n capturedOffline: obs.capturedOffline,\n baseVersion: obs.baseVersion,\n };\n}\n\nasync function applyOutcome(obs: LocalObservation, item: SyncResultItem | undefined): Promise<void> {\n const ts = now();\n if (!item) {\n obs.status = 'FAILED';\n obs.message = 'No result returned for this record';\n obs.attempts += 1;\n } else if (item.outcome === 'SYNCED' || item.outcome === 'DUPLICATE') {\n obs.status = 'SYNCED';\n obs.serverId = item.observation?.id ?? obs.serverId ?? null;\n obs.baseVersion = item.observation?.version ?? obs.baseVersion;\n obs.syncedAt = item.observation?.syncedAt ?? ts;\n obs.serverVersion = null;\n obs.message = null;\n } else if (item.outcome === 'CONFLICT') {\n obs.status = 'CONFLICT';\n obs.serverVersion = item.serverVersion ?? item.observation ?? null;\n obs.message = item.message ?? 'Record changed since capture — review';\n } else {\n obs.status = 'FAILED';\n obs.message = item.message ?? 'Sync failed';\n obs.attempts += 1;\n }\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n}\n\n/**\n * Drain the outbox once. Safe to call repeatedly (idempotent server-side via\n * clientId). Returns a summary; also appends a device-local history entry.\n */\nexport async function drainQueue(deps: SyncDeps): Promise<DrainSummary> {\n const summary: DrainSummary = {\n attempted: 0,\n synced: 0,\n duplicate: 0,\n conflict: 0,\n failed: 0,\n skipped: 0,\n photosUploaded: 0,\n };\n if (!deps.network.online || !deps.workspaceId) return summary;\n\n // Recover any records stranded in UPLOADING by a previous drain that was\n // interrupted (tab closed / crashed mid-sync). Re-queue them — the server sync is\n // idempotent (clientId), so a record that actually did reach the server just comes\n // back as DUPLICATE. Without this, an interrupted upload would strand forever.\n const stranded = await getAllObservations();\n for (const obs of stranded) {\n if (obs.status === 'UPLOADING') {\n obs.status = 'QUEUED';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n }\n }\n\n const all = await getAllObservations();\n const pending = all.filter(isSyncable);\n if (pending.length === 0) return summary;\n\n const batch: Array<{ obs: LocalObservation; input: SyncInputItem }> = [];\n for (const obs of pending) {\n let resolved: { fileIds: string[]; uploaded: number } | null;\n try {\n resolved = await resolvePhotoFileIds(obs, deps);\n } catch (err) {\n // A photo upload failed — mark THIS record failed (re-queueable) and keep\n // draining the rest of the outbox rather than aborting the whole batch.\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n obs.message = err instanceof Error ? err.message : 'Photo upload failed';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n continue;\n }\n if (!resolved) {\n summary.skipped += 1;\n continue; // deferred (Wi-Fi-only photos on a metered link)\n }\n summary.photosUploaded += resolved.uploaded;\n // Persist resolved fileIds even if the network sync later fails.\n obs.photoFileIds = resolved.fileIds;\n obs.status = 'UPLOADING';\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n batch.push({ obs, input: toSyncInput(obs, resolved.fileIds) });\n }\n\n if (batch.length === 0) return summary;\n summary.attempted = batch.length;\n\n try {\n const result = await syncObservations(\n { workspaceId: deps.workspaceId },\n batch.map((b) => b.input)\n );\n const byClientId = new Map(result.items.map((i) => [i.clientId, i]));\n for (const { obs } of batch) {\n const item = byClientId.get(obs.clientId);\n await applyOutcome(obs, item);\n if (item?.outcome === 'SYNCED') summary.synced += 1;\n else if (item?.outcome === 'DUPLICATE') summary.duplicate += 1;\n else if (item?.outcome === 'CONFLICT') summary.conflict += 1;\n else summary.failed += 1;\n }\n await recordHistory(deps, summary, 'complete');\n } catch (err) {\n // Transport / gateway failure — put everything back to QUEUED (or keep FAILED\n // after enough retries) so a later reconnect retries. Never lose a capture.\n const message = err instanceof Error ? err.message : 'Sync failed';\n for (const { obs } of batch) {\n obs.attempts += 1;\n obs.status = obs.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n obs.message = message;\n obs.updatedAt = Date.now();\n await saveObservation(obs);\n summary.failed += 1;\n }\n await recordHistory(deps, summary, 'failed', message);\n }\n\n return summary;\n}\n\nasync function recordHistory(\n deps: SyncDeps,\n summary: DrainSummary,\n mode: 'complete' | 'failed',\n message?: string\n): Promise<void> {\n const all = await getAllObservations();\n const touched = all.filter((o) => o.updatedAt >= Date.now() - 5000);\n const types = Array.from(new Set(touched.map((o) => o.observationType)));\n const entry: SyncHistoryEntry = {\n id: uid('hist'),\n at: Date.now(),\n kind: mode === 'failed' ? 'SYNC_FAILED' : summary.conflict > 0 ? 'CONFLICT' : 'SYNC_COMPLETE',\n syncedCount: summary.synced + summary.duplicate,\n duplicateCount: summary.duplicate,\n conflictCount: summary.conflict,\n failedCount: summary.failed,\n photoCount: summary.photosUploaded,\n message:\n mode === 'failed'\n ? `Sync failed${message ? ` — ${message}` : ''} · ${summary.failed} record(s) still queued`\n : `${summary.synced + summary.duplicate} record(s) synced` +\n (summary.photosUploaded ? `, ${summary.photosUploaded} photo(s) uploaded` : '') +\n (summary.conflict ? `, ${summary.conflict} conflict(s)` : ''),\n types,\n };\n await addHistoryEntry(entry);\n}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uality: "compressed",
|
|
8
|
+
autoStampGps: !0,
|
|
9
|
+
highAccuracyGps: !1,
|
|
10
|
+
conflictHandling: "review"
|
|
11
|
+
};
|
|
12
|
+
//#endregion
|
|
13
|
+
export { e as DEFAULT_SETTINGS };
|
|
14
|
+
|
|
15
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../src/healthybowl/offline/types.ts"],"sourcesContent":["/**\n * Offline field data capture & sync (BOFF-2883) — shared types.\n *\n * The device is the source of truth until a write reaches the server: every\n * capture is written to IndexedDB first, sits in a durable outbox, and is\n * replayed idempotently when connectivity returns.\n */\n\n/** The five field-observation types a farmer can capture. */\nexport type ObservationType = 'PEST' | 'CROP_HEALTH' | 'SOIL' | 'HARVEST' | 'LIVESTOCK';\n\n/** Per-record lifecycle in the local outbox. */\nexport type SyncStatus = 'QUEUED' | 'UPLOADING' | 'SYNCED' | 'CONFLICT' | 'FAILED';\n\n/** A photo captured offline, blob held locally until it uploads to files-svc. */\nexport interface LocalPhoto {\n /** Local id (also the IndexedDB key). */\n id: string;\n /** The observation this photo belongs to. */\n clientId: string;\n blob: Blob;\n filename: string;\n mimeType: string;\n /** files-svc id once uploaded on sync (undefined while still local-only). */\n fileId?: string;\n createdAt: number;\n}\n\n/** The server's view of a conflicting record, kept for the review screen. */\nexport interface ServerObservation {\n id: string;\n clientId: string;\n fieldId?: string | null;\n fieldName?: string | null;\n observationType: string;\n title?: 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 version: number;\n syncedAt?: string | null;\n updatedAt?: string | null;\n createdBy?: string | null;\n}\n\n/**\n * A locally-captured observation (the outbox record). `clientId` is the stable\n * idempotency key sent to the server; `version` mirrors the last-known server\n * version so an edit can be conflict-checked on replay.\n */\nexport interface LocalObservation {\n clientId: string;\n observationType: ObservationType;\n fieldId?: string | null;\n fieldName?: string | null;\n title?: 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 /** Local photo ids (blobs live in the `photos` store until uploaded). */\n photoLocalIds: string[];\n /** files-svc ids already resolved for this record's photos. */\n photoFileIds: string[];\n capturedAt: string;\n capturedOffline: boolean;\n /** Local lifecycle status. */\n status: SyncStatus;\n /** Server version this record is based on (null for a never-synced capture). */\n baseVersion: number | null;\n /** Server row id once synced. */\n serverId?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED/CONFLICT status. */\n message?: string | null;\n /** The conflicting server record, populated when status === 'CONFLICT'. */\n serverVersion?: ServerObservation | null;\n /** Retry bookkeeping. */\n attempts: number;\n createdAt: number;\n updatedAt: number;\n workspaceId: string;\n}\n\n/** One entry in the device-local sync history timeline. */\nexport interface SyncHistoryEntry {\n id: string;\n at: number;\n kind: 'SYNC_COMPLETE' | 'AUTO_SYNC' | 'MANUAL_SYNC' | 'SYNC_FAILED' | 'CONFLICT';\n syncedCount: number;\n duplicateCount: number;\n conflictCount: number;\n failedCount: number;\n photoCount: number;\n message: string;\n /** Observation types touched, for the timeline chips. */\n types: string[];\n}\n\n/** User-configurable offline & sync settings (persisted locally). */\nexport interface OfflineSettings {\n autoSyncOnReconnect: boolean;\n syncOverMobileData: boolean;\n /** Auto-sync interval in ms while online (0 = only on events / manual). */\n syncFrequencyMs: number;\n uploadPhotosOnWifiOnly: boolean;\n photoQuality: 'original' | 'compressed';\n autoStampGps: boolean;\n highAccuracyGps: boolean;\n /** How to handle a server-side conflict. */\n conflictHandling: 'review' | 'keepMine' | 'keepServer';\n}\n\nexport const DEFAULT_SETTINGS: OfflineSettings = {\n autoSyncOnReconnect: true,\n syncOverMobileData: true,\n syncFrequencyMs: 5 * 60 * 1000,\n uploadPhotosOnWifiOnly: false,\n photoQuality: 'compressed',\n autoStampGps: true,\n highAccuracyGps: false,\n conflictHandling: 'review',\n};\n\n/** Live connectivity snapshot. */\nexport interface NetworkState {\n online: boolean;\n /** 'wifi' | 'cellular' | 'none' | 'unknown' — best-effort from @capacitor/network. */\n connectionType: string;\n}\n\nexport const OBSERVATION_TYPE_LABELS: Record<ObservationType, string> = {\n PEST: 'Pest Sighting',\n CROP_HEALTH: 'Crop Health',\n SOIL: 'Soil Note',\n HARVEST: 'Harvest Count',\n LIVESTOCK: 'Livestock Health',\n};\n"],"mappings":";AA4HA,IAAa,IAAoC;CAC/C,qBAAqB;CACrB,oBAAoB;CACpB,iBAAiB,MAAS;CAC1B,wBAAwB;CACxB,cAAc;CACd,cAAc;CACd,iBAAiB;CACjB,kBAAkB;CACnB"}
|