Technical manual
About this manual
This manual explains how PHAEMA is built, installed, secured and run, so a council's IT team or a supplier can assess, host and support it. It covers the code on the main branch of phaema/phaema-app as of November 2026.
| Reader | Read first |
|---|---|
| Council IT and security teams | Architecture, Security, Compliance mapping |
| Hosting suppliers and system administrators | Installation, Deployment and operations, Troubleshooting |
| Developers and contributors | Technology stack, Code layout, Data model, Testing, Contributing |
The user manual covers how staff use the system. This manual covers the software underneath it. PHAEMA is free software under the GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later).
Architecture overview
PHAEMA is a single server-rendered Django application with a PostgreSQL/PostGIS database and an hourly scheduler, packaged as three Docker containers that each council runs on its own.

Only the reverse proxy faces the network; the web container listens on localhost. The scheduler uses the same image and database as web and also shares the media volume. The browser fetches map tiles directly from Ordnance Survey or OpenStreetMap.
How a request is handled
The browser sends an HTTPS request; the proxy ends TLS and forwards it to Gunicorn on port 8000.
Django middleware runs in order: security headers, WhiteNoise (static files are answered here), sessions, language, CSRF, authentication, messages, clickjacking, then PHAEMA's
CurrentUserMiddleware(records who is acting, for the audit trail) andRoleRequiredMiddleware(blocks users with no role).The URL is routed to an app's view, which checks the user's role and, for changes,
can_edit.The view reads or writes models through the Django ORM; every save or delete of an audited model writes an
AuditEntry.A Django template renders GOV.UK Frontend HTML, or the view returns a file (Excel, CSV, Word, GeoJSON, iCalendar) or JSON for the API.
Technology stack
PHAEMA is a Python 3.12 Django 5.2 application on PostgreSQL 17 with PostGIS, rendered on the server with GOV.UK Frontend. Every component is open source and none needs a paid licence. Version ranges come from requirements.txt and the Dockerfiles; the image installs the newest release within each range.
Server side
| Component | Version | Licence | What PHAEMA uses it for |
|---|---|---|---|
| Python | 3.12 (image python:3.12-slim-bookworm) | PSF | Language and runtime |
| Django | 5.2 LTS (>=5.2,<5.3) | BSD-3-Clause | Web framework: models, ORM, migrations, forms, templates, authentication, admin, translation |
GeoDjango (django.contrib.gis) | with Django | BSD-3-Clause | Spatial fields and queries for property boundaries and points |
| GDAL | Debian bookworm gdal-bin | MIT | Reads INSPIRE GML and other spatial formats for GeoDjango |
| Django REST framework | >=3.15,<4 | BSD-3-Clause | The open JSON API at /api/ |
| drf-spectacular | >=0.28,<1 | BSD-3-Clause | OpenAPI 3 schema at /api/schema/ and interactive docs at /api/docs/ |
| django-environ | >=0.12,<1 | MIT | Reads settings from environment variables and .env |
| psycopg 3 | >=3.2,<4 (binary) | LGPL-3.0 | PostgreSQL driver |
| Gunicorn | >=23,<24 | MIT | Production WSGI server, 3 workers, 300 s timeout |
| WhiteNoise | >=6.8,<7 | MIT | Serves compressed, cache-busted static files from the app |
| openpyxl | >=3.1,<4 | MIT | Excel import templates, imports and every Excel export |
| Pillow | >=11,<13 | MIT-CMU (HPND) | Property photo handling |
| Python-Markdown | >=3.7,<4 | BSD-3-Clause | Renders the in-app help pages |
| python-docx | >=1.1,<2 | MIT | Word export of letters and notices from the template library |
| extract-msg | >=0.48,<1 | GPL-3.0 (compatible with AGPL) | Reads Outlook .msg emails filed on cases |
Database
| Component | Version | Licence | Use |
|---|---|---|---|
| PostgreSQL | 17 (image postgres:17-bookworm) | PostgreSQL Licence | All application data |
| PostGIS | 3 (postgresql-17-postgis-3) | GPL-2.0 | Spatial types, indexes and functions |
The automated test run on GitHub uses postgis/postgis:16-3.4, so PHAEMA is tested on PostgreSQL 16 and run on 17.
Browser side
| Component | Version | Licence | Use |
|---|---|---|---|
| GOV.UK Frontend | 5.14.0, vendored | MIT, © Crown copyright | Accessible page components and layout. The GDS Transport font is removed (it is licensed only for GOV.UK) and no GOV.UK branding is used |
| OpenLayers | 10.11.0, vendored | BSD-2-Clause | Property maps and boundary drawing |
| Atkinson Hyperlegible | vendored | SIL OFL 1.1 | Typeface for the Clear style |
| PDF.js | 6.5.438, vendored | Apache-2.0, © Mozilla Foundation | Shows PDFs inside PHAEMA. Its bundled fonts and image decoders keep their own open-source licences beside them |
| PHAEMA's own scripts | static/js/phaema.js, phaema-map.js | AGPL-3.0 | Collapsible panels, map set-up and the PDF viewer page (pdf-view.mjs); no framework, no build step |
There is no Node.js build, no content delivery network and no third-party tracking. All browser files are served from the PHAEMA server. The one optional outside call is for map tiles: Ordnance Survey Maps API tiles when a council enters its OS key, otherwise OpenStreetMap tiles.
Development and testing
| Tool | Version | Use |
|---|---|---|
| pytest + pytest-django | >=8,<9, >=4.9,<5 | Automated tests |
| pyflakes | any | Lint for unused imports and undefined names |
| GitHub Actions | ubuntu-24.04 | Runs migrations check and tests on every pull request |
| Docker and Docker Compose | current | Local and single-server running |
Code layout
The repository is one Django project (phaema/) with fifteen apps under apps/, one per business area. Each app keeps its own models, views, URLs, migrations and tests.
Top-level folders
| Path | Contents |
|---|---|
phaema/ | Project settings (settings.py), root URLs and the WSGI entry point |
apps/ | The Django apps listed below |
templates/ | Shared and per-app Django templates (GOV.UK Frontend markup) |
static/ | css/ (phaema.css, themes.css, skins.css), js/, vendor/, help/ screenshots, training/ e-learning |
training/ | Source of the e-learning courses (course.py) and the script that builds them |
website/ | Source and build script for the public project website |
docs/ | Roadmap, roles, Mac set-up, single sign-on, releasing and translating guides, and procurement/: the procurement and information governance pack (service definition, security answers, accessibility statement, DPIA, record of processing, retention schedule) |
docker/db/ | The PostgreSQL 17 + PostGIS image |
Dockerfile, docker-compose.yml, phaema.sh | Container build, the three-service stack and the control script |
.github/ | The automated checks: tests with coverage, Ruff, dependency audit and image build (tests.yml), CodeQL (codeql.yml); Dependabot settings in .github/dependabot.yml |
LICENSE, LICENSING.md, CONTRIBUTING.md | Licences and contribution rules |
locale/cy/LC_MESSAGES/ | The Welsh interface text (django.po) and its compiled form (django.mo) |
CHANGELOG.md, SECURITY.md, ruff.toml | What changed in each release, the security policy, and the Ruff lint rules |
Django apps
| App | Responsibility | Main models |
|---|---|---|
core | Dashboards (estate and My work), roles, audit trail, settings, skins and themes, protected file serving | ModuleSettings, AuditEntry, StaffProfile |
properties | Property register, hierarchy, photos, titles, INSPIRE boundaries, maps, open data, demo data | Property, PropertyPhoto, PropertyPlan, Title, TitleDocument, InspireParcel |
leases | Leases and licences, parties, breaks, rent schedules, lease events, reminders, calendar feeds | Lease, Party, BreakOption, RentScheduleEntry, LeaseEvent, ReminderLog, CalendarFeed |
ledger | Rent demands, VAT, receipts, arrears, statements, finance export | DemandRun, Charge, Receipt, ExportBatch |
servicecharges | Service charge schedules, budgets, apportionment, year-end reconciliation | Schedule, ScheduleMember, ScheduleYear, BudgetLine, Expenditure, CostHeading |
cases | Case types, stages and tasks, approvals, notes, correspondence, MEES, dilapidations and conflict checks | CaseType, Case, CaseTask, CaseNote, Correspondence, CaseDocument, Approval |
maintenance | Contractors, contracts, components, planned tasks, reactive jobs, recharges | Contractor, Contract, Component, PlannedTask, Job |
compliance | Compliance types, requirements, certificates, actions, building safety (Golden Thread tiers) | Requirement, Certificate, Action, BuildingSafety |
valuations | CIPFA asset classes, valuation programme, Red Book fields, components, audit reviews | AssetClass, Valuation, ValuationComponent, Valuer, AuditReview |
projects | Developments, acquisitions, disposals, programmes and reviews: gateways, budget by financial year, risks, linked work, completion checklist | Project, ProjectType, GatewayDecision, BudgetLine, BudgetYear, Risk, CompletionStep, ProjectAccess |
documents | Letter and notice templates filled from cases, Word export | DocumentTemplate |
reports | Report builder, saved reports, Excel and CSV export of any list | Report |
imports | Spreadsheet templates and imports of properties, parties, leases, contractors and components | none |
help | In-app help pages written in Markdown | none |
space | Optional module: occupiers, floors, rooms and shared space, occupation, headcount, public use, building costs and how they are shared | Occupier, Space, Occupation, Headcount, UseMeasure, UseFigure, CostLine, BuildingCost, CostSharing, FixedShare |
Management commands
| Command | Run by | Does |
|---|---|---|
daily_tasks | The scheduler container, hourly | Stepped rents, lease events, reminder emails, and closing outside users' accounts whose access has ended |
ocr_scans | The scheduler container, every five minutes | Recognises the text in scanned PDFs waiting to be read (up to 20 a run; --limit to change). Run once with --backlog to queue every PDF already held |
send_reminders | ./phaema.sh reminders | Sends lease event reminders that are due |
import_inspire | ./phaema.sh import-inspire FILE | Loads HM Land Registry INSPIRE parcels from a zip |
load_demo_data | ./phaema.sh demo-data [--reset] | Loads the fictional Exampleton and Northfield estates |
Data model
PHAEMA holds 119 models (database tables) of business records across fifteen apps, organised around the property and the lease. Every other record hangs off one of those two, and every change is audited.

Cases can also link directly to a property, party or lease event, and jobs to a lease or case; those secondary links are left off the picture.
Key design rules
Property hierarchy. A property can be part of another (
parent), so a site, building and unit form a tree. Deleting a parent that has children is blocked (PROTECT).Identifiers.
referenceis the council's own unique asset ID;uprnis an optional Unique Property Reference Number of up to 12 digits.Spatial data. Boundaries are
MultiPolygonFieldin British National Grid (SRID 27700), with easting and northing for a point. INSPIRE parcels are stored separately (InspireParcel) and a surveyor picks parcels on the map to set a property's boundary from them. Geometry is converted to WGS 84 only for the browser.Leases cover several premises.
Lease.propertiesis many-to-many, as titles are to properties.Money is never deleted. Charges, receipts and demand runs use
PROTECT, and a credit note is a separate charge pointing at the one it credits. Invoice numbers are unique.Single settings row.
ModuleSettingsholds the council's switched-on modules and letter details.Audit by signals.
AuditEntryuses Django's content types to point at any record, storing the changed fields as JSON.
Lease management and classification fields
Added in November 2026 (leases.0005, properties.0007 and properties.0008). None of them adds a table except Portfolio.
| Record | Fields | Used by |
|---|---|---|
Lease | time_of_essence | LeaseEvent.time_of_essence (reviews only); events.essence_summary() for the dashboard; events list ?essence=1; My work |
Lease | demands_on_hold, demands_on_hold_reason | billing.billable_leases() leaves these out and billing.held_leases() lists them in the demand run preview; servicecharges/apportion.py skips them too |
Lease | billing_contact_name, billing_email, billing_phone, billing_address | Lease.billing returns each detail, falling back one by one to the counterparty's main contact; used by the rent account, statement, finance export and reports |
Lease | arrears_referral (debt collectors or legal), arrears_referred_on, arrears_referral_reference | Arrears list tag, ?referred= filter and download |
LeaseEvent | estimated_rental_value | Review and expiry events only (takes_erv); erv_uplift is the difference from the current rent |
LeaseDocument | review_date; document type insurance | review_rag(); events.documents_for_review(); DocumentListView at /leases/documents/; report dataset lease_documents |
Property | portfolio (to Portfolio, protected), strategy_section, purpose_review_date | Register filters, reports, import template, API |
events.event_summary() returns the dashboard rows. Lease expiries get a total row and then one row for each 1954 Act status (EXPIRY_SPLIT), each with the query string for the events list (?type=expiry&security=inside|out|other). events.tenancies_at_will() counts live tenancies at will; the dashboard links to the lease list with ?agreement_type=taw&live=1.
The case type insurance_certificate is seeded by apps/cases/seed.py on migrate, and cases:new accepts ?type=<code> to preselect a case type. Tests: apps/leases/test_lease_management.py and apps/properties/test_portfolios.py.
Government Property Data Standard fields and export
Added on 13 November 2026 by properties.0010_data_standard_fields, after PHAEMA's property record was compared with the Government Property Data Standard (GovS004-PDS010, version 1.0).
Two new tables.
PropertyUseis the council's list of uses (name,standard_usage,active,order), seeded fromapps/properties/uses.pyand kept under Manage data.PropertyCostholds one row for each property and financial year (year_starting,running_cost,rates,notes), unique on property and year.New fields on
Property:use_type(toPropertyUse, protected),acquired_on,built_year,condition_grade(A to D) andcondition_surveyed_on,listed_building,scheduled_monument,sssi,conservation_areaanddesignation_notes,vacant_since,vacancy_status,available_fromandavailable_until, anddisposal_method,disposal_reason,disposal_expected_onanddisposal_expected_value. Designations are blank for not known, so a gap can be told from a checked "no".Property.save()fillsbuilt_yearfrom the first year inbuiltwhen it is empty, and clears the vacancy fields when the occupation is not vacant. The migration does the first of these for existing records and matches existing use descriptions to the seeded list by name.apps/properties/standard.pybuilds the export.gather(user)returns plain rows for four sheets (properties, contracts held as tenant, vacant spaces, components), including valuations, energy certificates and components only whereapps.core.access.scopegives that user the whole module.workbook(data)writes them with openpyxl, each column headed with the standard's field name and reference;coverage(data)gives the share of current records with each field recorded;NOT_EXPORTEDlists the standard's fields left out, with the reason. Nothing is defaulted: an unrecorded fact is a blank cell.Views
properties:data-standard(the page) andproperties:data-standard-download(the workbook) are open to administrators and surveyors. Surveyors gain add, change and delete onPropertyCost.The field mapping was made from the standard's HTML page. It should be checked line by line against the published PDF before any public claim is made, and the wording to use is "mapped to", not "compliant with".
Tests:
apps/properties/test_data_standard.py.
Agreement terms, space and costing
Added on 18 November 2026 (migrations leases.0006, cases.0006, core.0017, core.0018, space.0001, space.0002).
Agreement terms.
Lease.rent_free_untiland a newLeaseOption(option type, exercisable by, exercise from and by, notice months, terms).workflow._wanted_eventsadds anoption:<id>event for each option with an exercise-by date and arent_startevent;EventTypegainsoptionandrent_start.ModuleSettings.reminder_days_option(default 180, 90, 30, 7); event types without their own setting use the "other" days. Tests:apps/leases/test_options_rent_free.py.Space module (
apps/space, last inINSTALLED_APPS, socreate_rolesruns after its permissions exist).Occupierhas a level (directorate, department, team, external), a parent andfamily().Spaceis a floor, room or shared space in a building.Occupationlinks an occupier to a space or the whole building from a date, with a share as a percentage or square metres (area(),percent(),current()).summary.pycomputes the stacking plan (stacking) and per-occupier holdings (holdings), spreading shared space by area held. Switched byModuleSettings.space_enabledand opened by the access area modulespace(the Estates area gets it incore.0018).Costing (
space_costing_enabled, access modulespacecosts, which also needsspace_enabled; the Finance area gets both inspace.0002).BuildingCostis one figure per building, financial year andCostLine(seeded; notional rent tagged, capital charges off).costs.building_costsfalls back toPropertyCostand to completed landlord maintenance jobs;share_outshares by area (vacant share left with the corporate landlord), headcount orFixedSharepercentages, rounding half up./space/costs/?format=xlsxwrites the finance workbook. Admin cost screens are hidden from people withoutspacecosts.On the property page and report.
space/overview.pyfor_property(prop, user)returns a summary for the property and each building within it that has space records, orNonewhen the person cannot use the module;latest_sharingpicks the newest financial year with costs. The property page shows it as Occupiers;apps/properties/report.pyadds the partsoccupationandoccupation_costs(also available to site visit sheets), andGatherednow carries the user so access is respected. Tests:apps/space/tests.py,test_costs.py,test_property_views.py.Demo data:
apps/space/demo.pyfills DM-S30 Exampleton Civic Centre (an invented building) and Northfield Library.
Estates strategy, step 1
Added on 18 November 2026 (migrations properties.0011 with the starting lists, cases.0007, cases.0008, core.0019). Core, not a module: nothing to switch on.
Holding purposes. The five
Property.HoldingPurposevalues stay fixed:valuations/seed.FROM_PURPOSE,properties/standard.pyand the surplus starter report depend on them.PurposeCategory(holding purpose, name, active, order) is the council's list of sub-categories;Property.purpose_categorymust belong to the property's purpose (Property.clean).Asset strategy.
AssetStrategyOptionis the council's list (follow_on: blank,developmentordisposal).AssetStrategyis one decision: property, option, decided on, reason, decided by, meeting date, minute reference, review date, source (challenge,direct,imported), case, recorded by. The newest is current (Property.own_strategy());Property.asset_strategy()returns it or the nearest ancestor's, with the property it comes from.strategy.effective_strategies()works this out for the whole register in two queries, for the overview and list filters. Saving a decision fills a blank review date fromModuleSettings.strategy_review_years(five) and, if it is the newest, setsProperty.purpose_review_date(now labelled "strategy review date").Asset Challenge.
CaseType.asset_challengeand a seeded typeasset_challengein the new group "Estate strategy" (seven tasks, approval before the decision).Case.proposed_strategy,decided_by,meeting_on,minute_reference. The case actionsave_proposalstores the proposal;decidewith Approved or Approved with conditions calls_record_challenge_outcome, which needs reasons and replaces any earlier decision from the same case; Refused or Withdrawn removes it.Suitability.
SuitabilityAssessment(grade A to D, assessed on, notes, assessed by); newest is current (Property.current_suitability()).Pages.
properties/strategy_views.py:/properties/<id>/strategy/and/properties/<id>/suitability/(surveyors who manage the property, withadd_assetstrategyoradd_suitabilityassessment)./properties/strategy/is the Estate strategy page (strategy.overview()). List filterscategory,strategy,suitability,challenge=open,purpose_review=90.projects:newtakes?type=<code>&property=<id>and links the property (disposeorimprove).core/mywork.pyadds Strategy review items. Report builder fieldspurpose_category,asset_strategy,strategy_decided,strategy_followed,suitability; property report rows; importer columns (EXTRA_FIELDS,_strategy_extras), which add a decision or grade only when it differs from the current one.Demo data:
apps/properties/demo_strategy.py. Tests:apps/properties/test_strategy.py.
Estates strategy, step 2: objectives, action plan, pipeline and health check
A new app, apps/strategy (in INSTALLED_APPS before space, URL prefix /strategy/). The estates strategy features are core: always on.
Strategy and objectives.
EstateStrategy: title, period, status (draft, adopted, replaced; adopting one replaces the others), approved by and on, minute reference, document link, principles;EstateStrategy.current().Objective: number, title, owner, target date and the six optional RICS parts (corporate aim, financial effect, risks, outcomes, measures), with the owner's reported status (green, amber, red, done), progress note and who reported it.Action: title, optional project or case, owner, target date, status, done on, notes.Suggested status.
strategy/progress.py:action_statereads a linked project's RAG, budget variance and high risks, a linked case's RAG, or a stand-alone action's dates;objective_statecombines them into a suggested status with reasons and exceptions;board()gathers the page. Confidential projects are left out for people who cannot see them.strategy/report.pywrites the board report in the document library's markup (page and Word).Pages and rules.
/strategy/(home),/strategy/objectives/<id>/(status, add or remove action plan links by PRJ or CAS reference or a title, action status),/strategy/report/(?format=docx). Administrators set the strategy and objectives in Manage data; an objective's owner or an administrator updates it.Property events pipeline.
strategy/pipeline.pybuild(user, today, portfolio)gathers lease events (Lease.key_dates, live agreements, split bydirection), disposals (expected disposal dates, disposal projects with income lines, and properties with an own asset strategy whosefollow_onis disposal but no date), acquisition projects andpurpose_review_date. Events are bucketed as overdue, one of five financial years (financial_year_of) or no date; lapsed breaks, notices and options are dropped; a property in a visible disposal project is counted once, under the project. Project visibility and budgets followprojects/rules.py. Page/strategy/pipeline/with?portfolio=,?format=xlsx(openpyxl, a sheet per section) and?format=docx.Annual health check.
HealthQuestion(heading from ten RICS headings, text, guidance, in use, order; 27 starting questions loaded by migrationstrategy.0002fromhealth.STARTING_QUESTIONS),HealthCheck(one per financial year, lead, status, finished on, summary),HealthAnswer(wording, guidance and heading copied in; answer yes, partly, no or n/a; notes; evidence; answered by and on; optional improvementAction),HealthNote(colleagues' notes on the check or an answer).strategy/health.py:start,sections(each answer with last year's, matched by question then wording, and better, worse or same),build_report. Pages/strategy/health/,/strategy/health/<id>/,/strategy/health/<id>/report/. Administrators start and reopen; the lead answers while in progress; anyone with a role adds notes.My work: actions due, objectives with no report for 90 days, and the lead's health check in progress. Demo data
apps/strategy/demo.py(a strategy with four objectives; last year's finished check and this year's part answered). Tests:strategy/tests.py,test_pipeline.py,test_health.py.
Site visits (site visit sheet level B)
Models (cases app, migrations
cases.0009and0010):SiteVisit(case, property, visited by, date, time, weather, people met, notes, to follow up, status, finished on);SiteVisitAnswer(checklist item, building for per-building items, and the item's heading, label, guidance, kind, choices andcheckscopied in with therecordedvalue at the start, so later changes do not rewrite the visit; value, note, answered at;resolutionapplied or kept, with who and when);SiteVisitPhoto(resized and stripped of location data byprocess_image; optional answer; optional copy as aPropertyPhoto). Photos are stored undercases/<id>/visits/.Logic in
cases/visit.py:start_visitfollows the level A plan (a group for the visit as a whole and one per building);visit_sections;answer_fromchecks each answer against its kind;is_difference(a "no" to an item that checks the record, or a written, chosen or measured answer that is not what was recorded);UPDATESmaps each checked detail to the property fields offered by the update form (floor areas include the standard, source and measured date: the check-measure);save_record_to_casestores the record as a WordCaseDocumenton finishing;build_record.Views in
cases/visit_views.py: start (POST,workflow.can_work: the case owner, the managing surveyor, administrators); the visit page (a form per section, details, photos withcapture="environment"in a drop zone, finish, which adds a case note; administrators reopen); the record page and Word;/cases/<id>/visits/<id>/update/<answer>/, aModelFormon the building or property with only theUPDATESfields, allowed byroles.can_edit, saved normally so the change log records the person; actionkeeprecords "left as it was".Reports dataset
site_visitsand cases fieldlast_visited; My work items for unfinished visits and differences to decide; hand-over itemsite_visits(unfinished visits). Demoapps/cases/demo_visits.py(a finished visit on the alterations case at DM-E01-U04 with differences to decide). Tests:cases/test_visits.py.
Floor areas and IPMS (IPMS level 1, #73)
Fields.
Propertykeepsgia_sqm,nia_sqm,gea_sqmwitharea_standard(now onlycomp6orother),area_source,areas_measured_on, and gainsareas_measured_byandareas_method. The IPMS set sits beside it:ipms1_sqm,ipms2_sqm,ipms3_sqm,ipms3_kind(3.1or3.2),ipms_measured_on,ipms_source(same choices asarea_source),ipms_measured_by,ipms_method,ipms_checked(yes/no),ipms_checked_howandipms_notes. Edited in the admin fieldset "Floor areas to IPMS: All Buildings".Setting.
ModuleSettings.area_basis(compdefault, oripms), labelled "Floor areas: show first" (migrationcore.0020_area_basis).Helpers on
Property.floor_area(kind)returns(value, label)forgross(GIA / IPMS 2),net(NIA / IPMS 3.x) orexternal(GEA / IPMS 1): the chosen basis first, the other if blank.area_lines()andarea_groups()give both sets for display, chosen basis first, each withcomp_basis_text()oripms_basis_text()and an estimate flag. The basis is read once per instance (_area_basis).Who uses
floor_area. Space costs (apps/space/costs.total_areaand the building's whole area: net, then gross), the data standard export (standard._floor_area, labelled e.g. "IPMS 2 (IPMS: All Buildings)"), the report builder (floor_area,floor_area_basis, plus the raw IPMS columns), the property page and property report (both groups, with a "Basis of measurement" row each). Not changed: open data, valuations, service charge apportionment (NIA),area_breakdown, dashboard and list NIA totals.Site visits.
visit.update_fields(key, target)offersUPDATES["floor_areas_ipms"]in place of the GIA/NIA/GEA set when the target'sarea_basis()isipms;initial_forfills IPMS source "survey", the visit date and checked "yes".Importer. Twelve columns appended to
COLUMNS(IPMS 1 m2 to IPMS notes)._choiceaccepts "IPMS 3.1"/"IPMS 3.2"; "Measured to" text starting "IPMS" raises a clear error.Migration
properties.0012_ipms_areas. Adds the fields, thenmove_ipms_figuresmoves GEA, GIA and NIA of any property witharea_standard = "ipms"into IPMS 1, 2 and 3, copies source and date, adds a note, and clears the Code fields. Not reversible in data (the reverse step does nothing).Demo and tests.
demo_standard._ipmsgives DM-S30 an invented IPMS survey. Tests:apps/properties/test_ipms.py(8).
Scanned documents (OCR, #75)
What it does. Any record that saves a PDF in a
FileFieldqueues it: a genericpost_savereceiver (apps/core/ocr.queue_record, connected inCoreConfig.ready) creates aTextCopyrow keyed by the stored file name, after the transaction commits.ocr_scansreads waiting rows: pdfminer counts the text on each page; a PDF with text on every page is markedhas_textand left alone; otherwise OCRmyPDF (MPL-2.0) runs Tesseract (Apache-2.0) withskip_text,output_type="pdf"andrasterizer="pypdfium", so Ghostscript is not needed. The copy is saved beside the original as<name>.text.pdf, so a confidential project's copy stays underprojects/and is served only by the project pages. The original is never changed.Model
TextCopy(migrationcore.0021):source,status(waiting, done, has_text, too_big, failed),copy,pages,pages_scanned,characters,poor,error,attempts,queued_at,finished_at. A failure is retried up to three times.pooris set when little text was read or under 60% of tokens look like words or numbers.ModuleSettings.ocr_enabled(default on) switches queuing and reading off.Serving.
core/views.protected_fileandprojects/views.project_filecallocr.serving_name(): the viewer and?raw=1get the searchable copy,?download=1the original,?download=1&searchable=1the copy.viewer.scan_state()gives the viewer's note (data-scan).Manage data, Scanned documents (
TextCopyAdmin): read only, filter by status, action "Read the selected documents again"; a warning names what is missing when Tesseract or OCRmyPDF is not installed (ocr.missing()). Without them, files stay waiting and nothing else is affected.Install. The Dockerfile installs
tesseract-ocr,tesseract-ocr-engandtesseract-ocr-cym;requirements.txtaddsocrmypdf17 (which needs Pillow 13). The scheduler loop indocker-compose.ymlrunsocr_scansevery five minutes between hourlydaily_tasksruns.ocr.tidy()removes copies whose original has gone.Demo and tests.
demo_media.scanned_pdfmakes an image-only counterpart lease on DL-0001. Tests:apps/core/test_ocr.py(13).
Rents payable and the Finance menu (#76)
The menu's Income heading is now Finance: Rents receivable (the rent ledger), Arrears, Rents payable, Service charges and Asset valuation (moved from Buildings). Finance always shows, because Rents payable needs no optional module.
apps/leases/payable.py:gather(today)takes agreements withdirection="in"and a live status, works out each payment for this month and the next eleven fromworkflow.payment_datesandrent_on(so the rent schedule applies), skips payments up torent_free_until, and totals by agreement and by month;to_xlsxwrites two sheets. Viewleases:payableat/leases/rents-payable/, open to every signed-in user like the lease list. Tests:apps/leases/test_rents_payable.py.
Cases in a project (#76)
Case.projectalready linked a case to a project. The project page now has a Cases in this project table, oldest first./cases/new/?project=<id>opens a case already in the project (cases.views._project_to_join, which needsprojects.rules.can_manage).The link action accepts
id:<pk>from a picker of open or on-hold cases on the project's properties, their parts and agreements (projects.views._case_choices), or a reference as shown on the case, including its/propertysuffix. A case already in another project is refused.Demo:
projects/demo._casesadds three DEMO-PRJ cases to the Hangar block redevelopment. Test:test_cases_in_a_project.
Commercial additions (25 November 2026)
Five pull requests, #86 to #90, merged in order. Migrations: leases.0007 to leases.0010, ledger.0004 and ledger.0005, cases.0011, properties.0013.
Indexation (
apps/leases/indexation.py).IndexSeries(CPI D7BT, CPIH L522 and RPI CHAW seeded byleases.0008) andIndexFigure(one value a month).Leasegainsindex_series,index_base_month,index_lag_months,index_cap_pct,index_collar_pct,index_compoundedandindex_upward_only;cpihjoinsReviewBasis.calculate(lease, review_date)returns aCalculation(figures, change, cap and collar rents, new rent, orproblem); the review event view fills the outcome form from it, andworkflow.complete_review(..., index_month=)moves the base month and marks the schedule entryindex.update_all()runs indaily_tasksand fetches the ONS time-series CSV when a figure is due (PHAEMA_FETCH_INDICES, on by default; off in tests)./leases/index-figures/shows the figures; administrators upload CSV or fetch.Dealings (
apps/leases/dealings.py).Dealing(kind, status, from and to party, guarantor,aga, premises, consent and completion dates, underlease term and rent, links to the underleaseLease, consentCaseand licenceLeaseDocument).Leasegainsassignment_terms,underletting_terms,dealings_with_part,aga_on_assignmentandheadlease(self).cases.workflow.open_caseand the case decision calldealings.from_case.complete()swaps the tenant and guarantor on an assignment;tenants()andliable_former_tenants()give the history;Party.arrangements()lists former tenants.Rent ledger (
apps/ledger/interest.py,apps/ledger/creditcontrol.py).Charge.Kind.INTEREST;BaseRate;ChaseStage(seeded byledger.0005: 7, 21, 35 and 60 days, with letter template codes),ChaseAction,PaymentPlanandInstalment.Leasegainsinterest_basis,interest_margin_pctandinterest_grace_days. Interest replays the account day by day with the same allocation asbilling.account()and starts after the last interest charge'speriod_end.due_actions()gives the next stage per debt episode (from the oldest unpaid charge);auto_open_cases()runs indaily_taskswhen the ledger is on.Rent deposit.
DepositEntry(in, out, interest) on the lease,deposit_account(lease)for the running balance;Lease.deposit_deed_date.Marketing (
apps/cases/marketing.py). Themarketingcase type andAgentInstruction(agent, basis, dates, fee, asking rent or price, terms, board, status). New library documentsagent-instructionandmarketing-particulars; new merge fields for property areas, use, availability and the instruction.ITZA (
apps/properties/itza.py).Propertygainsitza_sqm,itza_zone_depth_m,itza_workings(JSON),itza_measured_onanditza_notes.calculate(spec)zones a rectangle or takes measured zone areas, halves back (1, 1/2, 1/4, 1/8) and adds other areas at A/n.Property.zone_a_rent()divides the rent of the one current let agreement covering only that unit by the ITZA. The calculator is at/properties/<pk>/itza/.IFRS 16 data pack (#92,
apps/leases/ifrs16.py).Leasegainsifrs16_treatment(blank = right-of-use asset and lease liability;short_term,low_value,not_lease),ifrs16_lease_endandifrs16_notes(migrationleases.0011_ifrs16);clean()refuses a lease end before the term start.gather(year)takes agreements held by the council (directionin, not proposed) in force during the financial year (1 April to 31 March). The lease end isifrs16_lease_end, elseactual_end, elseterm_end.payments()runsworkflow.payment_dateson a copy of the lease with its end moved to that date, skips any rent-free period and prices each date withrent_on, undiscounted and in advance, without apportioning part periods. Problems flagged: no end date, nominal rent (£100 a year or less, or peppercorn), index-linked rent.changes()lists new and ended agreements, rent schedule entries other than the initial one, andAuditEntryupdates to the term and IFRS 16 fields.to_xlsx()writes the sheets Leases (28 columns, the last two yellow for finance), Payments, Changes in the year and Notes. Viewleases:ifrs16at/leases/rents-payable/ifrs16.xlsx?year=2026,can_do_financeonly (403 otherwise), years clamped from 2020 to next year. Testsapps/leases/test_ifrs16.py(7).
The full field list for every model is in each app's models.py, and the Django admin at /admin/ shows them all.
Front end
Every page is HTML built on the server by Django templates using GOV.UK Frontend components. Every task works without JavaScript; scripts only add conveniences on top.
Templates and styles
templates/base.htmlsets the header, menus, skip link, language and thedata-skin, theme and text-size attributes on<html>.Each app has its own template folder; shared pieces live in
templates/core/(form fields, errors, hints, pagination, sortable table headings, download buttons, place filters).static/css/phaema.cssholds PHAEMA's own layout;themes.cssthe colour themes;skins.cssthe skins.
Personal display settings
Each setting is a link that stores a cookie, so it works without JavaScript and follows the user on that browser.
| Setting | URL | Cookie | Options |
|---|---|---|---|
| Text size | /text-size/<size>/ | phaema_text_size | Smaller, Standard, Large, Largest |
| Colour theme | /theme/<theme>/ | phaema_theme | Standard, Dark, High contrast, Match my device |
| Style (skin) | /style/<skin>/ | phaema_skin | Classic, Clear (Atkinson Hyperlegible), Compact |
| Dashboard | /?view=mine or estate | phaema_dashboard | My work, Estate |
JavaScript
static/js/phaema.js: photo gallery, header menus (one open at a time, Escape closes), and collapsible panels. A panel issection.phaema-panel[data-panel]; the script adds a show/hide button to its heading and remembers closed panels inlocalStorageunderphaema_closed_panels.static/js/phaema-map.js: sets up OpenLayers maps, shows boundaries and lets surveyors draw them. Boundaries are stored in British National Grid (EPSG:27700) and sent to the browser as GeoJSON in WGS 84 (EPSG:4326); the map itself displays in Web Mercator.No framework, bundler or Node.js build is used; files are served as written, with cache-busting names from WhiteNoise.
Languages (from 26 November 2026, #100). Interface text is in English in the code, marked with Django's gettext and {% translate %}; Welsh is in locale/cy/LC_MESSAGES/django.po, compiled to django.mo and committed, so the image needs no gettext. LANGUAGES is English and Cymraeg. apps/core/language.py (LanguageMiddleware) replaces Django's LocaleMiddleware: the page is in Welsh only when ModuleSettings.welsh_enabled is on (migration core.0024) and the person has chosen Cymraeg, held in the phaema_language cookie set by /language/<code>/; the browser's Accept-Language header is ignored, because the Welsh is a draft awaiting review. Responses carry Content-Language and Vary: Cookie, and <html lang> follows. Words the page scripts show (Hide, Show, Photo n of m and so on) are listed in SCRIPT_TEXT in apps/core/context_processors.py, translated on the server and written into each page as a JSON data block (#phaema-text, via json_script), which phaema.js, phaema-map.js and pdf-view.mjs read; data blocks never run, so the Content-Security-Policy allows them. Records, council-kept lists, the manual, letter templates and emails are not translated. How to review the Welsh and refresh the file after changing English text: docs/translating.md. Tests: apps/core/test_language.py.
Accessibility
PHAEMA targets WCAG 2.2 level AA. GOV.UK Frontend supplies tested components. On top of that:
every colour theme and skin was designed to keep text contrast at AA, with a High contrast theme for those who need more;
collapsible panels use real buttons with
aria-expanded, and closed content is hidden from screen readers as well as from view;maps always have a text alternative (reference, address and grid reference) and nothing depends on the map;
motion is switched off when the device asks for reduced motion;
every page works with a keyboard alone; pages are checked with axe-core during development, with no violations on the main pages. A formal accessibility audit and statement are still to be done.
Security
Access is controlled by four roles held as Django groups, with record-level rules for surveyors, and every change to business records is written to an audit trail that cannot be edited.
Authentication
Users sign in with a username or an email address, and a password, at
/login/. Passwords are stored with Django's default PBKDF2-SHA256 hashing.Password rules: at least 12 characters, not similar to the user's details, not a common password, not all numbers.
Sessions use Django's signed session cookie; with
DEBUGoff, session and CSRF cookies are marked Secure unlessSECURE_COOKIES=False(only for local testing over plain HTTP).The API accepts API tokens and the browser session; a username and password (HTTP Basic) only when
PHAEMA_API_PASSWORD_SIGN_INis on. It must only be offered over HTTPS.Two-step sign-in (multi-factor authentication) uses any authenticator app (TOTP, RFC 6238) with single-use recovery codes. A council setting requires it for administrators (the default), for everyone, or makes it optional. The admin site signs in through the same page, and the API refuses a password alone for accounts that use it (API tokens still work for them, as an administrator made the token). Optional single sign-on with the council's own accounts is described below.
Email sign-in is UsernameOrEmailBackend in apps/core/auth_backends.py, the first entry in AUTHENTICATION_BACKENDS. It extends Django's ModelBackend, so permissions are unchanged. The username is tried first; an email address is matched without regard to case and only when exactly one account has it, because Django does not make addresses unique. An unknown name still runs the password hasher, so timing does not show whether an account exists. Two-step sign-in and the API rule apply the same way whichever name is typed. Tests: apps/core/test_email_sign_in.py.
Forgotten-password reset is in apps/core/password_reset.py. The form at /account/forgot-password/ takes an email address or a username and always shows the same "check your email" page, so it does not reveal whether an account exists. An email goes only to active accounts that have an email address: the account with that username, or every account with that address, each with its own link. The link (/account/reset-password/<uid>/<token>/) uses Django's PasswordResetConfirmView with ResetTokenGenerator, a subclass of Django's token generator with its own salt and a time limit of PHAEMA_PASSWORD_RESET_MINUTES (60 by default). The token is tied to the password hash and last sign-in, so it works once. It is separate from the first-password link sent to a new test account, which lasts the days set by Django's PASSWORD_RESET_TIMEOUT; neither kind of link opens the other page. Requests are limited through the cache to five an hour from one connection and three emails an hour to one account. Choosing a password does not sign the person in, so two-step sign-in still applies, and Django signs out their other sessions. When EMAIL_HOST is blank the form is replaced by a message to ask an administrator. On a test site, usernames starting demo. cannot be reset. Tests: apps/core/test_password_reset.py.
Emails to tenants go through GOV.UK Notify, not the SMTP relay. apps/core/notify.py saves each one first as an OutgoingEmail (kind, to, subject, body, agreement, demand run, status recorded/sent/failed, Notify reference, error, made by and when), then calls notifications-python-client only when PHAEMA_NOTIFY_API_KEY and PHAEMA_NOTIFY_TEMPLATE_ID are set; any failure is stored on the record, not raised. PHAEMA keeps the wording: the Notify template only carries ((subject)) and ((body)). apps/ledger/emails.py builds one email per agreement in a demand run (charges in the run, total, overdue balance from billing.account, and a pay link from ModuleSettings.payment_link with {reference}, {amount} and {account} URL-encoded), in the site's main language, to Lease.billing["email"]. An agreement is emailed once per run; again retries only failed ones. The page is /ledger/runs/<pk>/email/, behind finance_only, the full ledger scope and ModuleSettings.email_demands. The admin for OutgoingEmail is read-only with no add or delete. Tests: apps/ledger/test_email_demands.py.
The tenant portal is apps/portal, at /tenant/, switched on by ModuleSettings.tenant_portal_enabled (every portal URL returns 404 while it is off). Portal accounts (PortalAccount: tenant party, name, unique email, finance and facilities rights, active, invited by and when, last sign-in) are not Django users and never hold a role. Sign-in: the tenant enters an email address; if it belongs to an account that may sign in, SignInCode.issue cancels earlier codes and stores a new 6-digit code only as an HMAC-SHA256 keyed with SECRET_KEY, valid 15 minutes and 5 tries. The code goes through apps/core/notify.py with the plain code in the Notify body while the OutgoingEmail record keeps it masked. The answer page is the same whether or not the address exists. Rate limits through the cache: 5 codes an hour to an address and 20 requests an hour from a connection. A correct code cycles the session key and stores the account id under its own session key, separate from Django's authentication; access.current signs out after PHAEMA_PORTAL_IDLE_MINUTES or as soon as the account is inactive or has no visible agreement. Separation: every portal view gets agreements from access.agreements_for (let out to the account's party, not proposed, and not ended more than 365 days ago) and looks records up inside that queryset, so another tenant's agreement or document is a 404. Documents need LeaseDocument.shared_with_tenant. Portal responses carry their own Content-Security-Policy (no map tiles) and Cache-Control: no-store; /tenant/ is open in the role and two-step middleware because those apply to staff sign-in only. Changes a tenant makes are audited with no user and via "Tenant portal: name <email>". ContactChange records wait for accept (copies to the agreement's billing contact) or decline, from the read-only admin with actions; waiting changes appear on the dashboard of the property's managing surveyor, or administrators. Invitations are sent when estates add an account in the admin. Demo accounts: apps/portal/demo.py (@portal.example). Tests: apps/portal/tests.py.
Repair reports are shared by the tenant portal and the occupier liaison pages. RepairReport (in apps/maintenance: property, agreement or department, source tenant/department, portal account or PHAEMA user, reporter name, phone, location, description, danger flag, status new/job/tenant/duplicate/closed, reply, decided by and when, job) and RepairPhoto (up to 3, through process_image, so EXIF and GPS data are removed; served by the protected file view under the maintenance rule). apps/maintenance/reports.py holds the one RepairForm (property limited to the agreement's properties, or the building and its parts), submit, queue_for (new reports for buildings the user manages; administrators see all) and the decisions; raise_job calls workflow.open_job, so responsibility and target follow the usual rules, and records how_reported tenant or online. Triage pages are /maintenance/reports/ and /maintenance/reports/<pk>/ (maintenance module; deciding needs administrator or surveyor). Reporter pages: /tenant/agreements/<pk>/repair/ (facilities rights) and /occupier/building/<pk>/repair/ (liaisons, not read-only people); both hide when the maintenance module is off. RepairReport.progress() gives what the reporter sees. Tests: apps/maintenance/test_repair_reports.py.
Requests that open a case are shared the same way. CaseType has tenant_can_start, department_can_start, request_guidance and request_documents; the shipped consents and the new space_request type get them from seed.request_defaults (and migration cases.0012 for existing installations). apps/cases/requests.py holds the one RequestForm (type, title, details, up to 10 files through validate_case_file) and submit, which calls workflow.open_case with how_received portal or dept, portal_account, occupier or requested_by, files the text as incoming Correspondence (method online) and the files as CaseDocument with shared_with_requester=True. Requesters see cases from tenant_cases (portal cases on the account's agreements) or department_cases (department cases for the liaison's occupiers), with progress() and only shared documents; download views check both. Staff share or stop sharing a document at /cases/documents/<pk>/share/ (can_work). Administrators see open portal or department cases with no owner on their dashboard. Pages: /tenant/agreements/<pk>/request/, /tenant/requests/<pk>/, /occupier/building/<pk>/request/, /occupier/requests/<pk>/. Tests: apps/cases/test_requests.py.
Service charges in the portal reuse the staff statements: apps/servicecharges/tenant.py gives budget_context and statement_context (used by both the staff views and the portal) and published_years(lease), which returns only years whose budget has been issued (not draft) or whose year-end statements have been issued (reconciled). The statement bodies are shared templates (_budget_body.html, _statement_body.html). apportion.reconcile now counts as paid on account only charges with a period, so the balancing charges raised by finalise no longer zero the balance shown afterwards. Querying a line opens an sc_dispute case received through the portal. Tenant certificates: Certificate.portal_account, checked_by, checked_on and Requirement.tenant_reminded_on; the portal lists active responsible="tenant" requirements on the agreement's properties and records uploads through compliance.workflow.record; staff mark them checked on the property's compliance page. apps/portal/reminders.send_certificate_reminders, run by daily_tasks, emails facilities accounts through Notify when such a certificate is missing, expired or expires within 30 days, at most every 30 days per requirement. All of these need facilities rights and the relevant module. Tests: apps/portal/test_phase2.py.
Phase 3: PortalMessage (agreement, optional request case, direction, tenant account or staff author, text, sent, answered, read by the tenant). apps/portal/messaging.py: answerers(lease) is the managing surveyors of the agreement's properties plus anyone with a Cover for them today, or the administrators if none; from_tenant emails them through the normal email backend without the text; reply marks the thread's tenant messages answered and emails the tenants who wrote (or all the tenant's active accounts) through Notify, without the text; waiting_for(user) feeds the Message from a tenant dashboard item. Pages: /tenant/agreements/<pk>/messages/ and /leases/<pk>/messages/ (administrators and surveyors). Insurance upload at /tenant/agreements/<pk>/insurance/ only where Lease.insurance is tenant: a LeaseDocument of type insurance with portal_account, shared with the tenant, review date the cover end. Deposit (from deposit_account) and payment plan (from creditcontrol.plan_state) appear for finance rights. Tests: apps/portal/test_phase3.py.
Single sign-on is the first connector, in the optional app apps/connectors. It uses OpenID Connect, so Microsoft Entra ID (Microsoft 365), Keycloak and other services are only different settings. It is off unless the installer sets PHAEMA_SSO_ISSUER, PHAEMA_SSO_CLIENT_ID and PHAEMA_SSO_CLIENT_SECRET in the server's .env and an administrator ticks Sign in with the council's own accounts in Module settings; with either missing, /login/sso/ returns 404 and PHAEMA behaves as before. sso.py runs the authorisation code flow with PKCE: /login/sso/ keeps a state, nonce and code verifier in the session and redirects to the service; /login/sso/callback/ checks the state, exchanges the code at the token endpoint and checks the ID token's signature (keys from the service's jwks_uri, read with PyJWT), issuer, audience, expiry and nonce. The service's published settings are read from /.well-known/openid-configuration and cached for an hour. PHAEMA asks only for the openid profile email scopes and stores no tokens.
A person is matched by SsoIdentity (issuer and subject) once linked; the first time, by email address to exactly one active account that is not a superuser and not already linked. If the council allows it (sso_create_accounts), an account with no usable password is created instead. SsoGroupMapping rows give a group or app role from the groups and roles claims a PHAEMA role, an access area or both; sync_groups() applies them at each sign-in, changing only roles and areas that some mapping names, and leaving everything alone when the service reports more groups than it can list. The session is marked with SsoBackend, which never checks a password; TwoStepRequiredMiddleware does not ask those sessions for PHAEMA's two-step sign-in. password_allowed() applies the council's rule on PHAEMA passwords (sso_passwords): by default a linked person's password is refused by UsernameOrEmailBackend and they are sent no reset email, while administrators and superusers keep theirs as a fallback. Links, account creation and role changes go to the change log. The set-up guide for a council's IT team is docs/single-sign-on.md. Tests, against a stand-in service with its own signing key: apps/connectors/test_sso.py.
Sign-in limits, sessions and the secret key (from 25 November 2026). apps/core/throttle.py counts wrong passwords per account (10) and per connection (50) over 15 minutes in the shared cache; UsernameOrEmailBackend refuses sign-in past either limit, so the sign-in page, the admin site and API Basic authentication (when switched on) are all covered, and DRF adds request limits (30 a minute anonymous, 1,200 an hour signed in). The cache is a database table (phaema_cache, made by core.0022), shared by every worker. throttle.client_ip() reads X-Forwarded-For only when BEHIND_HTTPS_PROXY is set, and only its last address. Sessions end after PHAEMA_SESSION_HOURS (10) or PHAEMA_IDLE_MINUTES (120) without use (IdleTimeoutMiddleware). PHAEMA refuses to start without a SECRET_KEY of 32 or more characters unless DEBUG is on; phaema.sh writes one into .env. Single sign-on matches an account by the email claim only, ignores addresses marked unverified (email_verified, xms_edov) and never links an administrator by email.
API tokens (from 26 November 2026). ApiToken in apps/core/models.py (migration core.0025) holds a name, the account it acts as (user), access (read or change), resources (a list of router basenames: property, title, lease, party; empty means all), expires_on (at most MAX_DAYS, 731, ahead; the form suggests a year), the first 12 characters of the key (prefix) and a SHA-256 hash of the key (key_hash, unique). The key is phaema_ plus 32 random bytes from secrets.token_urlsafe, made by issue(); it has enough randomness that a plain SHA-256 is safe and lookups are one indexed query. ApiTokenAuthentication in apps/core/api_auth.py reads Authorization: Bearer (or Token) and refuses a key that is unknown, cancelled (revoked_at), past expires_on, or whose account is inactive, past its access end date or without a role. It records last_used_at and last_used_from (through throttle.client_ip) at most once a minute, with a plain update() so nothing reaches the change log. PhaemaPermission then refuses writes for a read token and any view whose basename is not in resources, before the usual role checks, so a token never has more than its account. Because DRF signs in after the middleware has run, both authentication classes call middleware.set_api_user(), so the change log names the account and fills AuditEntry.via ("API token: GIS layers (phaema_ab12…)" or "API: username and password"); the change log pages show it. ApiToken is registered with the change log, with key_hash excluded. Only administrators see Manage data, API tokens (ApiTokenAdmin); adding returns admin/core/apitoken/issued.html, which shows the key once with Cache-Control: no-store; there is no delete, only the Cancel the selected tokens action. Tokens an administrator made that end within 30 days appear under Coming up on their dashboard. PasswordOnlyBasicAuthentication returns nothing unless PHAEMA_API_PASSWORD_SIGN_IN is on. Tests: apps/core/test_api_tokens.py.
Letter template language (from 26 November 2026). Document templates are Django templates that administrators edit, so apps/documents/render.py renders them with its own Engine whose only built-in library holds the tags if, for and comment and the formatting filters in ALLOWED_FILTERS (add, capfirst, cut, date, default, default_if_none, first, floatformat, join, last, length, linebreaks, lower, pluralize, slice, title, truncatewords, upper, wordwrap, yesno); libraries is empty, so {% load %} finds nothing. Tags such as debug, include, now and templatetag, and filters such as pprint, do not exist there. DocumentTemplate.clean() compiles the text with the same engine (render.check), so a template using anything else cannot be saved; one that reached the database another way is not run, and its letters show a message asking an administrator to correct it. Merge values are reduced to plain text, numbers, dates and lists (_plain), so a template cannot reach other fields of a record through {{ value.field }}. python manage.py check_document_templates lists templates to correct and exits with status 1 if there are any.
Roles and permissions
apps/core/roles.py creates or refreshes the groups and their permissions after migrations (ensure_roles).
| Role | Can see | Can change |
|---|---|---|
| Administrators (and superusers) | Everything | Everything, including users, imports and settings |
| Surveyors | Everything | Properties they manage, with their photos, leases, components, planned tasks, compliance records and jobs; new properties they add; shared contact details |
| Contributors | Everything | Notes, documents and correspondence on cases they are added to |
| Viewers | Everything | Nothing |
| Signed in with no role | Help and open data only | Nothing |
Three layers enforce this: RoleRequiredMiddleware blocks anyone without a role; Django model permissions decide what kind of record a role may add or change; can_edit(user, obj) decides whether this user may change this particular record. The API applies the same rules through PhaemaPermission.
Audit trail
apps/core/audit.py connects to Django's save and delete signals for every business model. Each create, change and delete writes an AuditEntry with the time, the user (from CurrentUserMiddleware), the record and the old and new values. Users see it under Changes (/changes/); there is no screen for editing or deleting entries.
Locked in the database (from 26 November 2026, #94). Migration core.0023_audit_trail_lock adds a PostgreSQL trigger, phaema_audit_guard(), that refuses UPDATE, DELETE and TRUNCATE on core_auditentry, so entries cannot be altered through PHAEMA's database account, including by a bulk QuerySet.delete(). One update is allowed: clearing user_id when a user account is deleted (on_delete=SET_NULL), with every other column unchanged; the entry stays, without the name. Tests: apps/core/test_security_headers.py.
What the lock does and does not do. It protects the log against alteration through the application and its ordinary database connection. It is not absolute: a database superuser, or anyone who can change the schema, can drop or disable the trigger and alter rows, and anyone with the server's files can change the data directly. Councils should restrict and log administrator access to the database server, keep backups (which also hold earlier copies of the log) and keep the server's own logs. Describe the log as protected against ordinary application-level alteration, not as tamper-proof.
Bulk changes (from 26 November 2026, #108). The log is written from model signals, which QuerySet.update(), bulk_update() and bulk_create() do not send. apps/core/audit.py therefore has audited_update(queryset, **changes), which snapshots the records, updates them in one statement and writes an update entry for each record whose values changed, and audited_create(model, items), which writes a create entry for each new record; both do nothing extra for models not registered with the log. They are used for unlinking cases and other records from a project, putting charges into a finance export batch, cancelling an active payment plan, replacing the adopted estate strategy, ticking acknowledgement tasks, the main photo, a property's strategy review date, assigning lease events to the surveyor, ONS index corrections, and the tasks a new case is given. The blank question rows of a new site visit or health check are not logged one by one (the visit or check is), and neither are the API token's last use, retrying text recognition, seed data at install or INSPIRE parcel imports. Use the helpers for any new bulk change to an audited model. Tests: apps/core/test_audit_bulk.py.
Retention purge. The retention schedule suggests keeping change log entries for 7 years. A database administrator removes older ones in a single transaction that switches the lock off for that transaction only:
BEGIN;
SET LOCAL phaema.audit_purge = 'on';
DELETE FROM core_auditentry WHERE timestamp < now() - interval '7 years';
COMMIT;
Take a backup first (./phaema.sh backup), then run it from the PHAEMA folder in docker compose exec db psql -U phaema phaema. The setting ends with the transaction, so the lock is back on at once; the purge itself appears in the PostgreSQL log.
Access areas and cover
Roles decide what a person can change; access areas (AccessArea, apps/core/access.py) decide which optional modules they can open. Each area lists modules it opens in full, and may grant own_patch_finance (rent ledger and service charges limited to the person's patch) and finance_actions (raise rent, credit notes, finance exports, service charge approvals and finance imports, for Surveyors). Five areas are created by migration core.0013 and every user existing then was added to all of them.
Enforcement is on the server. Every view of an optional module goes through access.module_view(module, off_template), which returns 404 if the council has the module switched off and 403 if the person's areas do not open it, and sets request.access_scope to "full" or "patch". Templates receive modules as ModulesForUser, so every modules.*_enabled test is per person. The patch is computed by patch_people(): the person, everyone below them through StaffProfile.supervisor (the whole chain), and anyone they cover through a current Cover and that person's chain. The same rules apply to lease and party rent panels, dashboards, My work, the report builder (DATASET_MODULES in apps/reports/views.py), the change log (audit_visible), Hand over work receivers and works order approvers. Area membership and cover changes are written to the change log. Tests: apps/core/test_access.py; other tests put new users in every area unless marked own_areas.
Outside users. StaffProfile has is_external, organisation and access_ends; save() fills a blank end date for an outside user from ModuleSettings.outside_access_months (six by default). apps/core/outside.py holds the rules: access_ended(user) is true from the day after the end date. UsernameOrEmailBackend.user_can_authenticate refuses ended users, so password and API sign-in fail; connectors/sso.find_user refuses them too. get_user still returns an ended user so that AccessEndedMiddleware (after CurrentUserMiddleware) can sign them out and show core/access_ended.html with status 403 instead of a silent return to the sign-in page. The context processor sets access_ends_soon for the 14-day banner, and daily_tasks calls close_ended(), which unticks Active and writes the reason to the change log. Tests: apps/core/test_outside_users.py.
Occupier contacts (from 27 November 2026, #109). Departmental property liaisons (Occupier.liaison) and read-only people (Occupier.readers, migration space.0003) have no PHAEMA role. apps/space/liaison.py holds the rules: is_contact(user) is true when the space module is on and the person is named on an active occupier; occupiers_for() adds every occupier below those named (Occupier.family(), which now stops at an occupier already seen); editable_for() is the liaison's occupiers and those below; buildings_for() is the buildings with a current occupation by any of them. RoleRequiredMiddleware still refuses every page to a user without a role, except that an occupier contact is sent from / to /occupier/ and may reach liaison.PATHS (/occupier/, /account/password/, /account/two-step/) and the open pages (help, sign-out, page style). Everything else, including /files/, /api/ and /admin/, stays closed because every other check requires a role. apps/space/liaison_views.py serves /occupier/ (their buildings) and /occupier/building/<pk>/ (404 for a building none of their occupiers is in): the stacking plan names every occupier, but the holdings table and history show only their own occupiers. A liaison's POST creates or replaces the day's Headcount with from_department=True, a source naming them, and checked_by/checked_on empty. core/mywork.py lists unchecked department headcounts for buildings the person manages; /space/headcount/<pk>/check/ shows the figure beside the previous one and marks it checked; only the building's managing surveyor or an administrator can open it, without needing the space access area. The header shows a short menu (occupier_contact in the context processor). Help page: occupier-contacts. Tests: apps/space/test_occupier_contacts.py. Design: claude/design-occupier-liaison.md in the project notes.
Projects
apps/projects holds larger pieces of work with or without properties. A Project has a ProjectType (kind, starter phase names, confidential by default), a phase (PHASE_ORDER) and a status; workflow.record_gateway() is the only way to move phase: approved advances (gateway 4 closes), rejected stops. Visibility is in rules.py: visible(user) filters lists, reports (_project_rows in apps/reports/views.py) and property pages, so confidential projects reach only their team and administrators; _project() in the views returns 404 otherwise and writes a ProjectAccess row for each opening of a confidential project. Documents are stored under projects/ and served only by project_file; core/views.protected_file refuses that folder.
The budget (BudgetLine, BudgetYear) is keyed by the starting year of the April–March financial year (financial_year_of). can_see_budget and can_edit_budget add finance staff through their access areas. importing.SpendWorkbook (Import, Project spending) loads actuals. Cases, jobs and valuations carry a nullable project foreign key; project_for() shows the link only to people who can see the project.
completion.py builds the checklist from delivery onwards. Steps link to admin add or change forms with GET parameters to prefill them; it never writes to the register. Manual steps are CompletionStep rows; automatic steps are computed (a linked property; Property.disposed_on set, which also removes the property from open data). site_from_inspire unions INSPIRE parcels into site_boundary (EPSG:27700); map.geojson returns the site and properties in WGS 84 under the same visibility. Demo projects: apps/projects/demo.py, called by load_demo_data.
Site and buildings. Property holds the physical description of a site or building: location, description, when built, construction, storeys, roof, windows, parking, services and solar panels. The lists of choices are TextChoices on the model; physical_rows() returns the recorded facts as label and value pairs for the property page and reports. Site area is stored in hectares; the admin form (PropertyForm) also takes square metres and converts. PropertyPlan holds floor plans as PDF, DWG or DXF files up to 50 MB under plans/, checked by validate_plan in apps/core/files.py (extension and file signature) and deleted from storage with the record. apps/properties/report.py builds the property report, headed Initial valuation report when opened from a case in the Asset valuation group (/properties/<id>/report/?case=<id>). It writes the document library's markup, so apps/documents/render.py produces both the page and the Word file (?format=docx). It includes agreements that have not ended and open cases on the property, its parts and the properties it is part of, and ends with gaps(), the list of what is not yet recorded. Tests: apps/properties/test_site_and_buildings.py.
Site visit sheets. apps/cases/visit.py builds the sheet for a case that has a property (/cases/<id>/site-visit/, Word with ?format=docx): the case, what to know before visiting (from apps/compliance/safety.py, plus the hazards of the buildings within and the current occupiers), the property information, and the checklist. It is read-only: nothing entered on it is saved. Two things are set for each case type. CaseType.visit_parts is the list of property parts to print; the parts are the named sections of apps/properties/report.py (PARTS, sections()), which the property report also uses. CaseTypeChecklistItem rows are the checklist: heading, item, guidance, kind of answer, an optional detail of the property record to print beside it (checks; visit.recorded() reads the value from the property, then what it is part of, then the parts within it) and each_building, which repeats the item under each building of a site. Starting values for the case types PHAEMA ships with are in apps/cases/seed.py and were applied to existing installations by migration cases.0005; a council's later changes are not overwritten. The phone and print layouts are plain CSS on .phaema-sheet in static/css/phaema.css. Tests: apps/cases/test_site_visit.py.
Drag and drop. Every file chooser in the templates is wrapped in the GOV.UK Frontend file upload component (<div class="govuk-drop-zone" data-module="govuk-file-upload">), which lets a file be dropped onto it and falls back to the plain chooser without JavaScript; no other script is involved. A test checks that every chooser is wrapped and has the label the component needs. Three places take several files at once through a multiple input named files: the case page (action file_dropped: .eml and .msg files go through the existing email filing, everything else becomes a CaseDocument), the agreement page (/leases/<id>/files/, PDFs as LeaseDocument of the chosen type) and the property page (/properties/<id>/files/, floor plans or photos). Each file passes the same validators as a single upload and is filed on its own, so one refused file does not stop the others; file_each() in apps/core/files.py applies the limit of 20 files a time and collects the reasons, and title_from_filename() names each record. The pages submit as ordinary forms, so the existing permission checks and CSRF protection apply. Tests: apps/core/test_drag_and_drop.py.
Who may open a file (from 26 November 2026, #108). core/views.protected_file serves /files/<path> only when apps/core/file_access.may_open(user, path) agrees: the person must have a role, the path must belong to a record (it is looked up in every FileField and ImageField), and the record's model must have a rule in file_access.RULES. Core files (property photos and plans, title documents, lease documents, case documents, correspondence, site visit photos) open for everyone with a role, as their records do; maintenance job documents need the maintenance module, compliance certificates and building documents need compliance, and valuation reports and audit evidence need valuations (access.can_use, so the module must be switched on and opened by an access area, or the person is an administrator). Anyone else gets 404, the same as for a missing file. A path held by no record (an import being checked, a searchable copy of a scan) is never served, and project papers are refused here and served by project_file. A model with a file field but no rule is refused; a test (test_every_kind_of_file_has_a_rule) fails until a new one is given a rule. Tests: apps/core/test_file_access.py.
API checks (from 26 November 2026, #108). The property, title, lease and party serializers extend apps/core/api_validation.ModelCleanSerializer, which runs the model's clean() on the record as it would be saved and returns its errors as a 400, so the API applies the same rules as the forms, including "a property cannot be part of itself" round any loop. Property.ancestors(), descendants() and _descendant_ids() also stop at a property they have already seen, so a loop that reached the database some other way cannot make them run forever. Tests: apps/properties/test_api_hierarchy.py, apps/leases/test_api.py.
PDF viewer. PDFs are shown inside PHAEMA with PDF.js, kept in static/vendor/pdfjs/ (the pdfjs-dist package from npm: the library, its worker, the viewer components and their stylesheet and images, character maps, standard fonts and WebAssembly decoders; about 6 MB, no build step, nothing fetched from the internet). No link in the templates changed. The two views that serve files, core/views.protected_file and projects/views.project_file, ask apps/core/viewer.py whether the request is a person opening a page: a GET for a PDF whose Accept header contains text/html and which has no raw or download parameter. If so they return templates/core/pdf_view.html at that same address instead of the file; the page's script (static/js/pdf-view.mjs) then fetches the file from the same address with ?raw=1. Everything else (the viewer's own request, the API, scripts, images, other file types) gets the file exactly as before, and ?download=1 sends it as an attachment. The same permission checks run before either answer, so the viewer opens nothing a person could not already open. Both answers carry Vary: Accept, and the page is no-store. viewer.describe() finds the record that holds the file by looking the stored path up in every FileField, and takes the title, the download file name (the original name where one was kept) and the Back link from it; a file no record holds gets its stored name and a link back to the referring page if that is on the same host. The page works without JavaScript by offering the file to open or download. Scripting inside PDFs, XFA forms and eval are off, and links in a PDF open in a new tab with noopener noreferrer. Password-protected or damaged files show a message and the download link. The strip of small pages is PHAEMA's own code in the same script (the PDF.js package has no thumbnail component): one button per page, each drawn to a small canvas only when it scrolls into view, one at a time, so long documents stay quick; whether the strip is open is remembered in the browser's local storage. To update PDF.js, follow static/vendor/pdfjs/README.md. Tests: apps/core/test_pdf_viewer.py.
Leavers and hand-overs
Administrators use Hand over work (/people/hand-over/, view apps/core/handover_views.py, logic apps/core/handover.py) to move a person's open work to colleagues and, optionally, switch off their sign-in in the same step. Each kind of work is an Item naming its query, the user field it changes and the roles that may receive it: managed properties, open cases, open case tasks, pending case approvals, case contributions, open lease events, open maintenance jobs, pending works-order approvals, open valuation audit queries, projects led, project team places, open project tasks and risks, and supervised staff. Closed and completed records are never changed.
All moves run in one database transaction. Records are saved one at a time, not with a bulk update(), so each change fires the audit signals and appears in the change log under the administrator. Receivers are checked on the server: only active Surveyors and Administrators (and Contributors, for case contributions) are accepted. User accounts are deactivated, never deleted, so names stay on historical records. When adding a model with a user field, add an Item for it in handover.items().
Files
Uploaded photos and documents are stored outside the web root and served only through
/files/, which needs sign-in.Files are written with permissions
0640; form data other than files is limited to 5 MB per request.Responses carry
X-Content-Type-Options: nosniff; only PDF, JPEG and PNG open in the browser, everything else downloads.
Web protections
CSRF protection on every form (Django
CsrfViewMiddleware).Clickjacking protection:
X-Frame-Options: DENYin production.Template auto-escaping against cross-site scripting.
The ORM parameterises all database queries.
Excel and CSV exports neutralise cells starting
=,+,-or@, so a spreadsheet cannot run formulas planted in data.The calendar feed address contains a long random token that acts as its password; users can reset it.
Content-Security-Policy on every page (
apps/core/security_headers.py, #94): scripts only from PHAEMA itself, plus the two small inline scripts inbase.html, which carry a nonce made for each request (request.csp_nonce); no plug-ins (object-src 'none'); no framing (frame-ancestors 'none'); forms post only to PHAEMA; images and map tiles from PHAEMA, OpenStreetMap and Ordnance Survey. Inlinestyleattributes are allowed (they cannot run code). Static files are left out of the policy, because the e-learning page has its own inline script and carries no one's data.PHAEMA_CSP_REPORT_ONLY=Truesends the policy without enforcing it;PHAEMA_CSP_IMG_SOURCES,PHAEMA_CSP_CONNECT_SOURCESandPHAEMA_CSP_FORM_ACTIONSadd addresses;PHAEMA_CSP_ENABLED=Falseturns it off.Permissions-Policy turns off camera, microphone, location, payment, USB and serial access; Referrer-Policy
same-origin; Cross-Origin-Opener-Policysame-origin.HSTS is sent by PHAEMA as well as the Caddy proxy when
DEBUGis off (SECURE_HSTS_SECONDS, one year by default;SECURE_HSTS_INCLUDE_SUBDOMAINSandSECURE_SSL_REDIRECTare off unless set), so councils using their own proxy get it too.
Set at the web server, not in PHAEMA
These should be configured on the reverse proxy in front of PHAEMA (see Deployment):
HTTPS with TLS 1.2 or later, and HTTP redirected to HTTPS;
Strict-Transport-Security(HSTS);limits on repeated sign-in attempts, or the council's web application firewall;
a
Content-Security-Policyallowing scripts and styles from the PHAEMA host only (and the OS or OpenStreetMap tile host for maps).
Installation and configuration
PHAEMA installs as three Docker containers with one command, ./phaema.sh start, on any machine that runs Docker Compose, including Apple Silicon Macs.
Requirements
| Item | Minimum for a test install | Suggested for one council in production |
|---|---|---|
| Processor | 2 cores (x86-64 or ARM64) | 4 cores |
| Memory | 4 GB | 8 GB |
| Disk | 10 GB | 50 GB plus document storage, on encrypted disks |
| Software | Docker Engine with Compose v2, Git, Bash | The same, on a supported Linux (Ubuntu 24.04 LTS or Debian 12) |
| Network | None beyond the machine | HTTPS reverse proxy, outbound SMTP for reminders, optional outbound HTTPS to the OS Maps API |
The production figures are a starting estimate, not a measured benchmark.
The three containers
| Service | Image | Does |
|---|---|---|
db | docker/db (PostgreSQL 17 + PostGIS 3) | Holds all data in the db-data volume |
web | Dockerfile (Python 3.12) | Runs migrations on start, then Gunicorn on port 8000, bound to 127.0.0.1 only |
scheduler | Same image as web | Runs daily_tasks every hour and ocr_scans every five minutes |
Uploaded files live in the media volume, shared by web and scheduler.
First install
Install Docker and Git (on a Mac: Homebrew, Colima and Docker, as in
docs/setup-mac.md).git clone https://github.com/phaema/phaema-app.git && cd phaema-appcp .env.example .envand edit it (below). Never commit.env../phaema.sh start— builds the images and waits until/health/answers../phaema.sh admin— creates the first superuser.Sign in, open Manage data, Module settings, and switch on the modules the council uses.
Optionally
./phaema.sh demo-datato load the fictional demonstration estate.
Environment variables
| Variable | Default | Set it to |
|---|---|---|
SECRET_KEY | a development value | A long random string, unique to each install. Required in production |
DB_PASSWORD | phaema-local | A strong database password |
DEBUG | False | Always False outside development |
SECURE_COOKIES | False in Compose | True whenever PHAEMA is reached over HTTPS |
ALLOWED_HOSTS | localhost,127.0.0.1 | The host names users type, comma separated |
PHAEMA_ORGANISATION_NAME | Demonstration Council | The council's name for the header |
PHAEMA_BASE_URL | http://localhost:8000 | The public address, used in email links |
EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORD | blank, 587 | The council's SMTP relay. Blank writes emails to the log instead |
PHAEMA_NOTIFY_API_KEY, PHAEMA_NOTIFY_TEMPLATE_ID | blank | GOV.UK Notify key and the ID of an email template whose subject is ((subject)) and message ((body)), for emails to tenants. Blank records emails in PHAEMA without sending them. A Notify test key checks the connection without delivery |
PHAEMA_PORTAL_SHOW_CODES, PHAEMA_PORTAL_IDLE_MINUTES | False, 30 | Tenant portal. Test sites only: show sign-in codes on screen while Notify is not set up. Minutes without use before a tenant is signed out |
PHAEMA_PASSWORD_RESET_MINUTES | 60 | How long a forgotten-password link works, in minutes |
| PHAEMA_SSO_ISSUER | blank | Address of the council's sign-in service for single sign-on. For Microsoft 365: https://login.microsoftonline.com/<tenant ID>/v2.0. Blank means single sign-on is off |
| PHAEMA_OCR_LANGUAGES | eng | Tesseract languages for reading scans, joined with +. A Welsh council can use eng+cym (both are in the Docker image) |
| PHAEMA_OCR_MAX_PAGES | 500 | Scans with more pages than this are not read. PHAEMA_OCR_PAGE_SECONDS (180) and PHAEMA_OCR_JOBS (1) set the time allowed per page and pages read at once |
| PHAEMA_SSO_CLIENT_ID | blank | The application (client) ID the sign-in service gave PHAEMA |
| PHAEMA_SSO_CLIENT_SECRET | blank | The client secret. Note its expiry date: sign-in stops when it expires |
| PHAEMA_SSO_NAME | Microsoft | The name on the sign-in button: Sign in with Microsoft |
DEFAULT_FROM_EMAIL | PHAEMA <phaema@localhost> | The sender address for reminders |
Three more variables matter on a server behind an HTTPS proxy:
| Variable | Default | Set it to |
|---|---|---|
BEHIND_HTTPS_PROXY | False | True when a reverse proxy ends HTTPS, so Django trusts its X-Forwarded-Proto header. Safe because web listens on localhost only |
CSRF_TRUSTED_ORIGINS | blank | Any extra https:// addresses users reach PHAEMA by. An https:// PHAEMA_BASE_URL is trusted automatically |
EMAIL_USE_TLS | True | False only for a relay that does not support STARTTLS |
A typical server .env therefore has SECURE_COOKIES=True, BEHIND_HTTPS_PROXY=True, ALLOWED_HOSTS=phaema.example.gov.uk and PHAEMA_BASE_URL=https://phaema.example.gov.uk.
Council-specific choices (modules, letter details, invoice prefix, approval limits, Ordnance Survey Data Hub key and map style, open data) are kept in the database under Module settings, not in environment variables.
Control script
| Command | Does |
|---|---|
./phaema.sh start | Build if needed, start, wait for health check |
./phaema.sh stop | Stop; data is kept |
./phaema.sh update | git pull --ff-only, rebuild and restart (migrations run automatically) |
./phaema.sh status / logs | Show container state / follow logs |
./phaema.sh admin | Create a superuser |
./phaema.sh demo-data [--reset] | Load or reload the demonstration estate |
./phaema.sh import-inspire FILE | Import HM Land Registry INSPIRE parcels |
./phaema.sh reminders | Send due reminders now |
./phaema.sh backup | Write a compressed database dump to backups/ |
./phaema.sh reset-data | Delete all data after typing DELETE |
Deployment and operations
In production PHAEMA runs on one UK-hosted Linux server or virtual machine per council, behind an HTTPS reverse proxy, with nightly database backups copied off the server.
Hosting pattern
A Linux server in a UK data centre (council-owned, or a supplier such as IONOS UK cloud).
Docker and the PHAEMA stack as in Installation, with
.envset for production.A reverse proxy (Caddy, nginx or the council's load balancer) that ends HTTPS and forwards to
127.0.0.1:8000. Thewebport is bound to localhost so it is never exposed directly.A DNS name such as
phaema.example.gov.uk, added toALLOWED_HOSTSandPHAEMA_BASE_URL.Outbound SMTP to the council's mail relay or Microsoft 365 for reminders.
One stack per council keeps each council's data in its own database and makes it simple to show where the data lives. Several councils can share one physical host, each in its own stack with its own volumes and secrets.
Backups and restore
./phaema.sh backupwritesbackups/phaema-YYYYMMDD-HHMMSS.sql.gzwithpg_dump. Schedule it nightly with cron and copy the file to separate UK storage.Back up the
mediavolume (photos and documents) on the same schedule, for example withdocker run --rm -v phaema-app_media:/m -v $PWD/backups:/b alpine tar czf /b/media.tgz -C /m ..To restore: start an empty stack, then
gunzip -c FILE.sql.gz | docker compose exec -T db psql -U phaema phaema, and unpack the media archive into the volume.Test a restore at least every quarter.
Upgrades
./phaema.sh update pulls the latest code, rebuilds and restarts. Migrations run automatically when web starts. Take a backup first. To roll back, check out the previous version with Git (releases are not tagged yet) and restore that day's backup, because migrations are not reversed automatically.
Monitoring
/health/returns success when the app and database answer. Point an uptime monitor at it../phaema.sh logsshows Gunicorn, Django and scheduler output. On a server, ship Docker logs to the council's log service.The
schedulercontainer logs each hourlydaily_tasksrun and each ocr_scans run; a missing daily run means reminders are not going out, and "Not reading scanned PDFs" means Tesseract is missing.All containers restart automatically (
restart: unless-stopped).
Scaling
One server with 3 Gunicorn workers suits a single council's estates team. For more users, raise --workers in the Dockerfile command, or move PostgreSQL to a managed UK database service and run more web containers behind the proxy, with media on shared storage.
Testing and quality
PHAEMA has 630 automated tests in 61 files, run on every pull request by GitHub Actions against a real PostGIS database, with a check for missing migrations and Django's deployment checks; a pull request is merged only when they pass. The same workflow audits the Python packages for known vulnerabilities (pip-audit) and builds the container image; CodeQL scans the code weekly and on every pull request, and Dependabot proposes package and action updates each month (CodeQL's two steps as one pull request). From 26 November 2026 (#94) the test job also measures coverage with COVERAGE_CORE=sysmon and fails below 90% (it was 95%), a lint job runs Ruff with the rules in ruff.toml (pycodestyle, Pyflakes, import order, bugbear and Bandit's security rules), and every action is pinned to a commit hash, with the version in a comment. A test (core/test_api_schema.py) builds the OpenAPI description with --validate --fail-on-warn, so a change that makes the API description incomplete fails.
Releases are numbered and published on GitHub. The first is 0.9.0, the last alpha, published on 10 November 2026; beta releases will be numbered from 1.0.0-beta.1 and the first version for live council use will be 1.0.0. The number is held once, as PHAEMA_VERSION in phaema/settings.py, and is shown in the API description. It is changed in the pull request that precedes each release. CHANGELOG.md lists what changed in each release, with anything that needs action under Before updating, and docs/releasing.md gives the numbering rules and the steps (changelog, version, tag, GitHub release, test site, early adopters) and how security fixes go out as patch releases.
Running the tests
pip install -r requirements.txt
export DATABASE_URL=postgis://phaema:phaema@localhost:5432/phaema
python -m pytest
The database user needs permission to create the test database. A full run takes a few minutes. pytest.ini points pytest at phaema.settings and collects tests.py and test_*.py.
What the tests cover
| Area | Test files | Tests |
|---|---|---|
| Properties, maps, INSPIRE, open data | properties/tests.py, test_week2.py, test_features.py | 38 |
| Leases, events, parties, reminders | leases/tests.py, test_week3.py, test_events_parties.py | 28 |
| Cases and professional standards | cases/test_cases.py, test_standards.py | 29 |
| Service charges | servicecharges/test_service_charges.py | 16 |
| Reports and exports | reports/test_reports.py | 13 |
| Rent ledger | ledger/test_ledger.py | 13 |
| Roles, My work, place filters | core/test_roles.py, test_mywork.py, test_places.py | 14 |
| Maintenance | maintenance/test_maintenance.py | 8 |
| Imports | imports/test_imports.py | 8 |
| Compliance | compliance/test_compliance.py | 8 |
| Valuations | valuations/test_valuations.py | 7 |
| Projects | projects/test_projects.py | 20 |
| Document templates | documents/test_documents.py | 7 |
| Help pages | help/test_help.py | 6 |
| Space, costing, occupation on property pages | space/tests.py, test_costs.py, test_property_views.py | 40 |
| Outside users | core/test_outside_users.py | 10 |
| Options and rent-free periods | leases/test_options_rent_free.py | 8 |
| Estates strategy step 1 | properties/test_strategy.py | 13 |
| Estates strategy step 2, pipeline, health check | strategy/tests.py, strategy/test_pipeline.py, strategy/test_health.py | Objectives and suggested status, board report, pipeline sections and buckets, budgets and confidential projects, health check rules, comparison with last year, improvement actions, demo data. |
| Site visits | cases/test_visits.py | Starting per building, who can fill in, saving by section, photos, finishing and the saved record, differences, update the record and leave as it was, check-measures, hand-over, My work and reports. |
| IPMS floor areas | properties/test_ipms.py | Headline basis and fall-back, basis text, property page and report, space costs and the data standard, importer columns and the IPMS error, the migration that moves old figures, check-measure fields, the module setting. |
| Scanned documents (OCR) | core/test_ocr.py | Queuing on save, switched off, typed PDFs left alone, a scan read and served (original kept for download), waiting note, page limit, missing Tesseract, damaged files, the read-poorly check, backlog and tidy, Manage data, confidential project copies. Tests needing Tesseract are skipped where it is not installed. |
| Rents payable | leases/test_rents_payable.py | Payments following the rent schedule and rent-free periods, monthly and agreement totals agreeing, the page and Excel download, the Finance menu. |
| IFRS 16 data pack | leases/test_ifrs16.py | Which leases are in the year, the lease end and its source, payments from the year start to the lease end after a rent-free period and a step, nominal rents flagged, changes in the year from the rent schedule and audit trail, the workbook and Finance-only download. |
| Security headers and audit lock | core/test_security_headers.py | The Content-Security-Policy and its nonce on every page, a new nonce each request, report-only and off, extra sources; the database refusing to change or delete the audit trail, a deleted user's entries kept without the name, and the retention purge switch. |
| Languages | core/test_language.py | English unless the council offers Welsh, the browser language ignored, choosing Cymraeg, unknown languages and unsafe return addresses, and the Welsh file complete and compiled. |
| API tokens | core/test_api_tokens.py | Keys kept only as a hash; read-only and change tokens; parts of the API; never more than the account's role; ended, cancelled and closed-account tokens refused; two-step accounts; last use recorded without a change log entry; the change log naming the token; password sign-in off by default; making a token and seeing the key once; the two-year limit; administrators only; cancelling; no deleting; the reminder before a token ends. |
Other checks
Migrations: CI runs
makemigrations --check --dry-run, so a model change without its migration fails the build.Lint:
ruff check .(configured inruff.toml); CI runs it on every pull request.Accessibility: axe-core runs in a headless browser over the main pages during development; manual keyboard and screen reader checks for new screens.
User acceptance: the PHAEMA Test Programme document gives step-by-step tests for each section, against the demonstration data.
Demo data:
load_demo_datais itself tested, so record counts in the training and test programme stay true.
Integrations and data exchange
Today PHAEMA exchanges data through documented files (Excel, CSV, GeoJSON, iCalendar, Word) and an open REST API. Live connectors to finance, legal and CRM systems are planned for later releases.
Imports
| Import | Where | Format |
|---|---|---|
| Properties | Properties, Import (/properties/import/) | Excel template |
| Parties; leases and licences (with breaks) | Manage data, Import (/import/) | Excel workbook, one sheet per record type |
| Rent receipts from the finance system | Import hub | Excel; matched to leases by PHC invoice number or reference |
| Service charge spending | Import hub | Excel |
| Contractors and components | Import hub | Excel |
| Valuer's returned figures | Import hub | Excel |
| HM Land Registry INSPIRE Index Polygons | Properties, INSPIRE import, or ./phaema.sh import-inspire | .zip or .gml as downloaded from HM Land Registry |
Each Excel import has a downloadable template. Every row on every sheet is checked first; nothing is saved unless the whole file is clean, and then everything is saved in one database transaction.
Exports
| Export | Format | For |
|---|---|---|
| Any list or report | Excel or CSV | General use; formula injection neutralised |
| Finance export | Excel or CSV, 21 fixed columns | Invoice or journal import into Unit4, Oracle, SAP, Civica or others. Each export is a numbered batch so nothing is sent twice |
| Service charge budgets and accounts | Excel or CSV | Tenants, auditors |
| Valuation schedule, audit pack | Excel | Finance and external audit |
| Letters and notices | Word (.docx) | Legal and correspondence |
| Open data: land and assets; property available | CSV, JSON, GeoJSON at /open-data/ | Local Government Transparency Code publication, without sign-in |
| Lease event calendar | iCalendar feed /calendar/<token>.ics | Outlook, Google Calendar, Apple Calendar |
The finance export (apps/ledger/finance.py) has two columns added at the end, Billing contact and Billing email, so existing column mappings are not disturbed. Its customer address is the agreement's billing address where one is set.
REST API
Base address
/api/, with an OpenAPI 3 schema at/api/schema/and interactive documentation at/api/docs/.Resources:
properties,titles,leases,parties. Results are paged 50 at a time.Authentication by API token (
Authorization: Bearer phaema_…), or by session from a signed-in browser; permissions follow the PHAEMA role of the account the token acts for, narrowed by the token (see Security, API tokens). HTTP Basic with a username and password is off unlessPHAEMA_API_PASSWORD_SIGN_INis set.Example:
curl -H "Authorization: Bearer $PHAEMA_TOKEN" https://phaema.example.gov.uk/api/properties/?uprn=100023336956Client libraries and connectors are to be licensed Apache-2.0 so suppliers can build on them freely.
External services
| Service | Used for | Needed? |
|---|---|---|
| Ordnance Survey Maps API | Base maps, with the council's OS Data Hub key (free under the Public Sector Geospatial Agreement) | Optional; OpenStreetMap is used without a key |
| SMTP relay | Reminder and case emails | Optional; without it emails go to the log |
| HM Land Registry | INSPIRE polygons, downloaded by the council | Optional |
PHAEMA bundles no licensed data. SFG20 schedules, OS premium data and Land Registry services are connected under each council's own licence.
Extending PHAEMA and contributing
New features are added as Django code in the matching app, with tests, translatable text and an audit registration, and contributed back under AGPL-3.0 with a Developer Certificate of Origin sign-off.
Conventions
Every source file starts
# SPDX-License-Identifier: AGPL-3.0-or-later.Python follows PEP 8; keep functions small. Business rules live in plain modules beside the models (for example
cases/standards.py,compliance/safety.py,core/mywork.py), not in templates.All user-facing text is wrapped in
gettextor{% translate %}so a Welsh translation can be added underlocale/.Screens follow GOV.UK Design System patterns and the GOV.UK style guide's plain English.
Server-rendered pages must work without JavaScript.
Adding a feature: checklist
Add or change models in the right app and run
python manage.py makemigrations.Register new business models with the audit trail in the app's
apps.py(audit.register(model)).Add permissions to the right roles in
core/roles.py, and record-level rules tocan_editif surveyors may change it.Add views, URLs and templates using the shared partials in
templates/core/.Offer Excel and CSV export for any new list (
reports/export.py).Write tests, including the role rules.
Update the help page in
apps/help/pages/and, if screens changed, the training course intraining/course.py.Extend
load_demo_datawith fictional examples (ZZ postcodes, 9999 UPRNs, ZZ title numbers).Run the tests and pyflakes, then open a pull request.
Licensing
| Part | Licence |
|---|---|
| The application | AGPL-3.0-or-later: anyone running a changed version as an online service must publish their changes |
| Connectors, client libraries, SDKs | Apache-2.0 |
| Data model and schema documentation | CC BY 4.0 |
| Data councils publish through PHAEMA | Open Government Licence v3.0 |
Councils commissioning features should require the supplier to release the work under the project licence. Security problems should be reported privately, not in public issues to stuart@phaema.co.uk, as SECURITY.md in the repository explains, with response times and the known security gaps.
Compliance mapping
This table shows how PHAEMA's design supports each point of the Technology Code of Practice and the main legal duties. It is a self-assessment for councils to check, not a certification.
Technology Code of Practice
| Point | How PHAEMA supports it | Council still needs to |
|---|---|---|
| 1. Define user needs | Designed with a chartered surveyor around estates tasks; role dashboards; test programme | Run its own user research |
| 2. Make things accessible and inclusive | GOV.UK Frontend, WCAG 2.2 AA target, themes, text sizes, keyboard use, axe checks | Commission an audit and publish an accessibility statement |
| 3. Be open and use open source | AGPL source on GitHub; all dependencies open source | Publish any changes it makes |
| 4. Make use of open standards | UPRN, British National Grid, GeoJSON, CSV, OpenAPI 3, iCalendar, .docx, .xlsx | Use UPRNs in its own records |
| 5. Use cloud first | Containerised; runs on any UK cloud or on-premises | Choose a UK host |
| 6. Make things secure | Role-based access, audit trail, secure cookies, CSRF, protected files | Run HTTPS, patching, penetration test, IT health check |
| 7. Make privacy integral | Minimal personal data (tenants' contact details); data stays in the council's own database | Complete a DPIA and record of processing |
| 8. Share, reuse and collaborate | One code base for every council; contributions return to all | Contribute back commissioned work |
| 9. Integrate and adapt technology | REST API, documented finance export, spreadsheet imports | Map the finance export once |
| 10. Make better use of data | Report builder, exports, Transparency Code open data | Publish its open data |
| 11. Define your purchasing strategy | No licence fee; hosting and support can be bought from any supplier | Procure hosting and support competitively |
| 12. Make your technology sustainable | Small server footprint, no client build, server-rendered pages | Choose an energy-efficient host |
| 13. Meet the Service Standard | Internal staff tool; follows GOV.UK patterns | Decide whether a service assessment applies |
Legal and other standards
| Duty or standard | PHAEMA's part |
|---|---|
| Public Sector Bodies Accessibility Regulations 2018 | WCAG 2.2 AA target and accessible components; statement to be published by the council |
| UK GDPR and Data Protection Act 2018 | Role-based access, audit of every change, UK hosting, export and deletion through the admin; the council is the controller |
| Local Government Transparency Code 2015 | Land and assets dataset in CSV, JSON and GeoJSON |
| NCSC Cloud Security Principles | Supported by the hosting pattern: separate stack per council, encrypted transport, backups; the host supplier must evidence the rest |
| Building Safety Act 2022 (Golden Thread) | Building safety records, tiers and superseded documents kept with history |
| CIPFA Code of Practice on Local Authority Accounting | Asset classes, valuation bases and year-end schedules for finance |
| RICS professional standards | Red Book valuation fields, conflict of interest checks, MEES and dilapidations prompts |
Troubleshooting and reference
Most problems come from three settings: ALLOWED_HOSTS, HTTPS cookie and CSRF settings, and email.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| "Bad Request (400)" on every page | The host name is not in ALLOWED_HOSTS | Add it to .env, then ./phaema.sh start |
| Sign-in returns "Forbidden (403) CSRF verification failed" behind HTTPS | The proxy setting is off, so Django sees plain HTTP and the browser's https:// origin does not match | Set BEHIND_HTTPS_PROXY=True and an https:// PHAEMA_BASE_URL, then ./phaema.sh start |
| Sign-in works over HTTP but the session is lost | SECURE_COOKIES=True without HTTPS | Use HTTPS, or False only for local tests |
| "Waiting for PHAEMA to start" never finishes | Database still starting, or a migration failed | ./phaema.sh logs, look for the error in web |
docker: command not found or cannot connect on a Mac | Colima not running | colima start |
| Port 8000 already in use | Another program on 8000 | Stop it, or change the left-hand port in docker-compose.yml |
| Reminder emails never arrive | EMAIL_HOST blank, so emails go to the log | Set the SMTP variables; check scheduler logs |
| Demo data shows old counts | Old code still running | ./phaema.sh update, then ./phaema.sh demo-data --reset |
"Missing staticfiles manifest" outside Docker with DEBUG=False | No collectstatic manifest | Run python manage.py collectstatic, or use DEBUG=True for the development server |
| Map shows OpenStreetMap, not OS | No OS key in Module settings | Enter the council's OS Data Hub key |
Known issues to fix before production
| Issue | Effect | Planned fix |
|---|---|---|
| No limit on repeated sign-in attempts | Password guessing is not slowed | Rate-limit at the proxy now; add in-app throttling later |
| Single sign-on not yet proved on a live council tenant | It is tested against a stand-in sign-in service only; a council's own conditional access rules have not been tried | Try it with a pilot council's Microsoft 365 |
| No chat, file store or GIS connectors (Microsoft 365 or open-source alternatives) | Reminders and approvals arrive by email only; key dates are not in Outlook; documents are stored in PHAEMA, not SharePoint | On the roadmap: an optional connectors module on open standards, off by default |
| No tagged releases | No version numbers or security support periods (SECURITY.md now gives the security contact and response times) | Publish with the first release |
| No formal accessibility audit | Statement cannot yet be published | Commission an audit |
Fixed in November 2026: sign-in and forms failing behind an HTTPS proxy (BEHIND_HTTPS_PROXY, and CSRF_TRUSTED_ORIGINS and EMAIL_USE_TLS now passed through Docker Compose).
Useful addresses
| Address | Purpose |
|---|---|
/health/ | Health check, JSON {"status": "ok"} |
/admin/ | Django administration (superusers and administrators) |
/api/docs/ | Interactive API documentation |
/changes/ | Audit trail |
/help/ | In-app help and training courses |
/open-data/ | Published datasets |
Administrators also have /people/hand-over/ to move a leaver's work to colleagues. Administrators and supervisors have /people/cover/ to arrange cover for absence.
PHAEMA is free software under the GNU Affero General Public License v3.0. Screenshots show fictional demonstration data. Questions or corrections: stuart@phaema.co.uk.