@burdenoff/microfe-healthybowl 2026.902.6 → 2026.902.7

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.
@@ -1 +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\n// ── Queued scheme applications (BOFF-6179) ───────────────────────────────────\n\nexport interface SchemeApplicationInput {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n /**\n * The idempotency key. The server holds a unique index on\n * (workspace, clientMutationId), so a replay after a dropped connection\n * returns the ORIGINAL application rather than lodging a second one.\n */\n clientMutationId: string;\n notes?: string | null;\n amount?: number | null;\n}\n\nexport interface SchemeApplicationResult {\n id: string;\n clientMutationId: string | null;\n status: string;\n}\n\nconst CREATE_SCHEME_APPLICATION = `\n mutation CreateHealthyBowlSchemeApplicationOffline($input: CreateSchemeApplicationInput!) {\n createHealthyBowlSchemeApplication(input: $input) {\n id\n clientMutationId\n status\n }\n }\n`;\n\n/**\n * Replay a queued scheme application.\n *\n * Deliberately NOT the Apollo hook in `useHealthyBowlData`: replay runs from the\n * sync engine, outside React, where no hook can be called. `status` and\n * `schemeName` are not sent — the resolver ignores both, and passing a\n * client-invented status would imply an authority the client does not have.\n */\nexport async function createSchemeApplication(\n ctx: Ctx,\n input: SchemeApplicationInput\n): Promise<SchemeApplicationResult> {\n const res = await graphqlFetch<{ createHealthyBowlSchemeApplication: SchemeApplicationResult }>({\n gateway: 'workspace',\n query: CREATE_SCHEME_APPLICATION,\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?.createHealthyBowlSchemeApplication;\n if (!data) throw new SyncGraphQLError('Empty application 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\n// ── The server-backed observation log (BOFF-6048) ────────────────────────────────────────────\n//\n// `syncHealthyBowlFieldObservations` writes a real FieldObservation row, and until now that row\n// had NO READER anywhere in the product: every Field Capture screen showed the device-local\n// IndexedDB outbox. A capture was therefore invisible from a second device or browser, and\n// unreachable entirely once local storage was cleared, while the server row lived on with no way\n// to view or delete it. On a farm where workers capture on their own phones, a manager had no\n// server-backed view of any of it.\n//\n// These two are the ops that were already deployed and never called.\n\nexport interface ObservationFilter {\n observationType?: string | null;\n fieldId?: string | null;\n limit?: number;\n offset?: number;\n}\n\nconst OBSERVATIONS_QUERY = `\n query HealthyBowlFieldObservations($context: ContextInput!, $filter: FieldObservationFilterInput) {\n getHealthyBowlFieldObservations(context: $context, filter: $filter) { ${OBSERVATION_FIELDS} }\n }\n`;\n\n/**\n * The workspace's synced observations, straight from the server — not the device outbox.\n * Returns null on error so a failed read leaves the page rendering rather than blanking it.\n */\nexport async function fetchServerObservations(\n ctx: Ctx,\n filter: ObservationFilter = {}\n): Promise<ServerObservation[] | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldObservations: ServerObservation[] }>({\n gateway: 'workspace',\n query: OBSERVATIONS_QUERY,\n variables: { context: ctx, filter },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldObservations ?? null;\n}\n\nconst DELETE_OBSERVATION_MUTATION = `\n mutation DeleteHealthyBowlFieldObservation($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlFieldObservation(id: $id, context: $context)\n }\n`;\n\n/** Delete a SERVER observation. Throws on failure — a delete that silently no-ops is worse. */\nexport async function deleteServerObservation(ctx: Ctx, id: string): Promise<boolean> {\n const res = await graphqlFetch<{ deleteHealthyBowlFieldObservation: boolean }>({\n gateway: 'workspace',\n query: DELETE_OBSERVATION_MUTATION,\n variables: { id, 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 return res.data?.deleteHealthyBowlFieldObservation ?? false;\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,c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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\n// ── Queued scheme applications (BOFF-6179) ───────────────────────────────────\n\nexport interface SchemeDocumentInput {\n slot: string;\n fileId: string;\n fileName?: string | null;\n uploadedAt?: string | null;\n}\n\nexport interface SchemeApplicationInput {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n /**\n * The idempotency key. The server holds a unique index on\n * (workspace, clientMutationId), so a replay after a dropped connection\n * returns the ORIGINAL application rather than lodging a second one.\n */\n clientMutationId: string;\n notes?: string | null;\n amount?: number | null;\n /**\n * Supporting evidence (BOFF-6111). The server refuses a PARTIAL set — an application that\n * attaches some required documents but not all — and accepts an empty one, so an older queued\n * mutation replayed after this ships still drains rather than failing forever.\n */\n documents?: SchemeDocumentInput[];\n}\n\nexport interface SchemeApplicationResult {\n id: string;\n clientMutationId: string | null;\n status: string;\n}\n\nconst CREATE_SCHEME_APPLICATION = `\n mutation CreateHealthyBowlSchemeApplicationOffline($input: CreateSchemeApplicationInput!) {\n createHealthyBowlSchemeApplication(input: $input) {\n id\n clientMutationId\n status\n }\n }\n`;\n\n/**\n * Replay a queued scheme application.\n *\n * Deliberately NOT the Apollo hook in `useHealthyBowlData`: replay runs from the\n * sync engine, outside React, where no hook can be called. `status` and\n * `schemeName` are not sent — the resolver ignores both, and passing a\n * client-invented status would imply an authority the client does not have.\n */\nexport async function createSchemeApplication(\n ctx: Ctx,\n input: SchemeApplicationInput\n): Promise<SchemeApplicationResult> {\n const res = await graphqlFetch<{ createHealthyBowlSchemeApplication: SchemeApplicationResult }>({\n gateway: 'workspace',\n query: CREATE_SCHEME_APPLICATION,\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?.createHealthyBowlSchemeApplication;\n if (!data) throw new SyncGraphQLError('Empty application 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\n// ── The server-backed observation log (BOFF-6048) ────────────────────────────────────────────\n//\n// `syncHealthyBowlFieldObservations` writes a real FieldObservation row, and until now that row\n// had NO READER anywhere in the product: every Field Capture screen showed the device-local\n// IndexedDB outbox. A capture was therefore invisible from a second device or browser, and\n// unreachable entirely once local storage was cleared, while the server row lived on with no way\n// to view or delete it. On a farm where workers capture on their own phones, a manager had no\n// server-backed view of any of it.\n//\n// These two are the ops that were already deployed and never called.\n\nexport interface ObservationFilter {\n observationType?: string | null;\n fieldId?: string | null;\n limit?: number;\n offset?: number;\n}\n\nconst OBSERVATIONS_QUERY = `\n query HealthyBowlFieldObservations($context: ContextInput!, $filter: FieldObservationFilterInput) {\n getHealthyBowlFieldObservations(context: $context, filter: $filter) { ${OBSERVATION_FIELDS} }\n }\n`;\n\n/**\n * The workspace's synced observations, straight from the server — not the device outbox.\n * Returns null on error so a failed read leaves the page rendering rather than blanking it.\n */\nexport async function fetchServerObservations(\n ctx: Ctx,\n filter: ObservationFilter = {}\n): Promise<ServerObservation[] | null> {\n const res = await graphqlFetch<{ getHealthyBowlFieldObservations: ServerObservation[] }>({\n gateway: 'workspace',\n query: OBSERVATIONS_QUERY,\n variables: { context: ctx, filter },\n workspaceToken: true,\n workspaceId: ctx.workspaceId,\n suppressGlobalErrorEvent: true,\n });\n if (res.errors && res.errors.length) return null;\n return res.data?.getHealthyBowlFieldObservations ?? null;\n}\n\nconst DELETE_OBSERVATION_MUTATION = `\n mutation DeleteHealthyBowlFieldObservation($id: ID!, $context: ContextInput!) {\n deleteHealthyBowlFieldObservation(id: $id, context: $context)\n }\n`;\n\n/** Delete a SERVER observation. Throws on failure — a delete that silently no-ops is worse. */\nexport async function deleteServerObservation(ctx: Ctx, id: string): Promise<boolean> {\n const res = await graphqlFetch<{ deleteHealthyBowlFieldObservation: boolean }>({\n gateway: 'workspace',\n query: DELETE_OBSERVATION_MUTATION,\n variables: { id, 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 return res.data?.deleteHealthyBowlFieldObservation ?? false;\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;\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O,EAAI,MAAM,qCAAqC;AACxD"}
@@ -87,7 +87,8 @@ async function y(e, t) {
87
87
  declarationAccepted: r.payload.declarationAccepted,
88
88
  clientMutationId: r.clientId,
89
89
  notes: r.payload.notes ?? null,
90
- amount: r.payload.amount ?? null
90
+ amount: r.payload.amount ?? null,
91
+ ...r.payload.documents && r.payload.documents.length > 0 ? { documents: r.payload.documents } : {}
91
92
  });
92
93
  r.status = "SYNCED", r.serverId = n.id, r.serverStatus = n.status, r.syncedAt = f(), r.message = null, t.mutationsSynced += 1;
93
94
  } catch (e) {
@@ -1 +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 {\n LocalObservation,\n LocalPhoto,\n OfflineSettings,\n NetworkState,\n PendingMutation,\n SyncHistoryEntry,\n} from './types';\nimport {\n getAllObservations,\n saveObservation,\n getPhoto,\n savePhoto,\n addHistoryEntry,\n getAllPendingMutations,\n savePendingMutation,\n} from './store';\nimport {\n syncObservations,\n createSchemeApplication,\n SyncGraphQLError,\n type SyncInputItem,\n type SyncResultItem,\n} 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 /**\n * Failures that have used up every retry (BOFF-6364 review).\n *\n * A record at `MAX_ATTEMPTS` is excluded by `isSyncable` from every subsequent drain, so\n * it will never be retried. Counting it separately keeps the toast from promising a retry\n * that cannot happen — the exact class of dishonest status this ticket exists to remove.\n * These are a SUBSET of `failed`, not an addition to it.\n */\n exhausted: number;\n /**\n * Every record left in the outbox that can never sync again — including ones that used up\n * their retries in an EARLIER drain (BOFF-6364 review).\n *\n * `exhausted` only counts records that became terminal during THIS drain, so on the next\n * Sync Now `isSyncable` filters the stranded record out, the summary comes back empty, and\n * the toast would fall through to \"All synced — nothing is waiting\" while Pending Sync\n * still lists it. That is the original BOFF-6364 lie, re-entered by the back door. This\n * counter is read from the store, so it survives across drains.\n */\n terminalPending: number;\n skipped: number;\n photosUploaded: number;\n /** Queued non-observation writes that reached the server (BOFF-6179). */\n mutationsSynced: number;\n /** Queued non-observation writes that did not. */\n mutationsFailed: number;\n}\n\nconst PHOTO_FOLDER = '/HealthyBowl/FieldObservation';\n/**\n * Retry cap. Exported so the UI can tell a record that is merely failing from one that can\n * never be sent again — the two need different affordances, not just different wording.\n */\nexport const 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/** Queued mutations eligible to replay now (same retry cap as observations). */\nfunction isMutationSyncable(m: PendingMutation): boolean {\n return !m.requiresUserReview && (m.status === 'QUEUED' || m.status === 'FAILED') && m.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Replay queued non-observation writes (BOFF-6179).\n *\n * Runs BEFORE the observation path's early returns, because an application\n * queued on a device that captured no observations would otherwise never drain.\n *\n * ── A refusal is not a retry ─────────────────────────────────────────────────\n *\n * A `SyncGraphQLError` is the server declining — RBAC, validation, or the\n * soft-deleted-original case where the replay lookup filters `deletedAt: null`\n * but the unique index does not, surfacing as a P2002 masked as \"Unexpected\n * error\". Retrying cannot change any of those answers; it would spin to the\n * attempt cap while hiding the reason. Those land FAILED with the message.\n * Only a transport failure — the connection dropping again — is re-queued.\n */\nasync function drainPendingMutations(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n const all = await getAllPendingMutations();\n\n // Recover anything stranded UPLOADING by an interrupted drain. Replay is\n // idempotent on clientMutationId, so a request that did reach the server\n // simply returns the original row.\n for (const m of all) {\n if (m.status === 'UPLOADING') {\n m.status = 'QUEUED';\n m.updatedAt = Date.now();\n await savePendingMutation(m);\n }\n }\n\n for (const mutation of all.filter(isMutationSyncable)) {\n mutation.status = 'UPLOADING';\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n\n try {\n const result = await createSchemeApplication(\n { workspaceId: deps.workspaceId },\n {\n schemeId: mutation.payload.schemeId,\n applicantName: mutation.payload.applicantName,\n farmName: mutation.payload.farmName,\n declarationAccepted: mutation.payload.declarationAccepted,\n clientMutationId: mutation.clientId,\n notes: mutation.payload.notes ?? null,\n amount: mutation.payload.amount ?? null,\n }\n );\n mutation.status = 'SYNCED';\n mutation.serverId = result.id;\n mutation.serverStatus = result.status;\n mutation.syncedAt = now();\n mutation.message = null;\n summary.mutationsSynced += 1;\n } catch (err) {\n if (err instanceof SyncGraphQLError) {\n // NOT counted as exhausted: `isMutationSyncable` selects (FAILED && attempts <\n // MAX_ATTEMPTS), so a server-rejected mutation is still picked up by later drains.\n // Whether replaying an unchanged rejected payload is worthwhile is a separate\n // question — but while the engine does retry it, the counter must say so.\n mutation.status = 'FAILED';\n mutation.message = err.message;\n mutation.attempts += 1;\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n } else {\n mutation.attempts += 1;\n mutation.status = mutation.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n mutation.message = err instanceof Error ? err.message : 'Sync failed';\n }\n summary.mutationsFailed += 1;\n }\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n }\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 */\n\n/**\n * How the history line describes outstanding failures.\n *\n * \"still queued\" is false for a record at the retry cap — `isSyncable` excludes it, so the\n * timeline would permanently contradict Pending Sync and the toast (BOFF-6364 review).\n */\nfunction describeFailedForHistory(summary: DrainSummary): string {\n const failed = summary.failed + summary.mutationsFailed;\n const exhausted = Math.min(Math.max(summary.exhausted, 0), failed);\n if (exhausted === 0) return `${failed} record(s) still queued`;\n if (exhausted >= failed) return `${failed} record(s) out of retries`;\n return `${failed - exhausted} record(s) still queued, ${exhausted} out of retries`;\n}\n\n/**\n * Count everything left in the outbox that can never sync again.\n *\n * Read from the store rather than accumulated during the drain, because a record that used\n * up its retries in a previous pass is invisible to this one — `isSyncable` filters it out\n * before the drain ever sees it.\n */\nasync function stampTerminalPending(\n summary: DrainSummary,\n known?: { observations?: LocalObservation[] }\n): Promise<DrainSummary> {\n // Reuse the observation list the caller already loaded where there is one — the main drain\n // path reads the whole outbox anyway, and scanning it twice per sync is pure waste on a\n // device with a large queue. The mutation list is small and is not loaded on this path.\n const observations = known?.observations ?? (await getAllObservations());\n const mutations = await getAllPendingMutations();\n summary.terminalPending =\n observations.filter((o) => o.status === 'FAILED' && !isSyncable(o)).length +\n mutations.filter((m) => m.status === 'FAILED' && !isMutationSyncable(m)).length;\n return summary;\n}\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 exhausted: 0,\n terminalPending: 0,\n skipped: 0,\n photosUploaded: 0,\n mutationsSynced: 0,\n mutationsFailed: 0,\n };\n if (!deps.network.online || !deps.workspaceId) return stampTerminalPending(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 // Queued applications drain first, and unconditionally — the two early\n // returns below are about the OBSERVATION outbox, and a device with a queued\n // application but no observations hits them on every pass.\n await drainPendingMutations(deps, summary);\n\n const all = await getAllObservations();\n const pending = all.filter(isSyncable);\n if (pending.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n // Nothing was written since `all` was read, so it is still an accurate snapshot.\n return stampTerminalPending(summary, { observations: all });\n }\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 if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\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) {\n await recordMutationOnlyHistory(deps, summary);\n return stampTerminalPending(summary);\n }\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 {\n summary.failed += 1;\n // `applyOutcome` has already bumped `attempts`; a record that crossed the cap here is\n // just as terminal as one that failed in transport, and the toast must not promise it\n // a retry `isSyncable` will refuse.\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n }\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 if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\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 stampTerminalPending(summary);\n}\n\n/**\n * History for a drain that moved ONLY queued mutations.\n *\n * The observation path returns early when its outbox is empty, so without this\n * a farmer whose only queued item was an application would see the sync happen\n * and the timeline stay blank.\n */\nasync function recordMutationOnlyHistory(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n // A drain that uploaded nothing because every record FAILED still happened, and used to\n // leave the timeline blank — so a farmer chasing a stuck record found no trace of the\n // three attempts that had already failed (BOFF-6364). Deferred records are a setting\n // working as configured, not an event, so they are still not written here.\n const touchedSomething = summary.mutationsSynced + summary.mutationsFailed + summary.failed > 0;\n if (!touchedSomething) return;\n await recordHistory(deps, summary, summary.mutationsFailed + summary.failed > 0 ? 'failed' : 'complete');\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: string[] = Array.from(new Set<string>(touched.map((o) => o.observationType)));\n // `observationType` has no meaning for a queued application, so the chip is a\n // constant rather than a borrowed observation type.\n if (summary.mutationsSynced + summary.mutationsFailed > 0) types.push('SCHEME_APPLICATION');\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 + summary.mutationsSynced,\n duplicateCount: summary.duplicate,\n conflictCount: summary.conflict,\n failedCount: summary.failed + summary.mutationsFailed,\n photoCount: summary.photosUploaded,\n message:\n mode === 'failed'\n ? `Sync failed${message ? ` — ${message}` : ''} · ${describeFailedForHistory(summary)}`\n : `${summary.synced + summary.duplicate + summary.mutationsSynced} record(s) synced` +\n (summary.photosUploaded ? `, ${summary.photosUploaded} photo(s) uploaded` : '') +\n (summary.mutationsSynced ? `, ${summary.mutationsSynced} application(s) submitted` : '') +\n (summary.conflict ? `, ${summary.conflict} conflict(s)` : ''),\n types,\n };\n await addHistoryEntry(entry);\n}\n"],"mappings":";;;;AA0FA,IAAM,IAAe;AAOrB,SAAS,IAAc;CACrB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AAEA,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;AAGA,SAAS,EAAW,GAA8B;CAChD,QAAQ,EAAE,WAAW,YAAY,EAAE,WAAW,aAAa,EAAE,WAAA;AAC/D;AAOA,eAAe,EACb,GACA,GACyD;CAKzD,IAAM,IAAuB,CAAC;CAC9B,KAAK,IAAM,KAAO,EAAI,eAAe;EACnC,IAAM,IAAI,MAAM,EAAS,CAAG;EAC5B,AAAI,KAAG,EAAO,KAAK,CAAC;CACtB;CAKA,IAJoB,EAAO,MAAM,MAAM,CAAC,EAAE,MAItC,KAAe,EAAK,SAAS,0BAA0B,CAAC,EAAO,EAAK,OAAO,GAC7E,OAAO;CAGT,IAAI,IAAW,GACT,IAAoB,CAAC;CAC3B,KAAK,IAAM,KAAS,GAAQ;EAC1B,IAAI,EAAM,QAAQ;GAChB,EAAQ,KAAK,EAAM,MAAM;GACzB;EACF;EACA,IAAM,IAAQ,M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MAClF,GAAG,EAAQ,SAAS,EAAQ,YAAY,EAAQ,gBAAgB,sBAC/D,EAAQ,iBAAiB,KAAK,EAAQ,eAAe,sBAAsB,OAC3E,EAAQ,kBAAkB,KAAK,EAAQ,gBAAgB,6BAA6B,OACpF,EAAQ,WAAW,KAAK,EAAQ,SAAS,gBAAgB;EAChE;CAEoB,CAAK;AAC7B"}
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 {\n LocalObservation,\n LocalPhoto,\n OfflineSettings,\n NetworkState,\n PendingMutation,\n SyncHistoryEntry,\n} from './types';\nimport {\n getAllObservations,\n saveObservation,\n getPhoto,\n savePhoto,\n addHistoryEntry,\n getAllPendingMutations,\n savePendingMutation,\n} from './store';\nimport {\n syncObservations,\n createSchemeApplication,\n SyncGraphQLError,\n type SyncInputItem,\n type SyncResultItem,\n} 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 /**\n * Failures that have used up every retry (BOFF-6364 review).\n *\n * A record at `MAX_ATTEMPTS` is excluded by `isSyncable` from every subsequent drain, so\n * it will never be retried. Counting it separately keeps the toast from promising a retry\n * that cannot happen — the exact class of dishonest status this ticket exists to remove.\n * These are a SUBSET of `failed`, not an addition to it.\n */\n exhausted: number;\n /**\n * Every record left in the outbox that can never sync again — including ones that used up\n * their retries in an EARLIER drain (BOFF-6364 review).\n *\n * `exhausted` only counts records that became terminal during THIS drain, so on the next\n * Sync Now `isSyncable` filters the stranded record out, the summary comes back empty, and\n * the toast would fall through to \"All synced — nothing is waiting\" while Pending Sync\n * still lists it. That is the original BOFF-6364 lie, re-entered by the back door. This\n * counter is read from the store, so it survives across drains.\n */\n terminalPending: number;\n skipped: number;\n photosUploaded: number;\n /** Queued non-observation writes that reached the server (BOFF-6179). */\n mutationsSynced: number;\n /** Queued non-observation writes that did not. */\n mutationsFailed: number;\n}\n\nconst PHOTO_FOLDER = '/HealthyBowl/FieldObservation';\n/**\n * Retry cap. Exported so the UI can tell a record that is merely failing from one that can\n * never be sent again — the two need different affordances, not just different wording.\n */\nexport const 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/** Queued mutations eligible to replay now (same retry cap as observations). */\nfunction isMutationSyncable(m: PendingMutation): boolean {\n return !m.requiresUserReview && (m.status === 'QUEUED' || m.status === 'FAILED') && m.attempts < MAX_ATTEMPTS;\n}\n\n/**\n * Replay queued non-observation writes (BOFF-6179).\n *\n * Runs BEFORE the observation path's early returns, because an application\n * queued on a device that captured no observations would otherwise never drain.\n *\n * ── A refusal is not a retry ─────────────────────────────────────────────────\n *\n * A `SyncGraphQLError` is the server declining — RBAC, validation, or the\n * soft-deleted-original case where the replay lookup filters `deletedAt: null`\n * but the unique index does not, surfacing as a P2002 masked as \"Unexpected\n * error\". Retrying cannot change any of those answers; it would spin to the\n * attempt cap while hiding the reason. Those land FAILED with the message.\n * Only a transport failure — the connection dropping again — is re-queued.\n */\nasync function drainPendingMutations(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n const all = await getAllPendingMutations();\n\n // Recover anything stranded UPLOADING by an interrupted drain. Replay is\n // idempotent on clientMutationId, so a request that did reach the server\n // simply returns the original row.\n for (const m of all) {\n if (m.status === 'UPLOADING') {\n m.status = 'QUEUED';\n m.updatedAt = Date.now();\n await savePendingMutation(m);\n }\n }\n\n for (const mutation of all.filter(isMutationSyncable)) {\n mutation.status = 'UPLOADING';\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n\n try {\n const result = await createSchemeApplication(\n { workspaceId: deps.workspaceId },\n {\n schemeId: mutation.payload.schemeId,\n applicantName: mutation.payload.applicantName,\n farmName: mutation.payload.farmName,\n declarationAccepted: mutation.payload.declarationAccepted,\n clientMutationId: mutation.clientId,\n notes: mutation.payload.notes ?? null,\n amount: mutation.payload.amount ?? null,\n // Omitted entirely when absent, so a mutation queued before BOFF-6111 replays exactly as\n // it always did rather than sending an empty list the server would have to interpret.\n ...(mutation.payload.documents && mutation.payload.documents.length > 0\n ? { documents: mutation.payload.documents }\n : {}),\n }\n );\n mutation.status = 'SYNCED';\n mutation.serverId = result.id;\n mutation.serverStatus = result.status;\n mutation.syncedAt = now();\n mutation.message = null;\n summary.mutationsSynced += 1;\n } catch (err) {\n if (err instanceof SyncGraphQLError) {\n // NOT counted as exhausted: `isMutationSyncable` selects (FAILED && attempts <\n // MAX_ATTEMPTS), so a server-rejected mutation is still picked up by later drains.\n // Whether replaying an unchanged rejected payload is worthwhile is a separate\n // question — but while the engine does retry it, the counter must say so.\n mutation.status = 'FAILED';\n mutation.message = err.message;\n mutation.attempts += 1;\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n } else {\n mutation.attempts += 1;\n mutation.status = mutation.attempts >= MAX_ATTEMPTS ? 'FAILED' : 'QUEUED';\n if (mutation.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n mutation.message = err instanceof Error ? err.message : 'Sync failed';\n }\n summary.mutationsFailed += 1;\n }\n mutation.updatedAt = Date.now();\n await savePendingMutation(mutation);\n }\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 */\n\n/**\n * How the history line describes outstanding failures.\n *\n * \"still queued\" is false for a record at the retry cap — `isSyncable` excludes it, so the\n * timeline would permanently contradict Pending Sync and the toast (BOFF-6364 review).\n */\nfunction describeFailedForHistory(summary: DrainSummary): string {\n const failed = summary.failed + summary.mutationsFailed;\n const exhausted = Math.min(Math.max(summary.exhausted, 0), failed);\n if (exhausted === 0) return `${failed} record(s) still queued`;\n if (exhausted >= failed) return `${failed} record(s) out of retries`;\n return `${failed - exhausted} record(s) still queued, ${exhausted} out of retries`;\n}\n\n/**\n * Count everything left in the outbox that can never sync again.\n *\n * Read from the store rather than accumulated during the drain, because a record that used\n * up its retries in a previous pass is invisible to this one — `isSyncable` filters it out\n * before the drain ever sees it.\n */\nasync function stampTerminalPending(\n summary: DrainSummary,\n known?: { observations?: LocalObservation[] }\n): Promise<DrainSummary> {\n // Reuse the observation list the caller already loaded where there is one — the main drain\n // path reads the whole outbox anyway, and scanning it twice per sync is pure waste on a\n // device with a large queue. The mutation list is small and is not loaded on this path.\n const observations = known?.observations ?? (await getAllObservations());\n const mutations = await getAllPendingMutations();\n summary.terminalPending =\n observations.filter((o) => o.status === 'FAILED' && !isSyncable(o)).length +\n mutations.filter((m) => m.status === 'FAILED' && !isMutationSyncable(m)).length;\n return summary;\n}\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 exhausted: 0,\n terminalPending: 0,\n skipped: 0,\n photosUploaded: 0,\n mutationsSynced: 0,\n mutationsFailed: 0,\n };\n if (!deps.network.online || !deps.workspaceId) return stampTerminalPending(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 // Queued applications drain first, and unconditionally — the two early\n // returns below are about the OBSERVATION outbox, and a device with a queued\n // application but no observations hits them on every pass.\n await drainPendingMutations(deps, summary);\n\n const all = await getAllObservations();\n const pending = all.filter(isSyncable);\n if (pending.length === 0) {\n await recordMutationOnlyHistory(deps, summary);\n // Nothing was written since `all` was read, so it is still an accurate snapshot.\n return stampTerminalPending(summary, { observations: all });\n }\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 if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\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) {\n await recordMutationOnlyHistory(deps, summary);\n return stampTerminalPending(summary);\n }\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 {\n summary.failed += 1;\n // `applyOutcome` has already bumped `attempts`; a record that crossed the cap here is\n // just as terminal as one that failed in transport, and the toast must not promise it\n // a retry `isSyncable` will refuse.\n if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\n }\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 if (obs.attempts >= MAX_ATTEMPTS) summary.exhausted += 1;\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 stampTerminalPending(summary);\n}\n\n/**\n * History for a drain that moved ONLY queued mutations.\n *\n * The observation path returns early when its outbox is empty, so without this\n * a farmer whose only queued item was an application would see the sync happen\n * and the timeline stay blank.\n */\nasync function recordMutationOnlyHistory(deps: SyncDeps, summary: DrainSummary): Promise<void> {\n // A drain that uploaded nothing because every record FAILED still happened, and used to\n // leave the timeline blank — so a farmer chasing a stuck record found no trace of the\n // three attempts that had already failed (BOFF-6364). Deferred records are a setting\n // working as configured, not an event, so they are still not written here.\n const touchedSomething = summary.mutationsSynced + summary.mutationsFailed + summary.failed > 0;\n if (!touchedSomething) return;\n await recordHistory(deps, summary, summary.mutationsFailed + summary.failed > 0 ? 'failed' : 'complete');\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: string[] = Array.from(new Set<string>(touched.map((o) => o.observationType)));\n // `observationType` has no meaning for a queued application, so the chip is a\n // constant rather than a borrowed observation type.\n if (summary.mutationsSynced + summary.mutationsFailed > 0) types.push('SCHEME_APPLICATION');\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 + summary.mutationsSynced,\n duplicateCount: summary.duplicate,\n conflictCount: summary.conflict,\n failedCount: summary.failed + summary.mutationsFailed,\n photoCount: summary.photosUploaded,\n message:\n mode === 'failed'\n ? `Sync failed${message ? ` — ${message}` : ''} · ${describeFailedForHistory(summary)}`\n : `${summary.synced + summary.duplicate + summary.mutationsSynced} record(s) synced` +\n (summary.photosUploaded ? `, ${summary.photosUploaded} photo(s) uploaded` : '') +\n (summary.mutationsSynced ? `, ${summary.mutationsSynced} application(s) submitted` : '') +\n (summary.conflict ? `, ${summary.conflict} conflict(s)` : ''),\n types,\n };\n await addHistoryEntry(entry);\n}\n"],"mappings":";;;;AA0FA,IAAM,IAAe;AAOrB,SAAS,IAAc;CACrB,wBAAO,IAAI,KAAK,GAAE,YAAY;AAChC;AAEA,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;AAGA,SAAS,EAAW,GAA8B;CAChD,QAAQ,EAAE,WAAW,YAAY,EAAE,WAAW,aAAa,EAAE,WAAA;AAC/D;AAOA,eAAe,EACb,GACA,GACyD;CAKzD,IAAM,IAAuB,CAAC;CAC9B,KAAK,IAAM,KAAO,EAAI,eAAe;EACnC,IAAM,IAAI,MAAM,EAAS,CAAG;EAC5B,AAAI,KAAG,EAAO,KAAK,CAAC;CACtB;CAKA,IAJoB,EAAO,MAAM,MAAM,CAAC,EAAE,MAItC,KAAe,EAAK,SAAS,0BAA0B,CAAC,EAAO,EAAK,OAAO,GAC7E,OAAO;CAGT,IAAI,IAAW,GACT,IAAoB,CAAC;CAC3B,KAAK,IAAM,KAAS,GAAQ;EAC1B,IAAI,EAAM,QAAQ;GAChB,EAAQ,KAAK,EAAM,MAAM;GACzB;EACF;EACA,IAAM,I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a,EAAQ,SAAS,EAAQ;EACtC,YAAY,EAAQ;EACpB,SACE,MAAS,WACL,cAAc,IAAU,MAAM,MAAY,GAAG,KAAK,EAAyB,CAAO,MAClF,GAAG,EAAQ,SAAS,EAAQ,YAAY,EAAQ,gBAAgB,sBAC/D,EAAQ,iBAAiB,KAAK,EAAQ,eAAe,sBAAsB,OAC3E,EAAQ,kBAAkB,KAAK,EAAQ,gBAAgB,6BAA6B,OACpF,EAAQ,WAAW,KAAK,EAAQ,SAAS,gBAAgB;EAChE;CAEoB,CAAK;AAC7B"}
@@ -1 +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/**\n * A queued write that is NOT a field observation (BOFF-6179).\n *\n * The outbox shipped scoped to observations, so everything else — including\n * applying for a government scheme — needed a live gateway and simply failed\n * with no signal. This is the generic queue row that fixes that.\n *\n * ── Why the key is called `clientId` ─────────────────────────────────────────\n *\n * It IS the `clientMutationId` sent to the server, but `store.ts` derives every\n * memory-fallback key as `.clientId ?? .id`. Naming it `clientMutationId` here\n * would silently break the in-memory path used in private mode and SSR, where\n * IndexedDB is unavailable — the UI would appear to queue and then lose the row.\n *\n * ── Only ops the SERVER can deduplicate belong here ──────────────────────────\n *\n * `createHealthyBowlSchemeApplication` is the one HB mutation that carries\n * `clientMutationId` with a unique index behind it, so a replay returns the\n * original row. Queueing a mutation WITHOUT that guarantee would turn one\n * dropped connection into duplicate government applications — strictly worse\n * than today's honest failure. Adding a second kind means adding the backend\n * key first.\n */\nexport type PendingMutationKind = 'SCHEME_APPLICATION';\n\n/** Exactly the fields the resolver reads — it ignores `status` and `schemeName`. */\nexport interface SchemeApplicationPayload {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n notes?: string | null;\n amount?: number | null;\n}\n\nexport interface PendingMutation {\n /**\n * Stable idempotency key, sent as `clientMutationId`. Capped at 64 chars to\n * match the column.\n */\n clientId: string;\n kind: PendingMutationKind;\n payload: SchemeApplicationPayload;\n /**\n * Row text for the queue surfaces. Held locally because the scheme's name is\n * not readable offline — the queued row would otherwise be an opaque id.\n */\n label: string;\n /**\n * Reuses the observation lifecycle minus CONFLICT: a SchemeApplication has no\n * version column to compare, so there is nothing to review. Replay is\n * dedupe-only, which the server's unique index already guarantees.\n */\n status: Exclude<SyncStatus, 'CONFLICT'>;\n /**\n * Set by a storage migration when a legacy payload cannot be completed safely.\n * Such a row stays visible and discardable but is never sent with invented data.\n */\n requiresUserReview?: boolean;\n /** Server row id once it drains. */\n serverId?: string | null;\n /** Server-reported status once it drains (e.g. SUBMITTED). */\n serverStatus?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED status. */\n message?: string | null;\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":";AAoMA,IAAa,IAAoC;CAC/C,qBAAqB;CACrB,oBAAoB;CACpB,iBAAiB,MAAS;CAC1B,wBAAwB;CACxB,cAAc;CACd,cAAc;CACd,iBAAiB;CACjB,kBAAkB;AACpB"}
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/**\n * A queued write that is NOT a field observation (BOFF-6179).\n *\n * The outbox shipped scoped to observations, so everything else — including\n * applying for a government scheme — needed a live gateway and simply failed\n * with no signal. This is the generic queue row that fixes that.\n *\n * ── Why the key is called `clientId` ─────────────────────────────────────────\n *\n * It IS the `clientMutationId` sent to the server, but `store.ts` derives every\n * memory-fallback key as `.clientId ?? .id`. Naming it `clientMutationId` here\n * would silently break the in-memory path used in private mode and SSR, where\n * IndexedDB is unavailable — the UI would appear to queue and then lose the row.\n *\n * ── Only ops the SERVER can deduplicate belong here ──────────────────────────\n *\n * `createHealthyBowlSchemeApplication` is the one HB mutation that carries\n * `clientMutationId` with a unique index behind it, so a replay returns the\n * original row. Queueing a mutation WITHOUT that guarantee would turn one\n * dropped connection into duplicate government applications — strictly worse\n * than today's honest failure. Adding a second kind means adding the backend\n * key first.\n */\nexport type PendingMutationKind = 'SCHEME_APPLICATION';\n\n/** Exactly the fields the resolver reads — it ignores `status` and `schemeName`. */\n/**\n * One supporting document queued with a scheme application (BOFF-6111).\n *\n * Holds the wspace-files-svc id of a file that has ALREADY uploaded — the upload happens while the\n * farmer is still filling in the form, so a queued application carries a real reference rather than\n * a promise to upload something later. That matters offline: the outbox replays a mutation, not a\n * file transfer.\n */\nexport interface SchemeDocumentPayload {\n slot: string;\n fileId: string;\n fileName?: string | null;\n uploadedAt?: string | null;\n}\n\nexport interface SchemeApplicationPayload {\n schemeId: string;\n applicantName: string;\n farmName: string;\n declarationAccepted: true;\n notes?: string | null;\n amount?: number | null;\n documents?: SchemeDocumentPayload[];\n}\n\nexport interface PendingMutation {\n /**\n * Stable idempotency key, sent as `clientMutationId`. Capped at 64 chars to\n * match the column.\n */\n clientId: string;\n kind: PendingMutationKind;\n payload: SchemeApplicationPayload;\n /**\n * Row text for the queue surfaces. Held locally because the scheme's name is\n * not readable offline — the queued row would otherwise be an opaque id.\n */\n label: string;\n /**\n * Reuses the observation lifecycle minus CONFLICT: a SchemeApplication has no\n * version column to compare, so there is nothing to review. Replay is\n * dedupe-only, which the server's unique index already guarantees.\n */\n status: Exclude<SyncStatus, 'CONFLICT'>;\n /**\n * Set by a storage migration when a legacy payload cannot be completed safely.\n * Such a row stays visible and discardable but is never sent with invented data.\n */\n requiresUserReview?: boolean;\n /** Server row id once it drains. */\n serverId?: string | null;\n /** Server-reported status once it drains (e.g. SUBMITTED). */\n serverStatus?: string | null;\n syncedAt?: string | null;\n /** Human-readable reason for a FAILED status. */\n message?: string | null;\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":";AAoNA,IAAa,IAAoC;CAC/C,qBAAqB;CACrB,oBAAoB;CACpB,iBAAiB,MAAS;CAC1B,wBAAwB;CACxB,cAAc;CACd,cAAc;CACd,iBAAiB;CACjB,kBAAkB;AACpB"}