import { acknowledgeReview, approveReview, batchAcknowledgeReviews, getReviewForCompletion, getReviewInbox, returnReview, startReviewCorrection } from '@resgrid/api'; import { ChecklistReviewState, type ChecklistReviewView, ReviewInboxLane, type ReviewInboxLaneView } from '@resgrid/models'; import { create } from 'zustand'; import { persist } from 'zustand/middleware'; import { assertV4Success, unwrapItem } from '../core/envelope'; import { type DataError, toDataError } from '../core/errors'; import { dataPersistOptions, registerPersistedStore } from '../core/persist'; import { registerDataStoreReset } from '../core/reset'; import { dataNow, getDataApiContext, getDataSessionScope } from '../core/runtime'; import { createSliceRunner, emptySliceMeta, type FetchOptions, type SliceMeta, type SliceRunner } from '../core/slices'; /** Items read per inbox lane (Core caps a lane at 200). */ export const REVIEW_INBOX_PER_LANE = 25; /** Most reviews acknowledged in one batch (Core's cap). */ export const REVIEW_BATCH_MAX = 200; /** A reviewer's decision on one checklist run. */ export type ReviewDecision = 'acknowledge' | 'approve' | 'return'; const DECISION_STATE: Record = { acknowledge: ChecklistReviewState.Acknowledged, approve: ChecklistReviewState.Approved, return: ChecklistReviewState.Returned }; const DECISION_SENDERS: Record = { acknowledge: acknowledgeReview, approve: approveReview, return: returnReview }; /** Whether review can be used here: unknown until the inbox (or a run's review) answers once. */ export type ReviewsAvailability = 'unknown' | 'available' | 'unavailable'; /** 404 ReviewsUnavailable (Workforce.Pro or Workforce.Reviews off), or a server without the Reviews controller. A missing review is ReviewNotFound. */ export const isReviewsUnavailable = (error: DataError | null | undefined): boolean => error?.status === 404 && (error.problemType === undefined || error.problemType === 'department_task_ReviewsUnavailable'); /** 402 WorkforceProRequired: the add-on lapsed, review is read only. */ export const isReviewsReadOnlyError = (error: DataError | null | undefined): boolean => error?.status === 402; type ReviewsSlice = 'inbox' | 'review'; interface ReviewsData extends SliceMeta { availability: ReviewsAvailability; /** A write was refused with 402 (lapsed): decisions are hidden until the next session. */ readOnly: boolean; /** My reviews, lane by lane (operational labels, names and dates only). */ lanes: ReviewInboxLaneView[]; /** A completion's review (null: the run has no review), memory only: the log carries reviewers' notes. */ reviewsByCompletion: Record; actionError: DataError | null; } export interface ReviewsState extends ReviewsData { fetchInbox: (options?: FetchOptions) => Promise; fetchForCompletion: (completionId: string, options?: FetchOptions) => Promise; /** * Online: acknowledges, approves or returns a run's review at the revision read. Shown at once; a refusal puts it back and says * why (409 reads the review again, 402 turns review read only). Reviews are signed decisions, like a checklist witness: never queued. */ decide: (completionId: string, decision: ReviewDecision, note?: string | null) => Promise; /** Online: acknowledges the clean runs among these reviews (taken off the lane at once); the number acknowledged, or null when refused. */ batchAcknowledge: (reviewIds: readonly string[]) => Promise; /** Online: the submitter of a returned run starts (or reopens) its correction run; its completion id, or null when refused. */ startCorrection: (completionId: string) => Promise; clearActionError: () => void; } const initialData = (): ReviewsData => ({ ...emptySliceMeta(), availability: 'unknown', readOnly: false, lanes: [], reviewsByCompletion: {}, actionError: null }); /** The lanes without these checklist reviews (the inbox's checklist items are keyed by review id). */ const withoutChecklistItems = (lanes: readonly ReviewInboxLaneView[], reviewIds: ReadonlySet): ReviewInboxLaneView[] => lanes.map((lane) => { if (lane.Lane !== ReviewInboxLane.ChecklistRuns) return lane; const items = lane.Items.filter((item) => !reviewIds.has(item.Id)); const removed = lane.Items.length - items.length; return removed === 0 ? lane : { ...lane, Items: items, Count: Math.max(0, lane.Count - removed) }; }); /** The view as it will read once the decision lands: the state, this reviewer, the next revision, no further actions. */ export const viewAfterDecision = (view: ChecklistReviewView, decision: ReviewDecision, userId: string | null, now: number): ChecklistReviewView => ({ ...view, Review: { ...view.Review, State: DECISION_STATE[decision], Revision: view.Review.Revision + 1, ReviewedByUserId: userId ?? view.Review.ReviewedByUserId ?? null, ReviewedOn: new Date(now).toISOString() }, CanAcknowledge: false, CanApprove: false, CanReturn: false, }); let runner: SliceRunner; export const useReviewsStore = create()( persist( (set, get) => { runner = createSliceRunner('reviews', set); const ctx = () => getDataApiContext(); const markUnavailable = (error: DataError | null | undefined): void => { // The department has no supervisor review (any more): nothing it held is shown again. if (isReviewsUnavailable(error)) set({ ...initialData(), availability: 'unavailable' }); }; /** A refused write: why, and what it says about the module. */ const refused = (error: DataError): DataError => { set((state) => ({ actionError: error, readOnly: state.readOnly || isReviewsReadOnlyError(error) })); markUnavailable(error); return error; }; const putView = (completionId: string, view: ChecklistReviewView | null): void => { set((state) => ({ reviewsByCompletion: { ...state.reviewsByCompletion, [completionId]: view } })); }; return { ...initialData(), fetchInbox: async (options) => { const result = await runner.run( 'inbox', async () => unwrapItem(await getReviewInbox(ctx(), { perLane: REVIEW_INBOX_PER_LANE })), (inbox) => ({ lanes: inbox?.Lanes ?? [], availability: 'available' as const }), { trailing: options?.bypassCache === true } ); if (!result.ok) markUnavailable(result.error); }, fetchForCompletion: async (completionId, options) => { const known = completionId in get().reviewsByCompletion; const cached = get().reviewsByCompletion[completionId] ?? null; if (known && !options?.bypassCache) return cached; const result = await runner.run( 'review', async () => unwrapItem(await getReviewForCompletion(ctx(), { completionId })), (view, state) => ({ reviewsByCompletion: { ...state.reviewsByCompletion, [completionId]: view ?? null }, availability: 'available' as const }), { flightKey: `review:${completionId}`, raceKey: `review:${completionId}` } ); if (result.ok) return result.value ?? null; markUnavailable(result.error); return cached; }, decide: async (completionId, decision, note) => { const view = get().reviewsByCompletion[completionId]; if (!view) return false; const lanes = get().lanes; const revision = view.Review.Revision; set({ actionError: null, lanes: withoutChecklistItems(lanes, new Set([view.Review.Id])) }); putView(completionId, viewAfterDecision(view, decision, getDataSessionScope()?.userId ?? null, dataNow())); try { const review = unwrapItem(assertV4Success(await DECISION_SENDERS[decision](ctx(), { ReviewId: view.Review.Id, Revision: revision, Note: note?.trim() ? note.trim() : null }))); if (review) putView(completionId, { ...viewAfterDecision(view, decision, null, dataNow()), Review: review }); // The log and the flags come from the server's copy. void get().fetchForCompletion(completionId, { bypassCache: true }); return true; } catch (cause) { // Nothing changed on the server: the run is back as it was, and a stale revision is read again. putView(completionId, view); set({ lanes }); const error = refused(toDataError(cause)); if (error.status === 409) void get().fetchForCompletion(completionId, { bypassCache: true }); return false; } }, batchAcknowledge: async (reviewIds) => { const ids = [...new Set(reviewIds)].slice(0, REVIEW_BATCH_MAX); if (ids.length === 0) return 0; const lanes = get().lanes; set({ actionError: null, lanes: withoutChecklistItems(lanes, new Set(ids)) }); try { const result = unwrapItem(assertV4Success(await batchAcknowledgeReviews(ctx(), { ReviewIds: ids }))); // Skipped runs (a failed item, someone else's) come back with the inbox. void get().fetchInbox({ bypassCache: true }); return result?.Acknowledged ?? 0; } catch (cause) { set({ lanes }); refused(toDataError(cause)); return null; } }, startCorrection: async (completionId) => { const view = get().reviewsByCompletion[completionId]; if (!view) return null; set({ actionError: null }); try { const result = unwrapItem(assertV4Success(await startReviewCorrection(ctx(), { ReviewId: view.Review.Id }))); void get().fetchForCompletion(completionId, { bypassCache: true }); return result?.CompletionId ?? null; } catch (cause) { const error = refused(toDataError(cause)); // ReviewNotReturned: the review moved on (approved meanwhile, or the correction is already submitted). if (error.status === 409) void get().fetchForCompletion(completionId, { bypassCache: true }); return null; } }, clearActionError: () => set({ actionError: null }), }; }, dataPersistOptions>({ name: 'omni-reviews-storage', // The inbox is operational (labels, names, dates) and reads offline; reviews with their notes stay in memory. partialize: (state) => ({ availability: state.availability, lanes: state.lanes, fetchedAt: state.fetchedAt }), }) ) ); registerPersistedStore('omni-reviews-storage', useReviewsStore); registerDataStoreReset('reviews', useReviewsStore, initialData, () => runner.invalidate());