# Connect Sudbury Portal ? Deep Dive

This note captures semi-technical implementation details that help product, design, and engineering keep context when planning releases.

## Feature Overview (Non-Technical)

| Feature | What it does | Typical Uses & Benefits |
| --- | --- | --- |
| **Watch Reports Inbox** | Single view of all Watch submissions with filters for status, severity, community, forwarding state, and time windows. Each row shows attachments, custom fields, and whether it’s already part of a case. | Give duty officers a real-time picture of community intelligence; quickly triage, export, or open a detailed drawer without switching screens. |
| **Heatmaps** | Visual overlay of watch reports on the city map with severity/incident-density controls, plus filters for date range and category. | Helps planners spot clusters in seconds and adjust patrols or outreach accordingly. |
| **Cases** | Structured workspace where multiple Watch reports can be linked to a single investigation, with status/priority/sensitivity controls, notes, assignments, and attachments. Case cards now show the exact Watch report IDs linked. | Keeps investigations organized, prevents duplicate work, and provides auditability when briefings happen. |
| **Alerts Platform** | Compose & manage emergency alerts that appear inside the resident app. Includes categories, urgency, optional GeoJSON boundaries, and community targeting. | Shaves minutes off public communications during severe weather, missing-person notices, or road closures; ensures only approved communities receive messaging. |
| **Alerts Settings** | Admin panel to choose which communities a specific agency may target (e.g., Sudbury Police vs. other municipal departments in the future). | Prevents agencies from accidentally messaging areas outside their jurisdiction, enforcing governance without manual checks. |
| **Alert Categories Manager** | Lets admins create/update alert categories with color/icon/description. | Keeps the resident experience consistent (iconography, color semantics) and allows quick addition of new alert types (e.g., Air Quality). |
| **Role Manager & Permissions** | Role cards show granted permissions; CRUD toggles assign resource-level rights. Every page requires an explicit permission string enforced by `auth-guard.js`. | Enables least-privilege access, simplifies onboarding new staff, and documents what capabilities exist. |
| **Portal Users** | Invite, edit, and deactivate portal accounts, including forcing password resets. | Central place to manage staff, remove access for departures, and keep security posture tight. |
| **+ Case Modal** | Selecting Watch reports and pressing “+ Case” opens a modal with two paths: link to an existing case or create a new one (with smart defaults). | Reduces friction when converting Watch intel into workable cases, ensuring evidence/notes move together. |


## High-Level Architecture
- **Back end**: PHP 8 APIs in `/api`, sharing a common bootstrap (PDO connection, env loader, rate limiter). Requests are routed via Apache/Nginx to individual PHP files.
- **Database**: MySQL 8 hosting Watch reports, cases, alerts, and community directories. Data integrity relies on foreign keys (e.g., watch reports -> communities, cases -> watch reports).
- **Front end**: Static HTML pages in `/public` hydrated by vanilla ES modules under `/assets/js`. Styling is pure CSS (no preprocessor). There is no bundler: every page loads the exact JS file it needs.
- **Authentication**: Auth cookies/session tokens validated by `assets/js/auth-guard.js` calling `/api/auth.php`. Guard checks run on page load; unauthorized roles are redirected.

## Watch Reports Flow
1. `GET /api/watch-reports.php` returns incidents with attachments, updates, custom fields, and the newly introduced `linked_cases` field.
2. `assets/js/watch-reports.js` state machine handles filtering, pagination, CSV export, drawer display, and the **+ Case** modal.
3. Linking reports to cases happens in two modes: 
   - Existing case: `PATCH /api/cases.php?id=123` with merged `report_ids`.
   - New case: inline `POST /api/cases.php` that carries basic metadata and the selected reports.
4. Cases page (`assets/js/cases.js`) now renders report chips on each card and uses UTC parsing for proper timestamps.

## Alerts Platform
- Alerts, alert settings, and categories live in their own API surfaces (`/api/alerts.php`, `/api/alert-settings.php`, `/api/alert-categories.php`). 
- A helper (`lib/alert-helpers.php`) determines the active agency (Greater Sudbury Police for this deployment). 
- UI pages (`public/alerts.html`, `public/alerts-settings.html`, `public/alert-categories.html`) consume the new JS modules and CSS themes to match the rest of the portal.
- Community targeting is enforced through `alert_agency_communities`; the UI restricts selections accordingly.

## Role & Permission Matrix
- Role manager UI exposes CRUD toggles that map to permission strings (`alerts.view`, `alerts.settings`, etc.).
- New permission set for alerts (view/create/update/delete + settings) controls visibility of the new pages.
- `assets/js/auth-guard.js` checks the page-level permission defined via `data-page-permission` on `<body>`.

## Data Reliability Notes
- All timestamps are stored UTC in MySQL; front-end utilities now normalize to UTC before formatting to local time.
- Watch report geodata is optional. Heatmaps/incident markers guard against missing lat/lon to avoid Leaflet errors.
- Alerts module stores geometry (points, radius, polygons) as JSON strings. GeoJSON validation is server-side where possible; front-end enforces it through the new MapCN integration hooks.

## Open Follow-Ups
- **Audit logging**: Alerts and case updates log to activity tables but there is no UI for viewing audit history yet.
- **Attachment pipeline**: Currently points to S3-like storage; ensure signed URLs are refreshed if sessions last longer than upload retention.
- **Map provider**: Leaflet is still bundled while MapCN integration is staged; once MapCN is finalized, remove unused Leaflet assets.
- **Testing**: There is no automated test suite. Manual smoke tests (Watch reports filtering, case creation, alert compose) should be run before deployments.

This document should be updated whenever substantial architectural changes happen (new services, auth providers, deployment steps, etc.).
