# Map Configuration

The Map system is a containerized web application that visualizes geographic data from NocoDB on an interactive map using Leaflet.js. It's designed for canvassing applications and community organizing.

## Features

- 🗺️ Interactive map visualization with OpenStreetMap
- 📍 Real-time geolocation support for adding locations
- ➕ Add new locations directly from the map interface
- 🔄 Auto-refresh every 30 seconds
- 📱 Responsive design for mobile devices
- 🔒 Secure API proxy to protect NocoDB credentials
- 👤 User authentication with login system
- ⚙️ Admin panel for system configuration
- 🎯 Configurable map start location
- 📄 Walk Sheet generator for door-to-door canvassing
- 🔗 QR code integration for digital resources
- 🐳 Docker containerization for easy deployment
- 🆓 100% open source (no proprietary dependencies)

## Setup Process Overview

The setup process involves several steps that must be completed in order:

1. **Get NocoDB API Token** - Create an API token in your NocoDB instance
2. **Configure Environment** - Update the `.env` file with your NocoDB details
3. **Auto-Create Database Structure** - Run the build script to create required tables
4. **Get Table URLs** - Find and copy the URLs for the newly created tables
5. **Update Environment with URLs** - Add the table URLs to your `.env` file
6. **Build and Deploy** - Build the Docker image and start the application

## Prerequisites

- Docker and Docker Compose installed
- NocoDB instance with API access
- Domain name (optional but recommended for production)

## Step 1: Get NocoDB API Token

1. Login to your NocoDB instance
2. Click your user icon → **Account Settings**
3. Go to the **API Tokens** tab
4. Click **Create new token**
5. Set the following permissions:
   - **Read**: Yes
   - **Write**: Yes
   - **Delete**: Yes (optional, for admin functions)
6. Copy the generated token - you'll need it for the next step

!!! warning "Token Security"
    Keep your API token secure and never commit it to version control. The token provides full access to your NocoDB data.

## Step 2: Configure Environment

Edit the `.env` file in the `map/` directory:

```env
# NocoDB API Configuration
NOCODB_API_URL=https://your-nocodb-instance.com/api/v1
NOCODB_API_TOKEN=your-api-token-here

# These URLs will be populated after running build-nocodb.sh
NOCODB_VIEW_URL=
NOCODB_LOGIN_SHEET=
NOCODB_SETTINGS_SHEET=

# Server Configuration
PORT=3000
NODE_ENV=production

# Session Secret (generate with: openssl rand -hex 32)
SESSION_SECRET=your-secure-random-string

# Map Defaults (Edmonton, Alberta, Canada)
DEFAULT_LAT=53.5461
DEFAULT_LNG=-113.4938
DEFAULT_ZOOM=11

# Optional: Map Boundaries (prevents users from adding points outside area)
# BOUND_NORTH=53.7
# BOUND_SOUTH=53.4
# BOUND_EAST=-113.3
# BOUND_WEST=-113.7

# Production Settings
TRUST_PROXY=true
COOKIE_DOMAIN=.yourdomain.com
ALLOWED_ORIGINS=https://map.yourdomain.com,http://localhost:3000
```

### Required Configuration

- `NOCODB_API_URL`: Your NocoDB instance API URL (usually ends with `/api/v1`)
- `NOCODB_API_TOKEN`: The token you created in Step 1
- `SESSION_SECRET`: Generate a secure random string for session encryption

### Optional Configuration

- `DEFAULT_LAT/LNG/ZOOM`: Default map center and zoom level
- `BOUND_*`: Map boundaries to restrict where users can add points
- `COOKIE_DOMAIN`: Your domain for cookie security
- `ALLOWED_ORIGINS`: Comma-separated list of allowed origins for CORS

## Step 3: Auto-Create Database Structure

The `build-nocodb.sh` script will automatically create the required tables in your NocoDB instance.

```bash
cd map
chmod +x build-nocodb.sh
./build-nocodb.sh
```

### What the Script Creates

The script creates three tables with the following structure:

#### 1. Locations Table
Main table for storing map data:

- `Geo-Location` (Geo-Data): Format "latitude;longitude"
- `latitude` (Decimal): Precision 10, Scale 8
- `longitude` (Decimal): Precision 11, Scale 8
- `First Name` (Single Line Text): Person's first name
- `Last Name` (Single Line Text): Person's last name
- `Email` (Email): Email address
- `Phone` (Single Line Text): Phone number
- `Unit Number` (Single Line Text): Unit or apartment number
- `Address` (Single Line Text): Street address
- `Support Level` (Single Select): Options: "1", "2", "3", "4"
  - 1 = Strong Support (Green)
  - 2 = Moderate Support (Yellow)
  - 3 = Low Support (Orange)
  - 4 = No Support (Red)
- `Sign` (Checkbox): Has campaign sign
- `Sign Size` (Single Select): Options: "Regular", "Large", "Unsure"
- `Notes` (Long Text): Additional details and comments

#### 2. Login Table
User authentication table:

- `Email` (Email): User email address (Primary)
- `Name` (Single Line Text): User display name
- `Admin` (Checkbox): Admin privileges

#### 3. Settings Table
Admin configuration table:

- `key` (Single Line Text): Setting identifier
- `title` (Single Line Text): Display name
- `value` (Long Text): Setting value
- `Geo-Location` (Text): Format "latitude;longitude"
- `latitude` (Decimal): Precision 10, Scale 8
- `longitude` (Decimal): Precision 11, Scale 8
- `zoom` (Number): Map zoom level
- `category` (Single Select): Setting category
- `updated_by` (Single Line Text): Last updater email
- `updated_at` (DateTime): Last update time
- `qr_code_1_image` (Attachment): QR code 1 image
- `qr_code_2_image` (Attachment): QR code 2 image
- `qr_code_3_image` (Attachment): QR code 3 image

### Default Data

The script also creates:
- A default admin user (admin@example.com)
- A default start location setting

## Step 4: Get Table URLs

After the script completes successfully:

1. Login to your NocoDB instance
2. Navigate to your project (should be named "Map Viewer Project")
3. For each table, get the view URL:
   - Click on the table name
   - Copy the URL from your browser's address bar
   - The URL should look like: `https://your-nocodb.com/dashboard/#/nc/project-id/table-id`

You need URLs for:
- **Locations table** → `NOCODB_VIEW_URL`
- **Login table** → `NOCODB_LOGIN_SHEET`
- **Settings table** → `NOCODB_SETTINGS_SHEET`

## Step 5: Update Environment with URLs

Edit your `.env` file and add the table URLs:

```env
# Update these with the actual URLs from your NocoDB instance
NOCODB_VIEW_URL=https://your-nocodb.com/dashboard/#/nc/project-id/locations-table-id
NOCODB_LOGIN_SHEET=https://your-nocodb.com/dashboard/#/nc/project-id/login-table-id
NOCODB_SETTINGS_SHEET=https://your-nocodb.com/dashboard/#/nc/project-id/settings-table-id
```

!!! warning "URL Format"
    Make sure to use the complete dashboard URLs, not the API URLs. The application will automatically extract the project and table IDs from these URLs.

## Step 6: Build and Deploy

Build the Docker image and start the application:

```bash
# Build the Docker image
docker-compose build

# Start the application
docker-compose up -d
```

### Verify Deployment

1. Check that the container is running:
   ```bash
   docker-compose ps
   ```

2. Check the logs:
   ```bash
   docker-compose logs -f map-viewer
   ```

3. Access the application at `http://localhost:3000` (or your configured domain)

## Using the Map System

### User Interface

#### Main Map View
- **Interactive Map**: Click and drag to navigate
- **Add Location**: Click on the map to add a new location
- **Search**: Use the search bar to find addresses
- **Refresh**: Data refreshes automatically every 30 seconds

#### Location Markers
- **Green**: Strong Support (Level 1)
- **Yellow**: Moderate Support (Level 2)
- **Orange**: Low Support (Level 3)
- **Red**: No Support (Level 4)

#### Adding Locations
1. Click on the map where you want to add a location
2. Fill out the form with contact information
3. Select support level and sign information
4. Add any relevant notes
5. Click "Save Location"

### Authentication

#### User Login
- Users must be added to the Login table in NocoDB
- Login with email address (no password required for simplified setup)
- Admin users have additional privileges

#### Admin Access
- Admin users can access `/admin.html`
- Configure map start location
- Set up walk sheet generator
- Manage QR codes and settings

### Admin Panel Features

#### Start Location Configuration
- **Interactive Map**: Visual interface for selecting coordinates
- **Real-time Preview**: See changes immediately
- **Validation**: Built-in coordinate and zoom level validation

#### Walk Sheet Generator
- **Printable Forms**: Generate 8.5x11 walk sheets for door-to-door canvassing
- **QR Code Integration**: Add up to 3 QR codes with custom URLs and labels
- **Form Field Matching**: Automatically matches fields from the main location form
- **Live Preview**: See changes as you type
- **Print Optimization**: Proper formatting for printing or PDF export

## API Endpoints

### Public Endpoints
- `GET /api/locations` - Fetch all locations (requires auth)
- `POST /api/locations` - Create new location (requires auth)
- `GET /api/locations/:id` - Get single location (requires auth)
- `PUT /api/locations/:id` - Update location (requires auth)
- `DELETE /api/locations/:id` - Delete location (requires auth)
- `GET /api/config/start-location` - Get map start location
- `GET /health` - Health check

### Authentication Endpoints
- `POST /api/auth/login` - User login
- `GET /api/auth/check` - Check authentication status
- `POST /api/auth/logout` - User logout

### Admin Endpoints (requires admin privileges)
- `GET /api/admin/start-location` - Get start location with source info
- `POST /api/admin/start-location` - Update map start location
- `GET /api/admin/walk-sheet-config` - Get walk sheet configuration
- `POST /api/admin/walk-sheet-config` - Save walk sheet configuration

## Troubleshooting

### Common Issues

#### Locations not showing
- Verify table has required columns (`Geo-Location`, `latitude`, `longitude`)
- Check that coordinates are valid numbers
- Ensure API token has read permissions
- Verify `NOCODB_VIEW_URL` is correct

#### Cannot add locations
- Verify API token has write permissions
- Check browser console for errors
- Ensure coordinates are within valid ranges
- Verify user is authenticated

#### Authentication issues
- Verify login table is properly configured
- Check that user email exists in Login table
- Ensure `NOCODB_LOGIN_SHEET` URL is correct

#### Build script failures
- Check that `NOCODB_API_URL` and `NOCODB_API_TOKEN` are correct
- Verify NocoDB instance is accessible
- Check network connectivity
- Review script output for specific error messages

### Development Mode

For development and debugging:

```bash
cd map/app
npm install
npm run dev
```

This will start the application with hot reload and detailed logging.

### Logs and Monitoring

View application logs:
```bash
docker-compose logs -f map-viewer
```

Check health status:
```bash
curl http://localhost:3000/health
```

## Security Considerations

1. **API Token Security**: Keep tokens secure and rotate regularly
2. **HTTPS**: Use HTTPS in production
3. **CORS Configuration**: Set appropriate `ALLOWED_ORIGINS`
4. **Cookie Security**: Configure `COOKIE_DOMAIN` properly
5. **Input Validation**: All inputs are validated server-side
6. **Rate Limiting**: API endpoints have rate limiting
7. **Session Security**: Use a strong `SESSION_SECRET`

## Maintenance

### Regular Updates
```bash
# Stop the application
docker-compose down

# Pull updates (if using git)
git pull origin main

# Rebuild and restart
docker-compose build
docker-compose up -d
```

### Backup Considerations
- NocoDB data is stored in your NocoDB instance
- Back up your `.env` file securely
- Consider backing up QR code images from the Settings table

### Performance Tips
- Monitor NocoDB performance and scaling
- Consider enabling caching for high-traffic deployments
- Use CDN for static assets if needed
- Monitor Docker container resource usage

## Support

For issues or questions:
1. Check the troubleshooting section above
2. Review NocoDB documentation
3. Check Docker and Docker Compose documentation
4. Open an issue on GitHub