import { acknowledgeShiftLogHandover, addShiftLogEntry, finalizeShiftLog, getShiftLog, getShiftLogAccess, getShiftLogs, saveShiftLogSummary, signShiftLogHandover } from '@resgrid/api'; import { parseUtcMs } from '@resgrid/core/utils/dates'; import type { ShiftLogDetail, ShiftLogModuleAccess, ShiftLogsApiResult, ShiftLogSummary } from '@resgrid/models'; import { ProtectedPayloadError } from '@resgrid/offline'; import { create } from 'zustand'; import { persist } from 'zustand/middleware'; import { assertV4Success, unwrapItem, unwrapList } from '../core/envelope'; import { type DataError, toDataError } from '../core/errors'; import { defineDataHandler, submitWrite, type WriteResult } from '../core/outbox'; import { dataPersistOptions, registerPersistedStore } from '../core/persist'; import { registerQueuedMarkerSource, withoutMarkers } from '../core/queued-markers'; import { registerDataStoreReset } from '../core/reset'; import { dataNow, generateDataId, getDataApiContext } from '../core/runtime'; import { createSliceRunner, emptySliceMeta, type FetchOptions, type SliceMeta, type SliceRunner } from '../core/slices'; export const SHIFT_LOG_ENTRY_EVENT = 'shiftLogs.entry.add'; /** Entries of one log replay in the order they were written. */ export const shiftLogOrderKey = (logId: string): string => `shift-log:${logId}`; /** Log details kept besides the listed ones (most recently read first). */ export const SHIFT_LOG_DETAILS_MAX = 10; /** A queued entry: the log, when it happened (fixed when written, so a resend is the same entry), its category and text (private). */ export interface ShiftLogEntryPayload { logId: string; /** ISO UTC, set when the member wrote it. */ timeUtc: string; category: string | null; text: string; } /** An entry on the device the server has not acknowledged (no text: it stays in memory in `pendingEntries`). */ export interface QueuedShiftLogEntry { /** = outbox event id. */ id: string; logId: string; createdAt: number; state: 'queued' | 'rejected'; } export type ShiftLogsAvailability = 'unknown' | 'available' | 'unavailable'; /** A handover or close step on one log (online: signed and acknowledged as the signed-in session). */ export type ShiftLogCommand = 'sign' | 'acknowledge' | 'finalize'; /** The module is off: GetAccess says not offered, or a read answers 404 ShiftLogUnavailable (a missing log is LogNotFound). */ export const isShiftLogsUnavailable = (error: DataError | null | undefined): boolean => error?.status === 404 && (error.problemType === undefined || error.problemType === 'shift_log_ShiftLogUnavailable'); /** 402 WorkforceProRequired: the add-on lapsed, the logs are read only. */ export const isShiftLogsReadOnlyError = (error: DataError | null | undefined): boolean => error?.status === 402; /** How far apart (ms) the server's and the device's copies of an entry's time may be and still be the same entry (the server rounds). */ const ENTRY_TIME_TOLERANCE_MS = 1000; /** * Whether an entry was already added by an earlier attempt (an entry has no request id, so the log is the only witness): an entry by * this member at the same time and category, with the same text when the text is readable. */ export function entryAlreadyAdded(detail: ShiftLogDetail, payload: ShiftLogEntryPayload, userId: string): boolean { const at = parseUtcMs(payload.timeUtc); const category = (payload.category ?? 'general').toLowerCase(); const text = payload.text.trim(); return (detail.Entries ?? []).some((entry) => { const when = parseUtcMs(entry.TimeUtc ?? null); return ( entry.AuthorUserId === userId && at !== null && when !== null && Math.abs(when - at) <= ENTRY_TIME_TOLERANCE_MS && (entry.Category ?? 'general').toLowerCase() === category && (entry.TextWithheld || (entry.Text ?? '').trim() === text) ); }); } /** The log without its protected text (entry text, the handover summary): what may be written to the device. */ export const withoutLogText = (detail: ShiftLogDetail): ShiftLogDetail => ({ ...detail, HandoverSummary: null, Entries: (detail.Entries ?? []).map((entry) => (entry.Text ? { ...entry, Text: null } : entry)), }); type ShiftLogsSlice = 'access' | 'logs' | 'log'; interface ShiftLogsData extends SliceMeta { availability: ShiftLogsAvailability; access: ShiftLogModuleAccess | null; logs: ShiftLogSummary[]; detailsById: Record; queued: Record; /** Entries waiting to send, by event id (memory only: the text is protected). */ pendingEntries: Record; actionError: DataError | null; } export interface ShiftLogEntryDraft { /** When it happened; now when absent. */ timeUtc?: string | null; category?: string | null; text: string; } export interface ShiftLogsState extends ShiftLogsData { fetchAccess: (options?: FetchOptions) => Promise; fetchLogs: (options?: FetchOptions) => Promise; fetchLog: (id: string, options?: FetchOptions) => Promise; /** Offline-capable: one encrypted outbox entry per entry, ordered per log, its time fixed when written (a resend is the same entry). */ addEntry: (logId: string, draft: ShiftLogEntryDraft) => Promise; /** Online: saves the handover summary (before the sign-off). */ saveSummary: (logId: string, summary: string | null) => Promise; /** Online: signs the outgoing handover, acknowledges the incoming one, or finalizes the log. False with `actionError` when refused. */ runCommand: (logId: string, command: ShiftLogCommand, statement?: string | null) => Promise; clearActionError: () => void; /** Outbox handlers. */ applyDetail: (detail: ShiftLogDetail) => void; setQueued: (id: string, marker: QueuedShiftLogEntry | null) => void; } const initialData = (): ShiftLogsData => ({ ...emptySliceMeta(), availability: 'unknown', access: null, logs: [], detailsById: {}, queued: {}, pendingEntries: {}, actionError: null }); const COMMAND_SENDERS: Record = { sign: signShiftLogHandover, acknowledge: acknowledgeShiftLogHandover, finalize: finalizeShiftLog }; /** Details cut to the cap: listed logs stay, then the newest others. */ const retainDetails = (details: Record, keep: ReadonlySet, newest: string): Record => { const ids = Object.keys(details); if (ids.length <= SHIFT_LOG_DETAILS_MAX) return details; const ordered = [newest, ...ids.filter((id) => id !== newest)]; const kept = ordered.filter((id) => keep.has(id)); const others = ordered.filter((id) => !keep.has(id)).slice(0, Math.max(0, SHIFT_LOG_DETAILS_MAX - kept.length)); return Object.fromEntries([...kept, ...others].map((id) => [id, details[id]])); }; let runner: SliceRunner; export const useShiftLogsStore = create()( persist( (set, get) => { runner = createSliceRunner('shift-logs', set); const ctx = () => getDataApiContext(); const markUnavailable = (error: DataError | null | undefined): void => { // The department has no shift logs (any more): nothing it held is shown again; queued entries stay for Pending sync. if (isShiftLogsUnavailable(error)) set({ ...initialData(), availability: 'unavailable', queued: get().queued }); }; const refused = (error: DataError): void => { set((state) => ({ actionError: error, access: isShiftLogsReadOnlyError(error) && state.access ? { ...state.access, Writable: false, ReadOnly: true } : state.access, })); markUnavailable(error); }; const keepDetail = (detail: ShiftLogDetail | null): ShiftLogDetail | null => { if (!detail?.Log?.Id) return detail; set((state) => ({ detailsById: retainDetails({ ...state.detailsById, [detail.Log.Id]: detail }, new Set(state.logs.map((log) => log.Id)), detail.Log.Id), logs: state.logs.map((log) => (log.Id === detail.Log.Id ? detail.Log : log)), })); return detail; }; /** An online write answered with the log; a stale record reads it again, a lapse turns the module read only. */ const act = async (logId: string, send: () => Promise>): Promise => { set({ actionError: null }); try { keepDetail(unwrapItem(assertV4Success(await send()))); return true; } catch (cause) { const error = toDataError(cause); refused(error); if (error.status === 409) void get().fetchLog(logId, { bypassCache: true }); return false; } }; return { ...initialData(), fetchAccess: async (options) => { const result = await runner.run( 'access', async () => unwrapItem(await getShiftLogAccess(ctx())), (access) => ({ access, availability: access?.Offered === true ? ('available' as const) : ('unavailable' as const) }), { trailing: options?.bypassCache === true } ); // GetAccess never answers 404 while Core has the module: a 404 is a server without shift logs. if (!result.ok && result.error?.status === 404) markUnavailable({ ...result.error, problemType: undefined }); return result.ok ? result.value : get().access; }, fetchLogs: async (options) => { const result = await runner.run( 'logs', async () => unwrapList(await getShiftLogs(ctx())), (logs) => ({ logs, availability: 'available' as const }), { trailing: options?.bypassCache === true } ); if (!result.ok) markUnavailable(result.error); }, fetchLog: async (id, options) => { const cached = get().detailsById[id]; if (cached && !options?.bypassCache) return cached; const result = await runner.run( 'log', async () => unwrapItem(await getShiftLog(ctx(), { id })), () => ({}), { flightKey: `log:${id}`, raceKey: `log:${id}` } ); if (result.ok) return keepDetail(result.value); if (result.error?.problemType === 'shift_log_ShiftLogUnavailable') markUnavailable(result.error); return cached ?? null; }, addEntry: async (logId, draft) => { set({ actionError: null }); const payload: ShiftLogEntryPayload = { logId, timeUtc: draft.timeUtc ?? new Date(dataNow()).toISOString(), category: draft.category?.trim() || null, text: draft.text.trim() }; try { return await submitWrite({ type: SHIFT_LOG_ENTRY_EVENT, payload, orderKey: shiftLogOrderKey(logId), protected: true }); } catch (error) { // No payload cipher (web): the entry text is protected and never written to the device unencrypted, so send online only. if (!(error instanceof ProtectedPayloadError)) throw error; const sent = await act(logId, () => addShiftLogEntry(ctx(), { LogId: logId, TimeUtc: payload.timeUtc, Category: payload.category, Text: payload.text })); return { outcome: sent ? 'sent' : 'rejected', id: generateDataId() }; } }, saveSummary: (logId, summary) => act(logId, () => saveShiftLogSummary(ctx(), { LogId: logId, Summary: summary?.trim() || null })), runCommand: (logId, command, statement) => act(logId, () => COMMAND_SENDERS[command](ctx(), { LogId: logId, Statement: command === 'sign' ? statement?.trim() || null : null })), clearActionError: () => set({ actionError: null }), applyDetail: (detail) => { keepDetail(detail); }, setQueued: (id, marker) => set((state) => { if (marker) return { queued: { ...state.queued, [id]: marker } }; return { queued: withoutMarkers(state.queued, [id]), pendingEntries: withoutMarkers(state.pendingEntries, [id]) }; }), }; }, dataPersistOptions>({ name: 'omni-shift-logs-storage', // The logs, crew, digest and flags are operational; entry text and the handover summary stay in memory only. partialize: (state) => ({ availability: state.availability, access: state.access, logs: state.logs, detailsById: Object.fromEntries(Object.entries(state.detailsById).map(([id, detail]) => [id, withoutLogText(detail)])), queued: state.queued, fetchedAt: state.fetchedAt, }), }) ) ); registerPersistedStore('omni-shift-logs-storage', useShiftLogsStore); registerDataStoreReset('shift-logs', useShiftLogsStore, initialData, () => runner.invalidate()); registerQueuedMarkerSource('shift-logs', { ids: () => Object.keys(useShiftLogsStore.getState().queued), remove: (ids) => useShiftLogsStore.setState((state) => ({ queued: withoutMarkers(state.queued, ids), pendingEntries: withoutMarkers(state.pendingEntries, ids) })), }); /** The last refusal of a queued entry, for the screen that sent it (a network failure only waits). */ const noteRefusal = (failure: DataError): void => { if (failure.code === 'network' || failure.code === 'timeout') return; useShiftLogsStore.setState((state) => ({ actionError: failure, access: isShiftLogsReadOnlyError(failure) && state.access ? { ...state.access, Writable: false, ReadOnly: true } : state.access, })); }; /** * `shiftLogs.entry.add`: one encrypted event per entry, ordered per log. An entry has no request id, so a resend (attempt 2+) first * reads the log and is acknowledged when an earlier attempt already added it (same author, time, category and text). A refusal (402 * lapsed, 403 not on the crew, 409 finalized, 400 time outside the window) is dead-lettered into Pending sync. */ export const shiftLogEntryHandler = defineDataHandler({ type: SHIFT_LOG_ENTRY_EVENT, optimisticApply: (event) => { useShiftLogsStore.getState().setQueued(event.id, { id: event.id, logId: event.payload.logId, createdAt: event.createdAt, state: 'queued' }); useShiftLogsStore.setState((state) => ({ pendingEntries: { ...state.pendingEntries, [event.id]: event.payload } })); }, send: async (event, context) => { const { logId, timeUtc, category, text } = event.payload; if (context.attempt > 1) { const detail = unwrapItem(await getShiftLog(getDataApiContext(), { id: logId })); if (detail && entryAlreadyAdded(detail, event.payload, event.scope.userId)) return detail; } try { return unwrapItem(assertV4Success(await addShiftLogEntry(getDataApiContext(), { LogId: logId, TimeUtc: timeUtc, Category: category, Text: text }))); } catch (error) { noteRefusal(toDataError(error)); throw error; } }, afterAck: (event, detail) => { const store = useShiftLogsStore.getState(); store.setQueued(event.id, null); if (detail) store.applyDetail(detail); }, rollback: (event, reason) => { const store = useShiftLogsStore.getState(); const queued = store.queued[event.id]; store.setQueued(event.id, reason === 'discarded' || !queued ? null : { ...queued, state: 'rejected' }); }, }); /** Queued entries of one log (the detail's "waiting to send" rows). */ export const selectQueuedForLog = (state: Pick, logId: string): QueuedShiftLogEntry[] => Object.values(state.queued).filter((marker) => marker.logId === logId);