# Connecticut Elderly Services PCA Training Platform - Setup Guide

## Overview
This is a complete Node.js + Express web application for PCA (Personal Care Attendant) certification training based on the Connecticut DSS PCA Certification Test.

## Quick Start

### 1. Install Node.js
Download and install Node.js from https://nodejs.org/ (version 14 or higher recommended)

### 2. Install Dependencies
Open a terminal/command prompt and navigate to the project folder, then run:
```bash
npm install
```

### 3. Set Up Configuration
Copy `.env.example` to `.env` and update values as needed:
```bash
cp .env.example .env
```

Edit `.env` file:
- `PORT=3000` — Port to run the application
- `SESSION_SECRET=...` — Session encryption key (required; generate with `node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`)
- `ADMIN_SETUP_TOKEN=...` — One-time token for the browser-based first-admin setup (see Step 5 below)

> **Note:** There is no default admin password. You must create your first admin account before logging in.

### 4. Create the MySQL Table (cPanel only — do this once)

The app uses MySQL exclusively for admin accounts. You must create the `admin_users` table in phpMyAdmin before the bootstrap route will work.

1. In cPanel, open **phpMyAdmin**
2. Select your database (e.g. `connecticutelder_cesauth`) from the left sidebar
3. Click the **SQL** tab
4. Paste and run this query:

```sql
CREATE TABLE IF NOT EXISTS admin_users (
  id            INT          AUTO_INCREMENT PRIMARY KEY,
  username      VARCHAR(100) NOT NULL UNIQUE,
  display_name  VARCHAR(255) NOT NULL DEFAULT '',
  password_hash VARCHAR(255) NOT NULL,
  role          VARCHAR(50)  NOT NULL DEFAULT 'agency',
  active        TINYINT(1)   NOT NULL DEFAULT 1,
  last_login    DATETIME     NULL,
  created_at    DATETIME     NOT NULL DEFAULT CURRENT_TIMESTAMP
);
```

5. Click **Go**. You should see "1 query executed successfully."

> You only need to do this once. The table persists even when you upload a new version of the app.

### 5. Create the First Admin Account

There are two ways, depending on whether you have terminal access.

#### Option A — Browser-based setup (no terminal required, e.g. cPanel)

1. Set `ADMIN_SETUP_TOKEN` to a strong random value in your environment variables (cPanel → Node.js App → Environment Variables). Generate one with:
   ```
   node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"
   ```
2. Start the app (Step 6).
3. Visit: `https://yourdomain.com/admin/bootstrap?token=YOUR_TOKEN`
4. Fill in your username and password and submit the form.
5. After seeing the success message, **remove `ADMIN_SETUP_TOKEN`** from your environment variables and restart the app. This permanently closes the bootstrap route.

#### Option B — Script (if you have SSH / terminal access)

```bash
node scripts/create-admin.js <username> <password>
```

Example:
```bash
node scripts/create-admin.js tony MySecurePass@2024
```

Run it again at any time to reset a password.

### 6. Run the Application
```bash
npm start
```

The application will start on http://localhost:3000

## Using the Application

### For Learners
1. Go to http://localhost:3000
2. Click "Begin Training"
3. Enter your full name and select your agency
4. Complete all 12 training modules
5. Each module has:
   - A lesson to read
   - A knowledge check quiz (5 questions)
   - Must score 70% or higher to pass
6. After completing all modules, take the final exam
7. Final exam has 19 sections - must score 70%+ in ALL sections to pass
8. Download your certificate upon passing

### For Administrators
1. Create your admin account first (see Step 4 above)
2. Go to http://localhost:3000/admin/login
3. Enter your **username** and **password**
4. View:
   - Training statistics (total learners, completions, pass rate)
   - Learner roster with completion status
   - Agency codes
   - Certificate download links
4. Add new agency codes for different organizations

### Agency Codes
Pre-seeded agencies:
- **DEMO123** - Demo Agency
- **TEST456** - Test Agency

Add more agencies through the admin dashboard.

## Project Structure

```
ces-training/
├── app.js                      # Main application file
├── package.json                # Node dependencies
├── .env.example                # Environment template
├── SETUP.md                    # This file
├── data/                       # Auto-created on first run
│   ├── training.db            # SQLite — learner/module data
│   └── sessions.db            # SQLite — session store
├── public/                     # Static files
│   ├── css/style.css          # All styling
│   ├── js/main.js             # JavaScript utilities
│   └── certificates/          # Generated PDF certificates
├── scripts/
│   └── create-admin.js        # CLI: create/reset MySQL admin users
├── views/                      # EJS templates
│   ├── layout.ejs             # Base template
│   ├── index.ejs              # Home page
│   ├── start.ejs              # Name entry form
│   ├── modules/
│   │   ├── module.ejs         # Module lesson + quiz
│   │   └── complete.ejs       # Module completion
│   ├── exam.ejs               # Final exam
│   ├── result.ejs             # Results page
│   ├── error.ejs              # Error page
│   └── admin/
│       ├── login.ejs          # Admin login
│       ├── dashboard.ejs      # Admin panel
│       ├── change-password.ejs # Password change form
│       └── bootstrap.ejs      # First-admin setup
├── routes/                     # API routes
│   ├── learner.js             # Training routes
│   ├── exam.js                # Exam routes
│   └── admin.js               # Admin routes (MySQL auth, CSRF, rate limiting)
└── lib/                        # Libraries
    ├── db.js                  # SQLite — learner/module data
    ├── mysqldb.js             # MySQL — admin auth only
    ├── auth.js                # Shared crypto helpers (scrypt)
    ├── version.js             # BUILD_ID for deploy verification
    ├── modules.js             # Training content (12 modules)
    ├── examContent.js         # Exam questions (19 sections)
    ├── certificate.js         # PDF certificate generation
    └── email.js               # Email notifications (optional)
```

## Technology Stack
- **Backend**: Node.js + Express.js
- **Database**: SQLite3 (`sqlite3` npm package) — learner/module/exam data; MySQL/MariaDB — admin authentication
- **Templates**: EJS
- **PDF Generation**: PDFKit
- **Email**: Nodemailer
- **Styling**: Pure CSS (no dependencies)

## Training Content

### 12 Training Modules
1. Emergency Response
2. Universal Precautions
3. Communication
4. Monitoring Condition Changes
5. Positioning
6. Safe Lifting
7. Safe Transfers
8. Medication Safety
9. Professional Boundaries
10. Brain Injury, Dementia & Behavior
11. Reporting Abuse & Neglect
12. Personal Care - Bathing, Hair & Mouth Care

### 19 Final Exam Sections
Sections cover all aspects of PCA care:
- Preventing Emergency Situations
- Universal Precautions
- Communication
- Monitoring Condition Changes
- Positioning
- Lifting
- Transfers
- Medication
- Caregiver Boundaries
- Individuals with Acquired Brain Injury
- Reporting Abuse, Neglect, Exploitation and Abandonment
- Bathing
- Bathing Individuals with Dementia
- Bed Bath
- Washing Hair
- Washing Hair in Bed
- Mouth Care
- Mouth Care for Individuals with Dementia
- Dressing

## Database

### SQLite (`data/training.db`) — learner data only
Created automatically on first run. Contains three tables:

#### agencies
- id, name, code, created_at

#### learners
- id, agency_id, name, email, started_at, completed_at, passed, score_json, certificate_url

#### module_progress
- id, learner_id, module_num, completed_at

### MySQL/MariaDB (cPanel) — admin authentication only
The `admin_users` table stores hashed admin credentials. Managed via phpMyAdmin.
Connection configured via cPanel environment variables: `DB_HOST`, `DB_USER`, `DB_PASS`, `DB_NAME`, `DB_PORT`.

#### Inspect admin accounts (phpMyAdmin → SQL tab)
```sql
SELECT id, username, display_name, role, active, last_login, created_at
FROM admin_users
ORDER BY created_at;
```

#### Delete the legacy "admin" account (phpMyAdmin → SQL tab)
```sql
DELETE FROM admin_users WHERE username = 'admin';
```
Run this if the old default account exists. Confirm it says "1 row(s) affected."
After deletion, create your real admin account using `/admin/bootstrap` (see Step 5 above).

## Security Notes

1. **Admin passwords** are stored as scrypt hashes in the **MySQL database** (not SQLite).
   There is no plaintext password stored anywhere and no default password.
   Use `node scripts/create-admin.js` to create or reset accounts, or use the browser-based `/admin/bootstrap` route.

2. **Set the session secret** in .env before going to production:
   ```
   SESSION_SECRET=your-unique-secret-key
   ```
   The app will refuse to start in production (`NODE_ENV=production`) without this set.

3. **Email configuration** (optional):
   - Set EMAIL_HOST, EMAIL_PORT, EMAIL_USER, EMAIL_PASS to enable certificate emails
   - Currently, certificates are generated but email notifications are optional

## Troubleshooting

### Port Already in Use
Change the PORT in .env to an available port (e.g., 3001, 8000)

### Database Errors
Delete the `data/training.db` file and restart the app to recreate the database

### Certificates Not Generating
Check that the `public/certificates/` folder exists and is writable

### Module Content Not Showing
Verify that `lib/modules.js` exists and contains all 12 modules

## Development Tips

### View Console Logs
- Run with: `npm run dev` (requires nodemon)
- Check terminal output for errors

### Clear Sessions
Sessions are stored in `data/sessions.db` (SQLite) and persist across restarts. To clear all sessions, delete `data/sessions.db` and restart the app.

### Backup Learner Data
The SQLite database file at `data/training.db` contains all learner data. Backup regularly.

## Customization

### Change Colors
Edit the CSS variables at the top of `public/css/style.css`:
```css
--color-primary: #1a3a5c;      /* Navy blue */
--color-secondary: #f0a500;    /* Gold */
```

### Change Organization Name
Update in `views/layout.ejs` and `lib/certificate.js`

### Add/Remove Modules
Edit `lib/modules.js` and update the count in `lib/db.js`

## Deployment

### cPanel
1. Upload and extract `ces-training-v0.1-auth.zip` so files land at `public_html/ces-training/`
2. In cPanel → Node.js App → your app → **Environment Variables**, set ALL of these:

   | Variable | Value |
   |---|---|
   | `NODE_ENV` | `production` |
   | `SESSION_SECRET` | a long random string (generate: `node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"`) |
   | `ADMIN_SETUP_TOKEN` | another strong random string (remove after first login) |
   | `DB_HOST` | your cPanel MySQL hostname (usually `localhost`) |
   | `DB_USER` | your MySQL username (e.g. `connecticutelder_cesadmin`) |
   | `DB_PASS` | your MySQL password |
   | `DB_NAME` | your MySQL database name (e.g. `connecticutelder_cesauth`) |
   | `DB_PORT` | `3306` |

3. Set the **startup file** to `app.js`
4. Run `npm install` (cPanel → Node.js App → Run NPM Install)
5. Click **Restart**
6. Visit `https://yourdomain.com/admin/bootstrap?token=YOUR_ADMIN_SETUP_TOKEN` to create your first admin account
7. After a successful login, **delete `ADMIN_SETUP_TOKEN`** from Environment Variables and restart again

### Docker
```dockerfile
FROM node:16
WORKDIR /app
COPY . .
RUN npm install
EXPOSE 3000
CMD ["npm", "start"]
```

### Heroku
```bash
git push heroku main
heroku config:set SESSION_SECRET=your-secret
heroku run node scripts/create-admin.js tony YourPassword
```

## Support

For issues or questions:
1. Check the console for error messages
2. Verify all dependencies are installed: `npm install`
3. Ensure Node.js version is 14+
4. Check that the data folder exists and is writable

## License

Connecticut Elderly Services PCA Training Platform
© 2024 Connecticut Department of Social Services
