# משמר הבחירות האזרחי — Citizen Election Guard
Election day observer management system. Volunteer registration, station assignment, real-time field reporting, and ballot protocol review.
## Stack
- **Next.js 16** (React 19) — App Router, React Server Components
- **PayloadCMS 3** — Headless CMS with MongoDB
- **shadcn/ui** — New York style, Tailwind CSS v4
- **TypeScript 5.7** — Strict mode
- **Vercel AI SDK 6** — AI elements registry
## Features
- **Volunteer registration** — Public sign-up, SMS verification, approval workflow
- **Polling station assignment** — 5-step wizard with nearby city suggestions (Haversine), map view, party + shift selection
- **Election day reporting** — Structured field reports with urgency levels (blue/yellow/red), photo uploads, inspection checklists
- **HQ war room** — Real-time SSE feed, 3-column layout (alerts / new / in-progress), SMS replies
- **Protocol review** — Scanned ballot count verification, discrepancy flagging
- **Telemarketing** — Card-based outbound calling queue with locking
- **Dual authentication** — Staff (Payload cookie) + registrant (personal token JWT)
- **Localization** — Hebrew, Arabic, Russian, English with RTL support
- **Real-time events** — SSE streaming via custom Payload plugin
- **SMS integration** — Verification, assignment notifications, HQ messaging
## Quick Start
```bash
git clone <repo-url> mishmar-bechirot
cd mishmar-bechirot
cp .env.example .env
# Configure .env:
# DATABASE_URL=mongodb://...
# PAYLOAD_SECRET=your-secret
# BLOB_READ_WRITE_TOKEN=your-token (optional)
pnpm install
pnpm dev
```
Open [http://localhost:3000](http://localhost:3000) and follow on-screen instructions to create your admin user.
## Project Structure
```
src/
├── app/(frontend)/
│ ├── page.tsx # Home
│ ├── login/ # Staff login
│ ├── register/ # Public volunteer registration
│ ├── (protected)/dashboard/ # Admin stats dashboard
│ ├── hq/ # HQ war room
│ │ ├── alerts/
│ │ ├── reports/
│ │ ├── inspections/
│ │ ├── stations/
│ │ └── call-log/
│ ├── m/[token]/ # Registrant mobile flow
│ │ ├── assignment/step-{1..5}/ # Assignment wizard
│ │ └── dashboard/ # Election day actions
│ │ ├── inspection/
│ │ ├── messages/
│ │ ├── report/
│ │ └── results/
│ ├── management/ # Admin management
│ │ ├── registrants/
│ │ ├── cities/
│ │ ├── assignment-levels/
│ │ ├── blocked-cities/
│ │ └── waiting-list/
│ ├── regional/ # Regional observer views
│ ├── protocols/ # Protocol review
│ ├── protocols-management/ # Protocol admin + reviewers
│ └── telemarketing/ # Outbound calling
├── app/(payload)/ # Admin panel + API
├── collections/ # 13 Payload collections
├── globals/ElectionSettings.ts # Election config (global)
├── components/
│ ├── ui/ # shadcn components
│ ├── dashboard/ # Dashboard components
│ ├── assignment/ # Assignment wizard components
│ └── ai-elements/ # AI SDK components
├── plugins/payload-events/ # Real-time SSE plugin
├── lib/
│ ├── sms.ts # SMS service
│ ├── geo.ts # Geolocation (Haversine)
│ ├── registrant-auth.ts # Registrant token auth
│ └── utils.ts # cn() utility
└── proxy.ts # Route protection
```
## System Entities
### Users
Staff accounts with roles: `admin`, `hq_operator`, `regional_observer`, `protocol_reviewer`, `telemarketer`. Each user can be assigned to a regional committee and specific cities.
### Registrants
Volunteer observers. Register publicly, receive a personal SMS link (`/m/{token}`). Status progression: `pending_sms` → `verified` → `approved` → `frozen`/`cannot`/`review`. Israeli ID validation on verification.
### Cities
Election cities with importance levels (`critical` / `high` / `medium` / `low`), coordinates (lat/lng), and regional committee assignment. Cities can be blocked from new assignments.
### Regional Committees
Geographic groupings of cities. Staff users are assigned to a committee to scope their access.
### Polling Stations
Physical voting locations linked to a city. Include address, coordinates, voter count, committee members, and party lists. Can be marked as target stations.
### Parties
Political parties with localized names, ballot letter, cooperation flag, and logo.
### Assignments
Links a registrant to a polling station + shift + party. Tracks arrival, shift end, and age confirmation. Statuses: `active` / `cancelled` / `completed`.
### Reports
Observer field reports covering: arrival, committee check, inspection, report to HQ, ballot open/close, result photo, results entry, shift end. Urgency levels: blue (info), yellow (warning), red (critical). Can include photos, inspection data, and vote results.
### HQ Messages
Bidirectional messaging between HQ operators and observers. Supports structured questions with predefined choices. Tracks read status and SMS delivery.
### Protocols
Scanned ballot count protocols. Review workflow: `pending` → `in_review` → `reviewed` / `has_discrepancy`. Assigned to protocol reviewers. Contains vote data as structured JSON.
### Telemarketing Cards
Outbound calling queue for registrant follow-up. Card locking ensures one operator per card at a time. Tracks call history and outcomes.
### SMS Log
Audit trail of all SMS messages. Types: `verification`, `assignment`, `hq_reply`, `general`.
### Election Settings (Global)
Single global config: election date, shift times (morning/evening/counting), assignment open/close toggle, assignment levels per city importance, training videos, FAQ items, and social links.
## User Flows
### Volunteer Flow
1. **Register** (`/register`) — name, phone, email, city
2. **Receive SMS** with personal link → `/m/{token}`
3. **Verify identity** — enter Israeli ID number
4. **Wait for approval** (`/m/{token}/waiting`) — view training videos, FAQ, edit profile
5. **Assignment wizard** (`/m/{token}/assignment/step-1..5`):
- Choose shift → choose city (nearby suggestions via Haversine) → choose station (map view) → choose party → confirm age
6. **Pre-election dashboard** — shift info, station map, Waze link, guidelines
7. **Election day dashboard** — action grid: arrival → committee check → inspection checklist → report to HQ → messages → ballot open/close → photo upload → record results → shift end
8. **Post-election** — certificate, official results, feedback
### HQ Operator Flow
- 3-column war room: alerts | new reports | in-progress
- Real-time SSE feed of observer reports (color-coded by urgency)
- Report detail: view observer/station info, change status, tag, reply via SMS
- Station search, phone call logging
### Regional Observer Flow
- Dashboard scoped to assigned regional committee
- View forwarded reports, city list, station details, observer list
### Protocol Reviewer Flow
- Review queue of assigned protocols
- Side-by-side: scanned image + data entry form
- Mark as verified or flag discrepancy
### Telemarketer Flow
- Card-based interface, one registrant at a time
- Lock card → call → log result → send SMS → next card
### Admin Flow
- Stats dashboard with charts
- Registrant management (search, filter, edit, status changes)
- City management (importance levels, blocking)
- Assignment level configuration
- Waiting list management
## Authentication
Dual auth system: staff accounts (Payload cookie-based) and registrant access (personal token JWT).
### Staff Auth
Uses Payload's built-in auth with server actions and cookie sessions.
```typescript
// Server Actions (src/app/(frontend)/login/actions.ts)
export async function login(prevState, formData): Promise<LoginState>
export async function getCurrentUser()
export async function logout()
```
**Flow:** Login form → `payload.login()` → JWT stored as `payload-token` httpOnly cookie → `payload.auth({ headers })` on subsequent requests.
### Registrant Auth
Token-based access for volunteers. Each registrant receives a unique token via SMS.
- Personal URL: `/m/{token}` — all registrant pages are scoped under this route
- Token validated server-side via `registrant-auth.ts`
- No cookie required — token is in the URL path
## Protected Routes
### Middleware (`proxy.ts`)
Checks cookie **existence only** (not validity) to prevent redirect loops:
```typescript
const PROTECTED_PATHS = [
'/dashboard',
'/hq',
'/management',
'/regional',
'/protocols-management',
'/protocols',
'/telemarketing',
]
```
Matcher excludes `/api`, `/admin`, `/_next/static`, `/_next/image`, and static files. Registrant routes (`/m/[token]`) are not middleware-protected — they validate the token at the page level.
### Page-Level Auth
Each protected page validates the token server-side:
```typescript
export default async function DashboardPage() {
const user = await getCurrentUser()
if (!user) redirect('/login')
// ...
}
```
## Access Control
| Role | Access |
| ------------------ | ----------------------------------------- |
| Public | Registration, public report page |
| Registrant (token) | Own assignment, dashboard, messages |
| HQ Operator | War room, all reports/messages, call log |
| Regional Observer | Regional dashboard (their committee only) |
| Protocol Reviewer | Assigned protocols only |
| Telemarketer | Telemarketing cards |
| Admin | Everything |
## Localization
4 locales configured in PayloadCMS:
| Code | Language | Direction |
| ---- | ---------------- | --------- |
| `he` | Hebrew (default) | RTL |
| `ar` | Arabic | RTL |
| `ru` | Russian | LTR |
| `en` | English | LTR |
Localized fields: training video titles, FAQ items, party names. RTL support via `DirectionProvider`.
## Plugins
### Payload Events Plugin
Real-time event system using SSE. Located in `src/plugins/payload-events/`.
- Auto-broadcasts CRUD events for all collections
- Custom event publishing via `publish()` server action
- SSE endpoint at `/api/_events/stream`
- Automatic cleanup (events expire after 1 hour)
**Client usage:**
```typescript
import { usePayloadEvents } from '@/plugins/payload-events/client'
const { subscribe, connectionStatus } = usePayloadEvents()
useEffect(() => {
return subscribe('reports.create', (event) => {
console.log('New report:', event.payload)
})
}, [subscribe])
```
### Vercel Blob Storage
Media uploads stored in Vercel Blob:
```typescript
import { vercelBlobStorage } from '@payloadcms/storage-vercel-blob'
plugins: [
vercelBlobStorage({
collections: { media: true },
token: process.env.BLOB_READ_WRITE_TOKEN || '',
}),
]
```
## Commands
```bash
pnpm dev # Start dev server
pnpm build # Build for production
pnpm exec tsc --noEmit # Type check
pnpm test:int # Integration tests (Vitest)
pnpm test:e2e # E2E tests (Playwright)
pnpm generate:types # Regenerate Payload types
```
## Environment Variables
| Variable | Required | Description |
| ------------------------ | -------- | ------------------------------------------------ |
| `DATABASE_URL` | Yes | MongoDB connection string |
| `PAYLOAD_SECRET` | Yes | Secret for Payload auth/encryption |
| `NEXT_PUBLIC_SERVER_URL` | No | Server URL (defaults to `http://localhost:3000`) |
| `BLOB_READ_WRITE_TOKEN` | No | Vercel Blob storage token |
## Contributing
### Prerequisites
- Node.js 20+
- pnpm
- MongoDB (local or Atlas)
### Setup
```bash
git clone <repo-url>
cd mishmar-bechirot
cp .env.example .env # Configure DATABASE_URL and PAYLOAD_SECRET
pnpm install
pnpm dev
```
### Branch Naming
- `feature/` — new functionality
- `fix/` — bug fixes
- `refactor/` — code improvements
### Commit Conventions
Use conventional commits: `feat:`, `fix:`, `refactor:`, `docs:`, `chore:`.
### Architecture Notes
- **RSC by default** — client components only when necessary
- **Server actions for mutations** — no API routes for data changes
- **PayloadCMS local API only** — never use REST API internally
- **shadcn/ui** — use `pnpm dlx shadcn@latest` for component management
### PR Process
1. Create a feature branch from `main`
2. Make changes, ensure `pnpm exec tsc --noEmit` passes
3. Open a PR with a clear description
4. Address review feedback
## Docker
```bash
# Update .env: DATABASE_URL=mongodb://127.0.0.1/mydb
docker-compose up -d
pnpm dev
```
Docker Compose includes MongoDB and an optional (commented-out) PostgreSQL service.
## License
TBD