Files
Project-SDE-WP-Suite/server
n.siegfried 4d186ea6a0 T6.3/T6.4 - CR-004 and CR-018: picked not typed, and totals that add up
CR-004 and CR-018 are the same change seen from two ends. CR-018 is why the
Acumatica cost code came out rather than being relabelled — the tracking
dimension the team wants is floor and area, not an accounting code — and CR-004
is what makes that dimension exist. Committed together because a rollup keyed on
free text is not a rollup, and structured location with nothing rolling up by it
is a form change nobody asked for.

CR-004 - three dependent dropdowns

  Building filters Floor filters Sector, off the project's own taxonomy from
  T5.4. Clearing a parent clears its children: not doing that is how a package
  ends up filed under a floor that is not in the building it claims.

  PATHS are stored, not names and not bare codes. A floor's own code is not
  unique across buildings; `B-ONE/L1` is. That is what lets the dashboard filter
  by a building and match everything beneath it with a prefix test, and it is
  what CR-018 groups on.

  The list is fetched with include_inactive=true, which is not a contradiction of
  CR-005's "deactivating hides it from new work packages" — they are two
  questions. What may be CHOSEN is active only. What may be SHOWN is everything,
  because a package already referencing a deactivated value still has to render
  its label, and blanking it on open would write the blank back on the next save.
  A deactivated value that IS on the package is offered, labelled "(no longer
  offered)"; on a fresh package it is not offered at all. Both checked.

  X5, checked the way aggregates_check checks its own: localStorage is poisoned
  with a fake building and the dropdown is required to ignore it.

  wp_location survives as a hidden field. A package written before this keeps
  what it said, and the form says so rather than dropping it.

CR-018 - the rollup

  LOCATION_DIMENSIONS is now ("building", "floor", "sector"). T4.1's note said
  "only this tuple and the keys inside each group change - the response shape
  does not", and that held exactly.

  Rolled up at EVERY level, server-side, not just at the leaf. "How many on
  floor 2" is the question CR-018 asks and it is a level above the leaf groups;
  summing them in the browser would be the same per-browser arithmetic B4
  removed. Actual Hours rolls up along the same dimensions - that is the field
  CR-017 retained, and this is why that decision mattered.

  Packages with no location are an explicit "(unassigned)" row, not a gap. The
  reason is arithmetic: a group set that silently omits them does not add up to
  the project total, and a rollup that does not reconcile is decoration. The
  probe checks every level sums to the project total, and to the estimated and
  actual hour totals, using distinct primes so a mis-sum cannot land on the
  right number by luck.

  A package with a building but no floor lands in the floor-level unassigned row
  alongside the one with no location at all - which is the honest answer, and is
  asserted by its hours rather than by its count.

  Free text captured before CR-004 groups under itself as a building rather than
  collapsing into unassigned, one level deep. Pretending free text is a
  hierarchy would file "FAB / LVL 1" under a building called "FAB / LVL 1".

  server/app.py                 dimensions, _location_levels, hours per group
  html/wp-creation-index.html   three selects where the text box was
  html/wp-creation-app.js       the pickers, the filters, the rollup panel
  html/wp-creation-styles.css   .loc-picker, .loc-rollup
  tests/rollup_check.py         new - 63 checks

Done when — CR-004
  [x] all three render as dropdowns populated from project configuration
  [x] dependent filtering works, and clearing a parent clears its children
  [x] values persist as codes; confirmed by reading what collectPackage stored
  [x] the dashboard filters by each of the three
  [x] a work package referencing a deactivated value still renders correctly
  [x] all option data comes from the server - proved by poisoning the cache

Done when — CR-018
  [x] the dashboard groups and totals by Building, Floor and Sector
  [x] totals reconcile against an unfiltered count, at every level
  [x] Actual Hours rolls up along the same dimensions
  [x] grouping is computed server-side - proved by putting nine fake packages in
      localStorage and requiring the panel to show none of them
  [x] work packages with no location appear in an explicit unassigned group

No migration: location lives in the work package's JSON data blob like every
other per-package field. No colour literal added.

Verified one at a time
  rollup_check      63/63  new
  generalinfo_check 49/49
  browser_check     71/71
  pipeline          43/43
  a11y              22/22
  aggregates        16/16
  f_items           F1-F5 FIXED, F6 REPRODUCES (T7.2)

Question for the PR, per CLAUDE.md: the dashboard's location filters and the
rollup both key on the path, so a package saved with free text and no codes is
unreachable by any location filter and sits in its own building-level row. That
is correct and it is also a migration question - whether the existing free-text
locations should be mapped onto the taxonomy once the B100 list arrives, or left
as history. Nothing here decides it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-17 00:24:00 -05:00
..

Work Package Suite API

A small Python (FastAPI) service that stores project SOPs, Work Packages, and comments in PostgreSQL. NGINX serves the static site and proxies /api/ to this service.

browser → NGINX ──serves──> static site (index.html, …)
                └─proxy /api/─> api container (:8000) → db container (postgres)

Endpoints

Method Path Purpose
GET /api/health liveness check (unauthenticated)
POST /api/auth/login sign in ({username, password}) — sets the session cookie
POST /api/auth/logout clear the session cookie
GET /api/auth/me the logged-in user
POST /api/auth/password change your own password
GET /api/auth/users list accounts (admin)
POST /api/auth/users create an account (admin)
DELETE /api/auth/users/{id} delete an account (admin)
POST /api/sops create/update a SOP (upsert by id)
GET /api/sops list SOP summaries
GET /api/sops/latest?complete=true most recent (complete) SOP
GET /api/sops/{id} full SOP document
DELETE /api/sops/{id} delete a SOP
POST /api/wps create/update a Work Package (upsert by id)
GET /api/wps?sop_id=… list WPs (optionally for one SOP)
GET /api/wps/{id} full WP document
DELETE /api/wps/{id} delete a WP
POST /api/comments (and /api/feedback) add a comment
GET /api/comments?source=&sop_id=&wp_id=&step= list comments

Interactive docs once running: /api/docs.

The full client document is stored in each row's data (JSON) column; common fields (name, number, status, …) are promoted to columns for listing/filtering.


Login portal (user accounts)

The suite is gated by a username/password login. Sign-in issues a signed JWT that rides in an HttpOnly, SameSite=Lax cookie (wp_session); the cookie is marked Secure automatically whenever the request arrives over HTTPS (via NGINX's X-Forwarded-Proto). There is no server-side session store — each request is validated by checking the cookie's signature and expiry.

The real security boundary is the API: every /api/ data route is refused with 401 unless a valid session cookie is present (see auth_gate in app.py). The static pages additionally include auth-guard.js, which redirects to login.html when there's no session — that's for UX, not protection.

Passwords are stored only as bcrypt hashes (server/auth.py). Roles are admin (may manage users) and user.

Set the signing secret

Add AUTH_SECRET_KEY to .env (see .env.example). Required in production — without it the API uses a random per-process key, so logins reset on restart.

python -c "import secrets; print(secrets.token_urlsafe(48))"

Create the first admin

The /api/auth/users endpoint needs an existing admin, so bootstrap one from a shell (run from the project root, like uvicorn):

python -m server.manage_users create-admin alice --name "Alice Smith"
# prompts for a password (min 8 chars)

In Docker:

docker compose exec api python -m server.manage_users create-admin alice --name "Alice Smith"

Other commands: create <user> --role user, list, reset-password <user>, disable <user>, enable <user>. After that, admins can add users through the API (or you can keep using the CLI).


Local dev

cd server
python -m venv .venv && . .venv/bin/activate      # Windows: .venv\Scripts\activate
pip install -r requirements.txt
# No DATABASE_URL → uses a local sqlite file, so you can start immediately:
uvicorn server.app:app --reload --port 8000       # run from the PROJECT ROOT

Then open http://localhost:8000/api/docs.

Run uvicorn/gunicorn from the project root (the folder that contains the server/ directory), because the import path is server.app:app.


Production — Docker Compose

This is the recommended production setup. Three containers run in an isolated internal network; only NGINX is exposed to the outside via the external proxy network.

[external proxy network]
        │
   ┌────▼────┐   internal network   ┌──────────┐   ┌────────┐
   │  nginx  │ ───────────────────> │   api    │ → │   db   │
   └─────────┘                      └──────────┘   └────────┘

1. Create the credentials file

Create .env in the project root (same directory as docker-compose.yml). This file is never committed — add it to .gitignore.

# .env  — project root
POSTGRES_DB=wpsuite
POSTGRES_USER=wpsuite
POSTGRES_PASSWORD=<strong-random-password>

# Must match POSTGRES_* above; hostname is the compose service name "db"
DATABASE_URL=postgresql+psycopg://wpsuite:<strong-random-password>@db:5432/wpsuite

Generate a strong password:

openssl rand -base64 32

2. Add the Dockerfile

Create Dockerfile in the project root:

FROM python:3.12-slim
WORKDIR /app
COPY server/requirements.txt ./server/
RUN pip install --no-cache-dir -r server/requirements.txt
COPY server/ ./server/
EXPOSE 8000
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", \
     "-b", "0.0.0.0:8000", "--workers", "2", "server.app:app"]

3. Update the NGINX site config

The API is no longer at 127.0.0.1:8000 — it is the api container. Update the /api/ proxy block in your nginx conf (e.g. nginx/conf.d/wp-suite.conf):

location /api/ {
    proxy_pass http://api:8000;          # ← service name, not localhost
    proxy_http_version 1.1;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header X-Forwarded-Proto $scheme;
    client_max_body_size 5m;
}

4. docker-compose.yml

Replace your existing docker-compose.yml with:

services:

  webserver:
    image: nginx:alpine
    container_name: nginx_webserver
    volumes:
      - ./html:/usr/share/nginx/html:ro
      - ./nginx/conf.d:/etc/nginx/conf.d:ro
      - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro
      - ./logs:/var/log/nginx
    restart: unless-stopped
    depends_on:
      api:
        condition: service_started
    networks:
      - proxy       # external — reachable by your reverse proxy / traefik
      - internal    # needs a path to the api container

  api:
    build: .
    container_name: wp_api
    env_file: .env                        # loads DATABASE_URL
    restart: unless-stopped
    depends_on:
      db:
        condition: service_healthy        # waits for postgres to accept connections
    networks:
      - internal

  db:
    image: postgres:16-alpine
    container_name: wp_db
    env_file: .env                        # loads POSTGRES_DB / USER / PASSWORD
    volumes:
      - pgdata:/var/lib/postgresql/data
    restart: unless-stopped
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5
    networks:
      - internal

volumes:
  pgdata:

networks:
  proxy:
    name: proxy
    external: true
  internal:
    internal: true    # no outbound internet access from api/db

5. First-time startup

# Build the api image and start all containers
docker compose up -d --build

# Confirm all three containers are running
docker compose ps

# Tail logs (Ctrl-C to stop following)
docker compose logs -f api

Tables are created automatically on first API startup — no manual CREATE TABLE needed.

Authentication notes

Postgres → API authentication is handled entirely through DATABASE_URL in .env. The db container uses POSTGRES_USER / POSTGRES_PASSWORD to initialise the database on first run; the api container uses the matching credentials in DATABASE_URL to connect. Neither credential ever appears in the compose file itself.

Network isolation: the db container is on the internal network only — it has no port exposed to the host and is unreachable from outside the compose stack. Only the api container can open a connection to it.

Changing the password: update both POSTGRES_PASSWORD and the password in DATABASE_URL in .env, then:

# Stop api first (db must keep running to accept the ALTER USER command)
docker compose stop api
docker compose exec db psql -U wpsuite -c "ALTER USER wpsuite PASSWORD 'new-password';"
docker compose start api

Day-to-day operations

# Rebuild api after a code change
docker compose up -d --build api

# View postgres data directly
docker compose exec db psql -U wpsuite -d wpsuite

# Take a database backup
docker compose exec db pg_dump -U wpsuite wpsuite > backup-$(date +%F).sql

# Restore from backup
docker compose exec -T db psql -U wpsuite -d wpsuite < backup-2025-01-01.sql

# Stop everything (data volume is preserved)
docker compose down

# Stop everything AND delete all data
docker compose down -v

Quick test

/api/health is open; data routes now require a session, so log in first and reuse the cookie jar:

curl http://127.0.0.1:8000/api/health          # {"ok":true} — no auth needed

# Sign in, saving the session cookie to a jar
curl -c jar.txt -X POST http://127.0.0.1:8000/api/auth/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"alice","password":"<password>"}'

# Reuse the cookie on protected routes
curl -b jar.txt http://127.0.0.1:8000/api/comments

Without the cookie, protected routes return 401 {"detail":"Not authenticated"}.

Or via the nginx proxy (replace with your hostname):

curl https://wp-suite.company.local/api/health