PHAEMA

Technical manual

Updated 26 November 2026Download PDF

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.

ReaderRead first
Council IT and security teamsArchitecture, Security, Compliance mapping
Hosting suppliers and system administratorsInstallation, Deployment and operations, Troubleshooting
Developers and contributorsTechnology 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.

PHAEMA architecture · one stack per council
PHAEMA architecture · one stack per council

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

  1. The browser sends an HTTPS request; the proxy ends TLS and forwards it to Gunicorn on port 8000.

  2. 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) and RoleRequiredMiddleware (blocks users with no role).

  3. The URL is routed to an app's view, which checks the user's role and, for changes, can_edit.

  4. The view reads or writes models through the Django ORM; every save or delete of an audited model writes an AuditEntry.

  5. 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

ComponentVersionLicenceWhat PHAEMA uses it for
Python3.12 (image python:3.12-slim-bookworm)PSFLanguage and runtime
Django5.2 LTS (>=5.2,<5.3)BSD-3-ClauseWeb framework: models, ORM, migrations, forms, templates, authentication, admin, translation
GeoDjango (django.contrib.gis)with DjangoBSD-3-ClauseSpatial fields and queries for property boundaries and points
GDALDebian bookworm gdal-binMITReads INSPIRE GML and other spatial formats for GeoDjango
Django REST framework>=3.15,<4BSD-3-ClauseThe open JSON API at /api/
drf-spectacular>=0.28,<1BSD-3-ClauseOpenAPI 3 schema at /api/schema/ and interactive docs at /api/docs/
django-environ>=0.12,<1MITReads settings from environment variables and .env
psycopg 3>=3.2,<4 (binary)LGPL-3.0PostgreSQL driver
Gunicorn>=23,<24MITProduction WSGI server, 3 workers, 300 s timeout
WhiteNoise>=6.8,<7MITServes compressed, cache-busted static files from the app
openpyxl>=3.1,<4MITExcel import templates, imports and every Excel export
Pillow>=11,<13MIT-CMU (HPND)Property photo handling
Python-Markdown>=3.7,<4BSD-3-ClauseRenders the in-app help pages
python-docx>=1.1,<2MITWord export of letters and notices from the template library
extract-msg>=0.48,<1GPL-3.0 (compatible with AGPL)Reads Outlook .msg emails filed on cases

Database

ComponentVersionLicenceUse
PostgreSQL17 (image postgres:17-bookworm)PostgreSQL LicenceAll application data
PostGIS3 (postgresql-17-postgis-3)GPL-2.0Spatial 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

ComponentVersionLicenceUse
GOV.UK Frontend5.14.0, vendoredMIT, © Crown copyrightAccessible page components and layout. The GDS Transport font is removed (it is licensed only for GOV.UK) and no GOV.UK branding is used
OpenLayers10.11.0, vendoredBSD-2-ClauseProperty maps and boundary drawing
Atkinson HyperlegiblevendoredSIL OFL 1.1Typeface for the Clear style
PDF.js6.5.438, vendoredApache-2.0, © Mozilla FoundationShows PDFs inside PHAEMA. Its bundled fonts and image decoders keep their own open-source licences beside them
PHAEMA's own scriptsstatic/js/phaema.js, phaema-map.jsAGPL-3.0Collapsible 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

ToolVersionUse
pytest + pytest-django>=8,<9, >=4.9,<5Automated tests
pyflakesanyLint for unused imports and undefined names
GitHub Actionsubuntu-24.04Runs migrations check and tests on every pull request
Docker and Docker ComposecurrentLocal 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

PathContents
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.shContainer 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.mdLicences and contribution rules
locale/cy/LC_MESSAGES/The Welsh interface text (django.po) and its compiled form (django.mo)
CHANGELOG.md, SECURITY.md, ruff.tomlWhat changed in each release, the security policy, and the Ruff lint rules

Django apps

AppResponsibilityMain models
coreDashboards (estate and My work), roles, audit trail, settings, skins and themes, protected file servingModuleSettings, AuditEntry, StaffProfile
propertiesProperty register, hierarchy, photos, titles, INSPIRE boundaries, maps, open data, demo dataProperty, PropertyPhoto, PropertyPlan, Title, TitleDocument, InspireParcel
leasesLeases and licences, parties, breaks, rent schedules, lease events, reminders, calendar feedsLease, Party, BreakOption, RentScheduleEntry, LeaseEvent, ReminderLog, CalendarFeed
ledgerRent demands, VAT, receipts, arrears, statements, finance exportDemandRun, Charge, Receipt, ExportBatch
servicechargesService charge schedules, budgets, apportionment, year-end reconciliationSchedule, ScheduleMember, ScheduleYear, BudgetLine, Expenditure, CostHeading
casesCase types, stages and tasks, approvals, notes, correspondence, MEES, dilapidations and conflict checksCaseType, Case, CaseTask, CaseNote, Correspondence, CaseDocument, Approval
maintenanceContractors, contracts, components, planned tasks, reactive jobs, rechargesContractor, Contract, Component, PlannedTask, Job
complianceCompliance types, requirements, certificates, actions, building safety (Golden Thread tiers)Requirement, Certificate, Action, BuildingSafety
valuationsCIPFA asset classes, valuation programme, Red Book fields, components, audit reviewsAssetClass, Valuation, ValuationComponent, Valuer, AuditReview
projectsDevelopments, acquisitions, disposals, programmes and reviews: gateways, budget by financial year, risks, linked work, completion checklistProject, ProjectType, GatewayDecision, BudgetLine, BudgetYear, Risk, CompletionStep, ProjectAccess
documentsLetter and notice templates filled from cases, Word exportDocumentTemplate
reportsReport builder, saved reports, Excel and CSV export of any listReport
importsSpreadsheet templates and imports of properties, parties, leases, contractors and componentsnone
helpIn-app help pages written in Markdownnone
spaceOptional module: occupiers, floors, rooms and shared space, occupation, headcount, public use, building costs and how they are sharedOccupier, Space, Occupation, Headcount, UseMeasure, UseFigure, CostLine, BuildingCost, CostSharing, FixedShare

Management commands

CommandRun byDoes
daily_tasksThe scheduler container, hourlyStepped rents, lease events, reminder emails, and closing outside users' accounts whose access has ended
ocr_scansThe scheduler container, every five minutesRecognises 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 remindersSends lease event reminders that are due
import_inspire./phaema.sh import-inspire FILELoads 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.

Main records and how they link
Main records and how they link

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

Lease management and classification fields

Added in November 2026 (leases.0005, properties.0007 and properties.0008). None of them adds a table except Portfolio.

RecordFieldsUsed by
Leasetime_of_essenceLeaseEvent.time_of_essence (reviews only); events.essence_summary() for the dashboard; events list ?essence=1; My work
Leasedemands_on_hold, demands_on_hold_reasonbilling.billable_leases() leaves these out and billing.held_leases() lists them in the demand run preview; servicecharges/apportion.py skips them too
Leasebilling_contact_name, billing_email, billing_phone, billing_addressLease.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
Leasearrears_referral (debt collectors or legal), arrears_referred_on, arrears_referral_referenceArrears list tag, ?referred= filter and download
LeaseEventestimated_rental_valueReview and expiry events only (takes_erv); erv_uplift is the difference from the current rent
LeaseDocumentreview_date; document type insurancereview_rag(); events.documents_for_review(); DocumentListView at /leases/documents/; report dataset lease_documents
Propertyportfolio (to Portfolio, protected), strategy_section, purpose_review_dateRegister 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).

Agreement terms, space and costing

Added on 18 November 2026 (migrations leases.0006, cases.0006, core.0017, core.0018, space.0001, space.0002).

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.

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.

Site visits (site visit sheet level B)

Floor areas and IPMS (IPMS level 1, #73)

Scanned documents (OCR, #75)

Rents payable and the Finance menu (#76)

Cases in a project (#76)

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.

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

Personal display settings

Each setting is a link that stores a cookie, so it works without JavaScript and follows the user on that browser.

SettingURLCookieOptions
Text size/text-size/<size>/phaema_text_sizeSmaller, Standard, Large, Largest
Colour theme/theme/<theme>/phaema_themeStandard, Dark, High contrast, Match my device
Style (skin)/style/<skin>/phaema_skinClassic, Clear (Atkinson Hyperlegible), Compact
Dashboard/?view=mine or estatephaema_dashboardMy work, Estate

JavaScript

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:

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

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).

RoleCan seeCan change
Administrators (and superusers)EverythingEverything, including users, imports and settings
SurveyorsEverythingProperties they manage, with their photos, leases, components, planned tasks, compliance records and jobs; new properties they add; shared contact details
ContributorsEverythingNotes, documents and correspondence on cases they are added to
ViewersEverythingNothing
Signed in with no roleHelp and open data onlyNothing

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

Web protections

Set at the web server, not in PHAEMA

These should be configured on the reverse proxy in front of PHAEMA (see Deployment):

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

ItemMinimum for a test installSuggested for one council in production
Processor2 cores (x86-64 or ARM64)4 cores
Memory4 GB8 GB
Disk10 GB50 GB plus document storage, on encrypted disks
SoftwareDocker Engine with Compose v2, Git, BashThe same, on a supported Linux (Ubuntu 24.04 LTS or Debian 12)
NetworkNone beyond the machineHTTPS 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

ServiceImageDoes
dbdocker/db (PostgreSQL 17 + PostGIS 3)Holds all data in the db-data volume
webDockerfile (Python 3.12)Runs migrations on start, then Gunicorn on port 8000, bound to 127.0.0.1 only
schedulerSame image as webRuns daily_tasks every hour and ocr_scans every five minutes

Uploaded files live in the media volume, shared by web and scheduler.

First install

  1. Install Docker and Git (on a Mac: Homebrew, Colima and Docker, as in docs/setup-mac.md).

  2. git clone https://github.com/phaema/phaema-app.git && cd phaema-app

  3. cp .env.example .env and edit it (below). Never commit .env.

  4. ./phaema.sh start — builds the images and waits until /health/ answers.

  5. ./phaema.sh admin — creates the first superuser.

  6. Sign in, open Manage data, Module settings, and switch on the modules the council uses.

  7. Optionally ./phaema.sh demo-data to load the fictional demonstration estate.

Environment variables

VariableDefaultSet it to
SECRET_KEYa development valueA long random string, unique to each install. Required in production
DB_PASSWORDphaema-localA strong database password
DEBUGFalseAlways False outside development
SECURE_COOKIESFalse in ComposeTrue whenever PHAEMA is reached over HTTPS
ALLOWED_HOSTSlocalhost,127.0.0.1The host names users type, comma separated
PHAEMA_ORGANISATION_NAMEDemonstration CouncilThe council's name for the header
PHAEMA_BASE_URLhttp://localhost:8000The public address, used in email links
EMAIL_HOST, EMAIL_PORT, EMAIL_HOST_USER, EMAIL_HOST_PASSWORDblank, 587The council's SMTP relay. Blank writes emails to the log instead
PHAEMA_NOTIFY_API_KEY, PHAEMA_NOTIFY_TEMPLATE_IDblankGOV.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_MINUTESFalse, 30Tenant 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_MINUTES60How long a forgotten-password link works, in minutes
PHAEMA_SSO_ISSUERblankAddress 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_LANGUAGESengTesseract languages for reading scans, joined with +. A Welsh council can use eng+cym (both are in the Docker image)
PHAEMA_OCR_MAX_PAGES500Scans 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_IDblankThe application (client) ID the sign-in service gave PHAEMA
PHAEMA_SSO_CLIENT_SECRETblankThe client secret. Note its expiry date: sign-in stops when it expires
PHAEMA_SSO_NAMEMicrosoftThe name on the sign-in button: Sign in with Microsoft
DEFAULT_FROM_EMAILPHAEMA <phaema@localhost>The sender address for reminders

Three more variables matter on a server behind an HTTPS proxy:

VariableDefaultSet it to
BEHIND_HTTPS_PROXYFalseTrue when a reverse proxy ends HTTPS, so Django trusts its X-Forwarded-Proto header. Safe because web listens on localhost only
CSRF_TRUSTED_ORIGINSblankAny extra https:// addresses users reach PHAEMA by. An https:// PHAEMA_BASE_URL is trusted automatically
EMAIL_USE_TLSTrueFalse 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

CommandDoes
./phaema.sh startBuild if needed, start, wait for health check
./phaema.sh stopStop; data is kept
./phaema.sh updategit pull --ff-only, rebuild and restart (migrations run automatically)
./phaema.sh status / logsShow container state / follow logs
./phaema.sh adminCreate a superuser
./phaema.sh demo-data [--reset]Load or reload the demonstration estate
./phaema.sh import-inspire FILEImport HM Land Registry INSPIRE parcels
./phaema.sh remindersSend due reminders now
./phaema.sh backupWrite a compressed database dump to backups/
./phaema.sh reset-dataDelete 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

  1. A Linux server in a UK data centre (council-owned, or a supplier such as IONOS UK cloud).

  2. Docker and the PHAEMA stack as in Installation, with .env set for production.

  3. A reverse proxy (Caddy, nginx or the council's load balancer) that ends HTTPS and forwards to 127.0.0.1:8000. The web port is bound to localhost so it is never exposed directly.

  4. A DNS name such as phaema.example.gov.uk, added to ALLOWED_HOSTS and PHAEMA_BASE_URL.

  5. 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

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

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

AreaTest filesTests
Properties, maps, INSPIRE, open dataproperties/tests.py, test_week2.py, test_features.py38
Leases, events, parties, remindersleases/tests.py, test_week3.py, test_events_parties.py28
Cases and professional standardscases/test_cases.py, test_standards.py29
Service chargesservicecharges/test_service_charges.py16
Reports and exportsreports/test_reports.py13
Rent ledgerledger/test_ledger.py13
Roles, My work, place filterscore/test_roles.py, test_mywork.py, test_places.py14
Maintenancemaintenance/test_maintenance.py8
Importsimports/test_imports.py8
Compliancecompliance/test_compliance.py8
Valuationsvaluations/test_valuations.py7
Projectsprojects/test_projects.py20
Document templatesdocuments/test_documents.py7
Help pageshelp/test_help.py6
Space, costing, occupation on property pagesspace/tests.py, test_costs.py, test_property_views.py40
Outside userscore/test_outside_users.py10
Options and rent-free periodsleases/test_options_rent_free.py8
Estates strategy step 1properties/test_strategy.py13
Estates strategy step 2, pipeline, health checkstrategy/tests.py, strategy/test_pipeline.py, strategy/test_health.pyObjectives 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 visitscases/test_visits.pyStarting 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 areasproperties/test_ipms.pyHeadline 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.pyQueuing 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 payableleases/test_rents_payable.pyPayments following the rent schedule and rent-free periods, monthly and agreement totals agreeing, the page and Excel download, the Finance menu.
IFRS 16 data packleases/test_ifrs16.pyWhich 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 lockcore/test_security_headers.pyThe 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.
Languagescore/test_language.pyEnglish 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 tokenscore/test_api_tokens.pyKeys 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

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

ImportWhereFormat
PropertiesProperties, 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 systemImport hubExcel; matched to leases by PHC invoice number or reference
Service charge spendingImport hubExcel
Contractors and componentsImport hubExcel
Valuer's returned figuresImport hubExcel
HM Land Registry INSPIRE Index PolygonsProperties, 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

ExportFormatFor
Any list or reportExcel or CSVGeneral use; formula injection neutralised
Finance exportExcel or CSV, 21 fixed columnsInvoice 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 accountsExcel or CSVTenants, auditors
Valuation schedule, audit packExcelFinance and external audit
Letters and noticesWord (.docx)Legal and correspondence
Open data: land and assets; property availableCSV, JSON, GeoJSON at /open-data/Local Government Transparency Code publication, without sign-in
Lease event calendariCalendar feed /calendar/<token>.icsOutlook, 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

External services

ServiceUsed forNeeded?
Ordnance Survey Maps APIBase maps, with the council's OS Data Hub key (free under the Public Sector Geospatial Agreement)Optional; OpenStreetMap is used without a key
SMTP relayReminder and case emailsOptional; without it emails go to the log
HM Land RegistryINSPIRE polygons, downloaded by the councilOptional

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

Adding a feature: checklist

  1. Add or change models in the right app and run python manage.py makemigrations.

  2. Register new business models with the audit trail in the app's apps.py (audit.register(model)).

  3. Add permissions to the right roles in core/roles.py, and record-level rules to can_edit if surveyors may change it.

  4. Add views, URLs and templates using the shared partials in templates/core/.

  5. Offer Excel and CSV export for any new list (reports/export.py).

  6. Write tests, including the role rules.

  7. Update the help page in apps/help/pages/ and, if screens changed, the training course in training/course.py.

  8. Extend load_demo_data with fictional examples (ZZ postcodes, 9999 UPRNs, ZZ title numbers).

  9. Run the tests and pyflakes, then open a pull request.

Licensing

PartLicence
The applicationAGPL-3.0-or-later: anyone running a changed version as an online service must publish their changes
Connectors, client libraries, SDKsApache-2.0
Data model and schema documentationCC BY 4.0
Data councils publish through PHAEMAOpen 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

PointHow PHAEMA supports itCouncil still needs to
1. Define user needsDesigned with a chartered surveyor around estates tasks; role dashboards; test programmeRun its own user research
2. Make things accessible and inclusiveGOV.UK Frontend, WCAG 2.2 AA target, themes, text sizes, keyboard use, axe checksCommission an audit and publish an accessibility statement
3. Be open and use open sourceAGPL source on GitHub; all dependencies open sourcePublish any changes it makes
4. Make use of open standardsUPRN, British National Grid, GeoJSON, CSV, OpenAPI 3, iCalendar, .docx, .xlsxUse UPRNs in its own records
5. Use cloud firstContainerised; runs on any UK cloud or on-premisesChoose a UK host
6. Make things secureRole-based access, audit trail, secure cookies, CSRF, protected filesRun HTTPS, patching, penetration test, IT health check
7. Make privacy integralMinimal personal data (tenants' contact details); data stays in the council's own databaseComplete a DPIA and record of processing
8. Share, reuse and collaborateOne code base for every council; contributions return to allContribute back commissioned work
9. Integrate and adapt technologyREST API, documented finance export, spreadsheet importsMap the finance export once
10. Make better use of dataReport builder, exports, Transparency Code open dataPublish its open data
11. Define your purchasing strategyNo licence fee; hosting and support can be bought from any supplierProcure hosting and support competitively
12. Make your technology sustainableSmall server footprint, no client build, server-rendered pagesChoose an energy-efficient host
13. Meet the Service StandardInternal staff tool; follows GOV.UK patternsDecide whether a service assessment applies
Duty or standardPHAEMA's part
Public Sector Bodies Accessibility Regulations 2018WCAG 2.2 AA target and accessible components; statement to be published by the council
UK GDPR and Data Protection Act 2018Role-based access, audit of every change, UK hosting, export and deletion through the admin; the council is the controller
Local Government Transparency Code 2015Land and assets dataset in CSV, JSON and GeoJSON
NCSC Cloud Security PrinciplesSupported 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 AccountingAsset classes, valuation bases and year-end schedules for finance
RICS professional standardsRed 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

SymptomLikely causeFix
"Bad Request (400)" on every pageThe host name is not in ALLOWED_HOSTSAdd it to .env, then ./phaema.sh start
Sign-in returns "Forbidden (403) CSRF verification failed" behind HTTPSThe proxy setting is off, so Django sees plain HTTP and the browser's https:// origin does not matchSet BEHIND_HTTPS_PROXY=True and an https:// PHAEMA_BASE_URL, then ./phaema.sh start
Sign-in works over HTTP but the session is lostSECURE_COOKIES=True without HTTPSUse HTTPS, or False only for local tests
"Waiting for PHAEMA to start" never finishesDatabase still starting, or a migration failed./phaema.sh logs, look for the error in web
docker: command not found or cannot connect on a MacColima not runningcolima start
Port 8000 already in useAnother program on 8000Stop it, or change the left-hand port in docker-compose.yml
Reminder emails never arriveEMAIL_HOST blank, so emails go to the logSet the SMTP variables; check scheduler logs
Demo data shows old countsOld code still running./phaema.sh update, then ./phaema.sh demo-data --reset
"Missing staticfiles manifest" outside Docker with DEBUG=FalseNo collectstatic manifestRun python manage.py collectstatic, or use DEBUG=True for the development server
Map shows OpenStreetMap, not OSNo OS key in Module settingsEnter the council's OS Data Hub key

Known issues to fix before production

IssueEffectPlanned fix
No limit on repeated sign-in attemptsPassword guessing is not slowedRate-limit at the proxy now; add in-app throttling later
Single sign-on not yet proved on a live council tenantIt is tested against a stand-in sign-in service only; a council's own conditional access rules have not been triedTry 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 SharePointOn the roadmap: an optional connectors module on open standards, off by default
No tagged releasesNo version numbers or security support periods (SECURITY.md now gives the security contact and response times)Publish with the first release
No formal accessibility auditStatement cannot yet be publishedCommission 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

AddressPurpose
/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.