# Activity Logs Feature

## Overview

The Activity Logs feature provides a comprehensive timeline of clinical actions performed within the RxNetworx system. This feature displays patient-related activities on the doctor's dashboard, allowing healthcare providers to track prescription submissions, lab reviews, intake form updates, and other clinical events.

## Purpose

The activity log serves as:
- **Clinical History**: A chronological record of patient interactions and medical actions
- **Collaboration Tool**: Helps medical staff see what actions have been performed by other team members
- **Audit Trail**: Maintains a record of clinical decisions and actions for compliance and quality assurance

## Features

### 1. What the Doctor Should See (Clinical History)

The activity log displays **Clinical Actions**, not technical logs. This helps doctors understand the patient's medical story without seeing backend code or security data.

**View**: "Patient Timeline" or "Activity History"

**Content Examples**:
- "Prescription for Amoxicillin sent to CVS (Jan 20, 10:00 AM)"
- "Lab Results Reviewed by Dr. Smith (Jan 19, 2:00 PM)"
- "Intake Form Updated by Nurse Jones (Jan 19, 1:45 PM)"

**Goal**: Collaboration and preventing duplicate work.

### 2. Activity Log Components

Each activity log entry includes:

- **Action Type**: Category of the action (e.g., `prescription_sent`, `lab_reviewed`, `intake_updated`)
- **Description**: Human-readable summary of the action
- **Patient Name**: Full name of the patient
- **Patient Initials**: Avatar display (e.g., "SM", "DC")
- **Reference Number**: Identifier for the action (e.g., "RX #9425", "LAB #8821")
- **Details**: Additional context (medication, dosage, test results, etc.)
- **Performed By**: Staff member who performed the action
- **Status**: Current state (approved, pending, completed, cancelled)
- **Performed At**: Timestamp of when the action occurred

## Database Schema

### `activity_logs` Table

```sql
CREATE TABLE activity_logs (
    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    action_type VARCHAR(255) NOT NULL,
    description TEXT NOT NULL,
    patient_name VARCHAR(255) NOT NULL,
    patient_initials VARCHAR(10) NULL,
    reference_number VARCHAR(255) NULL,
    details TEXT NULL,
    performed_by VARCHAR(255) NULL,
    status VARCHAR(255) NULL,
    performed_at TIMESTAMP NOT NULL,
    created_at TIMESTAMP NULL,
    updated_at TIMESTAMP NULL
);
```

### Supported Action Types

- `prescription_sent`: Prescription submitted to pharmacy
- `prescription_pending`: Prescription awaiting approval
- `prescription_cancelled`: Prescription cancelled
- `prescription_declined`: Prescription request declined
- `lab_reviewed`: Laboratory results reviewed
- `intake_updated`: Patient intake form updated
- `consultation_completed`: Virtual consultation finished
- `info_requested`: Additional information requested from patient

### Supported Statuses

- `approved`: Action was approved/completed successfully
- `pending`: Action awaiting review or approval
- `completed`: Action finished
- `cancelled`: Action was cancelled
- `info`: Informational status

## Implementation

### Model

**Location**: `app/Models/ActivityLog.php`

```php
class ActivityLog extends Model
{
    protected $fillable = [
        'action_type',
        'description',
        'patient_name',
        'patient_initials',
        'reference_number',
        'details',
        'performed_by',
        'status',
        'performed_at',
    ];

    protected $casts = [
        'performed_at' => 'datetime',
    ];

    // Computed attributes
    public function getStatusColorAttribute(); // Returns badge color class
    public function getTimeSinceAttribute();   // Returns human-readable time
}
```

### Controller Methods

**Location**: `app/Http/Controllers/PrototypeController.php`

#### Dashboard Method
```php
public function dashboard()
{
    // Get recent activity logs (last 10 entries)
    $activityLogs = ActivityLog::orderBy('performed_at', 'desc')
        ->limit(10)
        ->get();
    
    return view('dashboard', compact('activityLogs'));
}
```

#### Helper Method for Logging Activities
```php
private function logActivity(
    $actionType, 
    $description, 
    $patientName, 
    $referenceNumber = null, 
    $details = null, 
    $performedBy = 'Dr. House', 
    $status = null
)
{
    // Extracts patient initials
    // Creates activity log entry
}
```

### Usage Example

When a doctor approves a prescription:

```php
$this->logActivity(
    'prescription_sent',
    'Prescription for Amoxicillin sent to pharmacy',
    'Sarah Martinez',
    'RX #9425',
    'Amoxicillin 500mg - 3x daily for 10 days',
    'Dr. House',
    'approved'
);
```

## View Integration

**Location**: `resources/views/dashboard.blade.php`

The dashboard displays activity logs in a card with:
- Card header: "Patient Timeline" with subtitle "Clinical Actions"
- List of activities with patient avatars, descriptions, and status badges
- Timestamp showing when action occurred and relative time
- "View All Activity" link for full history

### UI Components

1. **Patient Avatar**: Circle with patient initials and colored background
2. **Activity Content**: 
   - Primary text: Action description
   - Secondary text: Patient name and reference number
   - Details: Additional information (medication, dosage, etc.)
   - Timestamp: Date/time and relative time (e.g., "5 minutes ago")
3. **Status Badge**: Color-coded badge indicating action status

## Security Considerations

### Access Control
- Only doctors can view the activity dashboard
- Activity logs are filtered based on user permissions
- Sensitive information (passwords, tokens) is never logged

### Data Privacy
- Activity logs contain only necessary clinical information
- PHI (Protected Health Information) is handled according to HIPAA guidelines
- Logs are stored securely and access is audited

### Error Handling
- If activity logging fails, the primary action (e.g., prescription approval) still succeeds
- Logging errors are captured in application logs but don't interrupt workflows
- Empty states are handled gracefully in the UI

## Testing Strategy

### Unit Tests
- Test `ActivityLog` model creation and validation
- Test `getStatusColorAttribute()` method for all statuses
- Test `getTimeSinceAttribute()` formatting

### Integration Tests
- Test activity logging when prescription is approved
- Test activity logging when prescription is declined
- Test activity logging when info is requested
- Verify logs appear correctly on dashboard

### Edge Cases
- Handle empty activity log list
- Handle missing patient initials
- Handle null reference numbers
- Handle very long descriptions or details

## Logging Best Practices

### When to Log
- Prescription submitted to pharmacy
- Prescription approved/declined
- Lab results reviewed
- Intake forms updated
- Consultations completed
- Information requested from patient

### When NOT to Log
- User login/logout (use separate audit log)
- Page views or navigation
- System errors (use error logging)
- Background processes (use job logging)

### Description Guidelines
- Use clear, clinical language
- Focus on "what" not "how"
- Include relevant patient context
- Mention staff member who performed action
- Example: "Prescription for Amoxicillin sent to CVS" (Good)
- Avoid: "Database updated with new prescription record" (Bad - too technical)

## Future Enhancements

1. **Filtering**: Add filters for action type, date range, patient
2. **Pagination**: Load more activities as user scrolls
3. **Search**: Search activities by patient name or reference number
4. **Export**: Export activity history to PDF or CSV
5. **Notifications**: Real-time notifications for new activities
6. **Detailed View**: Click activity to see full details
7. **User-specific Logs**: Filter by "My Activities" vs "All Activities"

## Migration and Seeding

### Running Migrations
```bash
php artisan migrate
```

### Seeding Sample Data
```bash
php artisan db:seed --class=ActivityLogSeeder
```

This creates 10 sample activity log entries for testing and demonstration.

## API Endpoints (Future)

For future API integration:

```
GET /api/activity-logs          - List all activity logs
GET /api/activity-logs/{id}     - Get specific activity log
POST /api/activity-logs         - Create new activity log
GET /api/activity-logs/patient/{id} - Get logs for specific patient
```

## Summary

The Activity Logs feature provides doctors with a comprehensive view of clinical actions performed in the system. It focuses on presenting medically relevant information in a clear, chronological format that aids collaboration and prevents duplicate work. The implementation follows Laravel best practices and maintains security and privacy standards.
