/** * Operation readiness service: gathers per-subject participation signals from * settled operation facts, computes a deterministic advisory aggregate, persists * it idempotently, and serves it behind a permission gate. * * Privacy model: the aggregate stores only normalized scores, category weights, * and input counts. It never stores evaluator names, rater ids, or evaluation * comment text, and the read path returns only the stored aggregate -- raw * evaluation content is never surfaced. * * Sources (all post-settlement, never live/unsettled data): * - participation: applied `operation-effects` reached via their provenance * link (operation-events -> operation-effects) for the subject's actor id. * - assignments: `assignments` the subject belongs to. * - evaluation: metadata-only (performance level) aggregate of evaluations * where the subject is the ratee. Comment/rater are never read. * - objectives: validated `operation.objective` events for the subject. * - logistics: completed `shipments` created by the subject. */ import type { Payload, PayloadRequest } from "payload"; import type { OperationReadiness } from "@/payload-types"; import { hasPermission } from "@/utils/access-control/hasPermission"; import { Permission } from "@/permissions"; import { getPerformanceLevel } from "@/lib/evaluations/levels"; import { READINESS_CATEGORIES, READINESS_CALCULATION_VERSION, READINESS_NATURE, type ReadinessAggregate, type ReadinessCategoryInput, type ReadinessNature, } from "./readinessTypes"; import { computeReadinessAggregate, formatReadinessExplanation, isAggregateEqual } from "./readinessCompute"; import type { ReadinessInputs } from "./readinessTypes"; type PayloadType = Awaited>; export interface ReadinessScope { subjectType: "user" | "role"; /** User id for user-scoped readiness; null for role-scoped. */ subjectId: number | null; windowStart: Date; windowEnd: Date; /** Optional human label, e.g. an ISO week ("2026-W38"). */ windowLabel: string | null; /** Optional operation identity the window's data is attributed to. */ operationId: string | null; } export interface ReadinessReadResult { /** Forbidden when the requesting user lacks the read permission. */ status: "ok" | "forbidden" | "not-found"; data: unknown | null; } /** * Gather normalized per-category inputs for a subject over a window. Every query * is bounded and read-only; the evaluation path reads only the performance level * (metadata), never the private comment or rater. */ export async function gatherReadinessInputs( payload: PayloadType, scope: ReadinessScope, req?: PayloadRequest, ): Promise { const inWindow = { greater_than_equal: scope.windowStart.toISOString(), less_than_equal: scope.windowEnd.toISOString() }; // Operation participation via provenance link: validated // operation-events -> applied operation-effects for the subject's actor id. const events = await payload.find({ collection: "operation-events", where: { and: [ { status: { equals: "validated" } }, { occurredAt: inWindow }, { actor: { equals: scope.subjectId } }, ], }, limit: 1000, depth: 0, overrideAccess: true, req, }); const eventIds = events.docs.map((d) => d.id as number); let participationCount = 0; if (eventIds.length > 0) { const effects = await payload.find({ collection: "operation-effects", where: { and: [{ operationEvent: { in: eventIds } }, { status: { equals: "applied" } }] }, limit: 1000, depth: 0, overrideAccess: true, req, }); participationCount = effects.docs.length; } const objectives = await payload.find({ collection: "operation-events", where: { and: [ { status: { equals: "validated" } }, { type: { equals: "operation.objective" } }, { occurredAt: inWindow }, { actor: { equals: scope.subjectId } }, ], }, limit: 500, depth: 0, overrideAccess: true, req, }); const evaluations = await payload.find({ collection: "evaluations", where: { and: [{ ratee: { equals: scope.subjectId } }, { createdAt: inWindow }] }, limit: 500, depth: 0, overrideAccess: true, req, }); let evaluationScore: number | null = null; if (evaluations.docs.length > 0) { const scores = evaluations.docs .map((d) => getPerformanceLevel((d as { level: unknown }).level as string)) .filter((l): l is NonNullable => l !== null) .map((l) => l.score); if (scores.length > 0) { evaluationScore = Math.round(scores.reduce((sum, s) => sum + s, 0) / scores.length); } } const assignments = await payload.find({ collection: "assignments", where: { and: [{ members: { equals: scope.subjectId } }, { createdAt: inWindow }] }, limit: 200, depth: 0, overrideAccess: true, req, }); const shipments = await payload.find({ collection: "shipments", where: { and: [ { createdBy: { equals: scope.subjectId } }, { status: { equals: "completed" } }, { createdAt: inWindow }, ], }, limit: 500, depth: 0, overrideAccess: true, req, }); const countScore = ( category: ReadinessCategoryInput["category"], count: number, perUnit: number, ): ReadinessCategoryInput => count > 0 ? { category, score: Math.min(100, count * perUnit), inputCount: count } : { category, score: null, inputCount: 0 }; return { participation: countScore(READINESS_CATEGORIES.PARTICIPATION, participationCount, 25), assignments: countScore(READINESS_CATEGORIES.ASSIGNMENTS, assignments.docs.length, 25), evaluation: evaluationScore === null ? { category: READINESS_CATEGORIES.EVALUATION, score: null, inputCount: 0 } : { category: READINESS_CATEGORIES.EVALUATION, score: evaluationScore, inputCount: evaluations.docs.length }, objectives: countScore(READINESS_CATEGORIES.OBJECTIVES, objectives.docs.length, 25), logistics: countScore(READINESS_CATEGORIES.LOGISTICS, shipments.docs.length, 25), }; } export interface ComputeReadinessOptions { /** When supplied, writes join the caller's transaction (hook safety). */ req?: PayloadRequest; } /** * Recompute a subject's readiness for a window and store it idempotently. * * Idempotency: the aggregate is keyed by `subjectType:subjectId:windowStart`. * The stored row is freshly re-read; if the computed aggregate is unchanged the * row is returned as-is (no drift), otherwise it is replaced atomically. */ export async function computeReadiness( payload: PayloadType, scope: ReadinessScope, _options?: ComputeReadinessOptions, ): Promise { const inputs = await gatherReadinessInputs(payload, scope); const aggregate = computeReadinessAggregate(inputs); const explanation = formatReadinessExplanation(aggregate, scope.windowLabel); const data = { subjectType: scope.subjectType, subjectId: scope.subjectId, windowStart: scope.windowStart.toISOString(), windowEnd: scope.windowEnd.toISOString(), windowLabel: scope.windowLabel, operationId: scope.operationId, calculationVersion: READINESS_CALCULATION_VERSION, nature: READINESS_NATURE as ReadinessNature, readinessScore: aggregate.readinessScore, planningConfidenceScore: aggregate.planningConfidenceScore, contributingCategories: aggregate.contributingCategories, inputCount: aggregate.inputCount, explanation, recomputedAt: new Date().toISOString(), }; const existing = await payload.find({ collection: "operation-readiness", where: { and: [ { subjectType: { equals: scope.subjectType } }, { subjectId: { equals: scope.subjectId } }, { windowStart: { equals: scope.windowStart.toISOString() } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); if (existing.docs.length > 0) { const stored = existing.docs[0] as unknown as OperationReadiness; const storedAggregate = { readinessScore: stored.readinessScore, planningConfidenceScore: stored.planningConfidenceScore, contributingCategories: (stored.contributingCategories ?? []) as ReadinessAggregate["contributingCategories"], }; if (isAggregateEqual(storedAggregate, aggregate)) { return stored; } return await payload.update({ collection: "operation-readiness", id: stored.id, data, overrideAccess: true, depth: 0, }); } return await payload.create({ collection: "operation-readiness", data, overrideAccess: true, depth: 0, }); } /** * Read a stored readiness aggregate for a subject/window, gated by the * `operation-readiness:read` permission. Returns only the stored aggregate; raw * evaluation content is never included. */ export async function getReadiness( payload: PayloadType, scope: Pick, user: { id: number } | null | undefined, permission: Permission = "operation-readiness:read", ): Promise { const canRead = await hasPermission(payload, user, permission); if (!canRead) { return { status: "forbidden", data: null }; } const found = await payload.find({ collection: "operation-readiness", where: { and: [ { subjectType: { equals: scope.subjectType } }, { subjectId: { equals: scope.subjectId } }, { windowStart: { equals: scope.windowStart.toISOString() } }, ], }, limit: 1, depth: 0, overrideAccess: true, }); if (found.docs.length === 0) { return { status: "not-found", data: null }; } return { status: "ok", data: found.docs[0] }; }