# Feedback SMTP Troubleshooting Guide

## Current Issue

When TPs try to reply to feedback without TP SMTP configured:
1. TP clicks "Send reply" → ❌ Error `NO_TP_SMTP_CONFIGURED` → Shows modal ✅
2. TP clicks "Use System SMTP" in modal → ❌ Error `NO_SMTP_CONFIGURED` 

The error says "System SMTP is not configured" even though you believe it's configured.

## Root Cause

System SMTP is stored in the `app_settings` database table with key `smtp_config`, but it appears this record doesn't exist or the value is empty/null.

## How to Check if System SMTP is Configured

Run this SQL query in your database:

```sql
SELECT * FROM app_settings WHERE `key` = 'smtp_config';
```

**Expected result if configured:**
```
| id | key         | value                          | created_at | updated_at |
|----|-------------|--------------------------------|------------|------------|
| 1  | smtp_config | {"smtpHost":"...", ...}        | ...        | ...        |
```

**If you get NO rows** → System SMTP is NOT configured

## Solution Options

### Option 1: Configure System SMTP via Admin UI (Recommended)

Check if there's an admin settings page in your application:
- Navigate to Admin → Settings → System SMTP or Email Configuration
- Fill in the SMTP details (host, port, user, password, sender name, sender email)
- Save

### Option 2: Insert System SMTP Manually via SQL

If there's no UI, insert directly into database:

```sql
INSERT INTO app_settings (`key`, `value`, created_at, updated_at)
VALUES (
  'smtp_config',
  JSON_OBJECT(
    'smtpHost', 'smtp.gmail.com',
    'smtpPort', 587,
    'smtpUser', 'your-email@example.com',
    'smtpPassword', 'your-app-password',
    'smtpType', 'starttls',
    'senderName', 'PBPS MIS',
    'senderEmail', 'your-email@example.com'
  ),
  NOW(),
  NOW()
);
```

**Replace with your actual SMTP details:**
- `smtpHost`: Your SMTP server (e.g., `smtp.gmail.com`, `smtp.office365.com`)
- `smtpPort`: Usually `587` for STARTTLS or `465` for SSL
- `smtpUser`: Email username
- `smtpPassword`: Email password (or app-specific password for Gmail)
- `smtpType`: `starttls` or `ssl`
- `senderName`: Display name for emails (e.g., "PBPS MIS")
- `senderEmail`: From email address

### Option 3: Check Existing Configuration

If you think it's already configured, check the value:

```sql
SELECT id, `key`, JSON_PRETTY(value) as smtp_config 
FROM app_settings 
WHERE `key` = 'smtp_config';
```

This will show the formatted JSON. Verify all fields are present and correct.

## Flow After Fix

Once system SMTP is configured in `app_settings`:

1. TP clicks "Send reply" → No TP SMTP → Shows modal ✅
2. TP clicks "Use System SMTP" → ✅ Uses system SMTP from `app_settings` → Email sent! ✅

## Testing

After configuring system SMTP:

1. Restart backend server
2. Login as TP user
3. Go to Feedback page
4. Click "Send reply" on a feedback
5. Modal should appear (no TP SMTP)
6. Click "Use System SMTP"
7. ✅ Should send successfully with toast: "Reply sent and emailed to submitter"

## Code Flow Reference

**Backend:** `mis/backend/src/services/smtp.ts`
```typescript
// Line ~490: Checks for system SMTP
const systemSmtp = await prisma.appSetting.findFirst({
  where: { key: "smtp_config" },
  select: { value: true },
});

if (systemSmtp?.value) {
  // Uses system SMTP config
} else {
  // Throws NO_SMTP_CONFIGURED error
}
```

## Quick Diagnostic Script

Run this to check your current SMTP configuration status:

```sql
-- Check if system SMTP exists
SELECT 
  CASE 
    WHEN COUNT(*) > 0 THEN '✅ System SMTP configured'
    ELSE '❌ System SMTP NOT configured'
  END as system_smtp_status
FROM app_settings 
WHERE `key` = 'smtp_config' AND value IS NOT NULL;

-- Check TP SMTP configurations
SELECT 
  COUNT(*) as tp_smtp_count,
  GROUP_CONCAT(DISTINCT tp.name SEPARATOR ', ') as providers_with_smtp
FROM tp_smtp_configurations tsc
JOIN training_providers tp ON tsc.training_provider_id = tp.id
WHERE tsc.status = 'active';
```

