# Fieldwire Backend - Iterations A1-A9

Production-grade backend foundation with Express, Prisma, MongoDB, and complete authentication/session management, workflow templates, project workflow seeding, role-based work queues, plan annotations with offline-first sync, and in-app notifications with push foundation.

## Quick Start

### 1. Install Dependencies
```bash
npm install
```

### 2. Configure Environment
```bash
cp .env.example .env
# Edit .env with your configuration
```

### 3. Run Database Migration
```bash
npm run prisma:migrate
```

### 4. Seed Admin User
```bash
npm run seed:admin
```

First, add to `.env`:
```env
SEED_ADMIN_EMAIL=admin@example.com
SEED_ADMIN_PASSWORD=SecurePassword123
SEED_ADMIN_FIRST_NAME=Admin
SEED_ADMIN_LAST_NAME=User
```

This creates an admin user:
- Email: From SEED_ADMIN_EMAIL
- Password: From SEED_ADMIN_PASSWORD
- Role: ADMIN
- Status: ACTIVE

### 5. Start Development Server
```bash
npm run dev
```

Server will start on **http://localhost:7052**

## Swagger API Documentation

**Access Swagger UI**: http://localhost:7052/docs

### JWT Authentication in Swagger
1. Login using `POST /api/v1/auth/login` with demo credentials:
   - Email: `admin@fieldwire.com`
   - Password: `admin123`
2. Copy the `access_token` from the response
3. Click the **"Authorize"** button (🔒) in Swagger UI
4. Enter: `Bearer YOUR_ACCESS_TOKEN`
5. Click "Authorize" and "Close"
6. Now you can test all protected endpoints!

See `SWAGGER_AUTH_GUIDE.md` for detailed authentication instructions.

## Available Scripts

- `npm run dev` - Start development server with hot reload
- `npm run build` - Build for production
- `npm start` - Start production server
- `npm run prisma:migrate` - Run database migrations
- `npm run prisma:generate` - Generate Prisma client
- `npm run prisma:seed` - Seed database with admin user (legacy)
- `npm run seed:admin` - Seed admin user from environment variables

## API Endpoints

### Health Check
```
GET /api/v1/health
```

### Authentication
```
POST /api/v1/auth/login
POST /api/v1/auth/refresh
POST /api/v1/auth/logout
GET  /api/v1/auth/me
```

### Session Management
```
GET  /api/v1/sessions
POST /api/v1/sessions/:sessionId/revoke
POST /api/v1/sessions/revoke-all
```

### Workflow Templates (Admin only)
```
POST /api/v1/workflow-templates
GET  /api/v1/workflow-templates
GET  /api/v1/workflow-templates/:id
PUT  /api/v1/workflow-templates/:id
```

### Work Queue & Preferences
```
GET  /api/v1/projects/:projectId/work-queue/defaults
GET  /api/v1/projects/:projectId/preferences
PUT  /api/v1/projects/:projectId/preferences
```

### Plan Annotations (Offline-First Sync)
```
GET  /api/v1/projects/:projectId/plans/:planId/annotations
POST /api/v1/projects/:projectId/plans/:planId/annotations/bulk-sync
POST /api/v1/projects/:projectId/plans/:planId/annotations
PUT  /api/v1/projects/:projectId/plans/:planId/annotations/:annotationId
DEL  /api/v1/projects/:projectId/plans/:planId/annotations/:annotationId
```

### Notifications
```
GET  /api/v1/notifications
GET  /api/v1/notifications/unread-count
PUT  /api/v1/notifications/:notificationId/read
PUT  /api/v1/notifications/read-all
DEL  /api/v1/notifications/:notificationId
GET  /api/v1/notifications/preferences
PUT  /api/v1/notifications/preferences
POST /api/v1/notifications/device-tokens
DEL  /api/v1/notifications/device-tokens
```

See `API_A5_DOCUMENTATION.md` for complete API reference.

## Testing with cURL

### Health Check
```bash
curl http://localhost:7052/api/v1/health
```

### Login
```bash
curl -X POST http://localhost:7052/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "admin@fieldwire.com",
    "password": "admin123"
  }'
```

### Refresh Token
```bash
curl -X POST http://localhost:7052/api/v1/auth/refresh \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "YOUR_REFRESH_TOKEN"
  }'
```

### Logout
```bash
curl -X POST http://localhost:7052/api/v1/auth/logout \
  -H "Content-Type: application/json" \
  -d '{
    "refresh_token": "YOUR_REFRESH_TOKEN"
  }'
```

## Quick Test (PowerShell)

Run the automated test scripts:
```powershell
# Test A1 endpoints
.\test-api.ps1

# Test A2 endpoints (auth/me + sessions)
.\test-api-a2.ps1

# Test A8 endpoints (plan annotations)
.\test-api-a8-plan-annotations.ps1

# Test A9 endpoints (notifications)
.\test-api-a9.ps1
```

## Project Structure

```
backend/
├── prisma/
│   ├── schema.prisma       # Database schema
│   ├── seed.ts             # Database seeding
│   └── migrations/         # Migration files
├── src/
│   ├── app.ts              # Express app
│   ├── server.ts           # Server entry
│   ├── config/             # Configuration
│   ├── db/                 # Database connections
│   ├── middlewares/        # Express middlewares
│   ├── utils/              # Utilities
│   └── modules/            # Feature modules
├── .env                    # Environment variables
├── package.json
└── tsconfig.json
```

## Environment Variables

See `.env.example` for all required variables.

Key variables:
- `PORT` - Server port (default: 7052)
- `DATABASE_URL` - PostgreSQL connection string
- `MONGO_URI` - MongoDB connection string
- `JWT_ACCESS_SECRET` - JWT access token secret
- `JWT_REFRESH_SECRET` - JWT refresh token secret

## Architecture

- **Layered**: Routes → Controllers → Services → Repositories
- **Timestamps**: Epoch milliseconds (BigInt)
- **IDs**: UUID v4
- **Auth**: JWT access + refresh tokens
- **Security**: bcrypt passwords, SHA-256 token hashing
- **PostgreSQL**: Authoritative business state
- **MongoDB**: Logs and sync packets only

## Completed Iterations

- **A1**: Authentication & Session Management
- **A2**: User Profile & Session Listing
- **A3**: Flag Groups & Flag Values
- **A4**: Global Workflow Templates
- **A5**: Project Workflow Seeding & Flag Mapping
- **A6**: Task Management with Workflow Enforcement
- **A7**: Role-Based Work Queues + Quick Filtering + Mobile View Preference
- **A8**: Plan Annotations (Offline-First Sync) - Annotations Carry Forward Across Plan Versions
- **A9**: Notifications Module (In-App + Push Foundation + Preferences)

## Next Steps

Future iterations will add:
- Plan management with file uploads
- Media attachments for tasks
- Real-time notifications
- Offline synchronization
- Advanced reporting and analytics

See `Requirement.md` and `ITERATION_A9_COMPLETE.md` for detailed roadmap.
