# Portfolio Form Implementation Guide

## Overview
This document describes the Portfolio submission system implemented for the E-LOGBOOK PPDS-2 application. The portfolio feature allows trainees to document and submit clinical cases from different practice settings (Operating Room, Polyclinic, and Inpatient/Ward) with digital signatures for supervisor verification.

## Database Changes

### New Tables Created

#### 1. `portfolio` Table
Main table to store portfolio submissions with the following columns:

```sql
- id (INT, PRIMARY KEY, AUTO INCREMENT)
- user_id (INT, FOREIGN KEY to users.id)
- divisi (VARCHAR 100) - Specialty division (e.g., "fertilitas")
- semester (INT) - Academic semester (1-5)
- setting_type (ENUM) - Practice setting: "OK", "Poliklinik", "Rawat_Inap"
- nomor (INT) - Auto-incremented portfolio number per user/divisi/semester/setting
- tanggal (DATE) - Portfolio submission date
- identifikasi_pasien (TEXT) - Patient identification
- diagnosis (VARCHAR 255) - Clinical diagnosis
- tatalaksana (TEXT) - Clinical management/treatment
- kompetenszi (ENUM) - Competency level: "Level I", "Level II", "Level III", "Level IV"
- supervisor_name (VARCHAR 100) - Supervisor/DPJP name
- dpjp_signature (LONGBLOB) - DPJP's digital signature (base64 encoded)
- dpjp_verified (BOOLEAN) - Verification status by DPJP
- dpjp_verified_by (INT) - User ID of DPJP who verified
- dpjp_verified_at (TIMESTAMP) - Timestamp of DPJP verification
- trainee_signature (LONGBLOB) - Trainee's digital signature (base64 encoded)
- status (ENUM) - Document status: "draft", "submitted", "verified"
- created_at (TIMESTAMP) - Record creation time
- updated_at (TIMESTAMP) - Record update time

Indexes:
- idx_user_divisi_semester on (user_id, divisi, semester)
- idx_setting_type on (setting_type)
- idx_tanggal on (tanggal)
```

#### 2. `portfolio_counter` Table
Maintains auto-increment counters for portfolio numbers per user/divisi/semester/setting:

```sql
- id (INT, PRIMARY KEY, AUTO INCREMENT)
- user_id (INT, FOREIGN KEY to users.id)
- divisi (VARCHAR 100)
- semester (INT)
- setting_type (ENUM)
- counter (INT)
- updated_at (TIMESTAMP)

UNIQUE KEY: user_id, divisi, semester, setting_type
```

#### 3. Trigger: `portfolio_before_insert`
Automatically generates sequential portfolio numbers before inserting new records.

### Database Migration
Run the migration file to set up the portfolio tables:
```bash
mysql -h localhost -u root logbook_ppds < database/migration_portfolio.sql
```

## API Endpoints

### File: `php/portfolio.php`

#### 1. Get Next Portfolio Number
**Request:** GET `/php/portfolio.php?action=get_next_nomor&divisi=fertilitas&semester=1&setting_type=OK`
**Response:**
```json
{
    "success": true,
    "nomor": 1
}
```

#### 2. Create Portfolio Entry
**Request:** POST `/php/portfolio.php`
```json
{
    "action": "create",
    "divisi": "fertilitas",
    "semester": 1,
    "setting_type": "OK",
    "tanggal": "2026-02-25",
    "identifikasi_pasien": "Ny. Siti, 35 tahun, RM#12345",
    "diagnosis": "Fibroid uteri",
    "tatalaksana": "Histerektomi total...",
    "kompetenszi": "Level II",
    "supervisor_name": "dr. Ahmad, Sp.OG",
    "trainee_signature": "data:image/png;base64,..."
}
```
**Response:**
```json
{
    "success": true,
    "id": 1,
    "nomor": 1
}
```

#### 3. Get Portfolio Details
**Request:** GET `/php/portfolio.php?action=get&id=1`
**Response:**
```json
{
    "success": true,
    "data": {
        "id": 1,
        "nomor": 1,
        "tanggal": "2026-02-25",
        ...
    }
}
```

#### 4. List Portfolios (with filters)
**Request:** GET `/php/portfolio.php?action=list&divisi=fertilitas&semester=1&setting_type=OK`
**Response:**
```json
{
    "success": true,
    "data": [
        {
            "id": 1,
            "nomor": 1,
            "tanggal": "2026-02-25",
            "identifikasi_pasien": "...",
            "diagnosis": "...",
            "kompetenszi": "Level II",
            "status": "draft",
            "created_at": "2026-02-25 10:30:00"
        }
    ]
}
```

#### 5. Update Portfolio
**Request:** POST `/php/portfolio.php`
```json
{
    "action": "update",
    "id": 1,
    "tanggal": "2026-02-26",
    "diagnosis": "Updated diagnosis",
    "trainee_signature": "data:image/png;base64,...",
    ...
}
```

#### 6. Delete Portfolio
**Request:** POST `/php/portfolio.php`
```json
{
    "action": "delete",
    "id": 1
}
```

#### 7. Submit for Verification
**Request:** POST `/php/portfolio.php`
```json
{
    "action": "submit_for_verification",
    "id": 1
}
```

#### 8. DPJP Verification and Signature
**Request:** POST `/php/portfolio.php` (DPJP/Dosen only)
```json
{
    "action": "verify_dpjp",
    "id": 1,
    "dpjp_signature": "data:image/png;base64,..."
}
```

## Frontend Components

### Files Added/Modified

#### 1. `js/portfolio.js`
Main JavaScript file handling portfolio functionality:
- Portfolio form initialization
- Digital signature canvas management
- API communication
- Form validation and submission
- Portfolio list display and management

**Key Functions:**
- `initializePortfolio(divisi, semester, settingType)` - Initialize portfolio context
- `openPortfolioForm(portfolioId)` - Open form for new or edit
- `closePortfolioForm()` - Close portfolio form
- `getNextNomor()` - Fetch next portfolio number
- `loadPortfolioList()` - Load list of portfolios
- `savePortfolio()` - Save portfolio data
- `submitPortfolioForVerification()` - Submit for DPJP verification
- `deletePortfolio(id)` - Delete portfolio entry
- Drawing functions for trainee and DPJP signatures

#### 2. `index.html` Modifications
Added:
- Portfolio form modal with all required fields
- Portfolio list view table
- Signature canvas elements (trainee and DPJP)
- CSS styles for form, modal, and table display
- Import statement for `js/portfolio.js`

#### 3. `js/app.js` Modifications
Added:
- `handlePortfolioNavigation()` - Hash-based navigation for portfolio sections
- Portfolio context initialization based on menu selection
- Support for all divisions (fertilitas, fetomaternal, etc.) and semesters

## Form Features

### Fields in Portfolio Form

1. **Nomor (Portfolio Number)**
   - Auto-generated, read-only
   - Sequential per user/division/semester/setting type

2. **Tanggal (Date)**
   - Date picker input
   - Required field

3. **Identifikasi Pasien (Patient Identification)**
   - Text area
   - Contains: Name, Medical Record #, Age, Gender
   - Required field

4. **Diagnosis**
   - Text area
   - Clinical diagnosis from ICD-10
   - Required field

5. **Tatalaksana (Clinical Management)**
   - Text area
   - Detailed description of treatment/intervention
   - Required field

6. **Kompetensi (Competency Level)**
   - Dropdown selection: Level I, II, III, IV
   - Required field
   - Based on ACGME/CanMEDS framework

7. **Supervisor / DPJP**
   - Text input for supervisor name
   - Can be filled by trainee (optional)
   - Required for submission

8. **Tanda Tangan Trainee (Trainee Signature)**
   - HTML Canvas for digital signature capture
   - Mouse and touch support
   - Base64 encoded PNG
   - Required field

9. **Tanda Tangan E-Sign DPJP (DPJP E-Signature)**
   - HTML Canvas for DPJP signature
   - Digital ink only (no scanned images)
   - Requires DPJP/Dosen account login
   - For verification workflow

### Workflow States

1. **Draft** (Yellow badge)
   - Initial state when creating portfolio
   - User can edit all fields
   - User can delete the entry

2. **Submitted** (Blue badge)
   - After trainee submits for DPJP verification
   - Awaiting DPJP review and signature
   - Limited editing capability

3. **Verified** (Green badge)
   - DPJP has signed and verified
   - Final state
   - Read-only view

## Digital Signature Implementation

### Canvas-Based Signature Capture
- Uses HTML5 Canvas API for real-time signature capture
- Supports mouse and touch input
- Automatically saves to hidden input field
- Base64 encoded PNG format for database storage

### Signature Features
- Clear button to erase and re-sign
- Visual feedback during drawing
- Resolution: 400x200 pixels
- Smooth drawing with line joins and caps

### Security Considerations
- Signatures are stored as BLOB (binary) in database
- Base64 encoding for transport via JSON
- DPJP verification requires authenticated session with 'dosen' or 'admin' role
- Timestamp and user ID recorded for verification

## Usage Instructions

### For Trainees
1. Navigate to Portfolio submenu (e.g., "Portofolio > Kamar Operasi")
2. Click "Tambah Portofolio Baru" button
3. Fill in all required fields:
   - Patient identification
   - Diagnosis
   - Clinical management details
   - Competency level
   - Supervisor name
4. Draw your signature in the canvas
5. Click "Simpan Portofolio" to save as draft
6. Click "Ajukan untuk Verifikasi" when ready for DPJP review

### For DPJP/Dosen
1. Access trainee logbooks or portfolio submissions
2. Review submitted portfolio entries
3. Sign in the DPJP signature canvas
4. Click verification button to finalize
5. System records verification timestamp and verifier ID

## Styling

Portfolio form includes responsive CSS with:
- Dark theme header with light text
- Blue primary color for actions
- Green success buttons
- Red delete buttons
- Status-based color badges
- Mobile-responsive grid layout
- Smooth transitions and hover effects

## File Structure
```
logbook-ppds/
├── database/
│   └── migration_portfolio.sql      # Database migration
├── php/
│   └── portfolio.php                # Portfolio API handler
├── js/
│   ├── app.js                       # Updated navigation handler
│   └── portfolio.js                 # Portfolio form logic
├── components/
│   └── portfolio-form.html          # Reusable component
└── index.html                       # Updated with portfolio form
```

## Testing Checklist

- [ ] Database tables created successfully
- [ ] Portfolio form loads without errors
- [ ] Auto-numbering works for new entries
- [ ] Trainee signature canvas captures input
- [ ] DPJP signature canvas hidden from trainees
- [ ] Form validation prevents incomplete entries
- [ ] Portfolio list filters by division/semester/setting
- [ ] Edit functionality preserves existing data
- [ ] Delete operation removes entry from database
- [ ] Status transitions work correctly
- [ ] DPJP verification requires dosen account
- [ ] Signature images display after upload
- [ ] Responsive design on mobile devices

## Performance Considerations

- Portfolio counters cached in dedicated table
- Indexes on frequently queried columns
- Lazy loading of signature images
- Canvas operations optimized for smooth drawing
- API queries filtered by user_id for security

## Future Enhancements

1. Digital certificate/PKI integration for legal signature validation
2. PDF export with signature and verification details
3. Bulk operations (batch verification)
4. Advanced filtering and search
5. Analytics dashboard for portfolio coverage
6. Competency tracking across semesters
7. Integration with competency-based assessment
8. Mobile app synchronization
