# Push Notifications Debug Guide

## Testing Background Notifications

### 1. Check if Service Worker is Active

Open Chrome DevTools on mobile (via `chrome://inspect` on desktop with USB debugging):

```javascript
// In console:
navigator.serviceWorker.getRegistration().then(reg => {
  console.log('SW State:', reg.active?.state)
  console.log('SW Scope:', reg.scope)
})
```

**Expected:** `activated` state

### 2. Check Push Subscription

```javascript
// In console:
navigator.serviceWorker.ready.then(reg => {
  reg.pushManager.getSubscription().then(sub => {
    console.log('Subscription:', sub ? 'Active' : 'None')
    console.log('Endpoint:', sub?.endpoint)
  })
})
```

**Expected:** Active subscription with Google FCM or Mozilla endpoint

### 3. Check Server Logs

When a new order arrives, check PM2 logs:

```bash
pm2 logs erpfrontend --lines 50 | grep WebPush
```

**Expected output:**
```
[WebPush] Sending to 1 subscribers for roles: [1000000]
[WebPush] ✅ Sent to: https://fcm.googleapis.com/fcm/send/...
[WebPush] Results: { sent: 1, failed: 0, removed: 0 }
```

### 4. Test Background Delivery

**Setup:**
1. Install PWA (Add to Home Screen)
2. Grant notification permission
3. Minimize/background the PWA (don't close completely)
4. Create a test order from another device

**Check:**
- Did notification appear?
- Did phone vibrate?
- Check Chrome's notification log: `chrome://notifications-internals/`

### 5. Common Issues

#### Issue: "Notifications work when app is open, not in background"

**Android Chrome Limitations:**
- Works in background (app minimized) ✅
- Does NOT work when app is swiped away completely ❌
- This is a browser limitation, not our code

**Solution:** Install as PWA for better background persistence

#### Issue: "No notifications at all"

**Check:**
1. Notification permission granted? `Notification.permission === 'granted'`
2. Service worker registered? See test 1 above
3. Push subscription saved? Check SQLite: `SELECT * FROM push_subscriptions;`
4. Server sending? Check PM2 logs for `[WebPush]` messages
5. Network blocking push endpoints? Try different network

#### Issue: "Notifications marked as spam"

**Solution:**
- Long-press notification → Settings → Allow
- Install as PWA for better trust
- After a few notifications, Chrome learns they're legitimate

### 6. SQLite Database Check

On production server:

```bash
cd /opt/erp-nuxt-frontend/data
sqlite3 push-subscriptions.db "SELECT user_id, role_id, created_at FROM push_subscriptions;"
```

**Expected:** Your user subscription listed

### 7. Test Push Manually

Send a test push from the server:

```javascript
// In server/api/push/test.post.ts (create for testing)
import { sendPushToRoles } from '~/server/utils/pushNotifier'

export default defineEventHandler(async (event) => {
  await sendPushToRoles([1000000], {
    title: '🧪 Test Notification',
    body: 'This is a test push notification',
    url: '/sales/orders'
  })

  return { success: true }
})
```

Then call: `curl -X POST https://app.logship.de/api/push/test`

### 8. Push Options Explained

**Server-side (`pushNotifier.ts`):**
- `urgency: 'high'` - Tells push service to deliver immediately, even in background
- `TTL: 86400` - Message expires after 24 hours if not delivered
- `topic: 'new-orders'` - Groups notifications (newer ones replace older)

**Client-side (`sw-notifications.js`):**
- `tag: 'order-' + Date.now()` - Unique tag = each notification shows separately
- `renotify: true` - Always notify user, even if similar notification exists
- `requireInteraction: false` - Notification dismisses automatically
- `silent: false` - Enable sound/vibration

### 9. Browser Support

| Platform | Background Push | Notes |
|----------|----------------|-------|
| Android Chrome | ✅ Yes (when minimized) | ❌ Not when fully closed |
| Android PWA | ✅ Better persistence | ✅ Recommended |
| Desktop Chrome | ✅ Yes (even when closed) | Works perfectly |
| iOS Safari | ⚠️ Limited | Requires Home Screen install |
| iOS Chrome | ❌ No | Uses Safari engine |

### 10. Debugging Service Worker

**View Service Worker state:**
1. Mobile Chrome: `chrome://serviceworker-internals/`
2. Desktop debugging: `chrome://inspect` → Find your device

**Force service worker update:**
```javascript
navigator.serviceWorker.getRegistration().then(reg => {
  reg.update()
  console.log('Forced SW update check')
})
```

**Unregister and start fresh:**
```javascript
navigator.serviceWorker.getRegistration().then(reg => {
  reg.unregister()
  console.log('SW unregistered - refresh page')
})
```

## Expected Behavior

✅ **Desktop:** Notifications work even when browser is fully closed
✅ **Android Chrome (minimized):** Notifications work when app is in background
✅ **Android PWA:** Better background persistence than regular Chrome
⚠️ **Android Chrome (closed):** Does NOT work when app is swiped away
❌ **iOS:** Limited support, requires Home Screen install

## Quick Checklist

- [ ] Service worker registered globally (check DevTools)
- [ ] Notification permission granted
- [ ] Push subscription saved to database
- [ ] PWA installed (for best results on mobile)
- [ ] Server logs show `[WebPush] ✅ Sent to:` messages
- [ ] Test with app minimized (not closed)
- [ ] Check notification settings (not marked as spam)
