# Architecture Documentation - TinyQC

## Overview

TinyQC follows the **Model-View-Controller (MVC)** architectural pattern as defined by the CodeIgniter 4 framework. This document provides a detailed analysis of the application's architecture, components, and design patterns.

---

## Architecture Pattern

### MVC (Model-View-Controller)

```
┌─────────────────────────────────────────────────────────────────┐
│                         HTTP Request                             │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                     Front Controller                             │
│                      (public/index.php)                          │
└────────────────────────────┬────────────────────────────────────┘
                             │
                             ▼
┌─────────────────────────────────────────────────────────────────┐
│                        Router                                    │
│                     (app/Config/Routes.php)                      │
└────────────────────────────┬────────────────────────────────────┘
                             │
        ┌────────────────────┼────────────────────┐
        ▼                    ▼                    ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│   Controller  │   │    Filter     │   │   Middleware  │
│   (Handles    │   │   (Auth,      │   │   (Pre/post   │
│    request)   │   │    CSRF)      │   │    processing)│
└───────┬───────┘   └───────────────┘   └───────────────┘
        │                                            │
        ▼                                            │
┌───────────────┐                                     │
│    Model      │◄────────────────────────────────────┘
│   (Data &     │              Business Logic
│    Business   │
│    Logic)     │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│     View      │
│  (Template)   │
└───────┬───────┘
        │
        ▼
┌─────────────────────────────────────────────────────────────────┐
│                       HTTP Response                              │
│                    (HTML, JSON, Redirect)                        │
└─────────────────────────────────────────────────────────────────┘
```

---

## Component Details

### 1. Models Layer

The Models layer handles all data operations using CodeIgniter's Model class.

#### Base Model (`BaseModel.php`)
- Provides automatic camelCase/snake_case conversion
- Extends `CodeIgniter\Model` with custom functionality
- Standardized data handling across all models

#### Dictionary Models
| Model | Table | Purpose |
|-------|-------|---------|
| `DictDeptModel.php` | dict_dept | Department master data |
| `DictTestModel.php` | dict_test | Test/parameter master data |
| `DictControlModel.php` | dict_control | Control master data |

#### Entity Models
| Model | Table | Purpose |
|-------|-------|---------|
| `DeptModel.php` | dept | Department CRUD |
| `TestModel.php` | test | Test CRUD |
| `ControlModel.php` | control | Control CRUD |
| `ControlTestModel.php` | control_test | Control-test relationships |

#### Result Models
| Model | Table | Purpose |
|-------|-------|---------|
| `ResultModel.php` | results | Result data |
| `DailyResultModel.php` | daily_results | Daily QC entries |
| `MonthlyCommentModel.php` | monthly_comments | Monthly comments |
| `ResultCommentModel.php` | result_comments | Result annotations |

---

### 2. Controllers Layer

Controllers handle HTTP requests, interact with models, and return responses.

#### Page Controllers
| Controller | Base Class | Responsibilities |
|------------|------------|------------------|
| `BaseController.php` | `\CodeIgniter\BaseController` | Common controller setup |
| `Dashboard.php` | BaseController | Dashboard rendering |
| `Dept.php` | BaseController | Department management UI |
| `Test.php` | BaseController | Test management UI |
| `Control.php` | BaseController | Control management UI |
| `Entry.php` | BaseController | Entry forms (daily/monthly) |
| `Report.php` | BaseController | Report generation UI |
| `PageController.php` | BaseController | Generic page handling |

#### API Controllers
All API controllers extend base functionality and return JSON responses.

| Controller | Endpoints | Format |
|------------|-----------|--------|
| `DeptApiController.php` | GET/POST/PUT/DELETE /api/dept | JSON |
| `TestApiController.php` | GET/POST/PUT/DELETE /api/test | JSON |
| `ControlApiController.php` | GET/POST/PUT/DELETE /api/control | JSON |
| `EntryApiController.php` | POST /api/entry/* | JSON |

---

### 3. Views Layer

Views use PHP templates with TailwindCSS and DaisyUI for styling.

#### View Structure
```
app/Views/
├── layout/
│   └── form_layout.php          # Main layout template
├── dashboard.php                # Dashboard view
├── dept/
│   ├── index.php                # Department list
│   └── dialog_form.php          # Department form dialog
├── test/
│   ├── index.php                # Test list
│   └── dialog_form.php          # Test form dialog
├── control/
│   ├── index.php                # Control list
│   └── dialog_form.php          # Control form dialog
├── entry/
│   ├── daily.php                # Daily entry form
│   └── monthly.php              # Monthly entry form
├── report/
│   ├── index.php                # Report selection
│   └── view.php                 # Report display
└── errors/                      # Error page templates
```

#### Frontend Stack
- **TailwindCSS:** Utility-first CSS framework
- **Alpine.js:** Lightweight JavaScript framework
- **DaisyUI:** TailwindCSS component library
- **FontAwesome 7:** Icon library

---

## Data Architecture

### Database (SQL Server)

The application uses SQL Server as its primary database with the following schema pattern:

#### Core Tables
- `dict_dept` - Department dictionary
- `dict_test` - Test/parameter dictionary
- `dict_control` - Control dictionary
- `dept` - Department data
- `test` - Test data
- `control` - Control data
- `control_test` - Control-test relationships

#### Result Tables
- `results` - Result storage
- `daily_results` - Daily QC data
- `monthly_comments` - Monthly comments
- `result_comments` - Result annotations

#### Naming Convention
- Dictionary tables: `dict_*`
- Data tables: Singular lowercase
- Junction tables: `*_test` (noun-noun)

---

## API Design

### RESTful Endpoints

#### Department API (`/api/dept`)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/dept | List all departments |
| GET | /api/dept/:id | Get department by ID |
| POST | /api/dept | Create department |
| PUT | /api/dept/:id | Update department |
| DELETE | /api/dept/:id | Delete department |

#### Test API (`/api/test`)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/test | List all tests |
| GET | /api/test/:id | Get test by ID |
| POST | /api/test | Create test |
| PUT | /api/test/:id | Update test |
| DELETE | /api/test/:id | Delete test |

#### Control API (`/api/control`)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/control | List all controls |
| GET | /api/control/:id | Get control by ID |
| POST | /api/control | Create control |
| PUT | /api/control/:id | Update control |
| DELETE | /api/control/:id | Delete control |

#### Entry API (`/api/entry`)
| Method | Endpoint | Description |
|--------|----------|-------------|
| GET | /api/entry/controls | Get controls for entry |
| GET | /api/entry/tests | Get tests for entry |
| POST | /api/entry/daily | Save daily result |
| POST | /api/entry/monthly | Save monthly entry |
| POST | /api/entry/comment | Save comment |

---

## Configuration Management

### Environment Configuration
- File: `env` (copy to `.env`)
- Database settings in `app/Config/Database.php`
- Route definitions in `app/Config/Routes.php`

### Database Configuration
```php
database.default.hostname = localhost
database.default.port = 1433
database.default.database = tinyqc
database.default.username = sa
database.default.password = your_password
database.default.DBDriver = SQLSRV
```

---

## Development Workflow

### Code Organization
1. Models in `app/Models/` - Data access
2. Controllers in `app/Controllers/` - Request handling
3. Views in `app/Views/` - UI templates
4. Routes in `app/Config/Routes.php` - URL mapping

### Adding New Features
1. Create model in `app/Models/`
2. Create API controller in `app/Controllers/Api/`
3. Add routes in `app/Config/Routes.php`
4. Create views in `app/Views/[module]/`
5. Add menu item in layout if needed

---

## Security Considerations

- **Input Validation:** CodeIgniter 4 Validation library
- **CSRF Protection:** Built-in CodeIgniter CSRF filter
- **SQL Injection:** Parameterized queries via Query Builder
- **XSS Protection:** Output escaping in Views
- **Session Management:** CodeIgniter Session library

---

## Performance Considerations

- **Caching:** CodeIgniter 4 cache system available
- **Database:** SQL Server with optimized queries
- **Assets:** Static files served from `public/`
- **Debugbar:** Debug toolbar in development mode
