# Feedback Notification System

## Overview

The system sends automated email notifications to training providers about feedback submissions and approaching due dates using **System SMTP** (not TP SMTP).

## Email Notifications

### 1. New Feedback Submission (Automatic - Immediate)
**Sent to:** All TP users assigned to the training provider  
**Sent when:** A new feedback is submitted via public form  
**Uses:** System SMTP  
**Contains:**
- Reference code
- Category (Complaint/Suggestion/Question/Appreciation)
- Subject and submitter name
- Submission date and due date
- Days remaining to respond (7 days)
- Link to view in PBPS MIS

### 2. Due Date Reminders (Requires Setup - See Below)
**Sent to:** All TP users assigned to the training provider  
**Sent when:**
- **2 days before due date** - First reminder
- **1 day before due date** - Final reminder  
- **After due date:** No more reminders (feedback becomes overdue)

**Uses:** System SMTP  
**Contains:**
- Reference code and subject
- Days/hours remaining
- Original submission details
- Call-to-action to respond

## Requirements

### 1. System SMTP Configuration (Required)
System SMTP must be configured in App Settings to send notifications to providers:
- Uses the same SMTP as verification emails
- Configured in: App Settings → SMTP Config
- **No TP SMTP required** for provider notifications

### 2. TP User Accounts (Required)
Training providers must have staff accounts created via TP Staff Management:
- Staff users are linked to specific training providers through `tpStaffMemberships`
- All active staff users for that provider receive feedback notifications
- Managed via: Feedback/GRM → TP Staff Management
- Users must have valid email addresses

### 3. Scheduled Job Setup (Required for Reminders)
The reminder script must be scheduled to run daily. Choose one option below.

## What is `npx tsx scripts/send-feedback-reminders.ts`?

This command **manually runs** the reminder job for testing purposes. The system does NOT automatically send reminders unless you set up a scheduled job (cron).

### For Testing (Run Once Now):
```bash
cd backend
npx tsx scripts/send-feedback-reminders.ts
```

This will immediately check all feedback and send reminders where appropriate.

## Setting Up Automatic Reminders (Production)

You must set up a **scheduled job** to run the reminder script daily. Without this, reminders won't be sent automatically.

### Recommended: Ubuntu Server with Cron

**Step 1: Edit Crontab**
```bash
crontab -e
```

**Step 2: Add Daily Job (Runs at 9 AM every day)**
```cron
0 9 * * * cd /path/to/backend && /usr/bin/npx tsx scripts/send-feedback-reminders.ts >> /var/log/feedback-reminders.log 2>&1
```

Replace `/path/to/backend` with your actual backend path, for example:
```cron
0 9 * * * cd /home/ubuntu/pbps/backend && /usr/bin/npx tsx scripts/send-feedback-reminders.ts >> /var/log/feedback-reminders.log 2>&1
```

**Step 3: Verify Cron is Set**
```bash
crontab -l
```

**Step 4: Check Logs**
```bash
tail -f /var/log/feedback-reminders.log
```

### Alternative: PM2 (Process Manager)

If you're using PM2 to run your backend, you can also use PM2 for scheduled tasks:

```bash
# Install PM2 if not already installed
npm install -g pm2

# Add the cron job
pm2 start scripts/send-feedback-reminders.ts --cron "0 9 * * *" --name "feedback-reminders" --no-autorestart --interpreter tsx
```

View PM2 scheduled jobs:
```bash
pm2 list
pm2 logs feedback-reminders
```

## Notification Flow Diagram

```
New Feedback Submitted
    ↓
📧 Submitter receives acknowledgement (immediate, system SMTP)
📧 TP staff receives new feedback alert (immediate, system SMTP)
    ↓
    ⏱️ Wait 5 days
    ↓
📧 TP staff receives "2 days remaining" reminder (system SMTP)
    ↓
    ⏱️ Wait 1 day
    ↓
📧 TP staff receives "1 day remaining" reminder (system SMTP)
    ↓
    ⏱️ Due date passes
    ↓
❌ No more reminders (feedback is now overdue and affects timely rate)
```

## Testing Checklist

### Test 1: New Feedback Notification
1. Submit new feedback via public form
2. Check TP user inbox
3. ✅ Should receive "New Feedback" email within 1 minute
4. Verify all TP users for that provider received it

### Test 2: Reminder Schedule
1. Create test feedback with due date 2 days from now
2. Run reminder script manually
3. ✅ Should send "2 days remaining" reminder
4. Change due date to tomorrow, run again
5. ✅ Should send "1 day remaining" reminder
6. Change due date to yesterday, run again
7. ✅ Should send "OVERDUE" alert

### Test 3: No Double Notifications
1. Feedback that's already responded shouldn't trigger reminders
2. Add response to feedback
3. Run reminder script
4. ✅ Should skip that feedback (no reminder sent)

## Troubleshooting

### No emails received by TP staff

**Check 1: System SMTP Configuration**
```sql
SELECT * FROM app_settings WHERE `key` = 'smtp_config';
```
- System SMTP must be configured
- Same SMTP used for verification emails
- Check App Settings in admin panel

**Check 2: TP Staff Accounts**
```sql
SELECT u.email, u.name, ts.staffRole, ts.isActive
FROM users u
JOIN tp_staff_memberships ts ON u.id = ts.user_id
WHERE ts.training_provider_id = ? 
  AND ts.project_id = ?
  AND ts.is_active = 1;
```
- Must have at least one active TP staff member
- Staff must be assigned to the correct provider and project
- Users must have valid email addresses

**Check 3: Email Logs**
Check backend console for error messages:
```
[feedback] No system SMTP configured, skipping notification
[feedback] No TP users found for provider X
```

### Reminders not being sent automatically

**The script does NOT run automatically!** You must set up a cron job.

**Check:** Is the cron job configured?
```bash
crontab -l | grep feedback-reminders
```

**Check:** Review cron logs:
```bash
tail -f /var/log/feedback-reminders.log
```

**If no cron job exists:** Follow the setup instructions above to configure daily execution.

## Configuration Summary

| Feature | Requirement | Configuration Location |
|---------|-------------|------------------------|
| New feedback alerts | System SMTP + TP users | **Automatic** (no setup needed) |
| Due date reminders | **Cron job** + System SMTP | **Manual setup required** (see above) |
| Submitter acknowledgement | System SMTP | App Settings |
| Response emails | TP SMTP or System SMTP | Feedback detail page |

## Benefits

✅ **Proactive SLA Management**: Providers are alerted before deadlines  
✅ **Reduced Overdue Feedback**: Multiple reminders ensure timely responses  
✅ **Better Service Quality**: Submitters get faster responses  
✅ **Improved Compliance**: Meets 7-day response SLA requirements  
✅ **Audit Trail**: All notifications logged in console/email logs
