# TinyQC Product Requirements Document (PRD)

## 1. Executive Summary

### 1.1 Product Overview
**TinyQC** is a lightweight, web-based Laboratory Quality Control (QC) Management System designed to help laboratories record, track, and analyze quality control test results with statistical analysis capabilities.

### 1.2 Product Vision
Provide a simple yet powerful QC management solution that enables laboratory staff to efficiently manage dictionary data (departments, tests, control materials), enter QC results, and generate statistical reports—all through an intuitive web interface.

### 1.3 Target Users
- Laboratory technicians responsible for daily data entry
- QC managers overseeing quality control processes
- Laboratory directors managing department and test configurations

### 1.4 Problem Statement
Laboratories need a centralized system to:
- Maintain organized dictionaries for departments, tests, and control materials
- Record QC test results efficiently (daily and monthly entry modes)
- Calculate statistical parameters (mean, standard deviation)
- Identify out-of-range results that require attention
- Generate reports for quality assurance purposes

### 1.5 Scope (MVP)
The MVP includes core dictionary management, data entry functionality, and basic reporting capabilities. Future phases will add authentication, user management, advanced analytics, and export features.

---

## 2. User Personas

### 2.1 Laboratory Technician
**Role:** Day-to-day data entry and result recording

**Goals:**
- Quickly enter QC test results for the current day
- Perform bulk monthly data entry using an intuitive calendar interface
- Add comments and notes to explain unusual results
- Search and filter existing results when needed

**Pain Points:**
- Manual paper-based recording is error-prone
- No automatic statistical calculation
- Difficulty tracking which controls expire soon

**How TinyQC Helps:**
- Digital data entry with validation
- Automatic mean and SD calculations
- Expiry date tracking for control materials

---

### 2.2 QC Manager
**Role:** Oversight of quality control processes and reporting

**Goals:**
- Review QC data across multiple departments and tests
- Generate monthly reports for quality assurance documentation
- Identify out-of-range results (beyond 2 standard deviations)
- Maintain accurate dictionaries of tests and control materials

**Pain Points:**
- Manual compilation of reports from multiple sources
- Difficulty identifying trends in QC data
- No centralized view of control materials across departments

**How TinyQC Helps:**
- Consolidated reporting by test and control
- Automatic statistical analysis with out-of-range detection
- Centralized dictionary management with relationships

---

### 2.3 Laboratory Director
**Role:** Administrative oversight and system configuration

**Goals:**
- Manage department structure (add, edit, delete departments)
- Define test catalog with QC parameters
- Configure control materials with lot numbers and expiry dates
- Link tests to appropriate controls with statistical parameters

**Pain Points:**
- No systematic way to maintain test definitions
- Manual tracking of control material lots and producers
- Difficulty ensuring consistency in QC parameters

**How TinyQC Helps:**
- Complete CRUD operations for departments, tests, and controls
- Control-test linkage with configurable mean and SD values
- Soft delete functionality to preserve historical data

---

## 3. Functional Requirements

### 3.1 Department Management

#### 3.1.1 View Departments

**User Story:** As a user, I want to view all departments so I can understand the organizational structure of the laboratory.

### US-001: View Departments

**As a** user
**I want** to view all departments
**So that** I can understand the organizational structure of the laboratory

#### Acceptance Criteria
- [ ] Display department ID and name
- [ ] Show total count of tests and controls per department
- [ ] Allow sorting by name or ID
- [ ] Provide search functionality by department name

---

#### 3.1.2 Create Department

**User Story:** As an administrator, I want to create new departments so I can organize tests and controls by laboratory section.

### US-002: Create Department

**As an** administrator
**I want** to create new departments
**So that** I can organize tests and controls by laboratory section

#### Acceptance Criteria
- [ ] Provide input field for department name
- [ ] Validate that name is required and unique
- [ ] Show success notification upon creation
- [ ] Redirect to department list or stay on form after creation

---

#### 3.1.3 Edit Department

**User Story:** As an administrator, I want to edit department names so I can correct typos or reflect organizational changes.

### US-003: Edit Department

**As an** administrator
**I want** to edit department names
**So that** I can correct typos or reflect organizational changes

#### Acceptance Criteria
- [ ] Pre-populate form with current department name
- [ ] Validate name is required and unique (excluding current record)
- [ ] Track creation and modification timestamps
- [ ] Show success notification upon update

---

#### 3.1.4 Delete Department

**User Story:** As an administrator, I want to remove obsolete departments so the system remains accurate and current.

### US-004: Delete Department

**As an** administrator
**I want** to remove obsolete departments
**So that** the system remains accurate and current

#### Acceptance Criteria
- [ ] Display confirmation dialog before deletion
- [ ] Check for related records (tests, controls) and handle cascade or restrict
- [ ] Set deleted_at timestamp instead of permanent deletion
- [ ] Provide option to restore deleted departments

---

### 3.2 Test Management

#### 3.2.1 View Tests

**User Story:** As a user, I want to browse all tests so I can understand what tests are available for QC entry.

### US-005: View Tests

**As a** user
**I want** to browse all tests
**So that** I can understand what tests are available for QC entry

#### Acceptance Criteria
- [ ] Display test ID, name, unit, method, and associated department
- [ ] Show QC parameters: CVA (Control Value Average), BA (Base Average), TEA (Total Error Allowance)
- [ ] Display links to related controls
- [ ] Provide search functionality by test name or code
- [ ] Allow filtering by department

---

#### 3.2.2 Create Test

**User Story:** As an administrator, I want to add new tests with their QC parameters so they become available for QC data entry.

### US-006: Create Test

**As an** administrator
**I want** to add new tests with their QC parameters
**So that** they become available for QC data entry

#### Acceptance Criteria
- [ ] Provide fields: test name, unit, method, CVA, BA, TEA, department
- [ ] Validate that name and unit are required
- [ ] Enable department selection via dropdown
- [ ] Set automatic timestamps on creation
- [ ] Show success notification upon creation

---

#### 3.2.3 Edit Test

**User Story:** As an administrator, I want to update test parameters so QC targets remain accurate.

### US-007: Edit Test

**As an** administrator
**I want** to update test parameters
**So that** QC targets remain accurate

#### Acceptance Criteria
- [ ] Allow editing all fields except ID
- [ ] Preserve historical data associations
- [ ] Update modification timestamp
- [ ] Apply validation rules to edited fields

---

#### 3.2.4 Delete Test

**User Story:** As an administrator, I want to remove obsolete tests so they don't appear in data entry options.

### US-008: Delete Test

**As an** administrator
**I want** to remove obsolete tests
**So that** they don't appear in data entry options

#### Acceptance Criteria
- [ ] Display confirmation dialog before deletion
- [ ] Check for associated control links before deletion
- [ ] Preserve historical QC results
- [ ] Set deleted_at timestamp

---

### 3.3 Control Management

#### 3.3.1 View Controls

**User Story:** As a user, I want to view all available controls so I can select the correct one for data entry.

### US-009: View Controls

**As a** user
**I want** to view all available controls
**So that** I can select the correct one for data entry

#### Acceptance Criteria
- [ ] Display control ID, name, lot number, producer, expiry date
- [ ] Show associated department
- [ ] Indicate if control is active (based on expiry date)
- [ ] Provide search functionality
- [ ] Allow filtering by department

---

#### 3.3.2 Create Control

**User Story:** As an administrator, I want to register new control materials with their test associations so technicians can select them during data entry.

### US-010: Create Control

**As an** administrator
**I want** to register new control materials with their test associations
**So that** technicians can select them during data entry

#### Acceptance Criteria
- [ ] Provide fields: name, lot number, producer, expiry date, department
- [ ] Enable linking to one or more tests
- [ ] Allow setting mean and SD values for each test association
- [ ] Validate that name, lot, and expiry date are required
- [ ] Set automatic timestamps on creation

---

#### 3.3.3 Edit Control

**User Story:** As an administrator, I want to update control information when lot numbers change or new test associations are needed.

### US-011: Edit Control

**As an** administrator
**I want** to update control information
**So that** lot numbers remain current and test associations are accurate

#### Acceptance Criteria
- [ ] Allow editing all fields except ID
- [ ] Enable updating test associations and their parameters
- [ ] Update modification timestamp
- [ ] Apply validation rules to edited fields

---

#### 3.3.4 Delete Control

**User Story:** As an administrator, I want to remove discontinued controls so they don't appear in selection lists.

### US-012: Delete Control

**As an** administrator
**I want** to remove discontinued controls
**So that** they don't appear in selection lists

#### Acceptance Criteria
- [ ] Display confirmation dialog before deletion
- [ ] Preserve associated QC results
- [ ] Set deleted_at timestamp

---

### 3.4 Data Entry - Daily

#### 3.4.1 Daily Entry Interface

**User Story:** As a technician, I want to enter daily QC results quickly so I can maintain accurate quality records.

### US-013: Daily Entry Interface

**As a** technician
**I want** to enter daily QC results quickly
**So that** I can maintain accurate quality records

#### Acceptance Criteria
- [ ] Display date picker (defaults to current date)
- [ ] Provide department filter
- [ ] Show controls active for selected date
- [ ] Display tests associated with each control
- [ ] Provide input field for numeric result value
- [ ] Include optional comment field for notes
- [ ] Display save button with confirmation

---

#### 3.4.2 Save Daily Result

**User Story:** As a technician, I want my entered results saved so they contribute to statistical analysis.

### US-014: Save Daily Result

**As a** technician
**I want** my entered results saved
**So that** they contribute to statistical analysis

#### Acceptance Criteria
- [ ] Validate result is numeric
- [ ] Associate result with control, test, and date
- [ ] Store optional comment
- [ ] Return appropriate success/error response
- [ ] Clear form after successful save

---

### 3.5 Data Entry - Monthly

#### 3.5.1 Monthly Entry Interface

**User Story:** As a technician, I want to enter a full month of results efficiently using a calendar grid.

### US-015: Monthly Entry Interface

**As a** technician
**I want** to enter a full month of results efficiently using a calendar grid
**So that** I can complete monthly data entry quickly

#### Acceptance Criteria
- [ ] Provide month and year selector
- [ ] Display department filter
- [ ] Show calendar grid view of the month
- [ ] Display controls with their associated tests
- [ ] Provide input fields for each day of the month
- [ ] Highlight weekends and holidays
- [ ] Enable horizontal scrolling for multiple controls/tests

---

#### 3.5.2 Save Monthly Results

**User Story:** As a technician, I want to save multiple results at once so I don't have to save each one individually.

### US-016: Save Monthly Results

**As a** technician
**I want** to save multiple results at once
**So that** I don't have to save each one individually

#### Acceptance Criteria
- [ ] Accept array of results with dates and values
- [ ] Validate all entries before saving
- [ ] Support partial save with error reporting if any entry fails
- [ ] Show success notification

---

#### 3.5.3 Monthly Comments

**User Story:** As a technician, I want to add monthly notes so I can explain batch-wide observations or issues.

### US-017: Monthly Comments

**As a** technician
**I want** to add monthly notes
**So that** I can explain batch-wide observations or issues

#### Acceptance Criteria
- [ ] Enable selecting month, control, and test
- [ ] Provide text area for comment
- [ ] Associate comment with month rather than specific date
- [ ] Display comments in reports

---

### 3.6 Reporting

#### 3.6.1 Report Generation Form

**User Story:** As a QC manager, I want to configure report parameters so I can generate targeted quality reports.

### US-018: Report Generation Form

**As a** QC manager
**I want** to configure report parameters
**So that** I can generate targeted quality reports

#### Acceptance Criteria
- [ ] Provide month and year selector
- [ ] Display department filter
- [ ] Enable test selection (single or all)
- [ ] Allow control selection (up to 3)
- [ ] Display generate report button
- [ ] Provide preview mode before printing/export

---

#### 3.6.2 Report Display

**User Story:** As a QC manager, I want to view statistical analysis of QC results so I can assess quality performance.

### US-019: Report Display

**As a** QC manager
**I want** to view statistical analysis of QC results
**So that** I can assess quality performance

#### Acceptance Criteria
- [ ] Display control name, lot, and expiry
- [ ] Show test name and unit
- [ ] Present table of daily result values
- [ ] Calculate and display mean (average of all values)
- [ ] Calculate and display standard deviation (SD)
- [ ] Display number of results
- [ ] Show out-of-range count (beyond 2 SD from mean)
- [ ] Highlight out-of-range values
- [ ] Include monthly comments if present
- [ ] Provide responsive layout for screen viewing

---

#### 3.6.3 Out-of-Range Detection

**User Story:** As a QC manager, I want to quickly identify results requiring investigation so I can take corrective action.

### US-020: Out-of-Range Detection

**As a** QC manager
**I want** to quickly identify results requiring investigation
**So that** I can take corrective action

#### Acceptance Criteria
- [ ] Calculate mean and SD from entered values
- [ ] Define limits as mean ± 2 SD
- [ ] Flag values outside these limits
- [ ] Count and display number of out-of-range results
- [ ] Highlight individual out-of-range cells in report

---

## 4. Technical Requirements

### 4.1 Technology Stack

| Layer | Technology | Version |
|-------|------------|---------|
| Backend Framework | CodeIgniter 4 | 4.x |
| PHP Version | PHP | 8.1+ |
| Database | MySQL/MariaDB | 5.7+ |
| Frontend Framework | Alpine.js | 3.x |
| Styling | TailwindCSS | 3.x |
| UI Components | DaisyUI | Latest |
| Icons | FontAwesome | 6.5.1 |
| Charts | Chart.js | Latest |
| Notifications | Toastify-js | Latest |
| Testing | PHPUnit | Latest |

### 4.2 Architecture

#### 4.2.1 Backend Architecture
- **Pattern:** MVC (Model-View-Controller)
- **API Style:** RESTful JSON endpoints
- **Input Validation:** CodeIgniter validation library
- **Error Handling:** Exception catching with standardized error responses
- **Case Conversion:** Automatic camelCase/snake_case conversion for API

#### 4.2.2 Frontend Architecture
- **SPA-like experience:** Alpine.js for reactivity
- **Module-based:** ES6 modules with import statements
- **State Management:** Component-level Alpine data objects
- **AJAX:** Fetch API for all server communication

### 4.3 Database Requirements

#### 4.3.1 Supported Databases
- **Primary:** MySQL 5.7+ / MariaDB 10+
- **Secondary:** Microsoft SQL Server (via CodeIgniter drivers)

#### 4.3.2 Naming Conventions
- **Tables:** snake_case (e.g., `master_depts`, `master_tests`)
- **Columns:** snake_case (e.g., `dept_id`, `created_at`)
- **Primary Keys:** `{table_singular}_id` (e.g., `dept_id`, `test_id`)
- **Foreign Keys:** Match referenced primary key name

#### 4.3.3 Required Fields (All Tables)
- `created_at` DATETIME
- `updated_at` DATETIME
- `deleted_at` DATETIME (for soft deletes)

### 4.4 API Requirements

#### 4.4.1 Response Format
All API responses must follow this structure:

```json
{
  "status": "success" | "error",
  "message": "Human-readable message",
  "data": { } | [ ]
}
```

#### 4.4.2 HTTP Status Codes
- `200` - Success
- `201` - Created
- `400` - Bad Request / Validation Error
- `401` - Unauthorized
- `404` - Not Found
- `500` - Server Error

#### 4.4.3 Case Conversion
- **Input (Frontend → Backend):** Convert camelCase to snake_case
- **Output (Backend → Frontend):** Convert snake_case to camelCase
- Helper functions: `camel_to_snake()`, `snake_to_camel()`, `camel_to_snake_array()`

### 4.5 Security Requirements

#### 4.5.1 Input Validation
- All user inputs must be validated before processing
- Numeric fields must reject non-numeric values
- Date fields must use proper date format
- Required fields must be enforced

#### 4.5.2 SQL Injection Prevention
- Use CodeIgniter's Query Builder for all database operations
- Never concatenate user input into SQL queries
- Use parameterized queries

#### 4.5.3 XSS Prevention
- Escape output in views using CodeIgniter's esc() function
- Sanitize user-generated content before display

#### 4.5.4 CSRF Protection
- Enable CodeIgniter's CSRF protection
- Validate CSRF token on all POST/PATCH/DELETE requests

### 4.6 Performance Requirements

#### 4.6.1 Response Times
- Page load: < 2 seconds
- API responses: < 500 milliseconds
- Database queries: < 200 milliseconds

#### 4.6.2 Scalability
- Support up to 100 concurrent users
- Handle up to 10,000 result records
- Pagination for large result sets

---

## 5. Data Model

### 5.1 Entity Relationship Overview

```
┌─────────────────┐       ┌─────────────────┐
│   master_depts    │       │   master_tests    │
│   (1)──────────(N)     │                 │
│                 │       │ test_id         │
│ dept_id         │       │ name            │
│ name            │       │ unit            │
│ created_at      │       │ method          │
│ updated_at      │◄──────│ cva             │
│ deleted_at      │ dept_  │ ba              │
└─────────────────┘ ref_id │ tea             │
                            │ dept_ref_id     │
                            │ created_at      │
                            │ updated_at      │
                            │ deleted_at      │
                            └─────────────────┘
           ┌─────────────────┐       ┌─────────────────┐
           │ master_controls   │       │ control_tests   │
           │                 │       │                 │
           │ control_id      │       │ control_test_id │
           │ name            │(1)───(N)│ control_ref_id │
           │ lot             │       │ test_ref_id     │
           │ producer        │       │ mean            │
           │ expiry_date     │       │ sd              │
           │ dept_ref_id     │       │ created_at      │
           │ created_at      │       │ updated_at      │
           │ updated_at      │       │ deleted_at      │
           │ deleted_at      │       └─────────────────┘
           └─────────────────┘
                    │
                    ▼ (1)
           ┌─────────────────┐       ┌─────────────────┐
           │    results      │       │result_comments  │
           │                 │       │                 │
           │ result_id       │       │ comment_id      │
           │ control_ref_id  │       │ control_ref_id  │
           │ test_ref_id     │       │ test_ref_id     │
           │ resdate         │       │ commonth        │
           │ resvalue        │       │ comtext         │
           │ rescomment      │       │ created_at      │
           │ created_at      │       │ updated_at      │
           │ updated_at      │       │ deleted_at      │
           │ deleted_at      │       └─────────────────┘
           └─────────────────┘
```

### 5.2 Table Specifications

#### 5.2.1 master_depts (Departments)
| Column | Type | Description |
|--------|------|-------------|
| dept_id | INT UNSIGNED | Primary key, auto-increment |
| name | VARCHAR(100) | Department name, unique |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp (NULL if active) |

---

#### 5.2.2 master_tests (Tests)
| Column | Type | Description |
|--------|------|-------------|
| test_id | INT UNSIGNED | Primary key, auto-increment |
| name | VARCHAR(150) | Test name |
| unit | VARCHAR(50) | Measurement unit |
| method | VARCHAR(50) | Test method |
| cva | DECIMAL(10,2) | Control Value Average |
| ba | DECIMAL(10,2) | Base Average |
| tea | DECIMAL(10,2) | Total Error Allowance |
| dept_ref_id | INT UNSIGNED | Foreign key to master_depts |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp |

---

#### 5.2.3 master_controls (Controls)
| Column | Type | Description |
|--------|------|-------------|
| control_id | INT UNSIGNED | Primary key, auto-increment |
| name | VARCHAR(100) | Control name |
| lot | VARCHAR(50) | Lot number |
| producer | VARCHAR(100) | Control producer/manufacturer |
| expiry_date | DATE | Expiration date |
| dept_ref_id | INT UNSIGNED | Foreign key to master_depts |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp |

---

#### 5.2.4 control_tests (Control-Test Link)
| Column | Type | Description |
|--------|------|-------------|
| control_test_id | INT UNSIGNED | Primary key, auto-increment |
| control_ref_id | INT UNSIGNED | Foreign key to master_controls |
| test_ref_id | INT UNSIGNED | Foreign key to master_tests |
| mean | DECIMAL(10,4) | Expected mean value |
| sd | DECIMAL(10,4) | Standard deviation |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp |

---

#### 5.2.5 results (QC Results)
| Column | Type | Description |
|--------|------|-------------|
| result_id | INT UNSIGNED | Primary key, auto-increment |
| control_ref_id | INT UNSIGNED | Foreign key to master_controls |
| test_ref_id | INT UNSIGNED | Foreign key to master_tests |
| resdate | DATE | Result date |
| resvalue | DECIMAL(10,4) | Measured value |
| rescomment | TEXT | Optional comment for this result |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp |

---

#### 5.2.6 result_comments (Monthly Comments)
| Column | Type | Description |
|--------|------|-------------|
| comment_id | INT UNSIGNED | Primary key, auto-increment |
| control_ref_id | INT UNSIGNED | Foreign key to master_controls |
| test_ref_id | INT UNSIGNED | Foreign key to master_tests |
| commonth | VARCHAR(7) | Month in YYYY-MM format |
| comtext | TEXT | Comment text |
| created_at | DATETIME | Record creation timestamp |
| updated_at | DATETIME | Last modification timestamp |
| deleted_at | DATETIME | Soft delete timestamp |

---

### 5.3 Constraints

#### 5.3.1 Unique Constraints
- `master_depts.name` - Department names must be unique
- `master_tests.name` - Test names should be unique within a department
- `master_controls.lot` - Lot numbers should be unique per control name

#### 5.3.2 Foreign Key Relationships
- `master_tests.dept_ref_id` → `master_depts.dept_id`
- `master_controls.dept_ref_id` → `master_depts.dept_id`
- `control_tests.control_ref_id` → `master_controls.control_id`
- `control_tests.test_ref_id` → `master_tests.test_id`
- `results.control_ref_id` → `master_controls.control_id`
- `results.test_ref_id` → `master_tests.test_id`
- `result_comments.control_ref_id` → `master_controls.control_id`
- `result_comments.test_ref_id` → `master_tests.test_id`

---

## 6. Non-Functional Requirements

### 6.1 Usability Requirements
- Responsive design supporting desktop, tablet, and mobile devices
- Intuitive navigation with clear menu structure
- Modal-based forms for quick data entry without page navigation
- Toast notifications for user feedback (success, error, warning)
- Keyboard shortcuts for common operations (where applicable)
- Clear error messages with guidance for resolution

### 6.2 Reliability Requirements
- 99.5% uptime during business hours
- Data integrity through soft delete mechanism
- Automatic timestamp tracking for all records
- No data loss on form validation errors
- Graceful error handling with user-friendly messages

### 6.3 Maintainability Requirements
- Clean, documented code following CodeIgniter conventions
- Modular architecture separating concerns (controllers, models, views)
- Consistent naming conventions throughout the codebase
- Reusable components and layouts
- Centralized configuration (routes, database, environment)

### 6.4 Security Requirements
- Input validation on all user inputs
- SQL injection prevention via parameterized queries
- XSS protection through output escaping
- CSRF protection on state-changing operations
- No sensitive data exposure in error messages
- Secure password storage (when authentication is implemented)

### 6.5 Compatibility Requirements
- Modern browsers: Chrome, Firefox, Edge, Safari (latest 2 versions)
- Operating systems: Windows, macOS, Linux
- Screen resolutions: 1280x720 minimum, responsive to 4K
- Touch devices supported for mobile data entry

---

## 7. UI/UX Requirements

### 7.1 Design System

#### 7.1.1 Color Palette
- **Primary:** Blue tones (brand color)
- **Background:** Light slate/gray for content areas
- **Cards/Panels:** White with subtle shadows and borders
- **Text:** Dark slate for readability
- **Accents:** Status colors (green=success, red=error, amber=warning)

#### 7.1.2 Typography
- **Font:** System fonts or Inter/Sans-serif
- **Sizes:** 14px base, 12px for metadata, 16-24px for headings
- **Weights:** Regular for body, Semibold/Bold for headings

#### 7.1.3 Component Style
- Rounded corners (6-12px border-radius)
- Subtle shadows for depth
- Glass-morphism effects for overlays
- DaisyUI-style buttons and form elements

### 7.2 Layout Requirements

#### 7.2.1 Main Layout
- **Sidebar:** Collapsible navigation on the left
  - Logo/branding area
  - Menu items with icons
  - Collapsible menu groups
  - User info section
- **Header:** Top bar with page title and actions
- **Content Area:** Main content in central panel
- **Footer:** Version info and copyright

#### 7.2.2 Mobile Layout
- Hamburger menu to toggle sidebar
- Touch-friendly tap targets (44px minimum)
- Stacked layouts for forms and tables

### 7.3 Page Requirements

#### 7.3.1 Dashboard (`/`)
- Overview statistics cards
- Quick access to common actions
- Recent activity summary (future)

#### 7.3.2 Dictionary Pages (`/dept`, `/test`, `/control`)
- List view with search and filters
- "Add New" button prominent
- Action buttons (Edit, Delete) per row
- Modal form for Create/Edit
- Confirmation dialog for Delete

#### 7.3.3 Data Entry Pages (`/entry/daily`, `/entry/monthly`)
- Date/month selector
- Department filter
- Dynamic control/test selection
- Input fields with validation
- Save button with loading state
- Success/error feedback

#### 7.3.4 Report Pages (`/report`, `/report/view`)
- Parameter selection form
- Statistical summary section
- Data table with highlighting
- Responsive table with horizontal scroll
- Print-friendly view (future)

### 7.4 Interaction Requirements

#### 7.4.1 Forms
- Clear labels and placeholders
- Inline validation feedback
- Required field indicators
- Loading states on submit
- Auto-focus on first field

#### 7.4.2 Tables
- Sortable columns
- Search/filter functionality
- Pagination for large datasets
- Hover states for rows
- Action buttons clearly visible

#### 7.4.3 Modals
- Close on backdrop click
- ESC key to close
- Smooth transition animations
- Focus management for accessibility

#### 7.4.4 Notifications
- Toast notifications for actions
- Auto-dismiss after 3-5 seconds
- Persistent for errors (until dismissed)
- Multiple notifications stacked

---

## 8. API Endpoints Reference

### 8.1 Departments API (`/api/dept`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/dept` | List all departments |
| GET | `/api/dept/(:num)` | Get department by ID |
| POST | `/api/dept` | Create new department |
| PATCH | `/api/dept/(:num)` | Update department |
| DELETE | `/api/dept/(:num)` | Soft delete department |

### 8.2 Tests API (`/api/test`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/test` | List all tests |
| GET | `/api/test/(:num)` | Get test by ID |
| POST | `/api/test` | Create new test |
| PATCH | `/api/test/(:num)` | Update test |
| DELETE | `/api/test/(:num)` | Soft delete test |

### 8.3 Controls API (`/api/control`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/control` | List all controls |
| GET | `/api/control/(:num)` | Get control by ID |
| GET | `/api/control/(:num)/tests` | Get tests linked to control |
| POST | `/api/control` | Create new control |
| PATCH | `/api/control/(:num)` | Update control |
| DELETE | `/api/control/(:num)` | Soft delete control |

### 8.4 Entries API (`/api/entry`)

| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | `/api/entry/controls` | Get active controls by date/dept |
| GET | `/api/entry/tests` | Get tests for a control |
| POST | `/api/entry/daily` | Save daily result |
| POST | `/api/entry/monthly` | Save monthly results |
| POST | `/api/entry/comment` | Save monthly comment |

---

## 9. Future Considerations

The following features are identified for future development but are out of scope for the MVP:

### 9.1 Authentication & Authorization
- User registration and login
- JWT-based session management
- Role-based access control (RBAC)
- User permissions by feature

### 9.2 Enhanced Reporting
- PDF report export
- Excel/CSV data export
- Levey-Jennings charts
- Multi-month trend analysis

### 9.3 QC Validation
- Westgard QC rules implementation
- Configurable rule sets
- Automatic rule violation detection
- Email alerts for out-of-range results

### 9.4 Data Management
- Audit logging of all changes
- Data backup and restore
- Import from lab instruments
- Data migration tools

### 9.5 User Experience
- Dashboard with visualizations
- Keyboard shortcuts power user features
- Dark mode theme
- Multi-language support

---

## 10. Appendix

### 10.1 Glossary

| Term | Definition |
|------|------------|
| QC | Quality Control - processes to ensure test accuracy |
| CVA | Control Value Average - expected average control value |
| BA | Base Average - baseline average for comparison |
| TEA | Total Error Allowance - acceptable error range |
| SD | Standard Deviation - measure of data dispersion |
| Mean | Average of a set of values |
| Out-of-range | Value exceeding acceptable limits (typically mean ± 2 SD) |
| Soft Delete | Marking a record as deleted without physical removal |
| Control Material | Reference material with known values for QC testing |
| Lot Number | Manufacturer's batch identifier for control materials |

### 10.2 References
- CodeIgniter 4 Documentation: https://codeigniter4.github.io/userguide/
- Alpine.js Documentation: https://alpinejs.dev/
- TailwindCSS Documentation: https://tailwindcss.com/docs
- DaisyUI Documentation: https://daisyui.com/

---

**Document Information**

| Field | Value |
|-------|-------|
| Version | 1.0 |
| Status | Draft |
| Created | January 2026 |
| Last Updated | January 2026 |

---

*This PRD defines the requirements for the TinyQC MVP. All stakeholders should review and approve before development begins.*
