Commit graph

32 commits

Author SHA1 Message Date
ef6f217e45 Gate the administration area by role, not by is_staff
RBACMiddleware only guarded non-staff users, so any staff account stepped
past the role routing for /admin/ — an ops or buyer account with the flag
set could reach the admin index, which embeds the model registry, and a
later permission grant would have been inherited. Restrict /admin/ to the
admin role (superuser excepted) and hide the ops Admin link from non-admins.

Also close the second finding: the seed set is_staff only on creation, so
a buyer whose flag had drifted stayed staff on every re-run. Derive it from
the role on the update path too, and align existing rows with a one-off
migration so the flag never disagrees with the role.
2026-09-25 16:47:50 +00:00
df2a90bc71 Add the product specification screen to the ops portal
Operations can now create and edit a specification and its parameters
together, over the existing model, mirroring the admin's inline.

The approval half is deliberately held: the form does not expose status,
is_current, approved_by or approved_at, so a portal-created specification
is a draft and cannot be approved here. The edit screen warns when the
record is not a draft, because its parameters are the limits QC results
are judged against. Nothing is removed from the admin.

The parameter formset refuses an empty specification (with no parameters
every QC result would pass), a numeric parameter with no limits, and a
visual parameter with no allowed values.
2026-09-25 16:35:45 +00:00
f6aedc0002 Add the compliance registers to the ops portal
Facility, origin zone and collector group could only be registered in the
Django admin, which left the portal unable to onboard a new supply site,
zone or group. Add list/create/edit screens for all three, and create/edit
for mitigation actions, EUDR evidence and external-submission references
on a due-diligence case.

The origin-zone form keeps the map a view of the stored geometry, not a
check of it: the map wording is unchanged and geometry is only required to
be valid JSON. Verification is stamped from the acting user when the status
moves to verified/rejected, and cleared when it returns to unverified.

Nothing is removed from the admin; it stays as the superuser fallback.
Adds an nginx /tiles/ route on the ops host so the map imagery loads there
too (the tile view is root-mounted but ops remaps / to /ops/).
2026-09-25 16:26:59 +00:00
243d4eefcd Run with DEBUG off and add HSTS and CSP headers
DEBUG was on in production, so an error rendered a full traceback and the
DEBUG-only media route served /media/ixg-documents/... publicly, bypassing
the document permission checks. Set DJANGO_DEBUG=False in the env files
(untracked) and add friendly 500/404/403 templates.

With DEBUG off Django no longer serves /static/, so nginx does: the static
root moves to /var/www/ixg-platform-static (mounted into the app container)
because /root is not traversable by www-data.

HSTS (max-age 1y, includeSubDomains) is added to every HTTPS host, and a
pragmatic CSP to the app/ops/portal locations. 'unsafe-inline' is required
by the inline scripts/styles; self-hosting the CDN assets and nonces is a
follow-up.
2026-09-25 12:37:40 +00:00
8c8e7908fd Make logout a POST and end the Keycloak session
Clicking Logout returned 405: the base templates linked to the logout view
with a GET, which mozilla-django-oidc refuses. Both portals now post a CSRF
form instead.

A POST alone was not enough. OIDC_OP_LOGOUT_URL_METHOD is now set, so logout
builds the realm's RP-initiated end-session URL with the stored id token and
a registered post-logout redirect. Without it Keycloak kept its session and
silently signed the user back in, so the sign-in screen could never be
reached again on that browser.

Registered the post-logout redirect URIs on the ixg-platform client and
trimmed its redirect URIs to the callback on the hosts that actually serve
the platform.
2026-09-21 12:53:14 +00:00
19d67555da Add public buyer self-registration
A UK buyer can now create their own account at /portal/signup/. The screen
creates a Keycloak user through a least-privilege service account
(ixg-provisioning: manage-users, view-users) and the matching Django row as
a buyer, then sends them through the normal sign-in flow to the portal.

Staff status is derived from the role in the OIDC backend rather than
asserted, so a self-registered buyer is not staff and does not become staff
on a later sign-in. The platform root and the RBAC middleware now route
each role to its own portal, which also fixes a redirect loop that the
staff fix exposed for non-staff buyers.
2026-09-21 11:30:29 +00:00
5b6c4c48e4 Test the shipment screen, its API rules and the date inputs
Cover access on GET and POST for a buyer, each required field when blank, an ETD
after the ETA, a batch that already has a shipment (queried, not blocked), a
status change, and an edit updating in place. Add the shipment routes to both
OPS_ROUTES sweeps so the detail and edit screens render clean markup, and assert
the native date inputs carry ISO values — the defect that left the intake and
batch edit dates blank.
2026-09-17 16:03:14 +00:00
dae025f600 Enforce the shipment form's rules in the API
The ops form refuses a shipment with no vessel, container, ETD or ETA, and one
whose departure is after its arrival. The serializer now requires the same
fields and refuses the same contradiction, so the API cannot accept a record the
portal would reject. Partial updates stay partial: a status change alone does
not require the other fields, and the date check falls back to the stored values.
2026-09-17 16:03:11 +00:00
5e201b2035 Add a shipment entry screen to the ops portal
Walkthrough step 11 said shipment records came through the API or the admin
area, because the portal was read-only. The list and detail pages now carry New
shipment and Edit shipment controls, with /ops/shipments/new/ and
/ops/shipments/<uuid>/edit/ mirroring the intake and batch screens.

The form requires the fields the buyer's page reads — status, vessel, container,
ETD and ETA — and refuses a departure after the arrival. The bill of lading and
the forwarder stay optional, and the ports keep their model defaults. A batch
that already has a shipment is flagged in the dropdown and warned about after
saving rather than blocked, because a split consignment is legitimate. The batch
dropdown labels each batch with its own journey status, and a card explains that
the two statuses are independent.

Also fixes a pre-existing defect the new screen would have shared: the native
date inputs were rendered in the en-gb d/m/Y format, which the browser discards,
so the intake and batch edit forms silently opened with empty dates. They now
carry the ISO format a native date input requires.
2026-09-17 16:03:09 +00:00
b376c30300 Pin the API permission boundary for every viewset
A buyer account is a legitimate authenticated user, so IsAuthenticated alone
lets it through. Sweep every ModelViewSet endpoint and assert a buyer gets 403
on write, and on read where the API is ops-only; assert ops is not forbidden;
and keep an explicit allowlist for the chat, user, notification and subscription
reads a buyer may still make. Also assert the escalation is closed: a buyer
cannot PATCH their own role to admin, sees only themselves in the user API, and
cannot reach another user's notification or subscription.
2026-09-17 15:53:47 +00:00
8ad83a7a65 Restrict every data API to ops and admin
Batch writes were closed in 88eede5, but every other app's viewset still used
IsAuthenticated, which in this platform means any buyer. A buyer could rewrite a
document record, create a QC result (which moves the batch status and raises a
CAPA), and reach the write endpoints for CAPAs, certificates, ESG reports and
shipments.

- Use the one IsOpsOrAdmin from apps.compliance.permissions; drop the duplicate
  copy in apps/qc/views.py.
- Apply it to the whole viewset on shipments, qc, capa, esg, documents,
  certificates-of-analysis and regulatory-certs. The buyer portal is
  server-rendered through the ORM, so it needs none of these APIs.
- Keep the buyer chat working: AI interactions stay authenticated and scoped,
  and agent reads stay open while agent writes become ops/admin.
- Close a buyer-to-admin escalation in the users API: writes are admin-only and
  role/is_active are read-only, so a buyer can no longer PATCH their own row to
  role=admin and then pass every IsOpsOrAdmin check.
2026-09-17 15:53:44 +00:00
fa9295d15a Pin the batch form wording to what the form actually does 2026-09-17 14:50:07 +00:00
be2da9c6e4 Show the intake lineage and edit controls on the batch detail page 2026-09-17 14:48:23 +00:00
b4d6d4bb20 Harden the markup hygiene and seed idempotency tests
Replace the Bootstrap-prefix allowlist with a default-to-leak rule for bare
hyphenated tokens, parse tags quote-aware so a '>' inside an earlier attribute
cannot truncate the tag, render the batch edit and lineage screens in the sweep
with a seeded batch, and cover stale evidence in the seed re-run test.
2026-09-17 14:48:16 +00:00
8d209f3cbf Move conditional status classes inside the class attribute
A class list written outside the quotes left the badge colour as a bare
attribute, so the status rendered white-on-white. Also repair a stray quote on
the CoA release message, where class=text-muted mb-0 left the class unapplied.
2026-09-17 14:48:14 +00:00
30d07dba41 Drop stale evidence when the walkthrough seed is re-run
Evidence rows are keyed on the filename, so reassigning the in-flight batch's
intakes left the old harvest_document row behind. Delete anything the case no
longer references, mirroring the lineage cleanup in _batch.
2026-09-17 14:48:11 +00:00
88eede5d7a Restrict the processing-batch API to ops/admin
Any authenticated user could PATCH a batch, and the write serializer accepted
status, so a buyer could move a qc_fail batch to delivered. The buyer portal
reads batches through the ORM, not this API, so the whole viewset is closed to
ops/admin and the write serializer refuses a hand-set QC status and any
transition out of qc_fail.
2026-09-17 14:48:09 +00:00
4b4477d359 Add batch create, edit and lineage screens to the ops portal
The batch form refuses to type over a QC status or move a failed batch, and
the lineage formset refuses an allocation the intake cannot support. The
origin-facility help text and the QC status card now describe what the form
actually does, and buyer POSTs to the create and edit screens are refused.
2026-09-17 14:48:06 +00:00
6a3a902045 Enforce the intake allocation limit in the lineage API
The ops lineage screen refuses to allocate more of an intake than was
received, counting every batch, but POST /api/intake-batch-lineage/ accepted
9999 kg against a 100 kg intake. Move the rule into a shared helper so the
screen and the serializer refuse the same allocations.
2026-09-17 14:48:04 +00:00
e2a6784505 Assert rendered pages carry no unquoted multi-token attributes
The ops templates shipped with 346 of them: an unquoted attribute value ends at
the first whitespace, so the styles were never applied and status badges rendered
invisible. Assert it on the rendered HTML rather than the template source, because
a template may hold {{ }} inside an unquoted attribute that renders harmlessly —
the source is ambiguous, the response is not.
2026-09-17 14:00:10 +00:00
db05d6052a Quote the ops templates' HTML attributes so the classes apply
An unquoted attribute value ends at the first whitespace, so
``class=badge bg-danger`` is read by every browser as ``class="badge"`` plus two
meaningless attributes. Bootstrap was loading perfectly well; the markup simply
never asked for the styles. Across the ops portal that meant buttons rendered as
plain links, status badges were invisible (white text on a white background: a
failed result showed as nothing at all), the active sidebar item never
highlighted, and the flex utility classes did nothing. The buyer portal templates
quote their attributes, which is why only the ops portal looked unstyled.

346 attributes across 20 templates, rewritten mechanically with a conservative
transform that handles the three shapes in use — a Django tag as the value, a
multi-token class list, and a trailing simple conditional (the active-nav
highlight) — and leaves anything it does not recognise exactly as it was.
2026-09-17 13:57:53 +00:00
7d7248a23b Add an intake screen to the ops portal
Harvest intakes could only be recorded in the administration area or through the
API, so the first record the business actually creates was entered outside the
portal it works in. Add list, create and correct screens under Harvest Intakes.

The form is deliberately stricter than the model. HarvestIntake allows almost
everything to be blank because records also arrive by API, and the platform
copes by flagging the gaps later — the EUDR completeness check has an intake
data test whose whole job is to catch a missing date or weight. The form
therefore requires every field those checks read: reference, collector group,
origin zone, date, weight and grade.

Three things it does beyond capturing the fields: it suggests the next intake
reference for the year (editable, since it may have to match a weighbridge
ticket), fills the origin zone in from the collector group while leaving it
editable, and refuses a duplicate reference — including one differing only in
case. It queries, rather than blocks, when the chosen zone is not the one the
group is registered to, and it marks unverified zones in the dropdown, because
geolocation passes only for a verified zone.

Correcting amends the record in place: the reference a buyer or auditor quotes
does not change.
2026-09-17 13:45:39 +00:00
d5bc06802e Serve map tiles from our own origin
The origin-zone map drew its background from a public tile server, which made it
the only part of the admin page that depended on a third-party domain — and the
part that breaks. Where a viewer's network, proxy or browser filter refuses
tile.openstreetmap.org (the refusal arrives as a 403) the map never draws, while
the page, the Leaflet bundle and the polygon data are all same-origin and fine.

Fetch the tiles server-side and serve them from /tiles/{z}/{x}/{y}.png: cached
on disk, so a page opened repeatedly does not re-fetch, and gated on being
signed in, so the route is not an open tile relay. The upstream stays
configurable via LEAFLET_TILE_URL, and LEAFLET_TILE_PROXY_ENABLED=False puts the
browser back on direct fetches.

When a tile still cannot be fetched, answer an empty tile rather than an error
page and say so under the map, instead of leaving a viewer with a blank grid and
no explanation.
2026-09-17 13:00:59 +00:00
cdefbd010c Serve document and certificate files through a permission-checked download
Media was unreachable from either portal, which is why the certificate button on
the buyer compliance page returned page-not-found and no document row had
anything to click. The cause was structural: the portal and ops hosts proxy
location / to the app with a path prefix, so a stored /media/... URL arrives as
/portal/media/... and matches no route.

Add a download view per portal behind the same role gate as the page that links
to it — buyer-visible documents and published certificates for buyers, anything
the ops list shows for operations — resolving the stored path safely under
MEDIA_ROOT so a traversal or an absolute path is refused. Point the seven
templates that list files at the new routes.

Also add a portal-wide render sweep: nothing in the suite was fetching the ops
or portal pages, so a view could lose its template_name and 500 in front of a
user with every test still green.
2026-09-17 12:44:52 +00:00
5d0b5fe757 Origin zones: draw the stored polygon on a map in the admin (Leaflet 1.9.4)
Closes the "no map view" gap for origin zones: the polygon was stored as
coordinates and shown as raw JSON, so the shape could not be checked by eye.

- vendor Leaflet 1.9.4 into apps/core/static/vendor/leaflet. Self-hosted rather
  than pulled from a CDN, because this renders supplier-location data.
  PROVENANCE.md records the version, source, licence (BSD-2-Clause), checksums
  and upgrade steps; the checksums match the SRI hashes Leaflet publishes
- OriginZoneAdmin gains an "Area on a map" read-only row and its Media assets;
  apps/compliance/static/js/ixg_zone_map.js draws the polygon from the stored
  geometry, passed through a data attribute rather than injected into a script
- the tile source is a setting (LEAFLET_TILE_URL), so moving to self-hosted
  tiles is a config change, not a code change

Deliberately display only: it draws what is stored. It does not validate the
geometry, and it does not verify the zone - both remain open work, and the page
says so where the map appears.

Tests cover the drawn map, a zone with no coordinates, and the add page.
2026-09-16 16:39:07 +00:00
4667637265 Add seed_walkthrough management command
Builds one coherent, fully fictional batch chain for ops training, so the same
batch reference appears on every screen a trainer walks through: origin zone and
collector groups, harvest intakes and lineage, processing batch, QC result and
four-eyes verification, certificate of analysis with its supporting documents,
EUDR due-diligence case, shipment and ESG report.

Three batches on purpose: a completed happy path, one mid-flight, and one QC
failure with a CAPA so the exception branch has something to show.

Strictly synthetic data - no real buyer, supplier, collector or producer data.
2026-09-16 16:39:07 +00:00
c568a34dc0 Ops templates: show '-' when the acting user is null
Six ops list and detail pages dereferenced a nullable user to print their name,
which renders an empty cell when the field is unset. Guard each one so the cell
reads "-" instead.

Screens: batch detail, CoA review detail, document list, EUDR detail, and the two
QC verification pages.
2026-09-16 16:39:07 +00:00
ee4f7b5232 Help centre: portal-scoped guide audiences, and links that resolve
Guide visibility is now scoped by PORTAL first and role second:

- the buyer portal lists shared and buyer guides, even for an admin, because it
  is the buyer portal; admin guides never surface there
- the ops portal lists shared and ops guides, plus admin guides for an
  admin/superuser
- the detail view names its context object, so guide pages get a real browser
  title instead of a blank one

Link rewriting, so one page can serve both the wiki and the in-app help centre:

- absolute /en/user-guides/... links become the in-app help path
- other absolute /en/... links point at the wiki itself; the app hosts serve no
  /en/ routes, so leaving them untouched was a 404 for whoever clicked
- relative links keep their existing behaviour

Tests cover the new rewriting and the portal scoping rules. Also adds
docs/USER_GUIDES_VIEWER_SPEC.md, the spec this viewer was built to.
2026-09-16 16:39:07 +00:00
8f1649aaa1 Deployment hardening: HTTPS/CSRF settings, loopback-only app port, entrypoint passthrough
- settings: trust nginx X-Forwarded-Proto, mark session and CSRF cookies secure,
  and set the CSRF trusted origins for the ixgltd.com hosts
- docker-compose: bind the app port to 127.0.0.1 only; nginx fronts it, so there
  is no reason for 0.0.0.0
- entrypoint: when the container is given a command, run that instead of always
  starting gunicorn (needed for manage.py shell and the test suite)
- gitignore: keep Celery runtime state and stray local backups out of the tree

No functional change to the application itself.
2026-09-16 16:39:07 +00:00
6508cc25ef Add User Guides Viewer (Help Centre) - role-gated wiki help pages
- New apps/guides app with GuidePage model and audience mapping by wiki path
- sync_guides management command: one-way read-only sync from wikijs DB
- Read-only wikijs_ro DB role + WIKI_DB_* env config (secrets, gitignored)
- Markdown rendering with bleach sanitisation; rewrites internal guide links
  to the portal help root and wiki image paths to WIKI_PUBLIC_BASE
- /portal/help/ (buyer) and /ops/help/ (ops) index + detail views with
  role-based audience filtering (404 on cross-role guides)
- Help nav item added to both portal base templates
- Tests: audience filtering, markdown sanitisation, link rewriting, sync command
2026-08-07 14:19:49 +00:00
08096e168f P99C: compliance automation - CoA auto-generation and EUDR due diligence
- Versioned product specification table (Unrefined Shea Butter v1.0 seed) with
  spec-based QC evaluation replacing hard-coded thresholds
- Structured QC results with test methods and four-eyes verification
  (submitter cannot self-approve)
- reportlab IXG Quality Summary PDF auto-generated on quality approval,
  SHA-256 hashed; original independent lab PDF kept authoritative
- CertificateOfAnalysis version/status/hash/approval/supersede lifecycle;
  commercial release publishes to buyers and triggers notification
- EUDR evidence workflow: Facility, OriginZone, CollectorGroup, HarvestIntake,
  IntakeBatchLineage, DueDiligenceCase, EUDREvidence, RiskAssessment,
  MitigationAction, DueDiligenceStatementReference with rule-based
  completeness check and risk assessment (no AI legal conclusions)
- Ops portal: QC Approvals, CoA Reviews, EUDR Compliance screens
- Buyer portal: /portal/compliance page
- 22 automated tests covering four-eyes, CAPA, PDF+hash, publish/notify,
  EUDR blocks and buyer isolation
2026-08-05 13:58:39 +00:00
27b7fe7a13 Initial commit: IXG Platform 2026-07-29 16:48:48 +00:00