# Technical Context - Final Implementation

## Technology Stack - PRODUCTION READY

### Frontend Stack
- **Framework**: Next.js 16.0.1 (React 19.0.0)
- **Language**: TypeScript 5.8.3
- **Styling**: Tailwind CSS 4.0.0 with custom DeafGain theme
- **Icons**: Lucide React for modern iconography
- **Package Manager**: pnpm for efficient dependency management
- **Build**: Next.js optimized production builds

### Backend Stack
- **Runtime**: Node.js with TypeScript 5.8.3
- **Framework**: Express.js 5.0.1
- **Database ORM**: Prisma 7.0.0
- **Authentication**: JWT with bcrypt password hashing
- **File Upload**: Multer with UUID naming strategy
- **Email**: Nodemailer with Gmail SMTP integration
- **Logging**: Winston for comprehensive request/error logging
- **Security**: Helmet, CORS, rate limiting middleware

### Database & Infrastructure
- **Database**: PostgreSQL 17.5 with complete schema
- **Cache**: Redis 7-alpine for session management
- **Containerization**: Docker Compose for multi-service setup
- **File Storage**: Local filesystem with UUID naming
- **Environment**: Docker containers for PostgreSQL and Redis

### Email Integration
- **SMTP Provider**: Gmail SMTP (smtp.gmail.com:587)
- **From Address**: system@deafgain.org (Court Docket System)
- **Authentication**: Google App Password
- **Templates**: Professional HTML email templates
- **Automation**: Triggers on new docket entry creation

## Architecture Patterns - IMPLEMENTED

### Backend Architecture
```
backend/
├── src/
│   ├── index.ts              # Main Express server
│   ├── middleware/           # Security, auth, logging
│   │   ├── auth.ts          # JWT authentication
│   │   ├── errorHandler.ts  # Global error handling
│   │   └── requestLogger.ts # Winston request logging
│   ├── routes/              # API endpoints
│   │   ├── auth.ts          # Admin authentication
│   │   ├── docket.ts        # Docket CRUD operations
│   │   ├── documents.ts     # File upload/management
│   │   ├── subscriptions.ts # Email subscription
│   │   └── health.ts        # System health check
│   ├── services/            # Business logic
│   │   └── emailService.ts  # Gmail SMTP integration
│   └── utils/
│       └── logger.ts        # Winston configuration
├── prisma/
│   ├── schema.prisma        # Database schema
│   └── migrations/          # Database migrations
└── uploads/                 # File storage directory
```

### Frontend Architecture
```
frontend/
├── src/
│   └── app/
│       ├── layout.tsx       # Root layout with metadata
│       ├── page.tsx         # Public court docket display
│       ├── globals.css      # DeafGain theme styling
│       └── admin/
│           ├── page.tsx     # Admin login
│           ├── dashboard/
│           │   └── page.tsx # Admin dashboard
│           └── upload/
│               └── page.tsx # File upload interface
├── tailwind.config.js       # DeafGain color configuration
└── next.config.js          # API proxy configuration
```

## Database Schema - COMPLETE

### Tables Implemented
```sql
-- Admin users with secure authentication
admin_users (
  id SERIAL PRIMARY KEY,
  username VARCHAR(50) UNIQUE NOT NULL,
  password_hash VARCHAR(255) NOT NULL,
  created_at TIMESTAMP DEFAULT NOW(),
  last_login TIMESTAMP
)

-- Court docket entries
docket_entries (
  id SERIAL PRIMARY KEY,
  date DATE NOT NULL,
  title VARCHAR(500) NOT NULL,
  summary TEXT NOT NULL,
  notes TEXT,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
)

-- Document attachments
documents (
  id SERIAL PRIMARY KEY,
  docket_entry_id INTEGER REFERENCES docket_entries(id) ON DELETE CASCADE,
  title VARCHAR(255) NOT NULL,
  original_filename VARCHAR(255) NOT NULL,
  stored_filename VARCHAR(255) NOT NULL,
  file_path VARCHAR(500) NOT NULL,
  file_size INTEGER NOT NULL,
  mime_type VARCHAR(100) NOT NULL,
  summary TEXT,
  notes TEXT,
  display_order INTEGER DEFAULT 0,
  created_at TIMESTAMP DEFAULT NOW(),
  updated_at TIMESTAMP DEFAULT NOW()
)

-- Email subscriptions
subscriptions (
  id SERIAL PRIMARY KEY,
  email VARCHAR(255) UNIQUE NOT NULL,
  is_active BOOLEAN DEFAULT true,
  unsubscribe_token VARCHAR(255) UNIQUE NOT NULL,
  created_at TIMESTAMP DEFAULT NOW()
)
```

### Current Data
- **8 docket entries** with real court case information
- **3 active email subscribers** receiving notifications
- **1 admin user** with secure authentication
- **Complete relationships** between entries and documents

## API Endpoints - OPERATIONAL

### Public Endpoints
- `GET /api/health` - System health check
- `GET /api/docket-entries` - Fetch all docket entries with documents
- `POST /api/subscriptions/subscribe` - Email subscription

### Admin Endpoints (JWT Protected)
- `POST /api/auth/login` - Admin authentication
- `GET /api/auth/verify` - Token verification
- `GET /api/docket-entries/:id` - Get single docket entry
- `POST /api/docket-entries` - Create new docket entry (triggers email)
- `PUT /api/docket-entries/:id` - Update docket entry
- `DELETE /api/docket-entries/:id` - Delete docket entry
- `POST /api/documents/upload` - Upload PDF documents
- `GET /api/documents/:id/download` - Download documents

## Security Implementation - PRODUCTION READY

### Authentication & Authorization
- **JWT Tokens**: Secure admin authentication with expiration
- **Password Hashing**: bcrypt with salt rounds for admin passwords
- **Protected Routes**: Middleware-based route protection
- **Token Validation**: Comprehensive token verification

### Input Validation & Security
- **File Upload**: PDF-only validation with size limits (10MB)
- **Input Sanitization**: Joi validation for all API inputs
- **SQL Injection**: Prisma ORM prevents SQL injection
- **XSS Protection**: Helmet middleware for security headers
- **CORS**: Configured for frontend-backend communication
- **Rate Limiting**: Express rate limiting middleware

### File Security
- **UUID Naming**: Prevents file name conflicts and guessing
- **Type Validation**: Only PDF files accepted
- **Size Limits**: 10MB maximum file size
- **Secure Storage**: Files stored outside web root

## Styling & Design - DEAFGAIN THEME

### Color Palette
```css
:root {
  --primary: #647C90;        /* Slate blue */
  --secondary: #2C4A3E;      /* Forest green */
  --accent-snow: #F5F7F9;    /* Snow white background */
  --accent-mountain: #4A5568; /* Mountain gray text */
  --accent-lake: #A4C3D2;    /* Alpine lake blue */
}
```

### Design Features
- **Mountain/Nature Theme**: Professional outdoor-inspired colors
- **Gradient Headers**: CSS gradients for modern appeal
- **Hover Effects**: Smooth transitions and animations
- **Modern Cards**: Rounded corners with shadows
- **Responsive Design**: Mobile-first approach
- **Professional Typography**: Inter font for readability

### CSS Architecture
- **Tailwind CSS**: Utility-first styling framework
- **Custom Components**: Reusable button and card classes
- **CSS Variables**: Consistent color management
- **Modern Effects**: Gradients, shadows, animations
- **Print Styles**: Optimized for document printing

## Email System - GMAIL INTEGRATION

### SMTP Configuration
```env
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_SECURE=false
GOOGLE_EMAIL=system@deafgain.org
GOOGLE_APP_PASSWORD=ojvlysraxwjriwzy
```

### Email Features
- **Professional Templates**: HTML emails with court branding
- **Automatic Triggers**: Sends on new docket entry creation
- **Subscriber Management**: Database-driven subscription system
- **Delivery Confirmation**: Message ID tracking
- **Error Handling**: Graceful failure without breaking main flow

### Email Content
- **Court Case Header**: Professional branding
- **Filing Information**: Date, title, summary formatting
- **Direct Links**: Link to view complete docket
- **Responsive Design**: Works in all email clients
- **Unsubscribe Info**: Professional footer with instructions

## Performance & Optimization

### Frontend Performance
- **Next.js Optimization**: Automatic code splitting and optimization
- **Modern CSS**: Efficient Tailwind CSS with purging
- **Image Optimization**: Next.js automatic image optimization
- **Caching**: Browser caching for static assets

### Backend Performance
- **Database Indexing**: Optimized queries with Prisma
- **Connection Pooling**: PostgreSQL connection pooling
- **Efficient Queries**: Minimal database calls
- **Logging**: Structured logging without performance impact

### Development Experience
- **Hot Reloading**: Both frontend and backend auto-reload
- **TypeScript**: Full type safety across the stack
- **Error Handling**: Comprehensive error reporting
- **Development Tools**: Prisma Studio, logging, debugging

## Testing & Quality Assurance

### Testing Infrastructure
- **Comprehensive Guide**: Manual testing procedures (TESTING_GUIDE.md)
- **Automated Scripts**: API testing automation (test_all_apis.sh)
- **Security Testing**: Authentication and file validation
- **Performance Testing**: Load and response time verification

### Quality Metrics
- **Code Quality**: TypeScript, ESLint, proper error handling
- **Security**: JWT auth, input validation, file restrictions
- **Performance**: <2s page loads, <500ms API responses
- **Usability**: Mobile-responsive, accessible design
- **Reliability**: Error handling, logging, comprehensive testing

## Deployment Configuration

### Development Environment
- **Frontend**: http://localhost:3000 (Next.js dev server)
- **Backend**: http://localhost:3001 (Express with tsx)
- **Database**: PostgreSQL container on port 5432
- **Cache**: Redis container on port 6379

### Production Environment
**IMPORTANT**: Production server is **10.4.0.205** (NOT chrishaulmark.com)

- **Server**: 10.4.0.205 (public-websites VM behind NAT)
- **SSH Access**: `ssh chaulmark@10.4.0.205`
- **Project Location**: `~/websites/mad-lawsuit.org/`
- **Docker Volumes**: `/docker/websites/mad-lawsuit/`
- **Frontend Port**: 806 (internal Docker network)
- **Backend Port**: 901 (internal Docker network)
- **Reverse Proxy**: Caddy on caddy_network
  - Frontend IP: 172.18.0.6:806
  - Backend IP: 172.18.0.5:901

### Production URLs
- **Public Website**: https://mad-lawsuit.org
- **Backend API**: https://files.mad-lawsuit.org
- **SSL Certificates**: Let's Encrypt via Caddy (auto-renewing)

### Production Deployment Process
```bash
# SSH to production server
ssh chaulmark@10.4.0.205

# Navigate to project
cd ~/websites/mad-lawsuit.org

# Pull latest code
git pull

# Rebuild and restart containers
docker compose down
docker compose build
docker compose up -d

# Check container status
docker compose ps
docker compose logs -f
```

### Production Infrastructure
- **Docker Compose**: Multi-service container setup
- **Environment Variables**: Secure configuration management
- **Database Migrations**: Automated schema updates
- **File Storage**: `/docker/websites/mad-lawsuit/uploads/` (158MB of PDFs)
- **Database**: `/docker/websites/mad-lawsuit/postgres_data/` (47MB)
- **Redis Cache**: `/docker/websites/mad-lawsuit/redis_data/`
- **Logging**: Comprehensive request and error logging

## Current System Status

### Live Metrics
- **Docket Entries**: 8 total with real court data
- **Email Subscribers**: 3 active receiving notifications
- **Email Delivery**: Confirmed working to chris@sigd.net
- **Admin Access**: Secure JWT authentication operational
- **File Upload**: PDF validation and UUID storage working
- **Database**: PostgreSQL with complete schema and data

### Access Points
- **Public Website**: http://localhost:3000
- **Admin Login**: http://localhost:3000/admin (admin/admin123)
- **Admin Dashboard**: http://localhost:3000/admin/dashboard
- **File Upload**: http://localhost:3000/admin/upload
- **Email System**: system@deafgain.org (active and sending)

## Technical Achievements

### Completed Implementation
- ✅ **Full Stack Application**: Complete frontend and backend
- ✅ **Real Email Integration**: Gmail SMTP with actual delivery
- ✅ **Modern UI/UX**: DeafGain mountain theme with animations
- ✅ **Security**: JWT auth, input validation, file restrictions
- ✅ **Database**: Complete schema with relationships and data
- ✅ **Testing**: Comprehensive testing suite and automation
- ✅ **Documentation**: Complete technical documentation

### Production Ready Features
- **Scalable Architecture**: Clean separation of concerns
- **Security Best Practices**: Authentication, validation, protection
- **Modern Technology Stack**: Latest versions of all frameworks
- **Professional Design**: Court-appropriate styling and branding
- **Comprehensive Testing**: Manual and automated test coverage
- **Real-World Functionality**: Actual email delivery and file management

The court docket website is now a fully functional, production-ready application with modern technology stack, professional design, and real-world capabilities including Gmail email notifications and secure file management.
