# BNKops Influence Campaign Tool - File Structure Explanation

This document explains the purpose and functionality of each file in the BNKops Influence Campaign Tool.

## Overview

The BNKops Influence Campaign Tool is a comprehensive political engagement platform that allows users to create and participate in advocacy campaigns, contact their elected representatives, and track campaign analytics. The application features campaign management, user authentication, representative lookup via the Represent API, email composition and sending, and detailed analytics tracking.

## Campaign Settings System

The application includes a flexible campaign configuration system that allows administrators to customize campaign behavior and appearance. Campaign settings control user experience, data collection, and engagement tracking.

### Core Campaign Settings

**Email Count Display** (`show_email_count`):
- **Purpose**: Controls visibility of total emails sent metric on campaign landing pages
- **Implementation**: Checkbox field in campaigns table (default: true)
- **When Enabled**: Shows "X Albertans have sent emails through this campaign" banner
- **When Disabled**: Hides public email count while maintaining admin tracking
- **Use Cases**: 
  - ✅ Enable for public campaigns to demonstrate momentum and social proof
  - ❌ Disable for sensitive campaigns or when starting with low participation
- **Database**: `show_email_count` BOOLEAN field in campaigns table
- **Backend**: `getCampaignEmailCount()` fetches count when setting is enabled
- **Frontend**: `campaign.js` shows/hides `campaign-stats` div based on setting
- **Admin Panel**: Checkbox labeled "📊 Show Email Count" in create/edit forms

**SMTP Email** (`allow_smtp_email`):
- Enables server-side email sending through SMTP configuration
- When enabled, emails sent via backend with full logging and tracking

**Mailto Links** (`allow_mailto_link`):
- Allows browser-based email client launching via mailto: URLs
- Useful fallback when SMTP isn't configured or for user preference

**User Info Collection** (`collect_user_info`):
- When enabled, requests user's name and email before showing representatives
- Supports campaign tracking and follow-up communications

**Email Editing** (`allow_email_editing`):
- Allows users to customize email subject and body before sending
- When disabled, forces use of campaign template only

**Cover Photo** (`cover_photo`):
- Upload custom hero images for campaign landing pages
- Supported formats: JPEG, PNG, GIF, WebP (max 5MB)
- Displays as full-width background with overlay on campaign pages

**Target Government Levels** (`target_government_levels`):
- MultiSelect field for Federal, Provincial, Municipal, School Board
- Filters which representatives are displayed to campaign participants

**Campaign Status** (`status`):
- Draft: Hidden from public, testing only
- Active: Visible on main page and accessible via slug URL
- Paused: Temporarily disabled
- Archived: Completed campaigns, read-only

### Technical Implementation

**Database Schema** (`build-nocodb.sh`):
```javascript
{
    "column_name": "show_email_count",
    "title": "Show Email Count",
    "uidt": "Checkbox",
    "cdf": "true"  // Default enabled
}
```

**Backend API** (`campaigns.js`):
- `getCampaignBySlug()`: Checks `show_email_count` setting and conditionally fetches email count
- `getAllCampaigns()`: Includes email count for all campaigns (admin view)
- `getCampaignEmailCount()`: Queries campaign_emails table for total sent emails

**Frontend Display** (`campaign.js`):
```javascript
if (this.campaign.show_email_count && this.campaign.emailCount !== null) {
    document.getElementById('email-count').textContent = this.campaign.emailCount;
    document.getElementById('campaign-stats').style.display = 'block';
}
```

**Admin Interface** (`admin.html`):
- Create form: Checkbox with `id="create-show-count"` and `name="show_email_count"`
- Edit form: Checkbox with `id="edit-show-count"` pre-populated from campaign data
- Default state: Checked (enabled) for new campaigns

**Service Layer** (`nocodb.js`):
- Field mapping: `'Show Email Count': campaignData.show_email_count`
- Create/Update operations: Properly formats boolean value for NocoDB API
- Read operations: Normalizes field from NocoDB title to JavaScript property name

### Campaign Email Count Tracking

The email count feature tracks engagement across campaign participation. The system counts emails sent through:
- SMTP-based email sending (fully tracked with delivery status)
- Campaign email logs in NocoDB campaign_emails table
- Associated with specific campaign IDs for accurate attribution

**Count Calculation**:
- Queries campaign_emails table with `(Campaign ID,eq,{campaignId})` filter
- Returns total count of matching records
- Updates in real-time as users participate
- Cached in campaign response for performance

**Display Logic**:
- Only shows count when both `show_email_count=true` AND `emailCount > 0`
- Handles null/undefined counts gracefully
- Updates without page refresh using dynamic JavaScript rendering

## Authentication System

The application includes a complete authentication system supporting both admin and regular user access. Authentication is implemented using NocoDB as the user database, bcryptjs for password hashing, and express-session for session management. The system supports temporary users with expiration dates for campaign-specific access.

## Cover Photo Feature

Campaign cover photos enhance visual engagement and branding for advocacy campaigns. This feature allows administrators and authorized users to upload custom images that display as hero banners on campaign landing pages.

**Implementation Details:**
- **Backend:** Multer middleware handles file uploads with validation (JPEG/PNG/GIF/WebP, max 5MB)
- **Storage:** Files stored in `/app/public/uploads/` with unique timestamp-based filenames
- **Database:** NocoDB `cover_photo` field stores filename references in campaigns table
- **Frontend:** Dynamic background-image rendering with responsive CSS and overlay effects
- **API Routes:** FormData multipart/form-data support in create/update campaign endpoints
- **Security:** File type validation, size limits, and sanitized filenames prevent malicious uploads
- **Fallback:** Gradient background displays when no cover photo is uploaded

**User Experience:**
- Admin interface includes file input with current photo preview
- Campaign pages display cover photos as full-width hero backgrounds with semi-transparent overlays
- Mobile-responsive scaling ensures optimal display across all devices
- Optional feature - campaigns function normally without cover photos

## Root Directory Files

### Configuration Files
- **`.env`** - Environment configuration containing NocoDB API credentials, SMTP settings, session secrets, API tokens, and table URLs for database integration
- **`.env.backup.20250930_105913`** - Automated backup of environment configuration from September 30, 2025 at 10:59:13
- **`.env.backup.20250930_163827`** - Automated backup of environment configuration from September 30, 2025 at 16:38:27
- **`example.env`** - Template for environment configuration with placeholder values and documentation
- **`docker-compose.yml`** - Docker container orchestration with MailHog for email testing in development mode
- **`fix-campaigns-table.sh`** - Database repair script for fixing campaign table structure and data integrity issues

### Documentation
- **`API Reference Represent Elected Officials and Electoral Districts API for Canada.md`** - Complete API documentation for the Represent OpenNorth API used for representative lookup
- **`README.MD`** - Main project documentation with features overview, setup instructions, and usage guidelines
- **`files-explainer.md`** - This file, providing comprehensive documentation of the project structure and file purposes
- **`instruct.md`** - Development guidelines, implementation notes, and contribution instructions
- **`influence-campaign-setup.md`** - Detailed setup guide for deploying and configuring the influence campaign tool

## Application Structure (`app/`)

### Entry Point
- **`server.js`** - Express.js application entry point with comprehensive middleware setup, route mounting, security configuration, session management, and static file serving. Includes protected routes for admin and user areas, error handling, and environment-specific configurations

- **`Dockerfile`** - Container definition for the Node.js application with multi-stage build, security optimizations, and production configurations

- **`package.json`** - Node.js project manifest defining dependencies including Express.js, authentication libraries (bcryptjs, express-session), email services (nodemailer), API clients (axios), security middleware (helmet, cors), validation libraries, and development tools

### Controllers (`app/controllers/`)
Business logic layer that handles HTTP requests and responses:

- **`authController.js`** - Authentication controller managing user login/logout operations
  - `login()` - Handles user authentication with email/password validation, bcryptjs password verification, and session creation
  - `logout()` - Destroys user sessions and clears authentication state
  - `checkSession()` - Verifies current authentication status and returns user information
  - `register()` - User registration with password hashing and account creation
  - Integrates with NocoDB users table for credential storage and verification
  - Updates last login timestamps and manages session persistence

- **`campaigns.js`** - Core campaign management functionality with comprehensive CRUD operations
  - `getPublicCampaigns()` - **Public endpoint** retrieves only active campaigns without authentication, returns filtered data with email counts if enabled
  - `getAllCampaigns()` - Retrieves campaigns with filtering, pagination, and user permissions
  - `createCampaign()` - Creates new campaigns with validation, slug generation, and cover photo upload handling using multer
  - `updateCampaign()` - Updates campaign details, status management, and cover photo processing
  - `deleteCampaign()` - Removes campaigns with data cleanup and permission checks
  - `getCampaignBySlug()` - Public campaign access for landing pages and participation
  - `participateInCampaign()` - Handles user participation, representative lookup, and email sending
  - `getCampaignAnalytics()` - Generates campaign performance metrics and participation statistics
  - Cover photo feature: Supports image uploads (JPEG, PNG, GIF, WebP) up to 5MB, stores files in `/public/uploads/` with unique filenames, and saves filename references to NocoDB
  - Advanced features: attachment URL normalization, representative caching, email templating, and analytics tracking
  - File upload middleware configuration using multer with diskStorage, file size limits, and image type validation

- **`representatives.js`** - Representative lookup and caching functionality
  - `getByPostalCode()` - Main endpoint for finding representatives by postal code using Represent API
  - `refreshPostalCode()` - Force refresh of cached representative data
  - `testConnection()` - Health check for Represent API connectivity
  - `searchRepresentatives()` - Search functionality for finding specific representatives
  - Handles intelligent caching logic, fallback to API when cache fails, and data normalization

- **`emails.js`** - Email composition and delivery management
  - `sendEmail()` - Process and send emails to representatives with template support and test mode
  - `previewEmail()` - Generate email previews without sending for content review
  - `sendTestEmail()` - Send test emails to configured recipients for system verification
  - `sendCampaignEmail()` - Campaign-specific email sending with participant tracking
  - `getEmailLogs()` - Retrieve email history with filtering, pagination, and analytics
  - `testSMTPConnection()` - Test SMTP server connectivity for diagnostics
  - Integrates with email templates, logs all activity to database, and supports both HTML and text formats

- **`usersController.js`** - User management and administration
  - `getAll()` - Retrieve all users with role filtering and pagination
  - `create()` - Create new users with password generation and email notification
  - `update()` - Update user details, roles, and account settings
  - `delete()` - Remove users with data cleanup and session invalidation
  - `sendLoginDetails()` - Email login credentials to users with secure password handling
  - `broadcastEmail()` - Send mass emails to user groups with template support
  - `getExpiredUsers()` - Identify and manage temporary user account expiration
  - Features temporary user support, role-based access control, and comprehensive user lifecycle management

### Routes (`app/routes/`)
API endpoint definitions and request validation:

- **`auth.js`** - Authentication API routes with comprehensive security
  - POST `/api/auth/login` - User login endpoint with rate limiting and validation
  - POST `/api/auth/logout` - User logout endpoint with session cleanup
  - GET `/api/auth/session` - Session verification and user information endpoint
  - POST `/api/auth/register` - User registration endpoint with password requirements
  - Handles authentication requests with proper validation, error handling, and security measures

- **`api.js`** - Main API routes with extensive validation middleware
  - Campaign management endpoints: CRUD operations for campaigns, participation, analytics
  - GET `/api/public/campaigns` - **Public endpoint** (no auth required) returns all active campaigns with email counts if enabled
  - GET `/api/campaigns/:slug` - Public campaign lookup by URL slug for campaign landing pages
  - GET `/api/campaigns/:slug/representatives/:postalCode` - Get representatives for a campaign by postal code
  - POST `/api/campaigns/:slug/track-user` - Track user participation in campaigns
  - POST `/api/campaigns/:slug/send-email` - Send campaign emails to representatives
  - Representative endpoints with postal code validation and caching
  - Email endpoints with input sanitization, template support, and test mode
  - Email management: `/api/emails/preview`, `/api/emails/send`, `/api/emails/logs`, `/api/emails/test`
  - File upload endpoints for campaign attachments and media
  - Health check and system testing endpoints
  - Comprehensive rate limiting, input validation, and error handling middleware

- **`users.js`** - User management API routes (admin access)
  - GET `/api/users` - List all users with filtering and pagination
  - POST `/api/users` - Create new users with role assignment
  - PUT `/api/users/:id` - Update user details and permissions
  - DELETE `/api/users/:id` - Remove users with data cleanup
  - POST `/api/users/broadcast` - Send broadcast emails to user groups
  - Includes admin authorization checks and comprehensive user lifecycle management

- **`dashboard.js`** - User dashboard and analytics API routes
  - GET `/api/dashboard/stats` - User-specific dashboard statistics
  - GET `/api/dashboard/campaigns` - User's campaign participation history
  - GET `/api/dashboard/analytics` - Personal analytics and activity tracking
  - Provides personalized data views with role-based access control

### Services (`app/services/`)
External system integrations and data access layer:

- **`nocodb.js`** - Comprehensive NocoDB database integration service
  - User management: `getUserByEmail()`, `createUser()`, `updateUser()`, `deleteUser()`, `getAllUsers()`
  - Campaign operations: `createCampaign()`, `updateCampaign()`, `getCampaigns()`, `deleteCampaign()`
  - Representative caching: `getRepresentativesByPostalCode()`, `storeRepresentatives()`, `cacheRepresentatives()`
  - Email logging: `logEmail()`, `getEmailLogs()`, `updateEmailStatus()`
  - Generic CRUD operations: `create()`, `read()`, `update()`, `delete()`, `getAll()` with filtering and pagination
  - Advanced features: automatic table URL resolution, attachment handling, file upload support, and connection pooling
  - Robust error handling with automatic retry mechanisms and fallback strategies

- **`represent-api.js`** - Represent OpenNorth API integration for Canadian electoral data
  - `getRepresentativesByPostalCode()` - Fetch representatives for postal codes with multiple data sources
  - `getElectoralDistricts()` - Retrieve electoral district information and boundaries
  - `searchRepresentatives()` - Search functionality for finding specific representatives
  - `validatePostalCode()` - Canadian postal code format validation and normalization
  - Support for both concordance and centroid representative data with intelligent merging
  - Comprehensive error handling, rate limiting, and response caching

- **`emailTemplates.js`** - Advanced email template management service
  - Template loading and caching system with support for conditional blocks and dynamic content
  - Variable replacement and template processing for personalized emails
  - Multi-format support: HTML and text templates with automatic fallback
  - Template rendering with context-aware variable substitution
  - Available templates: representative-contact, campaign-email, test-email, login-details, user-broadcast
  - Template validation, error handling, and performance optimization through caching

- **`email.js`** - Comprehensive SMTP email service with extensive features
  - Template-based email composition using emailTemplates service
  - Multiple sending methods: `sendRepresentativeEmail()`, `sendCampaignEmail()`, `sendTestEmail()`, `sendLoginDetails()`
  - Email preview functionality with full template rendering without sending
  - SMTP connection testing and diagnostics for troubleshooting
  - Support for multiple SMTP providers with automatic failover
  - Email logging, delivery tracking, and bounce handling
  - Development mode with MailHog integration for local testing

### Utilities (`app/utils/`)
Helper functions and shared utilities:

- **`validators.js`** - Comprehensive input validation and sanitization
  - Postal code format validation for Canadian addresses (including Alberta T-prefix)
  - Email address validation with domain checking and format verification
  - Campaign slug generation and validation for URL-safe identifiers
  - HTML content sanitization for security and XSS prevention
  - Form input validation with detailed error messaging
  - Data type validation and conversion utilities

- **`rate-limiter.js`** - Advanced API rate limiting configuration
  - Endpoint-specific rate limiting with different limits for various operations
  - IP-based rate limiting with sliding windows and burst protection
  - User-based rate limiting for authenticated requests
  - Configurable limits via environment variables for different deployment environments
  - Integration with express-rate-limit for production-ready protection

- **`helpers.js`** - General utility functions and data processing helpers
  - User data sanitization for removing sensitive information from API responses
  - ID extraction and normalization utilities for database operations
  - Date and time formatting functions for consistent display
  - String manipulation utilities for text processing and cleanup
  - Data transformation helpers for API response formatting
  - Error handling utilities and logging helpers

### Middleware (`app/middleware/`)
Express.js middleware functions for request processing:

- **`auth.js`** - Comprehensive authentication middleware for route protection
  - `requireAuth()` - Ensures user is logged in with valid session
  - `requireAdmin()` - Ensures user has administrative privileges
  - `requireOwnership()` - Ensures user can only access their own resources
  - `checkTempUser()` - Handles temporary user restrictions and expiration
  - Redirects unauthenticated requests to appropriate login pages
  - Sets up `req.user` object for authenticated requests with full user context
  - Session validation and renewal functionality
  - Standardized error response formatting with consistent structure
  - Comprehensive error logging and security event tracking
  - Development vs production error detail levels for appropriate information disclosure

### Email Templates (`app/templates/email/`)
Professional HTML and text email templates with variable substitution:

- **`representative-contact.html/.txt`** - Template for direct constituent communications to representatives
  - Variables: MESSAGE, SENDER_NAME, SENDER_EMAIL, POSTAL_CODE, APP_NAME, TIMESTAMP
  - Professional styling with constituent information display and platform branding
  - Responsive design for various email clients and devices

- **`campaign-email.html/.txt`** - Template for organized campaign participation emails
  - Variables: MESSAGE, USER_NAME, USER_EMAIL, POSTAL_CODE, CAMPAIGN_TITLE, RECIPIENT_NAME, RECIPIENT_LEVEL
  - Campaign-specific styling with participant information and campaign branding
  - Conditional recipient information display and campaign context
  - Call-to-action buttons and engagement tracking

- **`test-email.html/.txt`** - Template for email system testing and diagnostics
  - Variables: MESSAGE, APP_NAME, TIMESTAMP
  - Warning styling and test indicators for system verification emails
  - Development-friendly formatting for debugging email delivery

- **`login-details.html/.txt`** - Template for sending user credentials and account information
  - Variables: USER_NAME, EMAIL, PASSWORD, LOGIN_URL, APP_NAME
  - Secure credential display with clear login instructions
  - Security warnings and best practices for password management

- **`user-broadcast.html/.txt`** - Template for administrator mass communications
  - Variables: MESSAGE, RECIPIENT_NAME, SENDER_NAME, APP_NAME, TIMESTAMP
  - Professional broadcast styling for announcements and updates
  - Rich text support for formatted content and multimedia

### Frontend Assets (`app/public/`)

#### HTML Pages
- **`index.html`** - Main application landing page and campaign discovery interface
  - Campaign listing with search and filtering capabilities
  - Featured campaigns display with engaging visuals
  - User registration and login integration
  - Responsive design with mobile-first approach

- **`login.html`** - User authentication page with comprehensive login functionality
  - Clean, professional login interface for user access
  - Email/password form with client-side validation and security features
  - Integration with authentication API and session management
  - Automatic redirect to dashboard on successful login
  - Session persistence and auto-login detection for returning users
  - Password reset functionality and security messaging

- **`admin.html`** - Administrative panel for campaign and user management (protected)
  - Requires admin authentication with role verification
  - Campaign creation and management interface with rich text editing and cover photo uploads
  - Cover photo upload: File input with image validation (jpeg/jpg/png/gif/webp, max 5MB)
  - Current cover photo preview in edit form with thumbnail display
  - User management with role assignment and account lifecycle controls
  - Email composition tools for broadcast communications
  - System analytics dashboard with campaign performance metrics
  - Representative data management and caching controls
  - File upload interface for campaign assets and attachments using FormData for multipart uploads

- **`dashboard.html`** - User dashboard for campaign participation and personal analytics
  - Personalized campaign recommendations and participation history
  - User profile management with account settings
  - Campaign creation tools for non-admin users (if permitted)
  - Email history and communication tracking
  - Personal analytics and engagement metrics
  - Responsive interface optimized for various screen sizes

- **`campaign.html`** - Dynamic campaign landing pages for public participation
  - Campaign-specific branding and visual design with cover photo hero sections
  - Cover photo display: Dynamically applies uploaded cover images as hero backgrounds with overlay effects
  - Responsive cover photo sizing with background-size cover and center positioning
  - Fallback gradient background for campaigns without cover photos
  - Representative lookup integration with postal code input
  - Email composition interface for campaign participation
  - Social sharing functionality and engagement tracking
  - Mobile-optimized interface for accessibility
  - Progress tracking and participation confirmation

- **`email-test.html`** - Comprehensive email testing interface (admin-only)
  - Protected admin interface for email system testing and diagnostics
  - Quick test email functionality with predefined templates
  - Email preview system with real-time rendering for content review
  - Email composition form with WYSIWYG editing capabilities
  - Email delivery logs with filtering and search functionality
  - SMTP connection testing and configuration validation
  - Test mode configuration and environment switching

- **`terms.html`** - Terms of service and privacy policy page
  - Legal documentation for user agreement and data handling
  - Privacy policy with data collection and usage transparency
  - User rights and responsibilities outlined clearly
  - Contact information for legal and privacy inquiries

#### Stylesheets (`app/public/css/`)
- **`styles.css`** - Comprehensive application styling with modern design principles
  - Responsive grid layouts for campaign and representative cards
  - Professional form styling with validation states and user feedback
  - Modal dialog systems for email composition and content editing
  - Mobile-first responsive design with progressive enhancement
  - Loading states, progress indicators, and skeleton screens
  - Error message styling and user notification systems
  - Campaign-specific theming and branding customization
  - Accessibility features including focus management and color contrast
  - Print-friendly styles for campaign materials and representative information

#### JavaScript (`app/public/js/`)
- **`main.js`** - Core application initialization and shared utilities
  - Global error handling and user message display system
  - Utility functions including postal code formatting and data sanitization
  - Mobile device detection and responsive behavior management
  - Application-wide constants and configuration management
  - Event delegation and global event handling

- **`api-client.js`** - Frontend API communication layer
  - HTTP client with comprehensive error handling and retry logic
  - API endpoint wrappers for all backend services with consistent interfaces
  - Request/response processing with automatic data transformation
  - Authentication token management and automatic session renewal
  - Error propagation and user-friendly error message generation
  - FormData upload methods: `postFormData()` and `putFormData()` for file uploads
  - Automatic content-type handling for multipart/form-data requests

- **`auth.js`** - Client-side authentication management
  - `AuthManager` class for handling complete authentication lifecycle
  - Login/logout operations with secure session management
  - Session state persistence across browser sessions
  - UI updates based on authentication status and user roles
  - Automatic redirect for protected pages requiring authentication
  - Integration with login forms, logout buttons, and protected routes
  - Role-based UI element visibility and feature access control

- **`campaign.js`** - Campaign participation and interaction management
  - `CampaignPage` class managing campaign landing page functionality
  - Dynamic campaign loading with slug-based routing
  - Cover photo rendering: Dynamically applies cover images as background with `.has-cover` class
  - Responsive cover photo display with overlay effects and text shadowing for readability
  - Fallback to gradient background when no cover photo exists
  - User information collection and validation for campaign participation
  - Representative lookup integration with postal code processing
  - Email composition interface with campaign context and template integration
  - Progress tracking through campaign participation workflow
  - Social sharing and engagement tracking functionality

- **`campaigns-grid.js`** - Public campaigns grid display for homepage
  - `CampaignsGrid` class for displaying active campaigns in a responsive card layout
  - Fetches public campaigns via `/api/public/campaigns` endpoint (no authentication required)
  - Dynamic grid rendering with automatic responsive columns
  - Campaign card generation with cover photos, titles, descriptions, and engagement stats
  - Email count display when enabled via campaign settings
  - Target government level badges for filtering context
  - Click-to-navigate functionality to individual campaign pages
  - Loading states and error handling with user-friendly messages
  - Automatic show/hide of campaigns section based on availability
  - HTML escaping for security against XSS attacks
  - Sort campaigns by creation date (newest first)

- **`dashboard.js`** - User dashboard and analytics interface
  - `UserDashboard` class managing personalized user experience
  - Campaign management interface for user-created campaigns
  - Personal analytics display with charts and metrics
  - Campaign participation history and tracking
  - User profile management and account settings
  - Campaign creation wizard for authorized users

- **`admin.js`** - Administrative interface management
  - `AdminPanel` class for comprehensive system administration
  - Campaign management with CRUD operations, advanced editing, and cover photo upload handling
  - Cover photo management: FormData-based file uploads with postFormData/putFormData methods
  - Current cover photo preview with thumbnail display in edit forms
  - File validation client-side before upload (image types, size limits)
  - User management with role assignment and account lifecycle
  - System analytics and performance monitoring
  - Email broadcast functionality with template selection
  - File upload management for campaign assets with multipart/form-data encoding

- **`postal-lookup.js`** - Postal code search and representative discovery
  - Form handling and input validation for Canadian postal codes
  - API integration for representative lookup with caching
  - Loading states and error display for user feedback
  - Results processing and display coordination with visual feedback
  - Representative data presentation with government level organization

- **`representatives-display.js`** - Representative data presentation and interaction
  - Dynamic HTML generation for representative cards with rich information display
  - Photo display with intelligent fallback to generated initials
  - Government level categorization and hierarchical sorting
  - Contact information formatting with clickable actions
  - Representative profile modal displays with detailed information

- **`representatives-map.js`** - Interactive map integration for representative boundaries
  - Map visualization of electoral districts and representative coverage
  - Interactive boundary display with postal code correlation
  - Representative location plotting with contextual information
  - Geographic search functionality and boundary visualization

- **`email-composer.js`** - Advanced email composition interface
  - Modal-based email composition with rich text editing capabilities
  - Template selection and dynamic content generation
  - Recipient data pre-population with representative information
  - Form validation and submission handling with progress tracking
  - Email preview functionality and template rendering
  - Attachment handling and file upload integration

- **`email-testing.js`** - Comprehensive email testing interface management
  - `EmailTesting` class managing all diagnostic functionality
  - Quick test email sending with predefined content and templates
  - SMTP connection testing and configuration validation
  - Email preview generation with real-time template rendering
  - Test email composition with form validation and sending
  - Email delivery logs management with filtering and pagination
  - Configuration status display and troubleshooting tools
  - Real-time UI updates and comprehensive error handling

- **`login.js`** - Login page functionality and user experience
  - Login form handling with client-side validation
  - Integration with authentication API and session management
  - Password visibility toggles and security features
  - Auto-redirect logic for authenticated users
  - Error display and user feedback for authentication issues

## Scripts Directory (`scripts/`)

- **`build-nocodb.sh`** - Comprehensive database setup automation with migration capabilities
  - Creates complete NocoDB base with all required tables for the influence campaign system
  - Table creation includes: users, campaigns, representatives, emails, postal_codes, campaign_emails
  - Advanced data migration support with `--migrate-data` flag for preserving existing data
  - Interactive source base and table selection for migration operations
  - Preserves original data while creating new base with improved schema
  - Automatic .env file updates with new base ID and table URLs
  - Comprehensive dependency checking (requires jq, curl, and valid NocoDB credentials)
  - Robust error handling with rollback capabilities and user feedback
  - User authentication table with email, name, password hash, admin flag, and activity tracking
  - Campaign management tables with full metadata, attachments, and analytics support

## Data Flow Architecture

### Campaign Participation Flow
1. **Campaign Discovery** → Users browse campaigns on main page or access via direct links
2. **Campaign Access** → Dynamic campaign pages loaded based on URL slug with branding
3. **User Information** → Postal code collection and user details for representative lookup
4. **Representative Lookup** → API call to Represent service with intelligent caching
5. **Email Composition** → Template-based email composition with campaign context
6. **Email Delivery** → SMTP sending with comprehensive logging and tracking
7. **Analytics Tracking** → Participation metrics and campaign performance data collection

### Campaign Management Flow
1. **Campaign Creation** → Admin/user creates campaign with details, messaging, and targeting
2. **Content Management** → Rich text editing, file uploads, and visual customization
3. **Publication** → Campaign status management (draft, active, paused, archived)
4. **Monitoring** → Real-time analytics, participation tracking, and performance metrics
5. **Communication** → Broadcast messaging to participants and stakeholder updates

### Authentication and Session Management
1. **User Registration** → Account creation with role assignment and email verification
2. **Login Process** → Secure authentication with bcryptjs password verification
3. **Session Management** → Express-session with secure cookie configuration and expiration
4. **Role-Based Access** → Middleware-enforced permissions for admin, user, and temporary access
5. **Account Lifecycle** → User management including temporary accounts with expiration dates

### Email System Architecture
1. **Template Selection** → Dynamic template selection based on email type and context
2. **Content Generation** → Variable substitution and personalization with user/campaign data
3. **SMTP Delivery** → Configurable SMTP providers with failover and retry logic
4. **Delivery Tracking** → Comprehensive logging with status tracking and analytics
5. **Test Mode** → Development-friendly email redirection and preview capabilities

### Representative Data Management
1. **Postal Code Input** → User provides postal code with client-side validation
2. **Cache Check** → NocoDB queried for existing representative data with TTL management
3. **API Fallback** → Represent API integration when cache miss or data refresh needed
4. **Data Processing** → Representative data normalization and government level organization
5. **Caching Strategy** → Intelligent caching with automatic invalidation and refresh policies
6. **Display Rendering** → Rich representative cards with photos, contact information, and actions

## Key Integration Points

### Advanced Authentication System
- **Multi-Level Access** → Support for admin, regular users, and temporary campaign participants
- **Session Security** → HttpOnly cookies, CSRF protection, and automatic session expiration
- **Password Management** → Bcryptjs hashing with secure password generation and recovery
- **Role-Based UI** → Dynamic interface adaptation based on user permissions and account type
- **Account Expiration** → Temporary user support with automatic cleanup and lifecycle management

### Comprehensive Campaign Management
- **Rich Content Creation** → WYSIWYG editing, file uploads, and multimedia attachment support
- **URL-Safe Routing** → Automatic slug generation with validation and conflict resolution
- **Status Workflow** → Campaign lifecycle management from draft through archive
- **Analytics Integration** → Built-in tracking for participation, engagement, and conversion metrics
- **Social Features** → Sharing capabilities and viral growth mechanisms

### Enhanced NocoDB Integration
- **Advanced Schema Management** → Dynamic table creation with complex relationship support
- **File Upload Handling** → Attachment management with URL normalization and CDN support
- **Bulk Operations** → Efficient data migration and batch processing capabilities
- **Connection Resilience** → Automatic retry logic and graceful degradation strategies
- **Performance Optimization** → Query optimization, caching layers, and connection pooling

### Sophisticated Email Infrastructure
- **Multi-Template System** → Context-aware template selection with rich variable support
- **SMTP Flexibility** → Multiple provider support with automatic failover and load balancing
- **Development Tools** → MailHog integration for local testing and email preview capabilities
- **Delivery Assurance** → Comprehensive logging, bounce handling, and retry mechanisms
- **Personalization Engine** → Advanced variable substitution with conditional content blocks

### Representative Data Excellence
- **Multi-Source Integration** → Represent API with intelligent data merging and validation
- **Geographic Accuracy** → Postal code validation with boundary checking and error correction
- **Performance Caching** → Multi-level caching with intelligent invalidation strategies
- **Data Enrichment** → Photo fetching, contact validation, and information completeness scoring
- **Real-Time Updates** → Automatic data refresh with change detection and notification

### Security and Compliance Framework
- **Input Validation** → Comprehensive sanitization and validation across all user inputs
- **Rate Limiting** → Advanced rate limiting with user-based and IP-based protection
- **CSRF Protection** → Cross-site request forgery prevention with token validation
- **Content Security** → HTML sanitization and XSS prevention throughout the application
- **Audit Logging** → Comprehensive activity logging for security monitoring and compliance

### Deployment and Operations
- **Docker Integration** → Production-ready containerization with multi-stage builds
- **Environment Management** → Flexible configuration with development/production modes
- **Monitoring Capabilities** → Built-in health checks and performance monitoring
- **Backup Automation** → Automated environment backups with restoration capabilities
- **Scaling Support** → Load balancer compatibility and horizontal scaling preparation

This architecture provides a robust, scalable, and secure solution for political engagement and advocacy campaign management, enabling Alberta residents and organizations to effectively connect with their elected representatives and coordinate grassroots political action.