# Mining Cadastre: Ministry of Mining, South Sudan

Phase 1 of the replacement for FlexiCadastre, built from the
*Requirements and Architecture* design doc and the *Newcomer Briefing*. It is one
Django + PostgreSQL/PostGIS application that the Ministry owns, with an OpenLayers staff map.
Licence types, workflow steps, deadlines, fees, document checklists and certificate
templates are all **configuration**, so they can be edited without changing code.

## Quick start (local, Docker)

Requirements: Docker with Compose. The ArcGIS export (`cadastre-export/`) must sit next to this folder,
or you can point `IMPORT_DATA_DIR` in `.env` at it.

```bash
cp .env.example .env            # change the secrets before any real use
docker compose up -d --build    # db + web + worker; migrations and seed config run automatically
docker compose exec web python manage.py import_export --report /tmp/exceptions.csv   # load + clean the ArcGIS data (~1 min)
```

Open http://localhost:8000. With `CREATE_DEMO_USERS=1`, one account is created per role.
All of them use the password set in `DEMO_PASSWORD` in your `.env`:

| User | Role | Can do |
|---|---|---|
| `registrar` | Registrar | Create applications, record payments, upload documents, validate the area and register (sets the priority) |
| `officer` | Title officer | Assessment, DG/Committee/Minister decisions, notices, granting |
| `head` | Head of Cadastre | Everything, plus configuration (`/admin/`), the audit log and import review |
| `finance` | Finance | Confirm payments against bank or cash records |
| `viewer` | Read-only | Register, map, reports, exports |
| `admin` | Superuser | Users and system administration |

Run the tests: `docker compose run --rm web python manage.py test` (37 tests).

## What phase 1 contains

Requirement IDs refer to the design doc.

| Area | What's built |
|---|---|
| **Register** (R-01..R-07) | Six licence types (rules as config), parties (individuals and companies), registered owners with share %, commodities list, a full status model with timestamped history, and a searchable register with CSV export |
| **Holder rules** (R-03) | Exploration is for companies only. Small-scale is for individuals or companies incorporated in South Sudan. Both rules are enforced in the application wizard |
| **Applications** (A-01..A-04, A-07..A-10) | New-application wizard. The area can be uploaded (GeoJSON, KML, GeoPackage, zipped shapefile, CSV coordinates in WGS 84 or UTM 34N–37N) or drawn on the map. It is snapped to the 15″ grid. The processing invoice is raised and the workflow starts automatically |
| **Grid engine** | Cell ID = `row × 86400 + col`, with `col = floor((lon+180)×240)` and `row = floor((lat+90)×240)`. Cells are never stored, only computed. Includes contiguity, single-part, size limits, exact km² and grid lines for the map |
| **Overlap and priority** (A-04, A-09) | Blocks overlap with live titles and with applications registered earlier. Allows the overlap types each licence type permits (e.g. small-scale over reconnaissance). Automatic trim with the applicant's consent (Reg 16(18)). Lists the "titles over the same ground" in priority order. Warns on protected areas, the 250 m national-border buffer and adjoining exploration licences of the same holder (Reg 16(6)) |
| **Priority integrity** | Registration sets `registered_at` from the server clock and writes the date, hour and minute into the code (`EL 07-2026/12/01-14:35`). After that it cannot be changed, enforced both in Python and by a database trigger |
| **Workflows** (W-01..W-07) | Table-driven engine. **Exploration** and **small-scale** application workflows are seeded from the 13 April 2015 diagrams: fee → documents → shape validation → register → DG evaluation, with parallel consultation (EL) → Mining Committee (with the 60-day extension) → Minister → notice of granting (re-sent once) → registration fee → grant. Deadlines are computed from registration: DG at 42 days, SSML SMRAC at 63, Minister at 70 or 77 (emergent / non-emergent), SSML registration fee at 84. Guards stop a step closing while its fee is unpaid, the checklist is incomplete or the area is invalid. Decisions record the body, date, reference and signed scan. Work queues show overdue, due today, this week, waiting on a decision and waiting on the applicant |
| **Deadlines job** | A worker container runs the daily job: flags overdue steps, applies deemed outcomes (e.g. rejection when the response window lapses) and expires licences past their expiry date. Migrated records flagged for review are skipped |
| **Fees** (F-01..F-03) | The full Reg 153 schedule from the 2015 workflows (33 rules, SSP), with flat, per-unit and per-unit × licence-year bases and effective dates. Invoices are raised by workflow steps. Payments can be cash, bank or mobile money, with proof. Receipts R-1, R-2 and N-10 are numbered without gaps and can't be changed or deleted. A second person confirms payments |
| **Documents** (D-01, D-02, D-04) | Per-licence-type checklists (A-2 / A-3 attachments, with company-only and individual-only items). Uploads store a SHA-256 checksum and keep versions. Templates (editable in Configuration) produce the registered copy, notice of granting, rejection notice, L-2 and L-3 certificates, and the R-1/R-2/N-10 receipts |
| **Map** (M-01) | OpenLayers: live licences by type, applications, expired/revoked titles, protected areas, states, counties, and the cadastral grid when zoomed in. Click a parcel to open its file. Each title page has a map that highlights overlapping cells in red |
| **Security and audit** | Named capabilities grouped into roles, with separation of duties (whoever records a payment can't grant, and whoever records a payment can't confirm it). Login is required everywhere, and sessions end after 30 minutes idle. An append-only, hash-chained audit log records every create, change, status move, login, export and configuration edit with old and new values. A database trigger blocks UPDATE and DELETE on it, and `manage.py verify_audit` (or the "Verify chain" button) checks the chain |
| **Reports** | Licences by type × status and by state, applications against statutory deadlines, fees invoiced and collected by month, licences expiring in the next 180 days, and grants in the last 12 months |
| **Public feed** | `/public/licences.geojson` returns live licences and pending applications with public fields only, ready for the phase-2 ArcGIS Online sync. Individuals' names are withheld |

## Data import and cleaning

`manage.py import_export` loads the states, counties and protected areas, then the 436 licence records.
Every decision it makes is written to an **exception report**: the *Data import* page, with a CSV download.
The run over the 1 Dec 2026 export produced:

* **423 titles** (147 mining + 289 exploration records, minus 1 exact duplicate and 12 extra polygons that were merged into multi-part titles), and **229 holders**, deduplicated by normalised name.
* Live register: 129 EL, 117 SSML and 3 LSML active, plus suspended, pending-revocation and approved titles. The rest are revoked, expired or rejected.
* Automatic fixes (*info*): Type variants → EL/SSML/LSML; status misspellings (`Revocked 2026`, `Revoked 26`, …) → Revoked; `Gold` → AU; `Area_km2` recomputed from the grid for 114 records; priority timestamps parsed from the licence codes.
* *Warnings*: 163 active licences have no grant date; 12 multi-part merges; 11 pairs of live titles overlap (mostly the newer `EXPL-2026-…` / `SSML-2026-…` records); 8 revocations still waiting for final documents; 2 SSMLs cover 10 units instead of 5.
* *Needs decision* (6): the code with DMS coordinates typed into it (replaced by its application number), the `ß` code, statuses `Inactive`, `To Delete` and blank (set to *Needs review*), and code `EXPL-2026-00017`, which two holder spellings share ("ASMG MONING" / "ASMG MINING").

Records flagged *needs review* are kept out of automatic expiry until a person resolves them.
The load is re-runnable with `--replace` while no migrated title has workflow, invoices or documents yet.
The original FlexiCadastre attributes are kept on every title (shown under "Source record").

## Configuration

`/admin/` (Head of Cadastre) is where you edit licence types, fee rules (add a new row with a new
effective date rather than changing old amounts), workflows and steps ("Save as new" creates a new version),
document checklists, templates, commodities, restricted areas (block or warn) and public holidays.
A running application keeps the workflow version it started under.

Step outcomes are JSON: `{code, label, next[], status, effects[], requires[], end, note_required, due_days}`.
Effects come from a fixed library (`raise_invoice:<FEE>`, `register`, `grant`, `issue:<TEMPLATE>`, `cancel_open_steps`, …).
Guards: `invoice_paid:<FEE>`, `checklist_complete`, `area_valid`, `area_invalid`, `emergent_set`.
Configuration can choose among these but cannot run arbitrary code.

## Assumptions to confirm with the Ministry

* **Fees** are the 2015 SSP amounts. The SSML rent of SSP 532 per unit still needs checking against the Third Schedule.
* **Response window after rejection** is set to 30 days (the briefing gives 21–90 depending on type).
* The **Minister deadline** for exploration is set to 84 days from registration (no explicit regulation found).
* **Holidays** for 2026–27 are seeded with fixed-date holidays only. Eid dates need adding.
* Reconnaissance and large-scale workflows aren't configured: there are no 2015 diagrams for them.

## Project layout

```
cadastre/   settings, URLs, base templates, CSS, map JS, vendored OpenLayers + htmx
core/       roles/capabilities, audit log, work queue, seed config, worker
registry/   licence types, parties, titles, grid engine, area validation, importer, map API, reports
workflow/   workflow definitions, engine, deadlines, decisions
finance/    fee rules, invoices, payments, receipts
documents/  document types, checklists, uploads, templates
```

Building where PyPI is unreachable: put wheels in `wheels/` and run
`docker compose build --build-arg PIP_ARGS="--no-index --find-links /app/wheels"`.

## Next steps (later phases in the design)

1. **Before go-live**: two-factor login for staff, an HTTPS reverse proxy, object storage for documents, managed Postgres with point-in-time recovery, the nightly encrypted copy to Juba, Terraform, monitoring, and a penetration test.
2. **Corrections workflow**: superseding a priority timestamp or a registered area needs Head of Cadastre approval. The database trigger already blocks direct edits.
3. **Phase 2**: retention, large-scale, reconnaissance and the generic processes (suspension, surrender, revocation, transfer, extension, relinquishment, consolidation, conversion); obligations (rent, reports, minimum expenditure, compliance notices); the **ArcGIS Online sync** to the existing Experience Builder viewer; public search and certificate QR verification; holder statements; PDF/A output; Martin vector tiles if the data grows.
4. **Phase 3**: applicant accounts, online lodging, payment gateway, SMS and email notices.
5. Data: staff review of the exception report, filling the missing grant dates from paper files, and resolving the overlapping live titles.
