---
agentTools:
  projectIndex: https://regscale.readme.io/llms.txt
---

# Questionnaire Overview

# RegScale Questionnaire System - Overview

## Executive Summary

The RegScale Questionnaire System is an enterprise-grade data collection and assessment platform designed for compliance, risk management, and attestation workflows. It provides dynamic question rendering, conditional logic via a powerful rule engine, automated scoring, flexible assignment options, and comprehensive workflow integrations.

## Table of Contents

1. [Core Concepts](#core-concepts)
2. [Assignment Options](#assignment-options)
3. [Scoring System](#scoring-system)
4. [Rule Engine](#rule-engine)
5. [Workflow & States](#workflow--states)
6. [Question Types](#question-types)
7. [Key Features](#key-features)
8. [Technical Architecture](#technical-architecture)

***

## Core Concepts

### Questionnaires vs. Instances

**Questionnaire (Template)**

* The master template containing questions, rules, and configuration
* Reusable across multiple assignments
* Defines structure, scoring rules, and conditional logic
* Stored in `Questionnaires` table

**Questionnaire Instance (Response)**

* A specific assignment of a questionnaire to one or more users
* Contains actual responses and completion data
* Tracks workflow state (Open → Submitted → Accepted/Rejected)
* Stored in `QuestionnaireInstances` table

### Questions

Individual questions within a questionnaire with properties:

* **QUID**: Unique question identifier within the questionnaire
* **Prompt**: The question text displayed to users
* **Question Type**: Text, Number, Date, Dropdown, Table, etc.
* **Section**: Organizational grouping
* **Required**: Validation flag
* **Scoring**: Max score and answer option scores
* **Conditional**: Can be shown/hidden by rules

***

## Assignment Options

The questionnaire system supports multiple assignment mechanisms to accommodate different use cases:

### 1. User-Based Assignment

Assign to internal users within your RegScale tenant.

**Features:**

* Select multiple assignees from user directory
* Each assignee receives email notification with unique link
* Supports per-user tracking and completion monitoring
* Assignee dashboard shows pending questionnaires

**Use Case:** Internal compliance surveys, employee attestations

### 2. Email-Based Assignment

Send questionnaires to external email addresses.

**Features:**

* Comma-separated email list support
* External users don't need RegScale accounts
* Optional: Require login or use access code only
* 9-digit access codes for security
* Bulk assignment via Excel upload

**Use Case:** Vendor assessments, external audits, customer feedback

### 3. Module-Based Assignment

Link questionnaires to specific records in other modules.

**Features:**

* Attach to assets, risks, controls, or any module record
* Contextual questionnaires tied to parent record
* Multiple questionnaires per parent record
* Accessible from parent record's subsystems tab

**Use Case:** Asset-specific assessments, risk evaluations, control testing

### 4. Self-Assignment (Public URLs)

Allow users to self-assign questionnaires via public link.

**Features:**

* Enable with `AllowPublicUrl` setting
* Public URL: `/questionnaires/response/{UUID}`
* Optional login requirement
* Access code protection for anonymous users
* Anonymous response tracking

**Use Case:** Public surveys, registration forms, self-service assessments

### 5. Recurring Assignments

Automate questionnaire delivery on a schedule.

**Features:**

* Recurrence patterns: Weekly, Monthly, Quarterly, Yearly
* Define start and end dates
* Automatic instance creation
* Email notifications on each occurrence
* Tracks last sent date

**Use Case:** Periodic compliance reviews, quarterly attestations, monthly check-ins

### 6. Bulk Assignment via Excel

Upload an Excel file to assign to multiple users at once.

**Excel Format:**

* Column A: Assignee email (required)
* Column B: Reviewer emails, comma-separated (optional)
* Column C: Due date (optional)
* Column D: Title override (optional)

**Features:**

* Mass distribution to hundreds/thousands of users
* Per-row customization (different reviewers, due dates)
* Validation and error reporting

**Use Case:** Organization-wide surveys, department-specific assessments

### Per-Question Assignment

Beyond instance-level assignment, you can assign specific questions to specific users.

**Features:**

* Enable with `EnableQuestionAssignment` setting
* Assign individual questions to different users
* `LimitQuestionAssigneesToAssignedQuestions`: Restrict users to only their questions
* Collaborative questionnaires with distributed responsibility

**Use Case:** Multi-stakeholder assessments where different teams answer different sections

***

## Scoring System

The questionnaire system supports sophisticated scoring mechanisms at both question and instance levels.

### Question-Level Scoring

#### Multiple Choice / Dropdown Questions

Each answer option has an associated score:

```json
{
  "StaticAnswerOptions": [
    { "AnswerOption": "Excellent", "AnswerScore": 10 },
    { "AnswerOption": "Good", "AnswerScore": 7 },
    { "AnswerOption": "Fair", "AnswerScore": 4 },
    { "AnswerOption": "Poor", "AnswerScore": 0 }
  ]
}
```

**Scoring:** Response score = selected option's score

#### Checkbox Questions (Multi-Select)

Sum of all selected options' scores.

**Example:**

* Select "Option A (10)" + "Option B (5)" = 15 points total

#### Table Questions

Complex scoring based on column configuration:

* Each column can have a base score
* Dropdown columns use option-specific scores
* Total score = sum of all filled cells with scoring
* Row-level aggregation

#### Manual Scoring

The `ResponseScore` field can be manually set to override calculated scores, useful for subjective assessments or grading by reviewers.

### Instance-Level Scoring

**Calculation Process:**

1. Calculate individual question scores
2. Set `CalculatedScore` for each question
3. If `ResponseScore` is empty, use `CalculatedScore`
4. Sum all question scores (excluding Instructional questions)
5. Store total in instance's `Score` field

**Max Scores:**

* Each question defines `MaxScore` (maximum possible points)
* Used to calculate percentage: (Score / MaxScore) × 100
* Displayed as progress indicators

### Grading

Beyond numeric scores, questionnaires support letter grades or pass/fail results:

* **Grade Field**: String value (e.g., "Pass", "Fail", "A", "B", "C")
* **Manual Grading**: Reviewers can set grades manually
* **Rule-Based Grading**: Rules can automatically set grades based on score thresholds
* **Display Options**: Can be shown/hidden via rule actions

**Example Grade Rules:**

* Score ≥ 90: Set grade to "A"
* Score ≥ 80: Set grade to "B"
* Score ≥ 70: Set grade to "C"
* Score < 60: Set grade to "Fail"

### Enabling Scoring

Set `EnableScoring = true` on the questionnaire template to activate scoring features. Rules can further control display with:

```
SETDISPLAYOPTIONS('displayscore=true')
```

***

## Rule Engine

The questionnaire rule engine is a **visual authoring tool** for creating conditional logic without coding. It enables dynamic questionnaires that adapt based on user responses.

### What Rules Can Do

Rules consist of **Conditions** (WHEN) and **Actions** (WHAT):

**Example Business Logic:**

* "If user selects 'Yes' for PII collection, show additional PII handling questions"
* "If risk level is 'High', add 10 points to the score"
* "If total score exceeds 75, set grade to 'Pass'"
* "If no parent record exists, hide compliance-specific questions"

### Rule Components

#### Conditions (WHEN to Execute)

**Condition Types:**

1. **QUESTION-based**
   * Check question responses: `@QUID.response == 'Yes'`
   * Check question properties: `@QUID.required == true`
   * Operators: Equals, Contains, Greater Than, Less Than, etc.

2. **SCORE-based**
   * Check current total score: `@__SCORE__ > 75`
   * Thresholds for grading

3. **GRADE-based**
   * Check assigned grade: `@__GRADE__ == 'Pass'`

4. **SYSTEM-based**
   * `NO_PARENT`: Check if no parent record exists
   * `NO_CONDITION`: Always execute (unconditional actions)

**Conditional Logic:**

* **AND**: All conditions must be true
* **OR**: Any condition can be true

**Supported Operators:**

* Comparison: `EQUALS`, `NOT_EQUALS`, `LESS_THAN`, `GREATER_THAN`
* String: `CONTAINS`, `NOT_CONTAINS`, `STARTS_WITH`, `ENDS_WITH`
* List: `IN`, `NOT_IN`
* Null: `IS_EMPTY`, `IS_NOT_EMPTY`
* Date: `BEFORE`, `AFTER`, `WITHIN_LAST`, `WITHIN_NEXT`, `BETWEEN`

#### Actions (WHAT to Do)

**Available Actions:**

1. **SHOW\_QUESTIONS** - Make questions visible
2. **HIDE\_QUESTIONS** - Make questions invisible (skip validation)
3. **ENABLE\_QUESTIONS** - Make questions editable
4. **DISABLE\_QUESTIONS** - Make questions read-only
5. **SET\_ANSWER** - Auto-populate question response
6. **CLEAR\_ANSWER** - Remove question responses
7. **SET\_SCORE** - Set total score to specific value
8. **ADD\_TO\_SCORE** - Add/subtract from current score
9. **CALCULATE\_TOTAL\_SCORE** - Calculate score from all responses
10. **SET\_GRADE** - Set questionnaire grade
11. **REPEAT\_QUESTIONS** - Dynamically repeat question sets
12. **SET\_DISPLAY\_OPTIONS** - Control display of score/grade

### Visual Rule Builder

The rule builder provides a drag-and-drop interface:

**Features:**

* Visual condition builder with dropdowns for questions, operators, values
* Multiple conditions with AND/OR logic
* Multiple actions per rule
* Rule ordering and prioritization
* Inline validation with real-time error highlighting
* Test mode with execution simulation

**Storage Format:**

* Database: Newline-delimited JSON (one rule per line)
* UI: Structured TypeScript objects with UUIDs

### Test Mode

Before deploying rules, use **Test Mode** to simulate execution:

**Features:**

* Render all questions with input controls
* Execute rules with sample test data
* Display detailed execution log:
  * Which rules executed vs. skipped
  * Which conditions matched (✓/✗)
  * Which actions fired
  * Final question state (visible/hidden, enabled/disabled)
  * Final score and grade

**Example Output:**

```
✅ Rule "Show PII Questions" EXECUTED
   ✓ Condition: "PII Collected" equals "Yes" (Answer: "Yes")
   ✓ Action: Showed 3 questions (PII_TYPE, PII_STORAGE, PII_ENCRYPTION)

⏭️ Rule "High Risk Bonus" SKIPPED
   ✗ Condition: "Risk Level" equals "High" (Answer: "Medium")

✅ Rule "Calculate Final Score" EXECUTED
   ✓ Condition: NO_CONDITION (always true)
   ✓ Action: Calculated total score = 85
   ✓ Action: Set grade to "Pass"
```

### Validation System

The rule engine validates rules in real-time:

**Validation Rules:**

* Rule name required
* At least one condition required
* At least one action required
* Referenced questions must exist in questionnaire
* Operators must match question types (e.g., numeric operators for number questions)
* Values required for most operators (except `IS_EMPTY`)
* Circular dependency detection

**UI Feedback:**

* Red borders on invalid fields
* Error badges on rule cards
* Validation summary modal before save
* Tooltips with specific error details

### Rule Execution

Rules execute in the Angular frontend during questionnaire response:

**Execution Flow:**

1. User loads questionnaire instance
2. System parses rules from database (newline-delimited JSON → `Rule[]`)
3. Rules execute in defined order
4. For each rule:
   * Evaluate conditions by replacing variable references with actual values
   * If all conditions pass, execute actions
   * Apply UI changes (show/hide, set values, calculate scores)
5. Re-evaluate rules when question responses change

**Performance Optimization:**

* Execution constraints: `RESPONSECHANGE('QUID')` - only re-run rule when specific question changes
* Prevents unnecessary computation on every keystroke

### Documentation

For detailed technical information, see:

* **User Guide**: `questionnaire-rules-user-guide.md`
* **Technical Guide**: `questionnaire-rule-builder-technical-guide.md`

***

## Workflow & States

Questionnaire instances progress through a multi-state workflow enabling submit/review/approval cycles.

### Instance States

1. **Open** - Initial state after assignment
   * Assignee can edit responses
   * Auto-saves as user progresses
   * Can submit for review when complete

2. **Submitted** - Assignee submitted for review
   * Read-only for assignee
   * Reviewer receives notification
   * Awaiting reviewer action

3. **Accepted** - Reviewer approved
   * Questionnaire complete
   * Historical snapshot saved
   * Can be closed or archived

4. **RequestChanges** - Reviewer rejected
   * Feedback provided to assignee
   * Assignee receives notification with comments
   * Can reopen for editing

5. **Closed** - Final archived state
   * Locked from editing
   * Permanent record

### State Transition Flow

```
Created
   ↓
  Open ←──────────────────┐
   ↓                      │
Submitted                 │
   ↓                      │
Accepted or RequestChanges │
   │                      │
   └──────────────────────┘ (reopen)
   ↓
 Closed
```

### Reviewer Workflow

**Current State:** Single reviewer per instance

* Reviewer receives email when questionnaire is submitted
* Can approve (`Accepted`) or reject (`RequestChanges`)
* Can provide feedback/comments to assignee
* Feedback triggers email notification to assignee

**Planned Enhancement:** Multiple reviewers

* Any reviewer can approve/reject ("First Approval Wins")
* Documented in `multiple-questionnaire-reviewers-implementation-plan.md`

### History Tracking

**Automatic Snapshots:**

* When instance transitions to `Submitted`
* When instance transitions to `Accepted`
* Stores full copy of all responses (`JsonData`)

**QuestionnaireHistoryEntry Table:**

* `QuestionnaireInstanceId` - Links to instance
* `JsonData` - Complete response snapshot
* `Discriminator` - State when snapshot taken
* Audit fields (CreatedBy, DateCreated)

**Use Cases:**

* Audit trail for compliance
* Version history for change tracking
* Rollback capability
* Before/after comparison

### Email Notifications

**Notification Types:**

1. **Assignment Notification**
   * Sent to assignees when instance created
   * Contains unique response link
   * Includes due date, title, instructions

2. **Reviewer Notification**
   * Sent to reviewer when submitted
   * Contains review link
   * Shows assignee name, completion date

3. **Feedback Email**
   * Sent to assignees when reviewer provides feedback
   * Contains reviewer comments
   * Link to view feedback and resubmit

4. **Reopen Notification**
   * Sent when instance is reopened
   * Notifies assignee to resume work

5. **Reminder Emails** (if configured)
   * Approaching due date notifications
   * Overdue notifications

### Completion Tracking

**Calculation:**

* Count required questions that are visible (not hidden by rules)
* Count answered required questions
* Special handling for table questions:
  * If table has required columns, count filled required cells
  * If table is required but has no required columns, count if any cell is filled
* Formula: `PercentComplete = (answered / total) × 100`

**Display:**

* Progress bar on instance view
* Percentage indicator
* Blocks submission until 100% complete (configurable)

***

## Question Types

The questionnaire system supports diverse question types for comprehensive data collection:

### 1. Text

* Free-form text input
* Multi-line support
* No validation constraints

**Use Case:** Comments, descriptions, explanations

### 2. Number

* Numeric input with validation
* Decimal support
* Min/max constraints (optional)

**Use Case:** Counts, measurements, percentages

### 3. Date

* Date picker control
* Validates date format
* Can set min/max date ranges

**Use Case:** Start dates, end dates, deadlines

### 4. Email

* Email format validation
* Single email address

**Use Case:** Contact information, email collection

### 5. PhoneNumber

* Phone number format validation
* International format support

**Use Case:** Contact numbers, emergency contacts

### 6. MultipleChoice (Radio Buttons)

* Single selection from predefined options
* `StaticAnswerOptions` with scores
* Visual radio button group

**Use Case:** Yes/No questions, single-choice selections, ratings

### 7. CheckBoxes (Multi-Select)

* Multiple selections allowed
* Each option has independent score
* Sum of selected option scores

**Use Case:** "Select all that apply", feature selections, multi-category

### 8. Dropdown (Select)

* Single selection from dropdown menu
* Space-efficient for many options
* `StaticAnswerOptions` with scores

**Use Case:** State/country selection, category selection, status

### 9. Table

* Dynamic grid for structured data
* Configurable columns via `TableConfig`
* Column types: Text, Number, Date, Dropdown
* Row-level add/delete
* Column-level scoring
* Required column validation

**Table Configuration:**

```json
{
  "TableColumns": [
    {
      "Title": "System Name",
      "DataType": "text",
      "Required": true,
      "Score": 0
    },
    {
      "Title": "Risk Level",
      "DataType": "dropdown",
      "Required": true,
      "Score": 5,
      "DropdownOptions": [
        { "Value": "High", "Score": 10 },
        { "Value": "Medium", "Score": 5 },
        { "Value": "Low", "Score": 2 }
      ]
    },
    {
      "Title": "Last Assessment",
      "DataType": "date",
      "Required": false,
      "Score": 0
    }
  ]
}
```

**Use Case:** Asset inventories, system lists, multi-row data collection

### 10. Instructional

* Display-only content
* No response collected
* No validation required
* Supports rich text/HTML

**Use Case:** Instructions, section headers, guidance text, warnings

***

## Key Features

### 1. Section Management

Organize questions into logical sections:

* Visual section dividers
* Section-based navigation
* Collapsible sections
* Section ordering via `SectionIndex`

**Benefits:**

* Improved user experience for long questionnaires
* Logical grouping of related questions
* Easier navigation and progress tracking

### 2. Control Mappings

Link questions to security control frameworks:

**Features:**

* Map questions to NIST 800-53, ISO 27001, CIS, etc.
* Junction table: `questionControl`
* Stores control family, ID, title
* Responses automatically linked as control evidence

**Use Cases:**

* Compliance assessments tied to controls
* Automated evidence collection
* Control effectiveness testing
* Audit preparation

**Storage:**

* Responses saved as `Properties` records
* `SecondaryId` = Security Control ID
* `SecondaryModule` = "security-controls"
* Accessible from control's evidence tab

### 3. Properties Storage (Dual Model)

Questionnaire responses are stored in two formats:

**1. JsonData (Structured)**

* Full question/response structure stored in instance
* Preserves question metadata, sections, ordering
* Used for display and editing

**2. Properties Table (Flattened)**

* Key/value pairs for each question/answer
* Enables cross-module search and reporting
* Report Builder integration

**Properties Structure:**

```
ParentId: QuestionnaireInstance.Id
ParentModule: "questionnaireinstances"
Key: Question.QUID
Value: Question.Response
Label: Question.Prompt
SecondaryId: SecurityControlId (if mapped)
SecondaryModule: "security-controls"
```

### 4. Anonymous Access

Enable public questionnaires without login requirements:

**Configuration:**

* `LoginRequired = false` on questionnaire
* `AllowPublicUrl = true` enables self-assignment
* 9-digit random access codes

**Security:**

* Unique access code per instance
* Code required for anonymous users
* Audit logging of access attempts
* Optional: Still require login for authenticated tracking

**Flow:**

1. User visits `/questionnaires/response/{UUID}`
2. If not authenticated and `LoginRequired = false`, prompt for access code
3. Validate access code matches instance
4. Allow questionnaire response
5. Save responses anonymously (or to authenticated user if logged in)

**Use Cases:**

* Public surveys
* Customer feedback forms
* Vendor self-assessments
* Registration forms

### 5. Import/Export Capabilities

#### Import (Upload)

Upload questionnaire templates via Excel:

**Service:** `ParseUploadedQuestionnaire()`

**Excel Format:**

* Columns: Question Text, Section, Question Type, Required, Answer Options, etc.
* Creates questionnaire + all questions in single operation
* Validates question types and configurations

**Use Case:** Bulk questionnaire creation from existing surveys, templates, or legacy systems

#### Export

**Export Types:**

1. **Questionnaire Template Export**
   * Excel format with all questions
   * Includes configuration, scoring, sections

2. **Single Response Export**
   * Individual instance with responses
   * Formatted for readability

3. **Bulk Response Export**
   * Multiple instances in one workbook
   * One sheet per instance or consolidated view

4. **All Responses Export**
   * All instances for a questionnaire
   * Comparative analysis format

**Format:** Excel (.xlsx) using SyncFusion libraries

**Features:**

* Question/answer pairs
* Metadata (assignee, reviewer, dates, score, grade)
* Section organization
* Professional formatting

### 6. Metadata Headers

Custom metadata fields beyond questions:

**QuestionnaireHeader Entity:**

* Define custom fields for instances
* Field types: Text, User, Dropdown
* Dropdown options configurable
* Stored in `HeaderValuesJson` on instance

**Use Cases:**

* Project codes
* Department identifiers
* Custom categorization
* Additional context not part of questionnaire questions

**Example:**

```json
[
  { "Title": "Project Code", "HeaderType": "text" },
  { "Title": "Department", "HeaderType": "dropdown", "DropdownOptions": ["IT", "Finance", "HR"] },
  { "Title": "Approver", "HeaderType": "user" }
]
```

### 7. Recurring Assignments

Automate questionnaire delivery on schedules:

**QuestionnaireRecurringAssignment Table:**

* `QuestionnaireId` - Template to deliver
* `Email` - Recipient address
* `StartDate`, `EndDate` - Active period
* `Recurrence` - Weekly, Monthly, Quarterly, Yearly
* `LastSent` - Tracks last execution

**Automation:**

* Background job checks for due recurring assignments
* Creates new instance automatically
* Sends assignment email to recipient
* Updates `LastSent` timestamp

**Use Cases:**

* Quarterly compliance attestations
* Monthly security reviews
* Annual employee surveys
* Weekly status reports

### 8. Report Builder Integration

Questionnaire data is accessible in Report Builder via the **QuestionnaireResponseEntity**:

**Features:**

* Virtual entity joining Properties, Instances, Questionnaires
* Flattened structure for reporting
* Filter by questionnaire, assignee, date range, score, grade
* Aggregate functions (count, average score, etc.)

**Use Cases:**

* Compliance dashboards
* Trend analysis over time
* Comparative reports (department, location, etc.)
* Score distribution charts

***

## Technical Architecture

### Backend (C# .NET)

**Controllers:**

* `QuestionnairesController` - Template CRUD and operations
* `QuestionnaireInstancesController` - Instance CRUD and workflow

**Services:**

* `QuestionnaireService` - Business logic, assignment, email
* `QuestionnaireScoreCalculationService` - Scoring algorithms
* `QuestionnaireExportService` - Excel export functionality

**Entities:**

* `Questionnaires` - Templates
* `QuestionnaireInstances` - Responses
* `Question` - Questions within templates
* `QuestionnaireInstanceAssignee` - Many-to-many assignees
* `QuestionAssignee` - Per-question assignments
* `QuestionnaireHistoryEntry` - Historical snapshots
* `QuestionnaireRecurringAssignment` - Scheduled delivery
* `QuestionnaireHeader` - Metadata fields
* `questionControl` - Control mappings

**Patterns:**

* Repository pattern for data access
* Service layer for business logic
* Multi-tenancy with tenant isolation
* Soft delete (IsDeleted flag)
* Audit trails (CreatedBy, UpdatedBy, DateCreated, DateLastUpdated)

### Frontend (Angular)

**Components:**

* `questionnaire-builder` - Template builder interface
* `questionnaire-rule-builder` - Visual rule editor
* `questionnaire-response` - Response interface (rule execution)
* `questionnaire-unified` - Combined response/review interface
* `questionnaire-assignments` - Assignment management
* `questionnaire-self-assign` - Self-assignment form

**Services:**

* `questionnaire.service.ts` - API client for templates
* `questionnaireInstance.service.ts` - API client for instances
* `questionnaire-rule.service.ts` - Rule conversion, validation, execution
* `questionnaireOptions.service.ts` - Metadata and options

**Rule Execution:**

* Client-side execution in Angular
* Real-time evaluation as user responds
* JavaScript eval (sandboxed) for condition evaluation
* DOM manipulation for show/hide actions

### API Endpoints

**Questionnaires:**

* `GET /api/questionnaires/getList` - List templates
* `GET /api/questionnaires/{id}` - Get template
* `POST /api/questionnaires/create` - Create template
* `PUT /api/questionnaires/{id}` - Update template
* `DELETE /api/questionnaires/{id}` - Delete template
* `POST /api/questionnaires/bulkUpdate/{id}` - Update sections/questions
* `POST /api/questionnaires/createInstancesFromQuestionnaires` \[v2.0] - Create instances
* `POST /api/questionnaires/selfAssignQuestionnaire` - Self-assignment
* `POST /api/questionnaires/createRecurringAssignment` - Create schedule
* `POST /api/questionnaires/upload` - Upload Excel template
* `POST /api/questionnaires/uploadBulkEmailAssignment/{id}` - Bulk assign via Excel
* `GET /api/questionnaires/exportQuestionnaire/{id}` - Export template
* `GET /api/questionnaires/exportAllResponses/{id}` - Export all responses

**Instances:**

* `GET /api/questionnaireInstances/{id}` - Get instance
* `POST /api/questionnaireInstances` \[v2.0] - Create instance
* `PUT /api/questionnaireInstances/{id}` - Update instance
* `DELETE /api/questionnaireInstances/{id}` - Delete instance
* `POST /api/questionnaireInstances/filterQuestionnaireInstances` - List/search
* `GET /api/questionnaireInstances/getAllByParent/{id}` - Instances for template
* `POST /api/questionnaireInstances/link` - Get instance for response
* `PUT /api/questionnaireInstances/updateResponses/{uuid}` - Save responses
* `PUT /api/questionnaireInstances/submitForFeedback/{uuid}` - Submit for review
* `PUT /api/questionnaireInstances/changeStateAccepted/{uuid}` - Approve
* `PUT /api/questionnaireInstances/changeStateRejected/{uuid}` - Reject
* `PUT /api/questionnaireInstances/reopenInstance/{uuid}` - Reopen
* `GET /api/questionnaireInstances/history/{id}` - Get history entries
* `POST /api/questionnaireInstances/assignQuestions/{id}` - Assign questions to users

### Database Schema

**Key Tables:**

* `Questionnaires` - Templates with Rules, Sections JSON
* `QuestionnaireInstances` - Responses with JsonData, Score, Grade
* `Question` - Questions with QUID, QuestionType, StaticAnswerOptions JSON
* `QuestionnaireInstanceAssignee` - Junction table for multiple assignees
* `QuestionAssignee` - Per-question user assignments
* `QuestionnaireHistoryEntry` - Historical snapshots
* `QuestionnaireRecurringAssignment` - Scheduled delivery configuration
* `QuestionnaireHeader` - Metadata field definitions
* `questionControl` - Question to security control mappings
* `Properties` - Flattened key/value storage for reporting

**Indexes:**

* `QuestionnaireInstances.ParentQuestionnaireId` - Fast instance lookup
* `Question.ParentQuestionnaireId` - Fast question lookup
* `Properties.ParentId`, `Properties.ParentModule` - Fast property lookup
* Tenant isolation via `TenantsId` on all entities

***

## Related Documentation

* **`questionnaire-rule-builder-technical-guide.md`** - Comprehensive technical guide for rule builder architecture
* **`questionnaire-rules-user-guide.md`** - End-user guide for creating and testing rules
* **`multiple-questionnaire-reviewers-implementation-plan.md`** - Plan for multiple reviewer support
* **Module Configuration:**
  * `atlas/Launcher/Seed/ModuleData/questionnaire.json` - Template module config
  * `atlas/Launcher/Seed/ModuleData/questionnaireInstances.json` - Response module config

***

## Summary

The RegScale Questionnaire System is a production-ready, enterprise-grade solution offering:

**Flexibility:**

* 10 question types including dynamic tables
* Multiple assignment mechanisms (user, email, module, self-assignment, recurring, bulk)
* Granular per-question assignments
* Anonymous and authenticated access

**Intelligence:**

* Visual rule builder with 12 action types
* Conditional logic (show/hide, enable/disable, auto-populate)
* Automated scoring and grading
* Test mode for rule validation

**Workflow:**

* Multi-state workflow (Open → Submitted → Accepted/Rejected)
* Single reviewer (planned: multiple reviewers)
* Historical snapshots and audit trail
* Email notifications at each stage

**Integration:**

* Security control mappings for compliance
* Properties storage for reporting
* Report Builder integration
* Import/Export via Excel
* Module-based contextual questionnaires

**Enterprise Features:**

* Multi-tenancy with tenant isolation
* Comprehensive audit trails
* Soft deletes and data retention
* Recurring automated delivery
* Metadata headers for custom categorization
* Performance optimization with proper indexing

The system is designed to scale from simple surveys to complex compliance assessments with hundreds of questions, thousands of users, and sophisticated conditional logic.