diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 974f2d5..ebcd041 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -59,6 +59,9 @@ export default defineConfig({ { text: "Introduction", link: "/database/" }, { text: "Key Entities", link: "/database/key-entities" }, { text: "ER Diagram", link: "/database/er-diagram" }, + { text: "Constraints", link: "/database/constraints" }, + { text: "Migration Scripts", link: "/database/migrations" }, + { text: "Seed Data", link: "/database/seed-data" }, ], }, { @@ -88,9 +91,16 @@ export default defineConfig({ items: [ { text: "Introduction", link: "/frontend/" }, { text: "Architecture", link: "/frontend/architecture" }, + { text: "Routing", link: "/frontend/routing" }, { text: "Pages and Components", link: "/frontend/pages-and-components" }, { text: "State Management", link: "/frontend/state-management" }, + { text: "Forms and Validation", link: "/frontend/forms-and-validation" }, + { text: "API Integration", link: "/frontend/api-integration" }, + { text: "Authentication", link: "/frontend/authentication" }, { text: "Maps and Real-time", link: "/frontend/maps-and-real-time" }, + { text: "Build and Tooling", link: "/frontend/build-and-tooling" }, + { text: "Testing", link: "/frontend/testing" }, + { text: "Deployment", link: "/frontend/deployment" }, ], }, { @@ -108,6 +118,10 @@ export default defineConfig({ text: "Setup", collapsed: true, items: [ + { text: "Deployment and Contribution", link: "/deployment/" }, + { text: "Deployment", link: "/deployment/deployment" }, + { text: "Branching and Pull Requests", link: "/deployment/branching-and-prs" }, + { text: "Code Contribution", link: "/deployment/code-contribution" }, { text: "Installation", link: "/setup/installation" }, { text: "Run Locally", link: "/setup/run-locally" }, { text: "Database Setup", link: "/setup/database-setup" }, @@ -137,4 +151,4 @@ export default defineConfig({ }, ], }, -}) +}) \ No newline at end of file diff --git a/docs/assets/dashboard.png b/docs/assets/dashboard.png new file mode 100644 index 0000000..171825d Binary files /dev/null and b/docs/assets/dashboard.png differ diff --git a/docs/assets/fishers.png b/docs/assets/fishers.png new file mode 100644 index 0000000..e994a9d Binary files /dev/null and b/docs/assets/fishers.png differ diff --git a/docs/assets/incidents.png b/docs/assets/incidents.png new file mode 100644 index 0000000..58221db Binary files /dev/null and b/docs/assets/incidents.png differ diff --git a/docs/assets/register.png b/docs/assets/register.png new file mode 100644 index 0000000..6ed1173 Binary files /dev/null and b/docs/assets/register.png differ diff --git a/docs/assets/reports.png b/docs/assets/reports.png new file mode 100644 index 0000000..c9f6202 Binary files /dev/null and b/docs/assets/reports.png differ diff --git a/docs/assets/responders.png b/docs/assets/responders.png new file mode 100644 index 0000000..a6168f4 Binary files /dev/null and b/docs/assets/responders.png differ diff --git a/docs/assets/settings.png b/docs/assets/settings.png new file mode 100644 index 0000000..7ccd317 Binary files /dev/null and b/docs/assets/settings.png differ diff --git a/docs/assets/signin.png b/docs/assets/signin.png new file mode 100644 index 0000000..ddc987d Binary files /dev/null and b/docs/assets/signin.png differ diff --git a/docs/assets/wristbands.png b/docs/assets/wristbands.png new file mode 100644 index 0000000..4e32d1c Binary files /dev/null and b/docs/assets/wristbands.png differ diff --git a/docs/database/constraints.md b/docs/database/constraints.md new file mode 100644 index 0000000..2f1d6e0 --- /dev/null +++ b/docs/database/constraints.md @@ -0,0 +1,75 @@ +# Constraints + +This page lists the rules the database enforces on its data. Items marked **TO CONFIRM** must be checked against the real schema before this page is treated as final. + +To inspect the real constraints of a table, connect with `psql` and run: + +```sql +\d fishers +``` + +Use `\d+` with no table name to list every table. Update this page whenever a migration adds, changes or removes a constraint. + +## Primary keys + +Every table has a single primary key. It is the bold column in the [entity relationship diagram](./er-diagram.md). + +## Foreign keys + +| Table | Column | References | Meaning | +| --- | --- | --- | --- | +| `fishers` | `operator_id` | `station_operators` | The operator who registered the fisher. | +| `wristbands` | `fisher_id` | `fishers` | The fisher the wristband is assigned to. | +| `trips` | `fisher_id` | `fishers` | The fisher taking the trip. | +| `locations` | `trip_id` | `trips` | The trip the GPS point belongs to. | +| `locations` | `fisher_id` | `fishers` | The fisher the GPS point belongs to. | +| `distressed_fisher_alerts` | `fisher_id` | `fishers` | The fisher in distress. | +| `distressed_fisher_alerts` | `location_id` | `locations` | Where the fisher was when the alert was raised. | +| `distressed_fisher_alerts` | `acknowledged_by_operator_id` | `station_operators` | The operator who acknowledged the alert. | +| `alert_responders` | `alert_id` | `distressed_fisher_alerts` | The alert being responded to. | +| `alert_responders` | `responder_fisher_id` | `fishers` | The nearby fisher asked to help. | + +`islands` and `alembic_version` have no foreign keys. + +## Unique constraints + +| Table | Column(s) | Purpose | Status | +| --- | --- | --- | --- | +| `fishers` | `phone_number` | No two fishers share a phone number. Adding this constraint to a database that already holds duplicates fails, so clean the data first. | **TO CONFIRM** | +| `wristbands` | `rfid_tag` | One physical tag maps to one wristband record. | **TO CONFIRM** | +| `station_operators` | `email` | One account per email address, used to log in. | **TO CONFIRM** | +| `alert_responders` | `alert_id`, `responder_fisher_id` | A fisher is asked to respond to a given alert only once. | **TO CONFIRM** | + +## Required and optional columns + +| Column | Rule | +| --- | --- | +| `station_operators.password_hash` | Required. Passwords are stored only as hashes, never in plain text. | +| `distressed_fisher_alerts.resolved_at` | Empty while the alert is open. Setting it closes the alert. | +| `distressed_fisher_alerts.acknowledged_by_operator_id`, `acknowledged_at` | Empty until an operator acknowledges the alert. **TO CONFIRM** | +| `alert_responders.arrived_at` | Empty until the responder reaches the fisher in distress. **TO CONFIRM** | +| `trips.checkout_at` | Empty until the trip ends. **TO CONFIRM** | +| All other columns | **TO CONFIRM** which are required. | + +## Allowed values + +| Column | Allowed values | Enforced by | +| --- | --- | --- | +| `wristbands.status` | **TO CONFIRM** | **TO CONFIRM** (database enum or check, or application only) | +| `trips.status` | **TO CONFIRM** | **TO CONFIRM** | + +## Deletion behaviour + +**TO CONFIRM:** what happens to dependent rows when a fisher, trip or operator is deleted (cascade, restrict or set null). Alerts, locations and responder records are emergency history, so deleting a fisher should not silently remove them. Prefer restricting deletes on rows that alerts depend on. + +## Indexes + +**TO CONFIRM** which indexes exist beyond the primary keys. Lookups worth indexing are the latest location per fisher (`locations` by `fisher_id` and `recorded_at`) and open alerts (`distressed_fisher_alerts` where `resolved_at` is empty). + +## Rules the application enforces + +Some rules live in the backend rather than the database: + +- An alert is open until `resolved_at` is set. +- Nearest responders and response status are calculated from the timestamps, not stored. +- Passwords are hashed before they reach the database. diff --git a/docs/database/index.md b/docs/database/index.md index 550ed0f..0203af4 100644 --- a/docs/database/index.md +++ b/docs/database/index.md @@ -15,6 +15,9 @@ MvuviGo stores everything in a **PostgreSQL** database named `MvuviGo`. The back - [Entity relationship diagram](./er-diagram.md): how the tables connect. - [Key entities](./key-entities.md): what each table stores and how an alert moves through them. +- [Constraints](./constraints.md): keys, unique rules, required columns and allowed values. +- [Migrations](./migrations.md): how the schema is versioned and changed with Alembic. +- [Seed data](./seed-data.md): the data a fresh database needs and how it is loaded. ## Working with the database locally diff --git a/docs/database/key-entities.md b/docs/database/key-entities.md index 469f4da..7234b24 100644 --- a/docs/database/key-entities.md +++ b/docs/database/key-entities.md @@ -1,30 +1,30 @@ # Key Entities -## fishers +## Fishers The people the system protects. Stores `full_name`, `phone_number`, the registering `operator_id`, and `created_at` / `updated_at`. A fisher can be in distress, or be asked to respond to someone else's alert. -## wristbands +## Wristbands The wearable that carries the RFID tag. Stores `rfid_tag`, `status`, the `fisher_id` it is assigned to, and `assigned_at`. Assigning a wristband to a fisher is what ties a physical signal to a person. -## station_operators +## Station_operators Staff who run a landing station and use the dashboard. Stores `first_name`, `last_name`, `email` and `password_hash`. Operators register fishers and acknowledge alerts. Passwords are never stored in plain text. -## trips +## Trips A fishing trip. Stores `fisher_id`, `total_fishers`, `checkin_at`, `checkout_at` and `status`. A trip is the context that gives location records meaning. -## locations +## Locations GPS points recorded during a trip. Stores `fisher_id`, `trip_id`, `latitude`, `longitude` and `recorded_at`. The latest location is what an alert points at. -## islands +## Islands Reference data for the fishing areas. Stores `island_name`, `island_latitude` and `island_longitude`. -## distressed_fisher_alerts +## Distressed_fisher_alerts One row per emergency. @@ -37,7 +37,7 @@ One row per emergency. | `acknowledged_at` | When the operator took it on. | | `resolved_at` | When the emergency ended. Empty while the alert is open. | -## alert_responders +## Alert_responders One row per fisher asked to help with an alert. diff --git a/docs/database/migrations.md b/docs/database/migrations.md new file mode 100644 index 0000000..5c38343 --- /dev/null +++ b/docs/database/migrations.md @@ -0,0 +1,53 @@ +# Migrations + +The schema is versioned with **Alembic** in `pixels-backend`. The SQLAlchemy models describe what the database should look like, and migrations are the steps that get a database there. The current version is recorded in the `alembic_version` table. + +## Rules + +- Every change to a SQLAlchemy model needs a new migration. +- Never edit the database by hand and leave the models behind. +- Keep one concern per migration, and keep it in the same PR as the model change. +- Read every generated migration before committing it. Autogenerate can miss renames and constraints. +- Write a working `downgrade` for every migration so it can be undone. + +## Commands + +Run these from the backend repository. + +| Task | Command | +| --- | --- | +| Apply all migrations | `alembic upgrade head` | +| Show the current version | `alembic current` | +| List the history | `alembic history --verbose` | +| Create a migration from model changes | `alembic revision --autogenerate -m "describe the change"` | +| Undo the last migration | `alembic downgrade -1` | +| Mark an existing schema as up to date | `alembic stamp head` | + +Migration files live in the Alembic `versions` folder (**TO CONFIRM** the path in `pixels-backend`). + +## Adding a migration + +1. Change the model in `pixels-backend`. +2. Run `alembic revision --autogenerate -m "describe the change"`. +3. Open the new file and check the `upgrade` and `downgrade` steps. +4. Run `alembic upgrade head` on your local database. +5. Run `alembic downgrade -1` and then `alembic upgrade head` again to prove both directions work. +6. Run the backend tests (`pytest`). +7. Commit the model change and the migration together. +8. Update [Key entities](./key-entities.md), [Constraints](./constraints.md) and the [entity relationship diagram](./er-diagram.md) if the schema changed. + +## Common problems + +| Symptom | Cause | Fix | +| --- | --- | --- | +| `relation "islands" already exists` | The tables were created before Alembic was set up on your machine. | Drop and recreate the local database, or run `alembic stamp head` and then `alembic upgrade head`. | +| Adding a unique constraint fails | The table already contains duplicate values. | Clean the duplicates first, for example in the migration itself, then upgrade again. | +| The app and the migrations disagree about the data | Alembic and the application are connected to different databases. | Make sure the connection setting in `.env` and the default in the application's database code name the same database. | + +PostgreSQL treats names that differ only in capitals, such as `MvuviGo` and `mvuvigo`, as different databases when the name was created with quotes. The documented name is `MvuviGo`. **TO CONFIRM** the exact spelling every environment must use, and use it everywhere. + +## Production + +- Take a database backup before every production migration. +- Run `alembic upgrade head` on every deploy, after the backup and before the new backend starts. +- Follow [Rollback and recovery](../deployment/deployment.md#rollback-and-recovery) if a migration has to be undone. diff --git a/docs/database/seed-data.md b/docs/database/seed-data.md new file mode 100644 index 0000000..7397901 --- /dev/null +++ b/docs/database/seed-data.md @@ -0,0 +1,33 @@ +# Seed Data + +Seed data is the information a fresh database needs before the system is useful. Everything else is created by people using the dashboard and by the wristbands and stations. + +## What needs seeding + +| Table | Why | Needed in production | +| --- | --- | --- | +| `islands` | Reference data for the fishing areas: `island_name`, `island_latitude` and `island_longitude`. | Yes | +| `station_operators` | At least one operator must exist to log in and register fishers. The password is stored as a hash, never in plain text. | Yes, the first operator only | +| `fishers`, `wristbands`, `trips`, `locations` | Sample records for local development and demos. | No | +| `distressed_fisher_alerts`, `alert_responders` | Sample alerts for local development and demos. | No | + +The list of islands to load: **TO CONFIRM**. + +## How seed data is loaded + +**TO CONFIRM:** whether seed data is loaded by a script, by a migration or by hand, and the exact command. Document it here once decided, for example: + +```bash +# TO CONFIRM: replace with the real command +python +``` + +If there is no seed mechanism yet, state "none" here and list how the first operator and the islands are created. + +## Rules + +- A seed script must be safe to run twice. Check for existing rows before inserting. +- Never load development sample data into production. +- Sample data uses invented names and phone numbers, never real people. +- Do not commit real passwords or real operator accounts. Create the first production operator through a secured step and store its credentials in the host's secret store. +- Backend tests create their own data and roll it back, so they do not depend on seed data. diff --git a/docs/deployment/branching-and-prs.md b/docs/deployment/branching-and-prs.md index b71745d..ed39912 100644 --- a/docs/deployment/branching-and-prs.md +++ b/docs/deployment/branching-and-prs.md @@ -14,7 +14,6 @@ git checkout develop git pull git checkout -b feature/ -# make your changes, then git add . git commit -m "Describe what changed" git push -u origin feature/ diff --git a/docs/deployment/deployment.md b/docs/deployment/deployment.md index fc8ea1b..a269fd0 100644 --- a/docs/deployment/deployment.md +++ b/docs/deployment/deployment.md @@ -2,51 +2,236 @@ ![Build and deployment pipeline](../assets/deployment-pipeline.svg) -MvuviGo has three parts to run or publish: the backend API, the dashboard and this documentation site. +This page describes how MvuviGo is built, deployed, configured, monitored and recovered. Items marked **TO CONFIRM** depend on infrastructure details that are not recorded in the repositories. Replace each one with the real value before relying on this page. -## Backend (`pixels-backend`) +## Overview -Requirements: Python, [uv](https://docs.astral.sh/uv/), and a PostgreSQL database. +| Part | Repository | Technology | Hosting | Deployed by | +| --- | --- | --- | --- | --- | +| Backend API | `pixels-backend` | FastAPI, SQLAlchemy, Alembic | **TO CONFIRM** | **TO CONFIRM** | +| Dashboard | `pixels-frontend` | Next.js (JSX), Tailwind | **TO CONFIRM** | **TO CONFIRM** | +| Database | none | PostgreSQL | **TO CONFIRM** | Alembic migrations | +| Documentation site | `pixels-technical-documentation` | VitePress | GitHub Pages | GitHub Actions | +| Public website | `pixels-informational-website` | **TO CONFIRM** | **TO CONFIRM** | **TO CONFIRM** | -```bash -uv sync -alembic upgrade head -uv run uvicorn main:app --reload -``` +## Deployment targets + +| Target | Purpose | Notes | +| --- | --- | --- | +| Development | Local work on a developer machine | Local PostgreSQL, `--reload`, `npm run dev`. | +| Staging | Pre-release checks | **TO CONFIRM** whether a staging environment exists. If not, state "none" here. | +| Production | Live system used by station operators | Deployed only from the release branch (see [Release process](#release-process)). | + +## Hosting + +### Hosting platform + +**TO CONFIRM:** name the platform or provider used for the backend, dashboard and database (for example a cloud provider, a PaaS or a VPS), the account or project that owns it, and who has access. + +### Backend hosting -- Drop `--reload` outside development. +- Runs as a Python process serving `main:app` with uvicorn. - The API is served under `/api/v1`. -- The database connection is read from environment settings, not from code. Never commit credentials. -- Run `alembic upgrade head` on every deploy so the schema matches the models. +- Host: **TO CONFIRM**. Public URL: **TO CONFIRM**. +- The host must provide the environment variables listed below and outbound access to the database. + +### Frontend hosting + +- Runs as a Next.js production server (`npm start`) after `npm run build`. +- Host: **TO CONFIRM**. Public URL: **TO CONFIRM**. +- The documentation site is a static VitePress build hosted on GitHub Pages. + +### Database hosting + +- PostgreSQL. Host or managed service: **TO CONFIRM**. Version: **TO CONFIRM**. +- The production database must not be reachable from the public internet. Only the backend should be able to connect. +- Backups: see [Rollback and recovery](#rollback-and-recovery). + +## External services + +| Service | Purpose | Used by | Configuration | +| --- | --- | --- | --- | +| GitHub | Source hosting, pull request checks, GitHub Actions, GitHub Pages | All repositories | Workflows in `.github/workflows` | +| Map tile provider | Base map for the Live Incidents map | Dashboard | **TO CONFIRM** provider and any API key | +| Figma | Design reference only | Developers | Not used at runtime | +| Other (email, SMS, push, storage) | **TO CONFIRM** | **TO CONFIRM** | If none exist, write "none". | + +## Environment variables + +Real values are never committed. Keep a `.env.example` in each repository that lists names with dummy values. + +### Backend + +| Variable | Purpose | Production value | +| --- | --- | --- | +| Database connection setting | Connection string for PostgreSQL. **TO CONFIRM** the exact variable name. | Production database, stored in the host's secret store | +| Authentication or signing secret | Signs tokens, if used. **TO CONFIRM** the name. | Long random value, different from development | +| Allowed CORS origins | Origins permitted to call the API. **TO CONFIRM** whether this is configurable. | The dashboard's production URL only | +| Debug flag | Enables verbose errors. **TO CONFIRM** the name. | Off | + +### Dashboard + +| Variable | Purpose | Production value | +| --- | --- | --- | +| API base URL | Base URL that `lib/api.js` calls. **TO CONFIRM** the exact variable name. | The backend's production URL ending in `/api/v1` | + +If the variable is exposed to the browser (a `NEXT_PUBLIC_` variable in Next.js), its value is fixed at build time. Rebuild the dashboard whenever it changes. + +### Where secrets live + +**TO CONFIRM:** name the place production secrets are stored (host secret manager, GitHub Actions secrets, and so on) and who can change them. Rotate any secret that has been exposed in a commit, log or chat. + +## Build process + +| Part | Commands | Output | +| --- | --- | --- | +| Backend | `uv sync` | Installed environment. There is no compile step. | +| Dashboard | `npm install` then `npm run build` | Production build in `.next` | +| Documentation | `npm install` then `npm run docs:build` | Static site in the VitePress output folder | + +## Deployment process + +Deploy in this order so each part finds what it depends on. + +1. **Back up the production database** (see [Rollback and recovery](#rollback-and-recovery)). +2. **Backend** + 1. Pull the release version of `pixels-backend`. + 2. Run `uv sync`. + 3. Run `alembic upgrade head` against the production database. Run it on every deploy so the schema matches the models. + 4. Restart the service with the production command below. +3. **Dashboard** + 1. Pull the release version of `pixels-frontend`. + 2. Confirm the API base URL points at the production backend. + 3. Run `npm install`, `npm run build`, then restart with `npm start`. +4. **Documentation** + 1. Merge the docs change through a pull request. + 2. When the change reaches the publishing branch, the GitHub Actions workflow builds the site and updates GitHub Pages. No manual step is needed. +5. Run the [smoke test](#health-checks) before announcing the release. + +**TO CONFIRM:** whether steps 2 and 3 run automatically from a pipeline or by hand on the host. Document the trigger and the person or team responsible. -## Dashboard (`pixels-frontend`) +## Production configuration -Requirements: Node.js and npm. +### Backend ```bash -npm install -npm run build -npm start +uv run uvicorn main:app --host 0.0.0.0 --port --workers ``` -For development use `npm run dev`. Point the app at the backend's base URL through its environment configuration so `lib/api.js` calls the right server. +- No `--reload`. +- Debug output off. +- Database connection and secrets come from environment variables. +- HTTPS is terminated by the host or a reverse proxy in front of uvicorn. +- CORS allows only the production dashboard origin. -## Documentation site +### Dashboard -This site is built with VitePress and published to GitHub Pages by a GitHub Actions workflow in `.github/workflows`. +- Build with `npm run build` and serve with `npm start`. Both run in production mode. +- The API base URL points at the production backend over HTTPS. + +## Development versus production + +| Setting | Development | Production | +| --- | --- | --- | +| Database | Local PostgreSQL with throwaway data | Hosted PostgreSQL (**TO CONFIRM**), backed up, private network only | +| API URL | `http://localhost:8000/api/v1` | `https:///api/v1` (**TO CONFIRM**) | +| Dashboard URL | `http://localhost:3000` | `https://` (**TO CONFIRM**) | +| Secrets | Local `.env`, never committed | Host secret store, unique per environment | +| Debug configuration | `--reload`, `npm run dev`, verbose errors | No reload, `npm start`, debug off | +| CORS | Allows `http://localhost:3000` | Allows only the production dashboard origin | +| Migrations | Run when models change | Run on every deploy after a backup | +| Authentication | Never weakened for local testing. Use a local-only override kept out of PRs. | Full authentication enforced | + +## Domain configuration + +| Part | Domain | Notes | +| --- | --- | --- | +| Backend | **TO CONFIRM** | DNS record points at the backend host. HTTPS certificate required. | +| Dashboard | **TO CONFIRM** | DNS record points at the dashboard host. HTTPS certificate required. | +| Documentation | `.github.io/pixels-technical-documentation` or a custom domain (**TO CONFIRM**) | If the site is served from a sub-path, the VitePress `base` setting must match it. | +| Public website | **TO CONFIRM** | | + +Record who owns the domain registration and where DNS is managed. + +## Service communication -```bash -npm install -npm run docs:dev # live preview while writing -npm run docs:build # production build ``` +Browser -> Dashboard (Next.js) -> Backend /api/v1 (FastAPI) -> PostgreSQL +``` + +- The dashboard calls the backend only through the shared client in `lib/api.js`, using the configured API base URL. +- The backend must allow the dashboard's origin through CORS. A wrong or missing origin shows up as blocked requests in the browser. +- Requests carry the user's authentication token. `401` and `403` responses show an authentication message in the dashboard. +- The backend is the only service that talks to the database, using the connection setting from its environment. + +## Health checks + +| Check | How | Healthy result | +| --- | --- | --- | +| Backend alive | `GET /api/v1/health` (**TO CONFIRM** the route exists, add it if not) | `200` | +| Database reachable | The same endpoint runs a trivial query such as `SELECT 1` | `200`, otherwise `503` | +| Dashboard alive | Load the login page | Page renders, no console errors | +| Docs published | Check the latest GitHub Actions run and open the site | Workflow green, new content visible | + +Smoke test after every deploy: + +1. The health endpoint returns `200`. +2. Log in to the dashboard. +3. Open the Live Incidents page and confirm data loads and the map renders. +4. Confirm there are no new errors in the logs. + +## Logging + +- **Backend:** uvicorn writes access and error logs to standard output and error. The host collects them. Viewing location: **TO CONFIRM**. +- **Dashboard:** server logs come from the host. Client errors appear in the browser console. +- **Documentation:** build logs are in the GitHub Actions run. +- Never log secrets, tokens or full request bodies containing personal data. +- Retention period: **TO CONFIRM**. + +## Monitoring + +Watch at least the following: + +- Backend uptime through the health endpoint. +- Rate of `5xx` responses and response time. +- Database storage, connections and backup success. +- Failed GitHub Actions runs. + +Monitoring tool: **TO CONFIRM**. Alerts go to: **TO CONFIRM**. If no tool exists yet, record that and check the health endpoint manually after each release. + +## Release process + +1. Work is merged into `develop` through pull requests (see [Branching and pull requests](./branching-and-prs.md)). +2. When `develop` is ready to ship, promote it to the release branch (**TO CONFIRM** the branch name, for example `main`). The documentation workflow publishes from this branch. +3. Tag the release, for example `v1.2.0`, so it can be redeployed or rolled back by name. +4. Complete the checklist below. +5. Deploy following [Deployment process](#deployment-process), then run the smoke test. + +Checklist before a release: + +- [ ] Migrations created for every model change and applied to the target database. +- [ ] Backend tests pass (`pytest`). +- [ ] Dashboard builds without errors. +- [ ] Environment variables set for the target environment. +- [ ] Production database backed up. +- [ ] Documentation updated for anything that changed. + +## Rollback and recovery + +### Application + +- Redeploy the previous release tag of the backend or dashboard, then restart. +- For the documentation site, revert the commit on the publishing branch. The workflow republishes the earlier version. + +### Database -Push your docs changes through a PR as described in [Branching and pull requests](./branching-and-prs.md). When the change reaches the publishing branch, the workflow builds the site and updates GitHub Pages. +- Take a backup before every production migration, for example `pg_dump`, or a snapshot if the provider offers one. +- To undo a migration, run `alembic downgrade -1`. This only works if the migration has a working `downgrade`, so write and test one for every migration. +- If data is damaged, restore the latest backup and redeploy the matching application version. +- Automated backup schedule and retention: **TO CONFIRM**. -## Checklist before a release +### Recovery notes -- Migrations applied and the schema matches the models. -- Backend tests pass (`pytest`). -- Dashboard builds without errors. -- Environment variables set for the target environment. -- Documentation updated for anything that changed. \ No newline at end of file +- Keep an up-to-date list of who can access the host, database and secrets. +- If a secret is exposed, rotate it and redeploy. +- Practise a restore from backup at least once and record how long it takes. diff --git a/docs/deployment/index.md b/docs/deployment/index.md index 6b65fa0..cbf9dd9 100644 --- a/docs/deployment/index.md +++ b/docs/deployment/index.md @@ -1,12 +1,12 @@ # Deployment and Contribution -This section covers how code gets from your laptop into the shared project, and how each part of MvuviGo is built and run. +This section covers how code gets from your laptop into the shared project, and how each part of MvuviGo is built, deployed, monitored and recovered. ## In this section - [Branching and pull requests](./branching-and-prs.md): the branch and PR workflow every change follows. - [Code contribution](./code-contribution.md): coding standards and what reviewers check. -- [Deployment](./deployment.md): building and running the backend, the dashboard and these docs. +- [Deployment](./deployment.md): hosting, environments, configuration, release, monitoring and rollback for the backend, the dashboard and these docs. ## The repositories @@ -17,4 +17,4 @@ This section covers how code gets from your laptop into the shared project, and | `pixels-informational-website` | The public MvuviGo website. | | `pixels-technical-documentation` | This documentation site. | -![Build and deployment pipeline](../assets/deployment-pipeline.svg) \ No newline at end of file +![Build and deployment pipeline](../assets/deployment-pipeline.svg) diff --git a/docs/frontend/api-integration.md b/docs/frontend/api-integration.md new file mode 100644 index 0000000..029363a --- /dev/null +++ b/docs/frontend/api-integration.md @@ -0,0 +1,78 @@ +# API Integration + +All backend calls go through one client, **`lib/api.js`**. Pages and components never call `fetch` directly. + +## Base URL and configuration + +The backend is the FastAPI service under `/api/v1`. The client builds every URL from a base URL set in an environment variable, so each environment can point to its own backend. + +| Setting | Purpose | Example | +| --- | --- | --- | +| `NEXT_PUBLIC_API_URL` | Backend host, without `/api/v1` | `http://localhost:8000` | + +The client appends `/api/v1` and the endpoint path to this base. + + +## Request mechanism + +`lib/api.js` wraps the browser `fetch` API. It: + +1. Builds the full URL from the base URL and the path. +2. Adds the headers (`Content-Type: application/json` and the auth header). +3. Sends the request and parses the JSON response. +4. Throws a readable error when the response is not successful. + +Pages call small named functions from the client, for example `getAlerts()` or `getFishers()`, rather than building requests themselves. + +## Authentication mechanism + +The client reads the token stored under `mvuvi_token` and sends it as: + +```http +Authorization: Bearer +``` + +The sign-in and registration requests are sent without a token. See [Authentication](./authentication.md). + +## Endpoints used + +| Endpoint | Used for | Page | +| --- | --- | --- | +| `/api/v1/alerts/` | Distressed fisher alerts shown on the map | Dashboard, Live Incidents | +| `/api/v1/alert-responders/` | Nearest responders for an alert | Responders and Messages | +| `/api/v1/fishers/` | Fisher details, registration, phone changes | Fishers, Settings | +| Sign-in endpoint | Exchange email and password for a token | Login | +| Registration endpoint | Create an operator account | Register | +| Wristbands endpoint | List wristbands, assign to a fisher | Wristbands | +| Reports endpoint | Incident history and report download | Reports | +| SMS messages endpoint | Messages sent to responders | Responders and Messages | + +## Response handling + +- Successful responses are parsed as JSON. +- Pages pass the raw response through a small **mapper** that converts backend field names to the shape the UI needs and supplies fallbacks for missing values, for example a default label when a responder has no name. +- Lists are returned in the order the backend sends them. Responders arrive nearest first. + +Example of the mapping idea: + +```js +function mapResponder(r) { + return { + name: r.name ?? "Unnamed responder", + distanceM: r.distance_m, + notifiedAt: r.received_at, + arrivedAt: r.arrived_at ?? null, + }; +} +``` + +## Error handling + +| Response | Client behaviour | +| --- | --- | +| `401` | Clear the token, redirect to `/login` | +| `403` | Show an access message, do not render an empty table | +| `422` | Show the field errors returned by the backend on the form | +| `5xx` or network failure | Show a short error and keep the rest of the page usable | + +Each page turns the error into its `error` state. See [State management](./state-management.md). diff --git a/docs/frontend/architecture.md b/docs/frontend/architecture.md index bd0fa93..51bfb6b 100644 --- a/docs/frontend/architecture.md +++ b/docs/frontend/architecture.md @@ -20,10 +20,42 @@ | Topic | Convention | | --- | --- | | Language | JSX, not TypeScript | +| Framework | Next.js, App Router | | Styling | Tailwind classes, Nunito font | | Data access | Always through `lib/api.js` | | Auth token | Stored under the key `mvuvi_token` | | Layout | Shared via the `(dashboard)` route group | +| State | Plain React hooks, no global store | + +## Project structure + +The tree below shows the layout the docs rely on. Names marked with `*` are the ones the rest of this section refers to. + +```text +pixels-frontend/ +├── app/ +│ ├── layout.jsx # root layout (fonts, global styles) +│ ├── login/page.jsx # sign-in page +│ ├── register/page.jsx # create-account page +│ └── (dashboard)/ # * signed-in route group +│ ├── layout.jsx # * shared Sidebar + TopBar, session check +│ ├── dashboard/page.jsx # Operations Dashboard +│ ├── incidents/page.jsx # Live Incidents +│ ├── fishers/page.jsx # Fishers +│ ├── wristbands/page.jsx # Wristbands +│ ├── responders/page.jsx # Responders and Messages +│ ├── reports/page.jsx # Incident Reports and History +│ └── settings/page.jsx # System Settings +├── components/ # * Sidebar, TopBar, maps, tables, popups +├── lib/ +│ └── api.js # * shared API client +├── public/ # static assets (logo, images) +├── .env.local # local environment variables (not committed) +├── next.config.mjs +├── tailwind.config.js +└── package.json +``` + ## Talking to the backend @@ -33,4 +65,6 @@ The dashboard consumes endpoints such as: | --- | --- | | `/api/v1/alerts/` | Distressed fisher alerts shown on the map. | | `/api/v1/alert-responders/` | Nearest responders for an alert. | -| `/api/v1/fishers/` | Fisher details. | \ No newline at end of file +| `/api/v1/fishers/` | Fisher details. | + +The full list, including sign-in and registration, is in [API integration](./api-integration.md). diff --git a/docs/frontend/authentication.md b/docs/frontend/authentication.md new file mode 100644 index 0000000..53d46c0 --- /dev/null +++ b/docs/frontend/authentication.md @@ -0,0 +1,66 @@ +# Authentication + +Operators authenticate with an email and password. The backend returns an access token, the browser keeps it under the key **`mvuvi_token`**, and `lib/api.js` sends it with every request. + +## Overview + +| Item | Behaviour | +| --- | --- | +| Credentials | Email and password | +| Token key | `mvuvi_token` | +| Token sent as | `Authorization: Bearer ` header, added by `lib/api.js` | +| Public pages | `/login`, `/register` | +| Everything else | Requires a valid token | + +## Login + +1. The operator opens `/login` and enters **Email** and **Password**. +2. The form checks the fields (see [Forms and validation](./forms-and-validation.md)). +3. `lib/api.js` posts the credentials to the backend sign-in endpoint. +4. On success, the access token is saved under `mvuvi_token` and the operator is sent to the dashboard. +5. On failure, the page stays on `/login` and shows the error message (see below). + +The **Forgot password** link starts the password reset. In **Settings**, an operator can also press **Send Reset Code** to have a reset code sent to the operator email. + +## Registration + +The `/register` page creates an operator account from first name, last name, email, password and confirm password. After a successful registration the operator signs in on `/login`. + +## Logout + +1. The operator chooses sign out from the operator menu in the `TopBar`. +2. The `mvuvi_token` key is removed from the browser. +3. The operator is redirected to `/login`, and the dashboard pages are no longer reachable until the next sign-in. + +## Session and token handling + +- The token is the only credential the frontend stores. It is read and written only through the shared auth helpers and `lib/api.js`, never by individual pages. +- Reading the token under another name, or calling `fetch` directly, makes pages appear signed out. +- The frontend does not decode the token. It trusts the backend to accept or reject it. + +## Protected routes + +The `(dashboard)` layout wraps every signed-in page. When it mounts it checks for `mvuvi_token`: + +| Token state | Result | +| --- | --- | +| Present | The page renders and its data requests carry the token | +| Missing | The operator is redirected to `/login` before any data is requested | +| Rejected by the backend (`401`) | The token is cleared and the operator is redirected to `/login` | + +Because the layout is shared, no individual page has to repeat this check. + +## Expiration + +Access tokens have a limited lifetime set by the backend. When a token expires, the next request returns `401`. The frontend then clears `mvuvi_token`, shows a "session expired, please sign in again" message and redirects to `/login`. Unsaved form input on the page is lost. + +## Authentication errors + +| Situation | What the operator sees | +| --- | --- | +| Wrong email or password | An inline error on the login form, fields stay filled in except the password | +| Validation failure | Field-level messages, no request is sent | +| `401` on a data request | Session-expired message and redirect to `/login` | +| `403` on a data request | "You do not have access" message. The page does not show an empty table | +| Backend unreachable | A short network error message, with a retry | + diff --git a/docs/frontend/build-and-tooling.md b/docs/frontend/build-and-tooling.md new file mode 100644 index 0000000..cb64ad9 --- /dev/null +++ b/docs/frontend/build-and-tooling.md @@ -0,0 +1,38 @@ +# Build and Tooling + +## Toolchain + +| Tool | Role | +| --- | --- | +| Node.js and npm | Runtime and package manager | +| Next.js | Framework, dev server and production build | +| React | UI library, written in JSX | +| Tailwind CSS (with PostCSS) | Styling | +| ESLint | Linting | + +## Scripts + +Run these from the `pixels-frontend` folder: + +| Command | What it does | +| --- | --- | +| `npm install` | Install dependencies | +| `npm run dev` | Start the development server on port 3000 | +| `npm run build` | Create the optimised production build | +| `npm run start` | Serve the production build | +| `npm run lint` | Run ESLint | + +## Environment variables + +| Variable | Purpose | +| --- | --- | +| `NEXT_PUBLIC_API_URL` | Backend base URL (see [API integration](./api-integration.md)) | + +Variables that start with `NEXT_PUBLIC_` are included in the browser bundle, so never put secrets in them. Keep local values in `.env.local`, which is not committed. + +## Build process + +1. `npm install` installs dependencies from `package-lock.json`. +2. `npm run build` compiles the pages, bundles the JavaScript and CSS, and generates the static assets. +3. The build fails on compile errors, so fix them before release. +4. `npm run start` serves the result for a final check. diff --git a/docs/frontend/deployment.md b/docs/frontend/deployment.md new file mode 100644 index 0000000..79f0bac --- /dev/null +++ b/docs/frontend/deployment.md @@ -0,0 +1,33 @@ +# Deployment + +For infrastructure and backend deployment, see the top-level `docs/deployment` section. This page covers the frontend. + +## Pipeline + +1. Merge approved changes into the main branch through a pull request. +2. Install dependencies with `npm install`. +3. Build with `npm run build`. +4. Serve the build with `npm run start`, or publish it on the hosting platform. +5. Check the release with the smoke test below. + +## Configuration per environment + +| Environment | `NEXT_PUBLIC_API_URL` | +| --- | --- | +| Local | `http://localhost:8000` | +| Staging | The staging backend URL | +| Production | The production backend URL | + +The value is read at build time, so rebuild after changing it. The backend must allow requests from the frontend origin (CORS). + +## Smoke test after release + +- [ ] `/login` loads and sign-in works. +- [ ] The Dashboard shows its counts and the map. +- [ ] A test alert appears on Live Incidents. +- [ ] Responders and Messages loads. + +## Rollback + +Redeploy the previous successful build. Because the app keeps only a token in the browser, no data migration is needed on the frontend. + diff --git a/docs/frontend/forms-and-validation.md b/docs/frontend/forms-and-validation.md new file mode 100644 index 0000000..7ddc97c --- /dev/null +++ b/docs/frontend/forms-and-validation.md @@ -0,0 +1,37 @@ +# Forms and Validation + +Forms are plain React controlled inputs. Each form holds its field values, field errors and a `submitting` flag in local state, validates on submit, and only then calls `lib/api.js`. + +## Forms in the app + +| Form | Page | Fields | Submit | +| --- | --- | --- | --- | +| Sign in | `/login` | Email, Password | **Login** | +| Create account | `/register` | First Name, Last Name, Email, Password, Confirm Password | **Create Account** | +| Add fisher | Fishers | Fisher details, including name and phone number | **Add Fisher** | +| Assign wristband | Wristbands | Wristband, fisher | **Assign** | +| Reset code | Settings | Operator Email (read from the account) | **Send Reset Code** | +| Change fisher phone | Settings | Search by name, new phone number, confirm new phone number | **Save Changes** | +| Search and filters | Fishers, Wristbands, Reports | Search text, date range | Applied as the operator types or picks | + +## Validation rules + +| Field | Rule | +| --- | --- | +| Email | Required, valid email format | +| Password (login) | Required | +| Password (register) | Required, minimum length | +| Confirm Password | Required, must equal Password | +| First Name, Last Name | Required | +| Phone number | Required, valid Kenyan format such as `+254 7xx xxx xxx` | +| Confirm new phone number | Required, must equal the new phone number | +| Fisher search | Required before **Save Changes** is enabled | + +## Behaviour + +- Errors appear under the field that caused them, in plain words (for example "Passwords do not match"). +- A form with errors is not sent to the backend. +- While a request is running, the submit button is disabled and shows a loading label to stop double submits. +- Backend validation errors (`422`) are shown next to the matching fields, and other failures show a message at the top of the form. +- After a successful submit the form shows a short success message, then redirects or refreshes the list. + diff --git a/docs/frontend/index.md b/docs/frontend/index.md index 33f6223..f65931a 100644 --- a/docs/frontend/index.md +++ b/docs/frontend/index.md @@ -4,15 +4,46 @@ The MvuviGo dashboard is the screen station operators use to watch for distresse ## What operators can do -- See fishers in distress on a live map (**Live Incidents**). +- Register an operator account, sign in and sign out. +- See fishers in distress on a live map (**Live Incidents**) and the headline numbers on the **Dashboard**. - See the nearest responders to an alert and the SMS messages sent to them (**Responders and Messages**), in either map view or list view. -- Sign in with their operator account. Everything else requires a valid session. +- Register fishers and look them up (**Fishers**). +- See which wristbands are available and assign them to fishers (**Wristbands**). +- Review past incidents, response times and download a report (**Reports**). +- Reset the operator password and change a fisher's phone number (**Settings**). + +Everything except the login and register pages requires a valid session. + +## At a glance + +| Area | Summary | Details | +| --- | --- | --- | +| Framework and language | Next.js (App Router), React, JSX | [Architecture](./architecture.md) | +| Styling | Tailwind CSS, Nunito font | [Architecture](./architecture.md) | +| State management | Plain React state and hooks, no global store | [State management](./state-management.md) | +| Routing | App Router with a `(dashboard)` route group | [Routing](./routing.md) | +| Pages and workflows | Nine screens, each with a documented workflow | [Pages and components](./pages-and-components.md) | +| Forms and validation | Login, register, add fisher, assign wristband, settings | [Forms and validation](./forms-and-validation.md) | +| Authentication | Token in the browser, sent on every request | [Authentication](./authentication.md) | +| API integration | One shared client, `lib/api.js` | [API integration](./api-integration.md) | +| Maps and real-time | Red SOS pins, popups, refreshing alerts | [Maps and real-time](./maps-and-real-time.md) | +| Build tooling and process | npm scripts, environment variables | [Build and tooling](./build-and-tooling.md) | +| Testing | Manual checklist and automated test notes | [Testing](./testing.md) | +| Deployment | Build, configure, release | [Deployment](./deployment.md) | ## In this section -- [Architecture](./architecture.md): how the app is structured and how it reaches the backend. -- [Pages and components](./pages-and-components.md): the screens and the building blocks they use. -- [State management](./state-management.md): how sign-in and data loading are handled. +- [Architecture](./architecture.md): how the app is structured, the project layout and how it reaches the backend. +- [Routing](./routing.md): every URL, the page behind it and who can open it. +- [Pages and components](./pages-and-components.md): the screens, their workflows and the building blocks they use. +- [State management](./state-management.md): how sign-in and data loading are handled, including loading and error states. +- [Forms and validation](./forms-and-validation.md): every form, its fields and its validation rules. +- [Authentication](./authentication.md): login, logout, token handling, protected routes, expiry and errors. +- [API integration](./api-integration.md): base URL, request client, auth header, response and error handling. - [Maps and real-time](./maps-and-real-time.md): how alerts reach the map and what happens when a pin is clicked. +- [Build and tooling](./build-and-tooling.md): scripts, environment variables and the build process. +- [Testing](./testing.md): what is tested and how to test the main workflows. +- [Deployment](./deployment.md): how the frontend is built and released. + +![Dashboard architecture](../assets/frontend-architecture.svg) -![Dashboard architecture](../assets/frontend-architecture.svg) \ No newline at end of file diff --git a/docs/frontend/maps-and-real-time.md b/docs/frontend/maps-and-real-time.md index 85507c7..a8fa563 100644 --- a/docs/frontend/maps-and-real-time.md +++ b/docs/frontend/maps-and-real-time.md @@ -14,8 +14,10 @@ ## Map behaviour - Only **red SOS pins** open the popup, and the popup is anchored to the pin that was clicked. -- Zoom buttons sit at the top-left of the map. +- Zoom buttons sit on the map in the same place on the Dashboard, Live Incidents and Responders maps. - The responders page offers the same map in a **Map view**, plus a **List view** of the same people. +- Pin colours: **red** for a distressed fisher, **green** for nearby fishers; amber pins also appear on the maps. + ## Responders data @@ -32,4 +34,9 @@ Responders are ordered by distance so the nearest appear first. ## Keeping the view current -Operators need to see new alerts quickly. The page should reload alert data from the backend while it is open. When you change how often or how it refreshes, check that it does not reset the operator's zoom level or close an open popup. \ No newline at end of file +Operators need to see new alerts quickly. The page reloads alert data from the backend while it is open. When you change how often or how it refreshes, check that it does not reset the operator's zoom level or close an open popup. + +| Item | Value | +| --- | --- | +| Update mechanism | Periodic reload of the alerts endpoint (polling) | +| Interval | To be confirmed | diff --git a/docs/frontend/pages-and-components.md b/docs/frontend/pages-and-components.md index 64c047d..e15a839 100644 --- a/docs/frontend/pages-and-components.md +++ b/docs/frontend/pages-and-components.md @@ -6,21 +6,76 @@ Every dashboard page renders inside the `(dashboard)` layout, which provides: -- **Sidebar**: navigation between pages. -- **TopBar**: the header. It takes an `onMenuClick` prop so the sidebar can be toggled on small screens. +- **Sidebar**: navigation between pages (Dashboard, Incidents, Fishers, Wristbands, Responders, Reports, Settings). +- **TopBar**: the header, showing the operations centre name (for example "Kisumu Operations Centre"), a notifications bell and the operator menu. It takes an `onMenuClick` prop so the sidebar can be toggled on small screens. Pages never render their own sidebar or top bar. Doing so creates the duplicate navigation that reviewers flag. -## Live Incidents +## Public pages + +### Login + +The "Welcome back" page: sign in to your MvuviGo account with **Email** and **Password**, a **Login** button, a **Forgot password** link and a **Register here** link for operators without an account. + +![Dashboard component tree](../assets/signin.png) + + +### Register + +The "Create Your Account" page, with fields for **First Name**, **Last Name**, **Email**, **Password** and **Confirm Password**, a **Create Account** button and a **Sign in** link for existing operators. + +![Dashboard component tree](../assets/register.png) + + +## Signed-in pages + +### Dashboard + +The Operations Dashboard for the landing site (for example Kisumu). + +- Three summary cards: **Active Incidents** (needs immediate attention), **Fishers on the Lake** (live wristband tracking) and **Responders Availability** (ready to respond). +- A lake overview map with a legend: **Distressed Fisher** (red) and **Nearby Fishers** (green). +- Popups on pins show the fisher and the case status. + +![Dashboard component tree](../assets/dashboard.png) + + +### Live Incidents A full map of active alerts. - Fishers in distress appear as **red SOS pins**. - Clicking a pin opens a popup that touches that pin. The popup does not open from anywhere else. -- Zoom buttons sit in the top-left corner of the map, matching the responders map. +- An **Incident Details** panel shows the fisher, number of fishers, location, time and a status badge, followed by a **Response Timeline** (SOS received from a wristband, SMS sent to nearby responders, responder acknowledged, responder dispatched). +- Zoom buttons sit on the map, matching the responders map. - The basemap uses a Stamen-style look. -## Responders and Messages +![Dashboard component tree](../assets/incidents.png) + + +### Fishers + +Manage registered fishers and monitor their wristband status. + +- A **Registered Fishers** table with columns Fisher name, Phone number, Registration date and Action (**View**). +- A search box (name, phone or wristband) and an **Add Fisher** button. +- A switch between the fisher list and the wristband view. + +![Dashboard component tree](../assets/fishers.png) + + +### Wristbands + +Manage monitored wristbands and the names of the fishers they are attached to. + +- Counters for **Registered** and **Assigned** wristbands. +- A table with Wristband ID, Status (**Available** or **Unavailable**) and Action (**Assign**). +- A search box for wristband or fisher name. + +![Dashboard component tree](../assets/wristbands.png) + + +### Responders and Messages Shows who can help and what has been sent to them. @@ -28,6 +83,44 @@ Shows who can help and what has been sent to them. - A responders list that falls back to a placeholder when a responder has no name. - An **SMS messages** table. Message data comes through the backend, which talks to the SMS provider. +![Dashboard component tree](../assets/responders.png) + + +### Reports + +Incident Reports & History. + +- Summary cards: **Total Incidents** this month, **Resolved Incidents** and **Average response time**. +- A **Date range** filter and a searchable **Incident History** table (Incident ID, Fisher, Date and time, Location, Status, Response time). +- A **Download Report** button. + +![Dashboard component tree](../assets/reports.png) + + +### Settings + +System Settings, split into two cards. + +- **Landing Site Operator Account Settings**: operator email and **Send Reset Code**. +- **Fisher Account Settings**: search a fisher by name, enter and confirm a new phone number, then **Save Changes**. + +![Dashboard component tree](../assets/settings.png) + + +## Main user workflows + +| Workflow | Steps | +| --- | --- | +| Sign in | Open `/login`, enter email and password, press **Login**. On success the token is stored and the dashboard opens. | +| Register | Open `/register`, fill all five fields, press **Create Account**, then sign in. | +| Respond to an SOS | Watch the Live Incidents map, click a red pin, read Incident Details, open Responders and Messages to see the nearest responders and the SMS sent to them. | +| Register a fisher | Fishers, **Add Fisher**, fill the form, save. The new fisher appears in the table. | +| Assign a wristband | Wristbands, find an **Available** wristband, press **Assign**, choose the fisher. | +| Review history | Reports, set a **Date range**, search the history, press **Download Report**. | +| Change a fisher's phone number | Settings, search the fisher, enter the new number twice, **Save Changes**. | +| Reset operator password | Settings, check the operator email, press **Send Reset Code**. | +| Sign out | Open the operator menu in the `TopBar` and choose sign out. | + ## Component guidelines | Do | Avoid | @@ -35,4 +128,5 @@ Shows who can help and what has been sent to them. | One component per file | Large page files that mix data, layout and map code | | Pass data down as props | Fetching in deeply nested presentational components | | Reuse `Sidebar` and `TopBar` | Copying them into pages | -| Show loading, error and empty states | Rendering an empty table when a request fails | \ No newline at end of file +| Show loading, error and empty states | Rendering an empty table when a request fails | +| Reuse one generic table component for the Fishers, Wristbands and Reports tables | Writing a new table for each page | diff --git a/docs/frontend/routing.md b/docs/frontend/routing.md new file mode 100644 index 0000000..4ac38fd --- /dev/null +++ b/docs/frontend/routing.md @@ -0,0 +1,37 @@ +# Routing + +The app uses the Next.js **App Router**. Each folder under `app/` with a `page.jsx` becomes a URL. Folders in parentheses, such as `(dashboard)`, group pages that share a layout without adding to the URL. + +## Routes + +| URL | Page | Access | Main data | +| --- | --- | --- | --- | +| `/login` | Welcome back (sign in) | Public | Operator credentials | +| `/register` | Create Your Account | Public | New operator details | +| `/dashboard` | Operations Dashboard | Signed in | Alert counts, fisher count, responder availability, map | +| `/incidents` | Live Incidents | Signed in | `alerts`, incident details and response timeline | +| `/fishers` | Fishers | Signed in | `fishers` | +| `/wristbands` | Wristbands | Signed in | Wristbands and their assignments | +| `/responders` | Responders and Messages | Signed in | `alert-responders`, SMS messages | +| `/reports` | Incident Reports & History | Signed in | Past incidents, response times | +| `/settings` | System Settings | Signed in | Operator account, fisher phone numbers | + + +## Navigation + +The `Sidebar` links to the seven signed-in pages in this order: Dashboard, Incidents, Fishers, Wristbands, Responders, Reports, Settings. The active page is highlighted. Inner pages also show a **Back to Dashboard** link above the page title. + +On small screens the `TopBar` calls `onMenuClick` to open and close the sidebar. + +## Protected routes + +Every route inside `(dashboard)` needs a valid session. The layout checks for the token and sends signed-out users to `/login`. See [Authentication](./authentication.md) for the full behaviour. + +## Redirects + +| Situation | Result | +| --- | --- | +| Signed-out user opens a dashboard URL | Redirected to `/login` | +| Successful sign-in | Redirected to the dashboard | +| Successful registration | Redirected to `/login` | +| Sign out | Token cleared, redirected to `/login` | diff --git a/docs/frontend/state-management.md b/docs/frontend/state-management.md index 9e6dd06..c535d68 100644 --- a/docs/frontend/state-management.md +++ b/docs/frontend/state-management.md @@ -11,7 +11,7 @@ The dashboard uses plain React state and hooks. There is no global store: each p 3. `lib/api.js` reads that key and adds the token to every request. 4. The backend checks the token and returns data for the signed-in operator. -Always use the `mvuvi_token` key and the shared client. Reading the token under a different name, or calling `fetch` directly, will make pages appear signed out. +Always use the `mvuvi_token` key and the shared client. Reading the token under a different name, or calling `fetch` directly, will make pages appear signed out. Full details are in [Authentication](./authentication.md). ## Page data @@ -23,6 +23,12 @@ Each page tracks three things: | `data` | The map, list or table | | `error` | A clear message | +A page shows exactly one of these at a time. A fourth case, **empty** (the request worked but returned nothing), shows a friendly "nothing to show yet" message instead of a blank table. + +## Form state + +Forms keep their own field values, field errors and a `submitting` flag in local state. See [Forms and validation](./forms-and-validation.md). + ## Error handling - **`401` / `403`**: show an authentication message so the operator knows to sign in again. Do not show an empty table, which looks like "no data". @@ -31,4 +37,4 @@ Each page tracks three things: ## Keeping components simple -Fetch data in the page, map it into the shape the UI needs, and pass it to child components as props. Child components stay easy to reuse and test. \ No newline at end of file +Fetch data in the page, map it into the shape the UI needs, and pass it to child components as props. Child components stay easy to reuse and test. diff --git a/docs/frontend/testing.md b/docs/frontend/testing.md new file mode 100644 index 0000000..fb940eb --- /dev/null +++ b/docs/frontend/testing.md @@ -0,0 +1,48 @@ +# Testing + +For project-wide testing practice, see the top-level `docs/testing` section. This page covers the frontend. + +## Levels + +| Level | What it covers | Tooling | +| --- | --- | --- | +| Lint | Code style and common mistakes | `npm run lint` | +| Build check | The app compiles and every page builds | `npm run build` | +| Manual workflow checks | The main operator workflows end to end | Checklist below | +| Component and unit tests | Mappers, form validation, shared components | Not set up yet | + + +## Manual workflow checklist + +Run against a development backend before each release. + +**Authentication** + +- [ ] Wrong password shows an error and stays on `/login`. +- [ ] Correct sign-in stores `mvuvi_token` and opens the dashboard. +- [ ] Opening a dashboard URL while signed out redirects to `/login`. +- [ ] Sign out clears `mvuvi_token` and returns to `/login`. +- [ ] An expired or removed token shows the session message and redirects. + +**Forms** + +- [ ] Register rejects mismatched passwords and empty fields. +- [ ] Settings rejects mismatched phone numbers. +- [ ] Submit buttons are disabled while a request runs. + +**Pages** + +- [ ] Each of the seven sidebar pages loads and shows loading, data, empty and error states. +- [ ] A request returning `401` or `403` shows an authentication message, not an empty table. + +**Maps and real-time** + +- [ ] A new alert appears as a red SOS pin without a page reload. +- [ ] Clicking a red pin opens the popup on that pin, and clicking elsewhere does not. +- [ ] A refresh does not reset zoom or close an open popup. +- [ ] Responders are listed nearest first, and a responder without a name shows the placeholder. + +**Layout** + +- [ ] No page renders its own sidebar or top bar. +- [ ] The sidebar toggles on small screens (check at 375px).