# Notification System - Future Roadmap

**Current Status**: Phase 1 Complete ✅  
**Environment**: Development  
**Last Updated**: November 2024

This document outlines planned enhancements and future phases for the M1 ERP notification system.

---

## 🎯 Phase 1 - COMPLETE

**Status**: ✅ Implemented and tested  
**Delivery Date**: November 2024

### What's Live
- ✅ Invoice payment reminders (5-stage escalation)
- ✅ Quote expiration alerts (3-stage)
- ✅ Work order due date notifications (3-stage)
- ✅ Product expiry tracking (3-stage with auto-quarantine)
- ✅ Calendar event reminders

### Next Action
- [ ] Install cron jobs in production environment
- [ ] Monitor for 1-2 weeks for feedback
- [ ] Document user response and effectiveness

---

## 🔧 Phase 1.5 - Enhancements (PLANNED)

**Priority**: Medium  
**Estimated Effort**: 2-3 weeks  
**Status**: Not started

### Enhancement 1: Smart @ Mention Targeting

**Problem**: Currently all notifications go to everyone (`target_audience='all'`)

**Solution**: Parse @ mentions to target specific users/groups

**Implementation**:
```php
// Parse attendees field or notification config
// Target: @sales-team, @management, specific user IDs
// Update announcements table with proper targeting
```

**Benefits**:
- Reduce notification fatigue
- Relevant alerts only
- Better user experience

**Files to Modify**:
- All 4 Phase 1 cron scripts
- `models/Announcement.php` - Add targeting logic
- `views/layouts/app.php` - Filter notifications by user

**Effort**: 1 week

---

### Enhancement 2: Email Notifications

**Problem**: Users must check ERP to see notifications

**Solution**: Send critical alerts via email

**Implementation**:
```php
// Add email notification function
// Only for high/critical priority
// Include notification details + link to ERP
```

**Requirements**:
- SMTP configuration
- Email templates
- User email preferences

**Files to Create**:
- `includes/email_helper.php` - Email sending functions
- `views/emails/notification_template.php` - HTML email
- Database migration for email preferences

**Effort**: 1 week

---

### Enhancement 3: Notification Preferences

**Problem**: No way for users to customize what they receive

**Solution**: User-configurable notification settings

**Implementation**:
- Settings page: `/settings/notifications`
- Toggle notifications by category
- Set frequency (immediate, daily digest, weekly)
- Channel preferences (in-app, email, SMS)

**Database Changes**:
```sql
CREATE TABLE user_notification_preferences (
    id INT PRIMARY KEY AUTO_INCREMENT,
    user_id INT NOT NULL,
    notification_type VARCHAR(50), -- 'invoice', 'quote', 'work_order', etc.
    enabled TINYINT(1) DEFAULT 1,
    frequency ENUM('immediate', 'daily', 'weekly') DEFAULT 'immediate',
    channels JSON, -- ['in_app', 'email', 'sms']
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
```

**Files to Create**:
- `controllers/NotificationPreferencesController.php`
- `views/settings/notification_preferences.php`
- `database/migrations/035_user_notification_preferences.sql`

**Effort**: 1.5 weeks

---

### Enhancement 4: Snooze & Dismiss Actions

**Problem**: Can't postpone or dismiss notifications

**Solution**: Add snooze/dismiss buttons to notification dropdown

**Implementation**:
- Snooze: Hide for X hours/days, then re-appear
- Dismiss: Mark as read, hide permanently
- Database tracking of dismissed/snoozed items

**Database Changes**:
```sql
ALTER TABLE announcements ADD COLUMN snoozed_until DATETIME NULL;
ALTER TABLE announcements ADD COLUMN dismissed_by JSON; -- User IDs who dismissed

-- Track individual user read status
CREATE TABLE user_notification_status (
    user_id INT,
    announcement_id INT,
    status ENUM('unread', 'read', 'dismissed', 'snoozed'),
    snoozed_until DATETIME NULL,
    PRIMARY KEY (user_id, announcement_id)
);
```

**UI Changes**:
- Add snooze dropdown (1 hour, 1 day, 3 days, 1 week)
- Add dismiss button (X icon)
- Show snoozed count in bell icon

**Effort**: 1 week

---

### Enhancement 5: Notification Analytics Dashboard

**Problem**: No visibility into notification effectiveness

**Solution**: Admin dashboard showing notification metrics

**Implementation**:
- Total notifications sent by type
- Click-through rates (how many clicked links)
- Dismissal rates
- Most active notification types
- User engagement metrics

**Features**:
- Charts: notifications over time
- Table: top 10 most-triggered notifications
- Heatmap: notification activity by hour/day
- Export to CSV

**Files to Create**:
- `controllers/NotificationAnalyticsController.php`
- `views/admin/notification_analytics.php`
- `models/NotificationAnalytics.php`

**Effort**: 1 week

---

## 📋 Phase 2 - HR Notifications (PLANNED)

**Priority**: Medium-High  
**Estimated Effort**: 1-2 weeks  
**Status**: Planned

### Use Cases

#### 1. Employee Review Due Dates
- **Trigger**: Performance review scheduled dates
- **Stages**: 30d, 7d, today, overdue
- **Target**: Employee + direct manager + @hr-team
- **Table**: `employee_reviews`

#### 2. Contract Renewals
- **Trigger**: Employment contract end dates
- **Stages**: 90d, 60d, 30d, 14d, expired
- **Target**: Employee + @hr-team + @management
- **Table**: `employee_contracts`

#### 3. Training Course Due Dates
- **Trigger**: Required training completion deadlines
- **Stages**: 14d, 7d, today, overdue
- **Target**: Employee + @hr-team
- **Table**: `training_enrollments`

#### 4. Certification Renewals
- **Trigger**: Professional certification expiration
- **Stages**: 90d, 60d, 30d, 14d, expired
- **Target**: Employee + direct manager + @hr-team
- **Table**: `employee_certifications`

#### 5. Probation Period Endings
- **Trigger**: New employee probation end date
- **Stages**: 30d, 14d, 7d, today
- **Target**: Employee + direct manager + @hr-team
- **Table**: `employees` (probation_end_date)

### Database Migration Required
```sql
-- Add notification tracking to HR tables
ALTER TABLE employee_reviews ADD COLUMN last_notified_at DATETIME;
ALTER TABLE employee_reviews ADD COLUMN notification_level VARCHAR(20);

ALTER TABLE employee_contracts ADD COLUMN last_notified_at DATETIME;
ALTER TABLE employee_contracts ADD COLUMN notification_level VARCHAR(20);

ALTER TABLE training_enrollments ADD COLUMN last_notified_at DATETIME;
ALTER TABLE training_enrollments ADD COLUMN notification_level VARCHAR(20);

-- Check if certifications table exists, create if needed
-- Similar for other HR tables
```

### Scripts to Create
1. `cron/employee_review_notifications.php`
2. `cron/contract_renewal_notifications.php`
3. `cron/training_due_notifications.php`
4. `cron/certification_renewal_notifications.php`
5. `cron/probation_ending_notifications.php`
6. `cron/install_phase2_crons.sh` (installer)

### Testing
- Create test data SQL script
- Verify all notification stages
- Check @ mention targeting
- Validate auto-status updates where applicable

**Estimated Timeline**: 1-2 weeks

---

## 🏭 Phase 3 - Operations Notifications (PLANNED)

**Priority**: Medium  
**Estimated Effort**: 1-2 weeks  
**Status**: Planned

### Use Cases

#### 1. Purchase Order Delivery Dates
- **Trigger**: Expected delivery dates from suppliers
- **Stages**: 7d, 3d, today, overdue
- **Target**: Purchasing agent + @purchasing + @inventory
- **Table**: `purchase_orders`

#### 2. Equipment Maintenance Schedules
- **Trigger**: Preventive maintenance due dates
- **Stages**: 14d, 7d, today, overdue
- **Target**: Maintenance supervisor + @maintenance + @manufacturing
- **Table**: `equipment_maintenance_schedules`

#### 3. Support Ticket SLA Violations
- **Trigger**: Response/resolution time approaching SLA
- **Stages**: 50% time, 75% time, 90% time, violated
- **Target**: Assigned agent + @support + @management
- **Table**: `support_tickets`

#### 4. Supplier Contract Renewals
- **Trigger**: Supplier contract expiration dates
- **Stages**: 90d, 60d, 30d, today, expired
- **Target**: Purchasing manager + @purchasing + @management
- **Table**: `supplier_contracts`

#### 5. Inventory Reorder Points
- **Trigger**: Stock levels below reorder point
- **Stages**: At reorder point, 50% below, critical (0 stock)
- **Target**: Inventory manager + @purchasing + @manufacturing
- **Table**: `products` (quantity vs reorder_point)

### Scripts to Create
1. `cron/po_delivery_notifications.php`
2. `cron/maintenance_schedule_notifications.php`
3. `cron/support_sla_notifications.php`
4. `cron/supplier_contract_notifications.php`
5. `cron/inventory_reorder_notifications.php`
6. `cron/install_phase3_crons.sh`

**Estimated Timeline**: 1-2 weeks

---

## 💰 Phase 4 - Financial Notifications (PLANNED)

**Priority**: Low-Medium  
**Estimated Effort**: 1 week  
**Status**: Planned

### Use Cases

#### 1. Budget Variance Alerts
- **Trigger**: Department spending vs budget threshold
- **Stages**: 75%, 90%, 100%, 110% of budget
- **Target**: Department head + @accounting + @management
- **Table**: `budget_items`, `journal_entries`

#### 2. Tax Filing Deadlines
- **Trigger**: Quarterly/annual tax filing dates
- **Stages**: 30d, 14d, 7d, today
- **Target**: @accounting + @management
- **Table**: `tax_deadlines` (would need to create)

#### 3. Audit Preparation Reminders
- **Trigger**: Scheduled audit dates
- **Stages**: 60d, 30d, 14d, 7d, today
- **Target**: @accounting + @management + affected departments
- **Table**: `audit_schedule` (would need to create)

#### 4. Fixed Asset Depreciation Reviews
- **Trigger**: Annual asset review dates
- **Stages**: 30d, 14d, today
- **Target**: @accounting + asset custodians
- **Table**: `fixed_assets`

#### 5. Financial Period Close Deadlines
- **Trigger**: Month/quarter/year end closing dates
- **Stages**: 7d, 3d, today
- **Target**: @accounting + @management
- **Table**: `accounting_periods`

**Estimated Timeline**: 1 week

---

## 🎨 Phase 5 - Advanced Features (FUTURE)

**Priority**: Low  
**Status**: Ideas / Backlog

### Feature Ideas

#### 1. SMS Notifications
- Send critical alerts via SMS
- Requires Twilio/SMS gateway integration
- User mobile number management

#### 2. Mobile App Push Notifications
- Native mobile app notifications
- Requires mobile app development
- Firebase/APNs integration

#### 3. Slack/Teams Integration
- Post notifications to team channels
- Reply to notifications from chat
- Webhook integrations

#### 4. Notification Rules Engine
- Visual rule builder (no-code)
- Custom notification conditions
- IF/THEN logic for complex scenarios

#### 5. AI-Powered Smart Notifications
- Learn user preferences over time
- Auto-snooze low-priority items
- Predict which notifications user will act on
- Batch similar notifications

#### 6. Notification Templates
- Admin-configurable message templates
- Placeholder variables
- Multi-language support
- A/B testing for effectiveness

---

## 🛠️ Technical Debt & Infrastructure

### Items to Address

#### 1. Cron Script Refactoring
**Problem**: Duplicate code across notification scripts

**Solution**: Create base notification class
```php
abstract class BaseNotification {
    protected $db;
    protected $announcementModel;
    protected $logFile;
    
    abstract protected function getNotificationData();
    abstract protected function getNotificationStages();
    
    public function run() {
        // Common execution logic
    }
}
```

**Effort**: 3-4 days

---

#### 2. Unit Testing
**Problem**: No automated tests for notification logic

**Solution**: Add PHPUnit tests
- Test notification creation
- Test escalation logic
- Test duplicate prevention
- Mock database for isolated testing

**Effort**: 1 week

---

#### 3. Logging Improvements
**Problem**: Separate log files, no centralized monitoring

**Solution**: 
- Centralized logging library (Monolog)
- Structured JSON logs
- Log levels (DEBUG, INFO, WARNING, ERROR)
- Log rotation policy

**Effort**: 2-3 days

---

#### 4. Error Handling & Retries
**Problem**: Script fails silently if DB connection lost

**Solution**:
- Try/catch around all DB operations
- Retry logic for transient failures
- Alert admin if script fails
- Dead letter queue for failed notifications

**Effort**: 3-4 days

---

#### 5. Performance Optimization
**Problem**: Queries may be slow with large datasets

**Solution**:
- Add database indexes (already done in Phase 1)
- Implement query result caching
- Batch processing for large result sets
- Query optimization analysis

**Effort**: 2-3 days

---

## 📊 Success Metrics

### KPIs to Track (Once in Production)

**User Engagement**:
- Notification click-through rate
- Average time to action
- Dismissal rate by type
- Snooze frequency

**Business Impact**:
- Invoice collection time (DSO reduction)
- Quote conversion rate improvement
- Work order on-time completion rate
- Product expiry incidents (should approach zero)

**System Health**:
- Notification delivery success rate
- Average script execution time
- Database query performance
- Cron job reliability

**User Satisfaction**:
- User feedback surveys
- Feature requests
- Bug reports
- Notification preference changes

---

## 🚀 Implementation Priority Matrix

### High Priority / High Impact
1. **Phase 1.5 Enhancement 1** - @ Mention Targeting
2. **Phase 2** - HR Notifications (if HR module is active)

### High Priority / Medium Impact
3. **Phase 1.5 Enhancement 2** - Email Notifications
4. **Phase 3** - Operations Notifications

### Medium Priority / High Impact
5. **Phase 1.5 Enhancement 3** - Notification Preferences
6. **Technical Debt Item 1** - Cron Script Refactoring

### Medium Priority / Medium Impact
7. **Phase 1.5 Enhancement 4** - Snooze & Dismiss
8. **Phase 1.5 Enhancement 5** - Analytics Dashboard
9. **Phase 4** - Financial Notifications

### Low Priority / Nice to Have
10. **Technical Debt Items 2-5** - Testing, Logging, Error Handling
11. **Phase 5** - Advanced Features (SMS, Mobile, AI)

---

## 💡 Decision Points

### When to Move from Phase 1 to Phase 2?

**Signals to proceed**:
- ✅ Phase 1 has been running for 2+ weeks
- ✅ No critical bugs reported
- ✅ Users are clicking/acting on notifications
- ✅ Management sees value in the system
- ✅ HR module is actively used in ERP

**Signals to pause**:
- ❌ Too many false positives/spam complaints
- ❌ Low engagement (nobody clicking notifications)
- ❌ Technical issues need resolution first
- ❌ HR module not in use yet

---

### When to Add Enhancements vs New Phases?

**Add Enhancements if**:
- Users requesting specific features (snooze, preferences)
- Notification fatigue becoming an issue
- Need better targeting to reduce noise
- Analytics needed for decision-making

**Add New Phases if**:
- Phase 1 working well as-is
- Other departments requesting coverage
- New data/tables available to track
- More coverage = more business value

---

## 📝 Notes & Considerations

### Security
- Notifications may contain sensitive data
- Ensure proper access control (who can see what)
- Encrypt email notifications if they contain PII
- Audit trail of who was notified about what

### Scalability
- Current design handles ~1000 notifications/day
- For higher volumes, consider:
  - Message queue (RabbitMQ, Redis)
  - Background job processing
  - Database partitioning
  - Caching layer

### Internationalization
- Currently English-only
- Future: Multi-language support
- Translate notification templates
- Localize date/time formats
- Currency formatting

### Compliance
- GDPR: Users must be able to opt-out
- Data retention: How long to keep old notifications?
- Audit requirements: Track notification delivery
- Industry-specific regulations (HIPAA, SOX, etc.)

---

## 📚 Related Documentation

- `PHASE1_NOTIFICATIONS_COMPLETE.md` - Phase 1 completion summary
- `NOTIFICATION_SYSTEM_PLAN.md` - Original system plan
- `cron/README.md` - Cron job setup and troubleshooting
- `database/migrations/034_phase1_notification_tracking.sql` - Phase 1 schema

---

## ✅ Checklist for Each New Phase

Before implementing any new phase:

- [ ] Review existing Phase 1 analytics (if available)
- [ ] Confirm tables exist and have correct columns
- [ ] Document notification stages and escalation logic
- [ ] Create database migration script
- [ ] Write cron notification script(s)
- [ ] Create test data SQL script
- [ ] Test all notification scenarios manually
- [ ] Write unit tests (if test infrastructure exists)
- [ ] Update main documentation
- [ ] Create installer script
- [ ] Run in development for 1 week before production

---

**Status**: This is a living document. Update as priorities change or new requirements emerge.

**Maintained By**: Development Team  
**Review Frequency**: Quarterly or as needed
