# Plan: User Transaction and Login Logs for Super Admin Dashboard

## Overview
Add a comprehensive logging system to track user logins and transactions in the super admin dashboard. This will help administrators monitor user activity, detect suspicious behavior, and track payment/subscription events.

## Current State
- `AuditLog` model exists in `app/models/features.py` with basic fields
- Admin audit log view exists at `app/templates/admin/audit.html`
- Login flow in `app/routes/auth.py` does not log login attempts
- Payment webhooks in `app/routes/billing.py` do not log transactions

## Implementation Plan

### 1. Enhance AuditLog Model
**File:** `app/models/features.py`

Add new fields to better categorize logs:
```python
# Add to AuditLog model:
log_type = db.Column(db.String(50), default="general")  # login, transaction, general
status = db.Column(db.String(20), default="success")    # success, failed, pending
user_agent = db.Column(db.String(500), nullable=True)   # Browser/device info
```

Create migration for new columns.

### 2. Add Login Logging
**File:** `app/routes/auth.py`

Create a helper function to log login attempts:
```python
def _log_login_attempt(user, success, ip_address, user_agent=None):
    from app.models.features import AuditLog
    log = AuditLog(
        user_id=user.id if user else None,
        action="login_attempt",
        log_type="login",
        status="success" if success else "failed",
        resource_type="User",
        resource_id=user.id if user else None,
        ip_address=ip_address,
        user_agent=user_agent,
        details={"email": user.email if user else "unknown"}
    )
    db.session.add(log)
    db.session.commit()
```

Update login route to log attempts (both success and failure).

### 3. Add Transaction Logging
**File:** `app/routes/billing.py`

Log payment events in the webhook handler:
```python
def _log_transaction(user_id, event_type, amount, currency, status, details):
    from app.models.features import AuditLog
    log = AuditLog(
        user_id=user_id,
        action=event_type,  # subscription_created, payment_completed, etc.
        log_type="transaction",
        status=status,
        resource_type="Subscription" if "subscription" in event_type else "MarketplacePurchase",
        details=details
    )
    db.session.add(log)
    db.session.commit()
```

### 4. Create Admin Activity Logs View
**File:** `app/templates/admin/activity_logs.html`

New dedicated page with:
- Filter by log type (login, transaction, general)
- Filter by status (success, failed, pending)
- Date range picker
- User search
- IP address search
- Export to CSV button

Display:
- Timestamp
- User (with link to profile)
- Action type
- Status (color-coded)
- IP address
- User agent (device/browser)
- Details (expandable JSON)

### 5. Add Admin Routes
**File:** `app/routes/admin.py`

Add new routes:
```python
@admin_bp.route("/activity-logs")
@admin_required
def activity_logs():
    # List with filters
    pass

@admin_bp.route("/activity-logs/export")
@admin_required
def export_activity_logs():
    # CSV export
    pass
```

### 6. Create Login-specific Dashboard Widget
**File:** `app/templates/admin/index.html`

Add to admin dashboard:
- Recent failed login attempts (security alert)
- Recent successful logins
- Recent transactions
- Map or chart of login locations by IP

### 7. Add Security Alerts
**File:** `app/models/features.py` or new `app/models/security_alerts.py`

Create security alert model for:
- Multiple failed logins from same IP
- Login from unusual location
- Suspicious transaction patterns

## Files to Create/Modify

### New Files
1. `migrations/versions/004_enhance_audit_logs.py` - Migration for new audit log fields
2. `app/templates/admin/activity_logs.html` - New activity logs view

### Modified Files
1. `app/models/features.py` - Add fields to AuditLog
2. `app/routes/auth.py` - Add login logging
3. `app/routes/billing.py` - Add transaction logging
4. `app/routes/admin.py` - Add activity logs routes
5. `app/templates/admin/index.html` - Add security widgets
6. `app/templates/admin/audit.html` - May update or deprecate in favor of new view

## Implementation Steps

1. Create migration for new AuditLog fields
2. Run migration
3. Update AuditLog model
4. Create logging helper functions
5. Integrate logging in auth routes (login, logout, failed attempts)
6. Integrate logging in billing routes (payments, subscriptions)
7. Create activity logs admin view with filters
8. Add admin routes for activity logs
9. Add security dashboard widgets to admin index
10. Test with various login attempts and transactions

## Database Changes

```sql
ALTER TABLE audit_logs ADD COLUMN log_type VARCHAR(50) DEFAULT 'general';
ALTER TABLE audit_logs ADD COLUMN status VARCHAR(20) DEFAULT 'success';
ALTER TABLE audit_logs ADD COLUMN user_agent VARCHAR(500);

CREATE INDEX idx_audit_logs_log_type ON audit_logs(log_type);
CREATE INDEX idx_audit_logs_status ON audit_logs(status);
CREATE INDEX idx_audit_logs_created_at ON audit_logs(created_at DESC);
```
