Files
classroomio/prd/compliance-training-platform/README.md
T
Rotimi BestRotimi Bestgreptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>Cursor AgentAbdulmuizz HamzatAdeyemi Adetunji
1e9a82e912 feat: complete rewrite of course (#622)
* theming improvements

* border style improvements

* refactor: migrate org routes to server-side data fetching

Move client-side API calls to server-side load functions for better
performance, security, and SEO. Implement permission-based course filtering

* refactor: clean up course and community components

This commit removes unused components and files related to courses and community features, streamlining the codebase. It also updates various routes to enhance performance and maintainability. Additionally, it introduces new types and constants for better type safety and organization.

* refactor: fix video formatting on website and other styles

* refactor: update course and dashboard components for improved styling and functionality

* more icon improvements

* refactor: streamline course and dashboard components

This commit updates various course and dashboard components for improved styling and functionality. It includes the removal of unused files, updates to imports and exports, and enhancements to type safety. Additionally, it introduces new routes and optimizes existing ones for better performance and maintainability.

* refactor: enhance lesson completion logic

* chore: delete all emails on dashboard and move other api routes to backend.

move all emails to the backend and

* feat: Refactor API and database queries for courses, quizzes, and lessons, migrating Supabase functions and schema management.

* get app loading

* fix ui and build error of cio/api

* refactor: move direct database queries to query layer

- Create query functions: getCourseWithOrgData, getOrganizationByCourseId, updateCourseVersion, updateLessonsSectionId, getProfileByGroupMemberId, getQuestionTypesByIds
- Refactor services to use query functions instead of direct db queries
- Add transaction support to updateCourseVersion and updateLessonsSectionId
- Fix getProfileByGroupMemberId to return profile directly (not nested)
- Fix updateLessonsSectionId to use .returning() instead of rowCount

This aligns services with architecture pattern where services orchestrate queries rather than executing them directly.

* exercise saving improvements

* fix and optimise exercise creation

* refactor: update dialog components for improved styling and functionality

- Adjusted dialog content width and maximum constraints for better responsiveness.
- Changed heading font size for consistency in the new exercise modal.
- Replaced CloseIcon with CrossIcon for a more modern appearance in dialog close button.

* refactor: enhance course and exercise management components

- Introduced new components for exercise creation, editing, and viewing, improving user experience.
- Refactored existing lesson and exercise components for better organization and maintainability.
- Updated routing for exercises and lessons to streamline navigation within the course structure.
- Added new utility functions and constants to support content management across the application.

* feat: implement course content management API and UI components

- Added new API routes for updating and deleting course content, enhancing content management capabilities.
- Introduced new Svelte components for displaying and managing course content, including content lists and action handlers.
- Updated existing course routing to integrate new content management features.
- Refactored content-related utility functions for improved organization and maintainability.

* refactor: remove Supabase references and implement course section management

- Removed Supabase-related environment variables and Dockerfile arguments to streamline configuration.
- Introduced a new section management API with routes for creating, updating, deleting, and reordering course sections.
- Updated course services to handle section operations, ensuring consistency in course content management.
- Refactored existing lesson section logic to align with the new course section structure, enhancing maintainability.

* chore: update .prettierignore to exclude additional file types

- Added exclusions for SQL and environment files to the Prettier ignore list.
- Included Dockerfile and .prettierignore itself to prevent formatting issues.

* feat: enhance course content management with translation support and UI improvements

- Added translation keys for user-facing text in course-related components, ensuring all UI copy is sourced from translation files.
- Updated lesson and exercise creation components to utilize translation keys for success and error messages, improving localization.
- Refactored course content management components to streamline the creation and editing process, enhancing user experience.
- Introduced new constants for content options and stepper states to standardize component behavior and improve maintainability.
- Improved styling and functionality of course content modals and steppers for better user interaction.

* feat: enhance course content management and UI components

- Updated .prettierignore to exclude storybook-static directory.
- Improved exercise creation logic by refining option handling and adding UUID support for option values.
- Enhanced navigation component with debugging output for custom links.
- Introduced a new method in CourseApi to update content items locally, improving state management during navigation.
- Added caching for exercise templates by tag in ExerciseTemplateApi to optimize performance.
- Refactored lesson and exercise components for better organization and maintainability, including updates to modal styling and functionality.
- Implemented local patching for lesson and exercise list items to ensure UI consistency after updates.

* student + teacher invite (not fully tested)

* refactor: streamline course team member middleware

- Removed unnecessary console logging and timing for checking user permissions.
- Simplified the logic for determining if a user is a course team member or organization admin.

* reorder course sidebar to move content to its own page.

* feat: implement unified course enrollment route and API

- Introduced a new enrollment route `/course/:slug/enroll` to replace the previous invite system.
- Unified enrollment logic for free and paid courses, allowing direct enrollment for free courses and invite token validation for paid courses.
- Updated course landing page to redirect to the new enrollment route for free courses.
- Removed obsolete invite routes and related logic, streamlining the enrollment process.
- Enhanced API with a new `POST /course/:courseId/enroll` endpoint for handling enrollments.
- Added rate limiting for enrollment requests to prevent abuse.
- Updated UI components to reflect changes in enrollment flow and messaging.

* chore: update docker stack, docs, and auth token automation

* chore: make prettier check ignore unknown file types

* fix: avoid using authClient on server file and keep authClient client focused

* chore: always get the server on demand depending on the environment

* chore: update dashboard configuration and Docker setup for environment variables

- Modified the Svelte configuration to directly use the PUBLIC_SERVER_URL environment variable.
- Enhanced the Docker Compose file to include health check formatting and added environment variable arguments for the dashboard build.
- Updated the Dockerfile to echo environment variable values during the build process, ensuring clarity on the configuration being used.

* chore: enhance Docker setup and documentation for production deployment

- Added a new production Docker Compose file and example environment file for published images.
- Updated README and usage documentation to include instructions for deploying with production images.
- Modified Svelte configuration to standardize the use of the posthog domain.
- Removed unnecessary console logs from the API client and layout server files for cleaner output.
- Improved overall clarity in Docker documentation regarding self-hosting and image publishing.

* chore(db): log function name in query catch blocks (console.error 'funcName error:', error)

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: multiple refresh issue

* fix: server key not passed to api

* fix: clarify usage of PRIVATE_SERVER_KEY and AUTH_BEARER_TOKEN in documentation

- Updated documentation to specify that PRIVATE_SERVER_KEY is used for server-to-server API key authentication and is validated by API key middleware.
- Clarified that AUTH_BEARER_TOKEN is a separate token not utilized by apiKeyMiddleware.
- Adjusted examples in Docker setup and self-hosting documentation to reflect these changes.

* fix migration script

* fix: improve language handling and add database reset script

- Updated language extraction to handle potential undefined values, defaulting to 'en' if necessary.
- Added a new script for resetting the database, including functionality to truncate public tables and run setup with optional seeding.

* feat: add promote ungrouped section functionality and enhance document handling in dashboard

- Implemented a new API endpoint to promote synthetic "Ungrouped" content into a real persisted section, allowing for better organization of course materials.
- Updated the dashboard to include a new component for displaying content count badges for lessons and exercises.
- Enhanced document management features, including a new document card component with dropdown actions for viewing, downloading, and removing documents.
- Improved file upload handling with a dedicated file drop zone and error handling for file type and size restrictions.
- Refactored existing components for better readability and maintainability, including updates to lesson and document lists.

* chore: use root env file for docker compose

* docs: document docker no-build startup flow

* chore: add no-build option to docker full stack script

* fix(email): handle SMTP TLS mode by port

* feat(auth): add configurable cookie domain env and docs

* apps/dashboard/src/lib/utils/services/auth/session.ts

* fix(email): make sender configurable via SMTP_SENDER

* chore(i18n): regenerate locale translations and support language targeting

* chore(config): switch api to PUBLIC_SERVER_URL

* fix(i18n): persist selected locale across navigation

* feat(assets): implement organization asset management routes and services

- Added new routes for managing organization assets, including listing, creating, updating, deleting, and exporting assets.
- Introduced asset-related services for handling asset operations such as creation, retrieval, and deletion.
- Integrated YouTube metadata resolution and asset attachment/detachment functionalities.
- Updated organization routes to include the new asset management routes.
- Enhanced error handling for asset-related operations.

* fix(document-list): update conditional rendering for edit mode in document list

* debug self hosted layout setup

* refactor(sidebar): simplify lms sidebar footer and improve navigation item rendering

* feat: tags

* chore: tags roadmap + translations

* fix(api): add authMiddleware to exercise, invites, and content routers

- exerciseRouter: apply authMiddleware before courseMemberMiddleware on all 10 routes
- invitesRouter: apply authMiddleware before courseTeamMemberMiddleware on all 4 routes
- contentRouter: add authMiddleware to PUT route (DELETE already had it)

Both courseMemberMiddleware and courseTeamMemberMiddleware document requiring
authMiddleware to be applied first. This aligns with lessonRouter pattern and
ensures explicit middleware contract regardless of global session middleware.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(course): use courseTeamMemberMiddleware for PUT, DELETE, and analytics routes

These routes require admin/tutor role per JSDoc but were using
courseMemberMiddleware which allows any course member including students.
Switch to courseTeamMemberMiddleware to restrict access to ADMIN/TUTOR
group members and org admins.

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* chore: unify pricing component between dashboard and website (#630)

* feat: modularize pricing card

* feat: initia implementation of pricing togge

* fix: minor amendment

* refactor: update pricing components for improved layout and styling

- Adjusted spacing in the pricing card layout for better visual consistency.
- Modified button styles and sizes for enhanced usability.
- Cleaned up the pricing toggle component by removing unnecessary console logs and restructuring the button rendering logic.

* add handle click

* chore(css): update Tailwind CSS output with new utility classes and theme variables

* fix(api): enable orgMemberMiddleware for stats route

This change ensures that the stats route is protected by orgMemberMiddleware, aligning access control with other routes. Additionally, removed unnecessary console log from the layout server file to clean up the code.

---------

Co-authored-by: Rotimi Best <best@classroomio.com>

* pass query parameter to signup from pricing page

* ui updates to pricing cards

* commit all PRDs

* add open api spec to api prd

* make blue default theme

* more prds

* sync option id sequence on question update

* docs: more classroomio features

* chore: more ui improvements

* docs: new component docs

* chore: CSP Configuration (#638)

* feat(validation): add GitHub repository name validation

- Add ZRepositoryName schema for validating GitHub repo names
- Add ZRepositoryOwner for owner/username validation
- Add ZRepositoryIdentifier for owner/repo format
- Follow GitHub rules: A-Za-z0-9_.-, 1-100 chars, reserved names
- Add translation keys for validation messages

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* Revert "feat(validation): add GitHub repository name validation"

This reverts commit 3436536bb17a0f05b3a9fe8dd7682cde64dd1dce.

* feat(dashboard): make CSP external domains configurable via env

Move hardcoded external domains from svelte.config.js to .env configuration
for on-premise deployments with strict security policies, data residency
constraints, or CISO-driven allowlists.

- ALLOWED_EXTERNAL_DOMAINS: single list for all CSP directives
- CSP_SCRIPT_SRC_DOMAINS, CSP_STYLE_SRC_DOMAINS, CSP_CONNECT_SRC_DOMAINS,
  CSP_FRAME_SRC_DOMAINS, CSP_FONT_SRC_DOMAINS: per-directive override
- When unset, defaults retain current SaaS behavior (backward compatible)

Fixes #637

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): self-hosted CSP uses only env vars, no defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* fix(dashboard): add all classroomio.com domains to CSP defaults

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add CSP ALLOWED_EXTERNAL_DOMAINS to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(docker): pass CSP domain env vars as build args to dashboard

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add SSO and token authentication routes and services

- Introduced new routes for SSO and token authentication under the organization namespace.
- Implemented SSO connection management including creation, update, activation, and deletion.
- Added token authentication configuration with support for secret rotation and status retrieval.
- Enhanced error handling for SSO and token authentication processes.
- Updated existing routes and services to integrate new functionalities.
- Improved gradebook service to fetch student marks and exercises.
- Refactored API structure for better organization and maintainability.

* update translations

* fix: add PUBLIC_SERVER_URL to .env.example to prevent localhost fallback in production (#641)

Co-authored-by: Cursor Agent <cursoragent@cursor.com>

* feat: new exercise question types

* MinIO S3 storage backend (#639)

* feat(storage): add MinIO/S3-compatible object storage backend

- Add OBJECT_STORAGE_* env vars for generic S3-compatible backends (MinIO, AWS S3)
- Create storage config module with Cloudflare R2 fallback for backward compatibility
- Refactor s3.ts to use configurable client and bucket names from config
- Update media.ts to use provider-neutral public URL (OBJECT_STORAGE_MEDIA_PUBLIC_BASE_URL or CLOUDFLARE_IMAGE_BUCKET_DOMAIN)
- Add MinIO service and init to docker-compose (profile: minio) with videos/documents/media buckets
- Add localhost:9000 to dashboard CSP for local MinIO presigned URL uploads
- Update self-hosting and Cloudflare docs with MinIO option
- Update .env examples and docker USAGE.md

Fixes #635

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* docs: add MINIO_ROOT_USER and MINIO_ROOT_PASSWORD to self-hosting guides

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat(media): refactor media management and integrate MinIO support

- Updated media API to use a new `mediaApi` module, replacing `mediaManagerApi` references across components.
- Added MinIO configuration options to the Docker setup, allowing for optional object storage exclusion.
- Enhanced environment variable management for MinIO in the `.env.example` file.
- Updated Content Security Policy (CSP) to allow local MinIO access in the dashboard.
- Introduced new media components for asset management, including asset cards and usage dialogs.

This refactor improves the modularity of the media handling system and provides better support for S3-compatible storage solutions.

* feat(dashboard): enhance logging and refactor auth session handling

- Added console logging for event and environment variables in hooks.server.ts to aid debugging.
- Refactored auth session handling to use authServerClient instead of authClient in session.ts for improved consistency.
- Updated Dockerfile to ensure the dashboard build output is present before starting the application.
- Expanded self-hosting documentation to include troubleshooting steps for disk space issues in PostgreSQL and Docker.

These changes improve the observability of the application and streamline the authentication process.

* refactor(dashboard): remove debug logging and enhance Postgres healthcheck

- Removed console logging for event and environment variables in hooks.server.ts to clean up the code.
- Updated Postgres healthcheck in docker-compose.yaml to require a successful `SELECT 1` query, ensuring dependent services only start once the database is ready.
- Expanded self-hosting documentation to include troubleshooting steps for database recovery issues.

These changes improve code clarity and reliability in service startup sequences.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: add Plyr media player icons and PDF.js integration

- Introduced new Plyr SVG icons for media player controls in both course and dashboard applications.
- Updated Plyr player configuration to use local icon assets.
- Integrated PDF.js for document viewing, replacing external CDN links with local paths for improved performance and reliability.
- Enhanced PDF viewer modal z-index for better visibility.

This update improves the media player experience and ensures consistent access to necessary resources.

* feat: enhance account and organization services with type definitions and promise return types

- Updated `getAccountData` to return a structured result type including profile and organizations.
- Modified `getOrganizationsWithFilters` to specify a promise return type for better type safety.
- Added new type imports for organization-related data structures to improve clarity and maintainability.

These changes improve type safety and enhance the overall structure of the account and organization services.

* feat: implement Redis caching for presigned URLs and refactor API interactions

- Added Redis caching for presigned download URLs in the API to reduce redundant S3 calls, improving performance.
- Introduced a new `PresignApi` class in the frontend to centralize presigned URL requests, enhancing code maintainability.
- Updated various components to utilize the new `presignApi` methods for document and video upload/download operations.
- Enhanced error handling for Redis operations to ensure graceful degradation in case of cache failures.

These changes optimize the presigned URL generation process and streamline API interactions across the application.

* fix: add better-auth dependency to dashboard (#645)

* chore: unify exercise answer data format

* feat: make selfhosting run under one org for simplicity (#647)

* feat: implement self-hosting PRD + license key system

Self-hosting single-org:
- Add PUBLIC_IS_SELFHOSTED to API env, block org creation when org exists
- Auto-add non-members as students in GET /account bootstrap
- getOrgSiteInfo: root domain returns single org for self-hosted
- App init: route to /lms when self-hosted + no orgs
- Hide org switcher and Add Org modal when self-hosted

Invite-only signup:
- Add settings.signup.inviteOnly via ZUpdateOrganization
- Allow public signups toggle in org auth settings
- Signup page: hide form when invite-only and no invite context
- Landing page nav: respect inviteOnly for signup link

First signup auto-verify:
- Self-hosted first signup (no orgs) auto-verifies email in createProfileHook

License key system:
- LICENSE_KEY, LICENSE_VERIFICATION_URL for external verification API
- Feature gates: SSO, token-auth, no-tracking (PostHog/Senja)
- requireLicense middleware for API routes
- Dashboard: license store, gate PostHog/Senja/SSO/token-auth UI
- docs/LICENSE_API_CONTRACT.md for external API spec

Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>

* feat: get rid of carbon completely

* chore: license verification happens only for selfhosted instance

* fix: in self hosted instance, orgSite is the default

* docs: how to write math in cio editor

* Update packages/db/src/queries/organization/organization.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* Update apps/api/src/services/license.ts

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

* fix: translations, cursor pr reviews, simplify license fetching and check

* refactor: update analytics setup for cloud and self-hosted deployments; enhance settings merge logic

* refactor: update license fetching URL for development environment; optimize organization query to prevent plan row loss

* more selfhosting improvements

* feat: enhance signup guard for self-hosted instances by requiring organization context when no org ID is provided

* pr reviews

* fix: correct query parameter handling in course navigation

* pr reviews

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Rotimi Best <rotimi-best@users.noreply.github.com>
Co-authored-by: Abdulmuizz Hamzat <103611443+buildwithhamzat@users.noreply.github.com>
Co-authored-by: Adeyemi Adetunji <tvnji01@gmail.com>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
2026-03-09 11:18:22 +01:00

34 KiB

Compliance Training Platform PRD

Status

  • Draft

Date

  • February 21, 2026

Purpose

Transform ClassroomIO into the go-to platform for companies that need to deliver, track, and prove compliance training for their employees. This PRD defines features for organizations in regulated industries (healthcare, finance, manufacturing, government) who must ensure their workforce stays compliant with regulations.


1. Executive Summary

The Problem

Companies in regulated industries struggle to:

  • Assign the right training to the right people based on their role/location
  • Track who completed training on time and who is overdue
  • Remind employees before deadlines and escalate to managers
  • Prove compliance to auditors with tamper-proof records
  • Renew certifications automatically when they expire

Target Customers

Industry Example Use Cases
Healthcare HIPAA training, patient safety, infection control, medical device handling
Financial Services Anti-money laundering, fraud prevention, data privacy, trading compliance
Manufacturing OSHA safety, quality control (ISO), hazardous materials handling
Government Security clearance, ethics training, procurement rules, FISMA
Education FERPA, Title IX, campus safety, student data handling
Retail/Hospitality Food safety, anti-harassment, PCI-DSS, workplace safety

Solution Overview

ClassroomIO becomes a Compliance Training Management System that helps organizations:

  1. Deploy compliance training programs efficiently
  2. Automate assignment, reminders, and renewals
  3. Monitor compliance status in real-time
  4. Report audit-ready evidence instantly
  5. Scale across thousands of employees and multiple locations

2. Current State vs. Required Features

✅ What ClassroomIO Already Does Well

Feature Current Capability Compliance Gap
Course Creation Rich content editor, videos, documents ✅ Good enough
Assessments Basic exercises with grading ⚠️ Need more question types & pass/fail rules
Certificates Generate PDF certificates ⚠️ Need expiration, renewal, revocation
User Management Invite students, track progress ⚠️ Need bulk assignment by role/department
SSO OIDC/SAML integration ✅ Enterprise-ready
Basic Reporting Course completion stats ❌ Need compliance-specific dashboards

❌ Critical Missing Features for Compliance Training

Missing Feature Why It Matters Customer Pain
Mandatory Training Assignment Compliance training isn't optional - everyone in a role MUST complete it Currently can only invite, can't enforce
Recurring/Refresh Training Many regulations require annual/quarterly retraining No automated renewal system
Compliance Dashboard See who is compliant, who is overdue, by department/role No bird's-eye view for compliance officers
Policy Acknowledgment Track who read and agreed to policies No policy attestation workflow
Audit Trail Prove "who did what when" to auditors No immutable activity log
Automated Reminders Notify employees before deadlines, escalate to managers Manual follow-up is unsustainable
Evidence Export One-click export of training records for auditors Manual report generation takes hours

3. Feature Requirements

3.1 Compliance Training Programs (The Container)

Purpose

A "Program" groups related training requirements (e.g., "Annual HIPAA Compliance" or "New Hire Safety Training"). This is the top-level entity compliance officers manage.

Requirements

CP-1: Program Management

  • Create programs with title, description, and regulatory framework (e.g., "HIPAA", "OSHA", "SOX")
  • Set program status: draft, active, archived
  • Assign program owner (compliance officer responsible)
  • Add custom fields for internal tracking (department codes, cost centers, etc.)

CP-2: Program Content

  • Link multiple courses/lessons to a program (e.g., HIPAA includes: Basics course, Security course, Quiz)
  • Set completion rules:
    • "Complete all courses"
    • "Complete any 2 of 3 courses"
    • "Complete Course A AND (Course B OR Course C)"
  • Set passing criteria: minimum score, attempt limits, time between retakes

CP-3: Program Assignment Rules

  • Assign by: role, department, location, employment type, custom attributes
  • Examples:
    • "All nurses in California hospitals"
    • "All new hires in first 30 days"
    • "All employees with security clearance Level 2+"
  • Support exclusions (e.g., "All managers EXCEPT contractors")

CP-4: Program Schedule

  • One-time assignment (e.g., new hire training)
  • Recurring: every N months/years from completion date OR fixed date
  • Grace period: days after due date before marked overdue
  • Prerequisites: must complete Program X before starting Program Y

Database Schema

-- Compliance training programs
CREATE TABLE compliance_program (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  title VARCHAR NOT NULL,
  description TEXT,
  framework VARCHAR, -- 'HIPAA', 'OSHA', 'SOX', 'GDPR', 'Custom'
  status VARCHAR DEFAULT 'draft', -- 'draft', 'active', 'archived'
  owner_id UUID REFERENCES profile(id),
  completion_rule JSONB NOT NULL DEFAULT '{"type": "all"}', -- { type: 'all' | 'any' | 'minimum', count: number }
  passing_criteria JSONB NOT NULL DEFAULT '{"minScore": 80, "maxAttempts": 3}',
  schedule_config JSONB NOT NULL DEFAULT '{}', -- { type: 'once' | 'recurring', intervalMonths: 12, graceDays: 7 }
  custom_fields JSONB DEFAULT '{}',
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Program content (courses/exercises linked to program)
CREATE TABLE compliance_program_content (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  program_id UUID NOT NULL REFERENCES compliance_program(id),
  content_type VARCHAR NOT NULL, -- 'course', 'exercise', 'lesson'
  content_id UUID NOT NULL,
  is_required BOOLEAN DEFAULT true,
  order_index INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Assignment rules (who gets this program)
CREATE TABLE compliance_program_assignment (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  program_id UUID NOT NULL REFERENCES compliance_program(id),
  rule_type VARCHAR NOT NULL, -- 'role', 'group', 'location', 'attribute', 'all'
  rule_value JSONB NOT NULL, -- { roleIds: [], groupIds: [], location: '', attributes: {} }
  is_exclusion BOOLEAN DEFAULT false,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

3.2 Learner Assignments & Tracking

Purpose

Track each learner's obligation, progress, and completion status for every program they're assigned.

Requirements

LA-1: Assignment Lifecycle

  • Assigned: User meets assignment rule criteria → creates assignment
  • In Progress: User started but not completed
  • Completed: User met all completion rules
  • Overdue: Past due date + grace period
  • Waived: Admin exempted user (with reason and expiration)
  • Expired: Previous completion past validity period → needs renewal

LA-2: Assignment Attributes

  • Assigned date, due date, completed date
  • Current status and status history with timestamps
  • Attempts count, best score, time spent
  • Certificate issued (if applicable)
  • Reminder history (when reminders were sent)

LA-3: Bulk Operations

  • Bulk assign to users matching criteria
  • Bulk extend due dates (e.g., grant extension to entire department)
  • Bulk waive with reason
  • Bulk re-enroll (force retake even if completed)

LA-4: Self-Service Portal (for Learners)

  • "My Compliance" dashboard showing all assigned programs
  • Visual indicators: due soon (yellow), overdue (red), completed (green)
  • Download certificates for completed programs
  • See upcoming renewals

Database Schema

-- Individual learner assignments
CREATE TABLE compliance_assignment (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  program_id UUID NOT NULL REFERENCES compliance_program(id),
  user_id UUID NOT NULL REFERENCES user(id),
  
  -- Assignment details
  assigned_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  due_date TIMESTAMPTZ NOT NULL,
  grace_period_days INTEGER DEFAULT 0,
  
  -- Status tracking
  status VARCHAR NOT NULL DEFAULT 'assigned', -- 'assigned', 'in_progress', 'completed', 'overdue', 'waived', 'expired'
  status_changed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  status_history JSONB DEFAULT '[]', -- [{ status, timestamp, reason }]
  
  -- Progress
  started_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  progress_percent INTEGER DEFAULT 0,
  
  -- Results
  attempts INTEGER DEFAULT 0,
  best_score INTEGER,
  passing_score INTEGER,
  time_spent_minutes INTEGER,
  
  -- Certificate
  certificate_id UUID,
  
  -- Waiver (if applicable)
  waived_at TIMESTAMPTZ,
  waived_by UUID REFERENCES profile(id),
  waiver_reason TEXT,
  waiver_expires_at TIMESTAMPTZ,
  
  -- For recurring programs
  is_renewal BOOLEAN DEFAULT false,
  previous_assignment_id UUID REFERENCES compliance_assignment(id),
  
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  
  UNIQUE(program_id, user_id, is_renewal) -- One active assignment per program per user
);

-- Assignment content progress (track individual courses within program)
CREATE TABLE compliance_assignment_progress (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  assignment_id UUID NOT NULL REFERENCES compliance_assignment(id),
  content_type VARCHAR NOT NULL,
  content_id UUID NOT NULL,
  status VARCHAR NOT NULL DEFAULT 'not_started', -- 'not_started', 'in_progress', 'completed', 'failed'
  started_at TIMESTAMPTZ,
  completed_at TIMESTAMPTZ,
  score INTEGER,
  attempts INTEGER DEFAULT 0,
  time_spent_minutes INTEGER,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

3.3 Automated Notifications & Escalations

Purpose

Ensure employees complete training on time without manual follow-up from compliance teams.

Requirements

NE-1: Reminder Schedule

  • Configurable reminder schedule per program (e.g., 30, 14, 7, 1 days before due)
  • Customizable email templates per reminder stage
  • Include: program name, due date, progress, direct link to training

NE-2: Escalation Paths

  • Level 1: Reminder to learner
  • Level 2: Notify learner + CC manager (when overdue)
  • Level 3: Escalate to compliance admin + learner's skip-level manager
  • Level 4: Flag for HR/executive review

NE-3: Manager Notifications

  • Weekly digest of team's compliance status
  • Immediate alert when direct report goes overdue
  • Dashboard showing team compliance rate

NE-4: Compliance Team Alerts

  • Daily summary of new overdue assignments
  • Alert when large group approaches deadline (e.g., "50 employees due in 3 days")
  • System health alerts (failed email deliveries, sync errors)

NE-5: Notification Preferences

  • Email, in-app notification, or both
  • SMS for critical alerts (optional add-on)
  • Digest mode vs. immediate notifications

Database Schema

-- Notification templates
CREATE TABLE compliance_notification_template (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  name VARCHAR NOT NULL,
  trigger_type VARCHAR NOT NULL, -- 'reminder', 'overdue', 'escalation', 'completion'
  trigger_days INTEGER, -- days before/after event (negative = before, positive = after)
  subject_template VARCHAR NOT NULL,
  body_template TEXT NOT NULL,
  recipients VARCHAR[] NOT NULL, -- ['learner', 'manager', 'compliance_admin']
  is_active BOOLEAN DEFAULT true,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Notification queue and history
CREATE TABLE compliance_notification (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  assignment_id UUID NOT NULL REFERENCES compliance_assignment(id),
  template_id UUID REFERENCES compliance_notification_template(id),
  notification_type VARCHAR NOT NULL,
  recipient_type VARCHAR NOT NULL, -- 'learner', 'manager', 'admin'
  recipient_id UUID NOT NULL,
  recipient_email VARCHAR NOT NULL,
  scheduled_at TIMESTAMPTZ NOT NULL,
  sent_at TIMESTAMPTZ,
  status VARCHAR NOT NULL DEFAULT 'pending', -- 'pending', 'sent', 'delivered', 'failed', 'bounced'
  error_message TEXT,
  opened_at TIMESTAMPTZ,
  clicked_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Notification schedule (tracks what reminders are due)
CREATE TABLE compliance_notification_schedule (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  assignment_id UUID NOT NULL REFERENCES compliance_assignment(id),
  reminder_type VARCHAR NOT NULL, -- '30_days', '14_days', '7_days', '1_day', 'overdue', 'escalation'
  scheduled_at TIMESTAMPTZ NOT NULL,
  is_sent BOOLEAN DEFAULT false,
  sent_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

3.4 Policy Attestation (Read & Acknowledge)

Purpose

Not all compliance is "training" - sometimes employees just need to read and acknowledge a policy. Track who has read and agreed to important documents.

Requirements

PA-1: Policy Management

  • Upload policy documents (PDF, Word, HTML)
  • Version control with version numbers and effective dates
  • Categorize (Security, HR, Safety, Code of Conduct, etc.)
  • Set required reading time (e.g., "Must view for at least 5 minutes")

PA-2: Attestation Workflow

  1. Employee receives notification of new/updated policy
  2. Employee opens and reads the document (viewer tracks time)
  3. Employee checks "I have read and understand this policy"
  4. Employee digitally "signs" with name, date, employee ID
  5. System records: user, policy version, timestamp, IP, time spent reading

PA-3: Attestation Tracking

  • Who has attested to which version
  • Who hasn't attested (and how overdue)
  • Bulk attestation for initial rollout (with verification)
  • Re-attestation required when policy version changes

PA-4: Attestation Certificate

  • Generate proof of attestation per employee
  • Include: policy name, version, attestation date, digital signature hash

Database Schema

-- Policy documents
CREATE TABLE compliance_policy (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  title VARCHAR NOT NULL,
  description TEXT,
  category VARCHAR NOT NULL, -- 'security', 'hr', 'safety', 'conduct', 'privacy'
  status VARCHAR DEFAULT 'draft', -- 'draft', 'active', 'archived'
  requires_reading_time_seconds INTEGER DEFAULT 0,
  created_by UUID NOT NULL REFERENCES profile(id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Policy versions
CREATE TABLE compliance_policy_version (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  policy_id UUID NOT NULL REFERENCES compliance_policy(id),
  version_number INTEGER NOT NULL,
  content_url TEXT NOT NULL, -- S3/MinIO URL
  content_hash TEXT NOT NULL,
  effective_date TIMESTAMPTZ NOT NULL,
  requires_reattestation BOOLEAN DEFAULT true,
  created_by UUID NOT NULL REFERENCES profile(id),
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE(policy_id, version_number)
);

-- Who needs to attest to which policy version
CREATE TABLE compliance_policy_assignment (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  policy_version_id UUID NOT NULL REFERENCES compliance_policy_version(id),
  assigned_to_type VARCHAR NOT NULL, -- 'role', 'group', 'department', 'all'
  assigned_to_id UUID,
  due_date TIMESTAMPTZ,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Attestation records (immutable)
CREATE TABLE compliance_policy_attestation (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  policy_version_id UUID NOT NULL REFERENCES compliance_policy_version(id),
  user_id UUID NOT NULL REFERENCES user(id),
  attested_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  ip_address INET,
  user_agent TEXT,
  time_spent_seconds INTEGER,
  digital_signature VARCHAR NOT NULL, -- hash of user+policy+timestamp
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  UNIQUE(policy_version_id, user_id)
);

3.5 Certificates with Lifecycle Management

Purpose

Issue certificates that expire, track renewals, and maintain a complete history for audit purposes.

Requirements

CE-1: Certificate Templates

  • Design certificate templates per program
  • Include: recipient name, program name, completion date, expiration date, certificate ID, QR code for verification
  • Custom fields (CE credits, accreditation body, instructor name)

CE-2: Certificate Issuance

  • Auto-issue upon program completion
  • Manual issue by admin (for external training imported into system)
  • Bulk issue for historical data import

CE-3: Certificate Lifecycle

  • Valid: Currently valid certificate
  • Expiring Soon: Within renewal window
  • Expired: Past expiration date
  • Revoked: Invalidated (with reason and revoked_by)
  • Renewed: Replaced by newer certificate (link to new cert)

CE-4: Certificate Verification

  • Public verification page (for external auditors)
  • QR code on certificate links to verification
  • Shows: valid/invalid/revoked status, original issue details

CE-5: Certificate History

  • Complete chain: Original → Renewal 1 → Renewal 2 → Current
  • Never delete - maintain full history even after revocation

Database Schema

-- Certificate definitions (linked to programs)
CREATE TABLE compliance_certificate_definition (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  program_id UUID NOT NULL REFERENCES compliance_program(id),
  name VARCHAR NOT NULL,
  template_url TEXT NOT NULL, -- S3/MinIO URL to template file
  validity_period_months INTEGER NOT NULL, -- 0 = no expiration
  renewal_window_days INTEGER DEFAULT 30,
  ce_credits DECIMAL(4,2), -- continuing education credits
  accreditation_body VARCHAR,
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

-- Issued certificates
CREATE TABLE compliance_certificate (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  certificate_number VARCHAR UNIQUE NOT NULL, -- human-readable number
  definition_id UUID NOT NULL REFERENCES compliance_certificate_definition(id),
  user_id UUID NOT NULL REFERENCES user(id),
  assignment_id UUID NOT NULL REFERENCES compliance_assignment(id),
  
  -- Certificate data
  issued_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  issued_by UUID NOT NULL REFERENCES profile(id),
  expires_at TIMESTAMPTZ,
  
  -- Certificate file
  certificate_url TEXT NOT NULL,
  certificate_hash TEXT NOT NULL,
  
  -- Lifecycle
  status VARCHAR DEFAULT 'valid', -- 'valid', 'expiring_soon', 'expired', 'revoked', 'renewed'
  revoked_at TIMESTAMPTZ,
  revoked_by UUID REFERENCES profile(id),
  revoke_reason TEXT,
  
  -- Renewal chain
  is_renewal BOOLEAN DEFAULT false,
  previous_certificate_id UUID REFERENCES compliance_certificate(id),
  renewed_by_certificate_id UUID REFERENCES compliance_certificate(id),
  
  -- Verification
  verification_token VARCHAR UNIQUE NOT NULL, -- for public verification URL
  
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

3.6 Compliance Dashboard & Reporting

Purpose

Give compliance officers and managers real-time visibility into organizational compliance posture.

Requirements

CD-1: Organization Compliance Overview

  • Overall compliance rate (% of required training completed on time)
  • Breakdown by: program, department, location, role
  • Risk indicators: overdue count, expiring soon count, non-compliant departments
  • Trend lines: compliance rate over time

CD-2: Program-Level Dashboard

  • Assignment status pie chart (completed, in progress, overdue, not started)
  • Completion rate over time
  • Average time to complete
  • Pass/fail rates for assessments
  • Upcoming due dates calendar view

CD-3: Individual Learner View

  • Complete training history
  • Current assignments and status
  • Certificates earned (with download links)
  • Policy attestations
  • Compliance "score" or rating

CD-4: Alerts & Warnings

  • High-risk situations: "50 people overdue on HIPAA training"
  • Approaching deadlines: "200 certifications expire next month"
  • Completion milestones: "90% of organization completed annual training"

CD-5: Manager Dashboard

  • My team's compliance rate
  • Direct reports' individual status
  • Overdue notifications sent
  • Team comparison to organization average

CD-6: Audit Reports

  • One-click generation of compliance packages
  • Include: training records, certificates, policy attestations, audit log excerpt
  • Tamper-evident (checksums, signed manifest)
  • Date range selection
  • Filter by: program, department, individual

API Endpoints

// Organization compliance overview
GET /compliance/dashboard/overview
  Response: {
    overallComplianceRate: number;
    totalAssignments: number;
    completedOnTime: number;
    completedLate: number;
    overdue: number;
    inProgress: number;
    notStarted: number;
    expiringSoon30Days: number;
    expiringSoon90Days: number;
    byProgram: ProgramComplianceSummary[];
    byDepartment: DepartmentComplianceSummary[];
    trends: { date: string; rate: number }[];
  }

// Program detail dashboard
GET /compliance/dashboard/programs/:programId
  Response: {
    program: ComplianceProgram;
    stats: {
      totalAssigned: number;
      completed: number;
      inProgress: number;
      overdue: number;
      averageCompletionTime: number;
      passRate: number;
    };
    statusBreakdown: { status: string; count: number; percentage: number }[];
    upcomingDueDates: { date: string; count: number }[];
    recentCompletions: AssignmentSummary[];
    atRiskLearners: AssignmentSummary[]; -- overdue or due soon
  }

// Generate audit report
POST /compliance/reports/audit-package
  Body: {
    title: string;
    dateRange: { start: string; end: string };
    filters: {
      programs?: string[];
      departments?: string[];
      users?: string[];
    };
    include: {
      trainingRecords: boolean;
      certificates: boolean;
      policyAttestations: boolean;
      auditLog: boolean;
    };
  }
  Response: {
    reportId: string;
    status: 'generating' | 'ready' | 'failed';
    downloadUrl?: string;
    expiresAt?: string;
    manifest: {
      generatedAt: string;
      generatedBy: string;
      recordCounts: Record<string, number>;
      checksums: Record<string, string>;
    };
  }

// Learner compliance profile
GET /compliance/learners/:userId/profile
  Response: {
    user: UserSummary;
    currentAssignments: AssignmentDetails[];
    completedPrograms: CompletedProgram[];
    certificates: CertificateSummary[];
    policyAttestations: AttestationSummary[];
    complianceScore: number;
    riskLevel: 'low' | 'medium' | 'high';
  }

3.7 Audit Trail & Evidence

Purpose

Provide immutable, tamper-evident records of all compliance-related activities for auditor review.

Requirements

AT-1: Comprehensive Event Logging Log every compliance-relevant action:

  • Program created, modified, archived
  • Assignment created, completed, waived, expired
  • Certificate issued, revoked, renewed
  • Policy published, attested
  • Notification sent, opened, clicked
  • Report generated, downloaded
  • Admin actions (bulk operations, settings changes)

AT-2: Log Entry Content

  • Timestamp (UTC, millisecond precision)
  • Actor (user ID, role, email)
  • Action type and description
  • Affected resources (program, assignment, user)
  • Before/after values for changes
  • IP address and user agent
  • Session ID

AT-3: Audit Log Characteristics

  • Append-only (no modifications allowed)
  • Retained for 7+ years (configurable)
  • Exportable to CSV/JSON/PDF
  • Full-text searchable
  • Filterable by: date range, actor, action type, resource

AT-4: Evidence Integrity

  • Cryptographic hash chain linking entries
  • Regular integrity verification reports
  • Tamper detection alerts

Database Schema

-- Audit event log (append-only)
CREATE TABLE compliance_audit_event (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  organization_id UUID NOT NULL REFERENCES organization(id),
  timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW(),
  
  -- Actor
  actor_id UUID REFERENCES user(id),
  actor_email VARCHAR,
  actor_role VARCHAR,
  
  -- Action
  action_category VARCHAR NOT NULL, -- 'program', 'assignment', 'certificate', 'policy', 'report', 'admin'
  action_type VARCHAR NOT NULL, -- 'created', 'updated', 'completed', 'revoked', etc.
  action_description TEXT,
  
  -- Resources
  resource_type VARCHAR, -- 'program', 'assignment', 'user', 'certificate'
  resource_id UUID,
  resource_name VARCHAR,
  
  -- Details
  changes JSONB, -- { field: { from: x, to: y } }
  metadata JSONB, -- additional context
  
  -- Context
  ip_address INET,
  user_agent TEXT,
  session_id UUID,
  
  -- Integrity
  previous_hash VARCHAR,
  entry_hash VARCHAR NOT NULL, -- hash of this entry including previous_hash
  
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_audit_org_time ON compliance_audit_event(organization_id, timestamp DESC);
CREATE INDEX idx_audit_action ON compliance_audit_event(action_category, action_type);
CREATE INDEX idx_audit_resource ON compliance_audit_event(resource_type, resource_id);
CREATE INDEX idx_audit_actor ON compliance_audit_event(actor_id);

4. User Experience Flows

4.1 Compliance Officer Journey

1. Create Compliance Program
   ↓
2. Add Content (courses, assessments)
   ↓
3. Set Assignment Rules (who needs to complete)
   ↓
4. Configure Schedule & Reminders
   ↓
5. Launch Program → System auto-assigns to users
   ↓
6. Monitor Dashboard → See completion rates, overdue alerts
   ↓
7. Send Reminders / Escalate / Waive as needed
   ↓
8. Generate Audit Report → Export for auditor

4.2 Employee (Learner) Journey

1. Receive Email: "New Required Training: HIPAA Compliance"
   ↓
2. Click Link → Login (if needed) → Go to "My Compliance" dashboard
   ↓
3. See: List of assigned programs with due dates
   ↓
4. Click Program → Start Training
   ↓
5. Complete Courses/Assessments
   ↓
6. Receive Certificate + Confirmation Email
   ↓
7. Certificate stored in "My Certificates" for future reference

4.3 Manager Journey

1. Weekly Email Digest: "Your Team's Compliance Status"
   ↓
2. Click to Manager Dashboard
   ↓
3. See: Team compliance rate, who's overdue, who's due soon
   ↓
4. Drill into individual → See their assignments
   ↓
5. Send reminder to specific team member
   ↓
6. Get notified when team member completes overdue training

4.4 Auditor Journey

1. Compliance officer generates "Audit Package" 
   ↓
2. Secure download link sent to auditor (time-limited)
   ↓
3. OR: Auditor given time-limited read-only portal access
   ↓
4. Auditor views/downloads:
      - Training completion records
      - Certificates with verification
      - Policy attestations
      - Activity audit log
   ↓
5. All auditor activity is itself logged

5. Implementation Roadmap

Phase 1: Core Assignment & Tracking (Weeks 1-6)

Goal: Basic compliance program delivery

Task Duration Deliverable
Compliance program data model 3 days Database schema
Program CRUD API 4 days Backend endpoints
Assignment engine 5 days Auto-assignment logic
Basic compliance dashboard 5 days Compliance overview UI
"My Compliance" learner view 4 days Learner dashboard
Assignment tracking 4 days Progress tracking UI
Milestone Companies can assign and track compliance training

Phase 2: Notifications & Reminders (Weeks 7-10)

Goal: Automated follow-up without manual work

Task Duration Deliverable
Notification template system 3 days Template CRUD API/UI
Reminder scheduling engine 4 days Background job processor
Email delivery & tracking 3 days Sendgrid/SES integration
Manager notifications 3 days Manager digest & alerts
Escalation workflows 4 days Multi-level escalation
Milestone Fully automated reminder system

Phase 3: Certificates & Renewals (Weeks 11-14)

Goal: Complete certification lifecycle

Task Duration Deliverable
Certificate templates 3 days Template designer
Certificate generation 3 days PDF generation
Certificate lifecycle mgmt 4 days Expire, revoke, renew
Recurring assignment engine 4 days Auto-renewal logic
Expiration dashboard 3 days Renewals view
Milestone Automated renewal cycles

Phase 4: Policy Attestation (Weeks 15-18)

Goal: Policy acknowledgment tracking

Task Duration Deliverable
Policy document management 3 days Policy CRUD
Document viewer with tracking 4 days Time-on-page tracking
Attestation workflow 3 days Sign/acknowledge flow
Attestation dashboard 3 days Who's attested view
Milestone Policy attestation system

Phase 5: Reporting & Audit (Weeks 19-24)

Goal: Audit-ready evidence and reporting

Task Duration Deliverable
Audit event logging 4 days Event capture system
Audit log viewer & export 4 days Log UI
Advanced dashboards 5 days Drill-down reports
Audit package generator 5 days One-click export
Auditor portal (read-only) 5 days External auditor access
Milestone Full audit readiness

Phase 6: Integrations & Scale (Weeks 25-30)

Goal: Enterprise integrations

Task Duration Deliverable
HRIS integration (Workday, BambooHR) 2 weeks User sync
SCIM provisioning 1 week Automated user lifecycle
Advanced analytics 1 week Trend analysis, predictions
API for external systems 1 week Public API endpoints
Milestone Enterprise-ready platform

6. Technical Architecture

New API Routes

/compliance/programs              # CRUD for compliance programs
/compliance/assignments           # Assignment management
/compliance/assignments/:id/progress  # Track learner progress
/compliance/certificates          # Certificate lifecycle
/compliance/policies              # Policy document management
/compliance/attestations          # Policy acknowledgment
/compliance/dashboard             # Dashboard data
/compliance/reports               # Report generation
/compliance/audit-events          # Audit log access
/compliance/notifications         # Notification management
/compliance/settings              # Organization compliance settings

Background Jobs

assignment-processor      # Create assignments based on rules
reminder-scheduler        # Queue upcoming reminders
notification-sender       # Send emails/SMS
expiration-checker        # Mark expired certifications
renewal-processor         # Create renewal assignments
report-generator          # Generate large audit reports
audit-archiver            # Archive old audit logs

Frontend Features

apps/dashboard/src/lib/features/compliance/
  pages/
    programs-list.svelte
    program-editor.svelte
    assignments.svelte
    dashboard.svelte
    reports.svelte
    audit-log.svelte
    settings.svelte
  components/
    program-card.svelte
    assignment-status-badge.svelte
    compliance-chart.svelte
    notification-template-editor.svelte
    certificate-viewer.svelte
    policy-uploader.svelte
    attestation-flow.svelte
  api/
    compliance.svelte.ts
  utils/
    types.ts
    constants.ts

7. Success Metrics

Product Metrics

Metric Target Measurement
Time to create compliance program < 30 minutes User testing
Time to assign training to 1000 people < 5 minutes Performance test
Training completion rate > 90% Dashboard tracking
Automated reminder open rate > 60% Email analytics
Time to generate audit report < 2 minutes Performance test

Business Metrics

Metric Target
Compliance-focused customer acquisition 10 new customers in 6 months
Compliance feature NPS > 50
Customer retention (compliance segment) > 95%
Expansion revenue from compliance add-on 20% of ARR

8. Competitive Differentiation

Feature ClassroomIO Competitors (LMS) Compliance Tools
Course creation quality ✅ Strong ✅ Strong ❌ Weak
Compliance-specific features 🆕 Building ⚠️ Limited ✅ Strong
Price 💰 Affordable 💰💰 Expensive 💰💰💰 Very expensive
Open Source ✅ Yes ❌ No ❌ No
Self-hosted option ✅ Yes ⚠️ Limited ❌ Rare
Ease of use ✅ Simple ⚠️ Complex ❌ Complex

Positioning: "The compliance training platform that doesn't suck - powerful enough for enterprise compliance, simple enough for anyone to use."


9. Open Questions

  1. Should we offer pre-built compliance program templates (e.g., "HIPAA Basics")?
  2. Do we need integration with third-party course libraries (Skillsoft, LinkedIn Learning)?
  3. Should we support instructor-led training tracking (ILT) or self-paced only?
  4. How important is mobile app support for field workers?
  5. Do we need e-signature integration (DocuSign) for high-stakes certifications?
  6. Should we build a marketplace for compliance content creators?

10. Next Steps

  1. Validate this PRD with 3-5 compliance officers at target companies
  2. Prioritize Phase 1 features for immediate development
  3. Design the compliance dashboard UI mockups
  4. Prototype the program creation wizard
  5. Plan data migration strategy for existing ClassroomIO courses