Skip to content

Appraisal Workflow Architecture ​

Overview ​

The appraisal workflow is built on two core patterns:

  1. Aggregator Pattern — A service that collects data from multiple PPP domains (users, activities, CPD, wellness, 360/MSF) and assembles it into a unified appraisal data structure.
  2. State Machine Pattern — A workflow engine that manages the appraisal lifecycle from draft through to completion.

Both patterns follow SOLID principles with clear separation of concerns, single-responsibility collectors, and dependency injection via the tRPC context.


Service Architecture ​

┌─────────────────────────────────────────────────────┐
│                  tRPC Procedures                     │
│  appraisal.getAppraisalData                         │
│  appraisal.submitAppraisal                          │
│  appraisal.updateAppraisalStatus                    │
│  appraisal.generatePdpGoals                         │
└──────────────┬──────────────────┬───────────────────┘
               │                  │
    ┌──────────▼──────────┐  ┌───▼────────────────────┐
    │ AppraisalAggregation│  │ AppraisalWorkflow       │
    │ Service             │  │ Service                 │
    │                     │  │                         │
    │ - collectAll()      │  │ - transition()          │
    │ - collectSection()  │  │ - validate()            │
    │ - snapshot()        │  │ - getPermittedActions()  │
    └──────┬──────────────┘  └─────────────────────────┘
           │
    ┌──────▼──────────────────────────────────────────┐
    │              Data Collectors                      │
    │                                                  │
    │  ┌──────────────┐  ┌──────────────────────────┐ │
    │  │ ProfileData  │  │ YearInReviewCollector     │ │
    │  │ Collector    │  │ - CPD plans, EOY          │ │
    │  │ - users      │  │ - logbook stats           │ │
    │  │ - speciality │  └──────────────────────────┘ │
    │  │ - hospitals  │                                │
    │  └──────────────┘  ┌──────────────────────────┐ │
    │                    │ WellnessCollector         │ │
    │  ┌──────────────┐  │ - WHO-5 scores            │ │
    │  │ CpdCollector │  │ - readiness trends        │ │
    │  │ - activities  │  │ - health metrics          │ │
    │  │ - plan acts   │  └──────────────────────────┘ │
    │  │ - categories  │                               │
    │  └──────────────┘  ┌──────────────────────────┐ │
    │                    │ MsfCollector              │ │
    │  ┌──────────────┐  │ - 360 reviews             │ │
    │  │ WbaCollector │  │ - MCR responses           │ │
    │  │ - by type     │  │ - QMF/MSF activities      │ │
    │  │ - ratings     │  └──────────────────────────┘ │
    │  └──────────────┘                                │
    └──────────────────────────────────────────────────┘

AppraisalAggregationService ​

Responsibility ​

Collect and assemble data from all PPP domains for a given user and appraisal period. Each data domain has its own collector function — a pure function that takes (userId, periodStart, periodEnd, ctx) and returns a typed result.

Collector Interface ​

typescript
interface CollectorParams {
  userId: number;
  periodStart: Date;
  periodEnd: Date;
}

interface AppraisalCollector<T> {
  collect(params: CollectorParams, ctx: TrpcContext): Promise<T>;
}

Collectors ​

CollectorSource TablesOutput Shape
ProfileDataCollectorusers, speciality, user_hospitals, user_supervisors{ personalDetails, hospitals, supervisors }
YearInReviewCollectorcpd_plans, cpd_end_of_year, activities (logbookCase){ cpdPlanStatus, eoyReflection, logbookStats }
WellnessCollectorwellness_questionnaire, wellness_score_daily, health_metric_daily{ who5Scores, readinessTrend, healthMetricsSummary }
CpdCollectoractivities, cpd_plan_activities, cpd_categories{ activitySummary, categoryBreakdown, completionRate }
WbaCollectoractivities (type=wba){ byType: { cex, cbd, pba, ssa }, ratingProgression }
MsfCollectorppp_360, ppp_360_reviewers, ppp_360_reviews, mcr_assessor_responses, activities (qmf){ reviews360, mcrSummary, msfSummary }

Aggregation Flow ​

typescript
// Pseudo-code for the aggregation service
async function collectAll(
  params: CollectorParams,
  ctx: TrpcContext,
): Promise<AppraisalData> {
  // Run all collectors in parallel for performance
  const [profile, yearReview, wellness, cpd, wba, msf] = await Promise.all([
    profileCollector.collect(params, ctx),
    yearReviewCollector.collect(params, ctx),
    wellnessCollector.collect(params, ctx),
    cpdCollector.collect(params, ctx),
    wbaCollector.collect(params, ctx),
    msfCollector.collect(params, ctx),
  ]);

  return { profile, yearReview, wellness, cpd, wba, msf };
}

Snapshot on Submission ​

When a doctor submits their appraisal, the aggregated data is frozen into a snapshotData jsonb column on the appraisals table. This ensures the appraisal record reflects the data at submission time, even if underlying records change later.

typescript
async function snapshot(
  appraisalId: number,
  params: CollectorParams,
  ctx: TrpcContext,
): Promise<void> {
  const data = await collectAll(params, ctx);
  await db
    .update(appraisals)
    .set({ snapshotData: data })
    .where(eq(appraisals.id, appraisalId));
}

AppraisalWorkflowService ​

Responsibility ​

Manage the appraisal lifecycle using a state machine pattern. Enforce valid transitions, permission checks, and side effects (notifications, PDF generation).

State Machine ​

                 ┌──────────┐
                 │  draft    │
                 └────┬─────┘
                      │ submit
                      ▼
                 ┌──────────┐
                 │ submitted │◄──────────────┐
                 └────┬─────┘               │
                      │ start_review        │ request_changes
                      ▼                     │
                 ┌──────────────┐           │
                 │ under_review ├───────────┘
                 └────┬────────┘
                      │ complete / defer
                      ▼
              ┌───────┴────────┐
              │                │
         ┌────▼─────┐   ┌─────▼────┐
         │ completed │   │ deferred │
         └──────────┘   └──────────┘

State Transitions ​

FromToActionActorSide Effects
draftsubmittedsubmitDoctorSnapshot data, notify appraiser
submittedunder_reviewstart_reviewAppraiser—
under_reviewsubmittedrequest_changesAppraiserNotify doctor
under_reviewcompletedcompleteAppraiserSet outcome, notify doctor, generate PDF
under_reviewdeferreddeferAppraiserSet outcome, notify doctor

Transition Validation ​

typescript
interface TransitionRequest {
  appraisalId: number;
  action: 'submit' | 'start_review' | 'request_changes' | 'complete' | 'defer';
  actorId: number;
  payload?: {
    outcome?: 'satisfactory' | 'unsatisfactory' | 'deferred';
    summary?: string;
  };
}

async function transition(
  request: TransitionRequest,
  ctx: TrpcContext,
): Promise<Appraisal> {
  const appraisal = await getAppraisal(request.appraisalId, ctx);

  // 1. Validate state transition is allowed
  validateTransition(appraisal.status, request.action);

  // 2. Validate actor has permission
  validateActor(appraisal, request.actorId, request.action);

  // 3. Run pre-transition checks (e.g., all sections complete before submit)
  await preTransitionChecks(appraisal, request.action, ctx);

  // 4. Apply transition
  const newStatus = getNextStatus(appraisal.status, request.action);
  const updated = await updateAppraisalStatus(
    request.appraisalId,
    newStatus,
    request.payload,
    ctx,
  );

  // 5. Run side effects
  await postTransitionEffects(updated, request.action, ctx);

  return updated;
}

Permission Model ​

ActionPermitted Actor
submitDoctor (appraisal owner)
start_reviewAssigned appraiser
request_changesAssigned appraiser
completeAssigned appraiser
deferAssigned appraiser

PdpGenerationService ​

Responsibility ​

Generate AI-powered Personal Development Plan suggestions based on the doctor's appraisal data, feedback trends, and practice patterns.

Design ​

typescript
interface PdpGenerationInput {
  userId: number;
  appraisalData: AppraisalData; // Output from AggregationService
  existingGoals?: PdpGoal[]; // Previous year's goals
}

interface PdpGoalSuggestion {
  title: string;
  description: string;
  rationale: string; // Why this goal was suggested
  suggestedTargetDate: Date;
  sourceData: string[]; // Which appraisal sections informed this
}

interface PdpGenerationService {
  generateGoals(
    input: PdpGenerationInput,
    ctx: TrpcContext,
  ): Promise<PdpGoalSuggestion[]>;
}

Implementation Strategy ​

  • Phase 1 (Part 2): Manual PDP goal creation via forms
  • Phase 2 (Part 5): AI-generated suggestions using Google Gemini (aligns with existing Gemini integration for OCR/sticker analysis)
  • The service follows a strategy pattern — ManualPdpStrategy for Phase 1, GeminiPdpStrategy for Phase 2, both implementing the same interface

Database Schema Proposal ​

Formal Drizzle ORM definitions will be created in Part 2 (#2462). This section outlines the conceptual design.

appraisals Table ​

sql
CREATE TABLE appraisals (
  id              SERIAL PRIMARY KEY,
  user_id         INTEGER REFERENCES users(id) ON DELETE CASCADE,
  appraiser_id    INTEGER REFERENCES users(id) ON DELETE SET NULL,
  year            INTEGER NOT NULL,
  period_start    DATE NOT NULL,
  period_end      DATE NOT NULL,
  status          VARCHAR(20) NOT NULL DEFAULT 'draft',
    -- draft | submitted | under_review | completed | deferred
  outcome         VARCHAR(20),
    -- satisfactory | unsatisfactory | deferred
  checklist       JSONB,
  appraiser_summary TEXT,
  doctor_signed_off_at  TIMESTAMP,
  appraiser_signed_off_at TIMESTAMP,
  snapshot_data   JSONB,  -- frozen aggregated data at submission
  created_at      TIMESTAMP DEFAULT NOW(),
  updated_at      TIMESTAMP DEFAULT NOW(),
  created_by      INTEGER,
  updated_by      INTEGER
);

appraisal_pdp_goals Table ​

sql
CREATE TABLE appraisal_pdp_goals (
  id              SERIAL PRIMARY KEY,
  appraisal_id    INTEGER REFERENCES appraisals(id) ON DELETE CASCADE,
  title           VARCHAR(500) NOT NULL,
  description     TEXT,
  target_date     DATE,
  status          VARCHAR(20) NOT NULL DEFAULT 'not_started',
    -- not_started | in_progress | completed | carried_forward
  ai_generated    BOOLEAN DEFAULT false,
  ai_prompt_used  TEXT,
  created_at      TIMESTAMP DEFAULT NOW(),
  updated_at      TIMESTAMP DEFAULT NOW(),
  created_by      INTEGER,
  updated_by      INTEGER
);

appraisal_status_history Table (Audit Trail) ​

sql
CREATE TABLE appraisal_status_history (
  id              SERIAL PRIMARY KEY,
  appraisal_id    INTEGER REFERENCES appraisals(id) ON DELETE CASCADE,
  from_status     VARCHAR(20),
  to_status       VARCHAR(20) NOT NULL,
  action          VARCHAR(30) NOT NULL,
  actor_id        INTEGER REFERENCES users(id),
  notes           TEXT,
  created_at      TIMESTAMP DEFAULT NOW()
);

tRPC Procedure Design ​

Procedures will be implemented in Part 3 (#2463).

Proposed Procedures ​

appraisal.
├── getAppraisalData        # GET: Aggregated data for a user/year
├── getAppraisal            # GET: Single appraisal record
├── listAppraisals          # GET: User's appraisal history
├── createAppraisal         # POST: Create draft appraisal
├── updateAppraisal         # PUT: Update draft fields
├── submitAppraisal         # POST: Submit (draft → submitted)
├── transitionAppraisal     # POST: State transition (appraiser actions)
├── getAppraisalPdf         # GET: Generate PDF export
├── pdpGoals.
│   ├── list                # GET: Goals for an appraisal
│   ├── create              # POST: Add a goal
│   ├── update              # PUT: Update goal
│   ├── delete              # DELETE: Remove goal
│   └── generateSuggestions # POST: AI-generate goal suggestions
└── statusHistory.
    └── list                # GET: Audit trail for an appraisal

Router Location ​

api/backend-ppp/src/routers/procedures/appraisalWorkflow/
├── index.ts                    # Router aggregation
├── getAppraisalData.ts         # Aggregation procedure
├── getAppraisal.ts             # Single record
├── listAppraisals.ts           # History
├── createAppraisal.ts          # Create draft
├── submitAppraisal.ts          # Submit transition
├── transitionAppraisal.ts      # Appraiser transitions
├── pdpGoals.ts                 # PDP CRUD + AI
└── statusHistory.ts            # Audit trail

Frontend Integration Points ​

UI components will be implemented in Part 4 (#2464).

Proposed Pages ​

RouteComponentPurpose
/appraisals/workflowAppraisalWorkflowPageList of appraisals + create new
/appraisals/workflow/:idAppraisalDetailPageFull appraisal view with all sections
/appraisals/workflow/:id/editAppraisalEditPageEdit draft appraisal
/appraisals/workflow/:id/reviewAppraisalReviewPageAppraiser review interface

Integration with Existing UI ​

The existing appraisals container (instances/ppp/src/containers/appraisals/index.tsx) manages MCR, 360, and MSF tabs. The new appraisal workflow will be added as a sibling route, not a replacement:

/appraisals/mcr          ← Existing (MCR assessments)
/appraisals/360          ← Existing (360 reviews)
/appraisals/msf          ← Existing (MSF feedback)
/appraisals/workflow     ← NEW (Annual appraisal workflow)

Sequence Diagrams ​

Doctor Creates & Submits Appraisal ​

Doctor              Frontend            tRPC API            Database
  │                    │                   │                   │
  │  Create Appraisal  │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │  createAppraisal  │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  INSERT appraisals│
  │                    │                   ├──────────────────►│
  │                    │                   │◄──────────────────┤
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤  Draft created    │                   │
  │                    │                   │                   │
  │  View Appraisal    │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │ getAppraisalData  │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  Parallel queries │
  │                    │                   │  (6 collectors)   │
  │                    │                   ├──────────────────►│
  │                    │                   │◄──────────────────┤
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤  Aggregated data  │                   │
  │                    │                   │                   │
  │  Add PDP Goals     │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │  pdpGoals.create  │                   │
  │                    ├──────────────────►│                   │
  │                    │                   ├──────────────────►│
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤                   │                   │
  │                    │                   │                   │
  │  Submit Appraisal  │                   │                   │
  ├───────────────────►│                   │
  │                    │ submitAppraisal   │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  1. Validate      │
  │                    │                   │  2. Snapshot data  │
  │                    │                   │  3. Update status  │
  │                    │                   │  4. Notify appraiser│
  │                    │                   ├──────────────────►│
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤  Submitted        │                   │

Appraiser Reviews & Completes ​

Appraiser           Frontend            tRPC API            Database
  │                    │                   │                   │
  │  Open Review       │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │  getAppraisal     │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  Read snapshot    │
  │                    │                   ├──────────────────►│
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤  Appraisal data   │                   │
  │                    │                   │                   │
  │  Start Review      │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │  transition       │                   │
  │                    │  (start_review)   │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  submitted →      │
  │                    │                   │  under_review     │
  │                    │                   ├──────────────────►│
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤                   │                   │
  │                    │                   │                   │
  │  Complete Review   │                   │                   │
  ├───────────────────►│                   │                   │
  │                    │  transition       │                   │
  │                    │  (complete)       │                   │
  │                    │  + summary        │                   │
  │                    │  + outcome        │                   │
  │                    ├──────────────────►│                   │
  │                    │                   │  1. Update status  │
  │                    │                   │  2. Set outcome    │
  │                    │                   │  3. Log history    │
  │                    │                   │  4. Notify doctor  │
  │                    │                   │  5. Generate PDF   │
  │                    │                   ├──────────────────►│
  │                    │◄──────────────────┤                   │
  │◄───────────────────┤  Completed        │                   │

Design Principles ​

  1. Single Responsibility: Each collector handles one data domain. The aggregation service composes them.
  2. Open/Closed: New collectors can be added without modifying existing ones (e.g., adding a MandatoryTrainingCollector when LMS integration is built).
  3. Dependency Inversion: All services depend on the TrpcContext abstraction, not concrete database implementations.
  4. Interface Segregation: The AppraisalCollector<T> interface is minimal — just collect().
  5. Snapshot Immutability: Once submitted, appraisal data is frozen. The snapshot cannot be modified without creating a new draft.

Existing Pattern References ​

  • Service pattern: api/backend-ppp/src/services/appraisalReminderService/ — batch processing with typed results and error handling
  • tRPC procedure pattern: api/backend-ppp/src/routers/procedures/ — standard router structure
  • State machine precedent: ppp_360.status field already uses status-based workflow (supervisor_review, etc.)
  • AI integration precedent: Google Gemini for OCR/sticker analysis — same provider for PDP generation
  • Documentation style: docs/site/integrations/stripe.md, docs/site/integrations/fhir.md

Internal documentation — org members only