# Digital Signature on eRX Prescriptions - Feature Documentation

## Overview

This feature automatically applies the prescriber's uploaded digital signature to all generated electronic prescriptions (eRX). When a doctor approves and signs a prescription request, their signature (previously uploaded in their profile) is embedded in the eRX document and displayed when viewing the prescription.

## Business Requirements

### Core Functionality
- **Signature Upload**: Doctors upload their digital signature in the Profile section (Due Diligence tab)
- **Auto-Application**: When approving a prescription, the system automatically applies the uploaded signature
- **Visibility**: The signature appears on the generated eRX document when viewed or printed
- **Security**: Signature is stored securely and associated with the prescriber

### Compliance & Legal
- Digital signatures provide authentication for electronic prescriptions
- Meets requirements for prescriber identification on eRX documents
- Supports audit trail and legal compliance for prescription issuance

## Technical Implementation

### 1. Data Flow

```
Doctor Profile → Upload Signature → Session Storage → Prescription Approval → eRX Document Display
```

#### Step-by-step Process:
1. Doctor uploads signature image via Profile > Due Diligence tab
2. Signature is stored in `public/uploads/signatures/` directory
3. File path is stored in session (`signature_file`)
4. When doctor approves prescription, signature path is attached to the prescription record
5. When viewing eRX, signature image is displayed from the stored path

### 2. File Structure

#### Modified Files

**Controller**: `app/Http/Controllers/PrototypeController.php`
- Modified `processPatientRequest()` method to include signature path when creating prescriptions
- Updated demo prescription data to include signature paths
- Added signature path to prescription defaults

**View**: `resources/views/prescriptions/view.blade.php`
- Added signature display section in prescription footer
- Implemented conditional rendering (shows signature if available, fallback message if not)
- Added CSS styling for signature presentation

#### Storage Locations
```
public/
  └── uploads/
      └── signatures/
          └── signature_[timestamp].[ext]
```

### 3. Database Schema

The signature functionality uses the existing `signature_file` field from the users table:

```sql
-- From migration: 2026_01_20_125049_add_profile_fields_to_users_table.php
$table->string('signature_file')->nullable()->after('license_file');
```

### 4. Code Changes

#### PrototypeController.php - processPatientRequest()

**Before:**
```php
$approvedPrescriptions[] = [
    'erx_id' => $erxId,
    'patient_id' => $patient['id'],
    // ... other fields
    'status' => 'Sent to Pharmacy',
    'status_class' => 'success'
];
```

**After:**
```php
// Get prescriber signature from session (uploaded in profile)
$signaturePath = session('signature_file', null);

$approvedPrescriptions[] = [
    'erx_id' => $erxId,
    'patient_id' => $patient['id'],
    // ... other fields
    'status' => 'Sent to Pharmacy',
    'status_class' => 'success',
    'signature_path' => $signaturePath  // NEW
];
```

#### prescriptions/view.blade.php - Signature Display

```blade
@if(!empty($prescription['signature_path']) && file_exists(public_path($prescription['signature_path'])))
<div class="signature-container mt-2">
    <img src="{{ asset($prescription['signature_path']) }}" 
         alt="Prescriber Signature" 
         class="signature-image">
</div>
@else
<div class="mt-2">
    <em class="small text-muted">Digital signature on file</em>
</div>
@endif
```

**CSS Styling:**
```css
.signature-container {
    padding: 0.5rem;
    background: white;
    border: 1px solid #dee2e6;
    border-radius: 0.25rem;
    display: inline-block;
    max-width: 250px;
}

.signature-image {
    max-width: 100%;
    max-height: 80px;
    height: auto;
    display: block;
}
```

### 5. Session Data Structure

The signature path is stored in the session as:

```php
session(['signature_file' => 'uploads/signatures/signature_1737389123.png']);
```

Prescription data structure with signature:

```php
[
    'erx_id' => 'eRX-0001',
    'patient_name' => 'John Smith',
    'medication' => 'Lisinopril 10mg',
    // ... other prescription fields
    'prescriber_name' => 'Dr. James Wilson, MD',
    'signature_path' => 'uploads/signatures/signature_1737389123.png',  // NEW
    'date_approved' => '2026-01-20 10:30:00'
]
```

## User Workflow

### For Doctors

#### 1. Upload Signature (One-time Setup)
1. Navigate to Profile (click name in sidebar → "My Profile")
2. Click "Due Diligence" tab
3. Scroll to "Digital Signature" section
4. Click "Choose File" and select signature image (PNG, JPG, JPEG)
5. Click "Upload Signature"
6. Success: Signature is now stored and ready for use

#### 2. Approve Prescription with Signature
1. Navigate to Patients tab
2. Click "View Details" on a patient request
3. Review patient information and medication details
4. Click "Approve & Sign" button
5. System automatically:
   - Generates eRX ID
   - Attaches uploaded signature to prescription
   - Creates prescription record

#### 3. View eRX with Signature
1. Navigate to Prescriptions tab
2. Click "View" on any prescription
3. Scroll to bottom of eRX document
4. See "Electronically Signed By" section with:
   - Prescriber name
   - Date and time of signature
   - Digital signature image (if uploaded)

### For Pharmacy/Recipients

When viewing or printing the eRX:
- Signature is visible in the footer section
- Signature prints clearly on paper copies
- Provides visual authentication of prescriber

## Error Handling

### Scenarios & Responses

| Scenario | System Behavior |
|----------|----------------|
| No signature uploaded | Shows "Digital signature on file" text instead of image |
| Invalid signature file path | Falls back to text message (file_exists check) |
| Signature file deleted | Falls back to text message |
| Invalid image format during upload | Validation error: "Invalid image file" |
| File too large (>2MB) | Validation error: "File size exceeds limit" |

### Validation Rules

**Signature Upload** (ProfileController.php):
```php
'signature' => 'nullable|image|mimes:png,jpg,jpeg|max:2048'
```

- **nullable**: Signature is optional
- **image**: Must be an image file
- **mimes**: Allowed formats: PNG, JPG, JPEG
- **max**: Maximum size: 2048 KB (2 MB)

## Testing Guide

### Test Case 1: Upload and Apply Signature
**Objective**: Verify signature uploads and appears on eRX

1. Login as doctor (`doctor@rxnetworx.com`)
2. Go to Profile → Due Diligence
3. Upload a signature image
4. Navigate to Patients tab
5. Approve a patient request
6. Go to Prescriptions tab
7. View the approved prescription
8. **Expected**: Signature image appears in "Electronically Signed By" section

### Test Case 2: Prescription Without Signature
**Objective**: Verify graceful handling when no signature is uploaded

1. Login as doctor (fresh session, no signature uploaded)
2. Navigate to Prescriptions tab
3. View any demo prescription
4. **Expected**: Text "Digital signature on file" appears instead of image

### Test Case 3: Update Signature
**Objective**: Verify signature updates apply to new prescriptions

1. Upload initial signature
2. Approve a prescription (Prescription A)
3. Update signature with a different image
4. Approve another prescription (Prescription B)
5. View both prescriptions
6. **Expected**: 
   - Prescription A shows old signature
   - Prescription B shows new signature

### Test Case 4: Print Functionality
**Objective**: Verify signature prints correctly

1. View a prescription with signature
2. Click "Print" button
3. In print preview, verify:
   - Signature is visible
   - Signature maintains quality
   - Signature doesn't break page layout
4. **Expected**: Signature renders properly in print view

### Test Case 5: Invalid File Upload
**Objective**: Verify validation works

1. Try uploading a PDF file as signature
2. **Expected**: Error message about invalid file type
3. Try uploading an image > 2MB
4. **Expected**: Error message about file size

## Security Considerations

### Current Implementation
1. **File Upload Validation**: Only accepts image files (PNG, JPG, JPEG)
2. **Size Limits**: Maximum 2MB to prevent abuse
3. **Storage Location**: Public directory for web access
4. **File Naming**: Timestamped to prevent collisions
5. **Session-based**: Uses session storage (prototype phase)

### Production Recommendations
1. **Database Storage**: Move signature path to database linked to user account
2. **Authentication**: Verify user owns the signature before displaying
3. **File Integrity**: Implement hash verification for signature files
4. **Access Control**: Implement proper authorization checks
5. **Audit Trail**: Log all signature uploads and applications
6. **Encryption**: Consider encrypting signature files at rest
7. **Watermarking**: Add digital watermark to prevent unauthorized use

## Logging & Audit

### Events to Log (Production)
- Signature upload (timestamp, user ID, file hash)
- Signature application to prescription (prescription ID, user ID, timestamp)
- Signature file access (who viewed, when)
- Signature updates/deletions

### Example Log Entry
```json
{
    "event": "signature_applied",
    "timestamp": "2026-01-20T10:30:45Z",
    "user_id": 123,
    "user_name": "Dr. James Wilson",
    "prescription_id": "eRX-0001",
    "signature_hash": "a3f5e8d9c1b2...",
    "patient_id": "PT-001"
}
```

## Future Enhancements

### Phase 2 Features
1. **Multi-format Support**: Support for SVG, digital signature pads
2. **Signature Verification**: Cryptographic signature verification
3. **Timestamp Authority**: Third-party timestamp certification
4. **Biometric Integration**: Touch ID / Face ID for mobile devices
5. **Signature Templates**: Pre-defined signature styles
6. **Versioning**: Track signature changes over time
7. **Expiration**: Require signature renewal periodically

### Phase 3 Features
1. **PKI Integration**: Public Key Infrastructure for advanced security
2. **Blockchain**: Immutable signature record on blockchain
3. **AI Validation**: Detect forged or manipulated signatures
4. **Multi-signature**: Require co-signature for controlled substances
5. **QR Code**: Embedded verification QR code

## Troubleshooting

### Common Issues

#### Issue: Signature not appearing on eRX
**Cause**: No signature uploaded or file path not saved
**Solution**: 
1. Check Profile → Due Diligence → Digital Signature section
2. Verify signature image is displayed
3. If not, upload signature again

#### Issue: "Digital signature on file" shows instead of image
**Cause**: Signature file missing or path invalid
**Solution**:
1. Check if file exists in `public/uploads/signatures/`
2. Re-upload signature if file is missing
3. Check file permissions on uploads directory

#### Issue: Signature doesn't print
**Cause**: CSS print styles not loading
**Solution**:
1. Check browser print preview settings
2. Ensure "Background graphics" is enabled
3. Verify print CSS rules in view file

#### Issue: Old signature shows on new prescriptions
**Cause**: Session not updated after signature change
**Solution**:
1. Logout and login again
2. Re-upload signature
3. In production, this won't be an issue with database storage

## API Reference (Future)

### Proposed Endpoints

```
POST   /api/v1/signatures/upload          - Upload signature
GET    /api/v1/signatures/current          - Get current user's signature
DELETE /api/v1/signatures                  - Remove signature
GET    /api/v1/prescriptions/{id}/signature - Get prescription signature
```

## Related Documentation

- [Profile Implementation Summary](./PROFILE_IMPLEMENTATION_SUMMARY.md)
- [Profile Feature Documentation](./PROFILE_FEATURE.md)
- [Profile Testing Guide](../PROFILE_TESTING_GUIDE.md)
- [Patients Tab Flow](./PATIENTS_TAB_FLOW.md)

## Changelog

### Version 1.0.0 - 2026-01-20
- Initial implementation
- Signature upload via Profile
- Auto-application to eRX on approval
- Display on prescription view
- Print support

---

**Last Updated**: January 20, 2026  
**Document Version**: 1.0.0  
**Feature Status**: ✅ Implemented
