CONFIDENTIAL · ArrAI internal · MedR client review · not for distribution outside ArrAI
MedR · Knowledge Transfer · Deck 1 of 3

System Architecture

How the MedR referral platform is actually built, as read from the code on dev-v-2-0. Every claim on this page is traceable to a file and line. Where the written documentation and the code disagree, the code is what is shown here.

Branch dev-v-2-0 HEAD 2132e624 · 5 Aug 2026 Django 5.2.3 + DRF + Celery React 18 + Vite (design export) AWS eu-west-2

00The system in one paragraph

MedR is a UK private-practice referral network. A verified practitioner searches a directory of other practitioners by speciality, insurer and geographic distance, attaches a patient record and clinical history, and sends a referral. The receiving practitioner accepts, rejects, books, or marks did-not-attend. Both sides — plus optional delegate staff acting on a practitioner's behalf — are notified in-app and by email. It is a Django REST API with a React single-page app in front, run as four Docker containers on a single EC2 instance per environment.

96
Routed API endpoints
3
Django apps
540
Backend tests — all green
0
Emails that reach an inbox

Endpoint count from the Endpoint enum registries in users/endpoints.py, referral/endpoints.py, system/endpoints.py. Test result from an executed run of the suite: 539 passed, 1 skipped, 540 collected.

One structural fact that governs everything else

The React frontend described in the repository's own CLAUDE.md — three npm workspaces named medr-components, medr-logic-lib, medr-ui, with an API client generated from the OpenAPI schema — no longer exists. It was deleted on 22 April 2026 in commit ad09a47b ("DELET OLD FRONTEND DIRS", 984 files, 139,192 deletions), together with the entire Cypress end-to-end suite.

The live frontend is _design_frontend_export/MedR Clinical Dashboard 12 03 2026/ — an export from a design tool, first committed 13 March 2026, and developed in place ever since (192 commits). Dockerfile.frontend builds the production image directly from that folder. This is not a mock-up sitting beside the real app; it is the app.

01Environment topology

Two fully separate environments on the client's AWS account (381491949502, eu-west-2). Deliberately plain: EC2 and Docker Compose, no Lambda, no edge, no managed container service.

CLIENT / BROWSER Practitionerbrowser DNS Route 53medr.co.uk zone DEMO ( = STAGING ) ALBACM · HTTPS Target grp EC2 · docker compose nginx :80 frontend :3000 backend :8000 redis :6379 SQLite file (in container) S3 (demo bucket) Basic auth demo / demo123 covers SPA only — /api/ and /medr/ are open PRODUCTION EC2 · docker compose nginx :80 frontend :3000 backend :8000 redis :6379 RDS Postgres S3 (prod bucket) No load balancer today — root A record points straight at EC2. ALB being built in parallel; DNS swaps over for v2. apex → EC2 THIRD PARTY Mailjet Slack webhooks Google geocoding Jawg map tiles
Verified against docker-compose.demo.yml, nginx/conf.d/*, scripts/constants.sh, and the client's recorded infrastructure walkthrough of 31 Aug 2026.
The demo box's API and Django admin are not behind the demo password

In nginx/conf.d/demo/default.conf the basic-auth directives are declared at server level on line 60, after the location blocks. /api/ (line 41) and /medr/ — the Django admin login — (line 51) both carry auth_basic off. Only the SPA shell at / is gated.

Verified live, and worse than it reads: the demo backend also runs with DEBUG = True, so a 404 through that unauthenticated path returns Django's debug page listing all 105 URL patterns.

A likely typo in the production nginx server name

nginx/conf.d/medr/default.conf:55 reads server_name medr.co.uk, www.medr.co.uk;. nginx separates server names with spaces, not commas, so the first token becomes the literal string medr.co.uk, and matches nothing — the apex domain would fall through to the default server block, which serves the API rather than the app. Worth a live check rather than a code change.

02Runtime — what a request actually touches

BrowserSPA bundle nginxCONFIG_ENV frontend :3000 static build, nginx try_files → index.html backend :8000 gunicorn · Django 5.2 Knox token auth drf-spectacular / /api/ /medr/ DatabaseSQLite | RDS PG S3static · media · private redis :6379celery broker celery worker — ABSENT commented out of both compose files nothing drains the queue Mailjet · Slack · Google · Jawg outbound HTTPS from backend SHARED DOCKER VOLUMES backend-staticfiles · backend-mediafiles backend writes → nginx serves backend-logs the dummy mailer writes here
Four containers per environment. Redis runs; the consumer that would drain it does not.
ContainerImage / buildPortsPresent in devPresent in demo/prodNotes
nginxDockerfile.nginx80, 443yesyes (ECR :latest)Config chosen by CONFIG_ENV. Nothing in the repo listens on 443.
frontendDockerfile.frontend3000yesyes (ECR :latest)Builds the design export; npm ci --legacy-peer-deps.
backendDockerfile.backend8000yesyes (ECR :latest)Migrations run in the entrypoint on start.
redisredis:7-alpine—yesyesBroker only when ENV_TYPE is STAGING or PRODUCTION.
postgrespostgres:16-alpine—yesabsentDemo/prod DB comes from the server's own .env.
celery worker——commented outcommented outCommand reads -A base; the app is named backend.
celery beat——commented outcommented outNeeds django_celery_beat, which is not a dependency. Nothing schedules periodic work, so beat is not required.

03Backend layering

Three Django apps and a consistent four-layer call path. Understanding this one path explains most of the codebase, because every referral action follows it.

1 View MedrBaseAPIView subclass permission check resolve acting practitioner 2 Service referral/services/ orchestrates side effects fans out notifications 3 Manager models/*/manager.py wraps in audit_context resolves target profile 4 Model Referral.accept_referral() status guard authorisation guard SIDE EFFECTS FIRED BY THE SERVICE LAYER ReferralEventclinical timeline row EventNotificationin-app bell, per recipient Slack taskops channel ping Mailjet task ×3referrer · target · patient — never delivered CROSS-CUTTING AuditLog via audit_context one row per operation, success or failure APILoggingMiddleware method · path · status per request Knox token auth 14-day TTL · auto-refresh · unlimited per user
The four-layer path in referral/services/full_referral.py → referral/models/referral/manager.py → referral/models/referral/model.py.

users

Identity, practitioners, delegates, reference data

UserProfile · ClinicianRoleProfile · DelegateUserLink · Address · ClinicCenter · ClinicianContact · FavouriteClinician · InsuranceAgreement · JobRole · NotificationsSettings · VerificationCode · EventNotification

57 migrations

referral

The clinical workflow

Patient · Referral · ReferralEvent. Also holds the referral service layer and the whole analytics query surface.

28 migrations

system

Cross-cutting platform concerns

AuditLog · HelpRequest · EmailSent. Plus the Mailjet service, the Slack service, and the two Celery tasks.

9 migrations

Two auth facts worth holding onto

Almost nothing uses the DRF default permission

MedrBaseAPIView sets permission_classes = [IsVerifiedClinicianOrDelegate]. Since nearly every view inherits it and few override, that — not the project-wide IsAuthenticated — is the real gate. A user must be authenticated, have a UserProfile, be isVerified, and sit in the Clinician or Delegate group.

A delegate is transparently swapped for their practitioner

get_clinician_user_profile() returns the delegate's own profile for audit attribution, but substitutes the linked practitioner's profile for every data query. So a delegate reads and writes the practitioner's referrals and patients without any special-casing downstream. The link is one delegate to exactly one practitioner.

04Domain model

Userdjango.contrib.auth UserProfileisVerifiedregistrationNumber 1:1 ClinicianRoleProfilepractitioner @ clinic 1:N ClinicCenterclinic / practice FK Addresslat / lon geocoded FK JobRole= speciality M2M DelegateUserLink5 permission flags ×2 FK InsuranceAgreement M2M NotificationsSettings EventNotificationin-app bell Referral status · urgencyLevel createdOn · acceptedOn completedOn · dnaOn referrer FK targetClinician FK jobRole FK Patient no login · no account primaryEmail FK ReferralEventCREATED · ACCEPTED · … 1:N Address AuditLogevery audited operation VerificationCodeemail links · 1 day TTL EmailSentmessage_id · status table is always empty HelpRequest
Every model in users and referral extends a shared BaseModel providing update_from_dict() and a recursive __repr__. A referral points at ClinicianRoleProfiles, not user profiles — it targets a practitioner at a specific practice.

05Referral state machine

Five stored statuses. Transitions are guarded in the model: the caller must be the target practitioner and must still hold the referral's speciality, or the action raises.

PENDINGon create ACCEPTED REJECTED BOOKED completed DNA did not attend accept reject accept (re-open) reject book dna dna book Guards on every transition: · current status must be allowed · caller must be the target practitioner · caller must still hold the speciality Referrer-side rules: · edit / delete only while PENDING · the referrer cannot drive any transition Nothing ever returns to PENDING.
Each transition also writes a ReferralEvent, an EventNotification per recipient, one Slack message, and three Mailjet tasks.

06The email pipeline — and where it breaks

There is exactly one outbound email mechanism. Django's own mail framework is never used. Every email event builds a dataclass, hands it to a Celery task, and the task calls Mailjet with a template ID and a variables dictionary. The email bodies themselves live in Mailjet, not in this repository.

Trigger referral created, accepted, booked… Input dataclass recipient, patient, referrer, target, host Celery .delay() eager in dev, queued in prod send_medr_email real sender OR dummy log-only sender Mailjet v3.1 TemplateID + Variables Recipient inbox clinician / delegate / patient 1 No worker exists Worker + beat commented out of both compose files. In production mode tasks queue to Redis and nothing ever consumes them. The worker command also reads -A base, which is the wrong app. 2 Master switch is off Sending is enabled only when ENV_TYPE is STAGING or PRODUCTION. Every env file in the repo says DEVELOPMENT, so the dummy sender runs and only writes to the log. 3 18 of 24 template IDs are placeholders Literal integers 1–18 stand in for every referral email and both delegate emails. Only 6 real Mailjet templates exist. 4 Wrong recipient All ten practitioner-facing referral emails overwrite the address with the patient's. Turning sending on today would mail clinician notifications to patients. This must be fixed before, not after, the switch is flipped.
Four independent break points. Fixing any one of them alone still delivers nothing, or delivers to the wrong person.
Verified: practitioner referral emails are addressed to the patient

All ten *ReferrerInput and *TargetInput classes in backend/system/services/email/emails.py contain the identical line self.receivers = EmailUserInfo(Name=self.patient_name, Email=self.patient_email) inside get_email_variables() — at lines 407, 440, 509, 542, 611, 644, 713, 746, 815 and 848. The caller in full_referral.py correctly passes the clinician's own recipient_email; the value is then discarded.

Net effect if sending were switched on as-is: the patient receives three differently-templated emails per referral event, each carrying the other parties' names, roles, email addresses and phone numbers. The practitioners receive nothing. Independently re-derived from source and confirmed.

Email familyDispatch siteTemplate IDState
Clinician verify emailusers/models/userprofile/manager.py8075893real
Clinician add-clinic promptusers/models/userprofile/manager.py8077177real
Password reset requestusers/models/userprofile/manager.py8077202real
Password updatedusers/models/userprofile/manager.py8077228real
Invite a practitionerusers/views/views_crp.py8114519real
Help requestsystem/models/helprequest.py8114565real
Delegate verify emailusers/models/delegateuserlink/manager.py1placeholder
Delegate registration completeusers/models/delegateuserlink/manager.py2placeholder
Staff error notificationsystem/views/views_requests.py3placeholder
Referral created — referrer / target / patientreferral/services/full_referral.py4, 5, 6placeholder
Referral accepted — referrer / target / patientreferral/services/full_referral.py7, 8, 9placeholder
Referral rejected — referrer / target / patientreferral/services/full_referral.py10, 11, 12placeholder
Referral booked — referrer / target / patientreferral/services/full_referral.py13, 14, 15placeholder
Did not attend — referrer / target / patientreferral/services/full_referral.py16, 17, 18placeholder

24 members in MedrEmailTemplates. 6 real, 18 placeholder. Counted mechanically and cross-checked against EMAILS_KEY, which the service asserts is the same length at start-up.

Three further gaps in the same pipeline

Links in referral emails go nowhere

All ten practitioner dispatch sites pass host="", producing the bare fragment ?type=referral&referral_id=42 instead of a URL. The five patient templates carry no link variable at all. An EMAIL_LINK_BASE_DOMAIN variable exists in the env files and is read by no Python code.

Every referral subject line is the same

All fifteen read You have been referred by {referrer_name} — including the rejection, the booking confirmation and the did-not-attend notice.

No delivery tracking of any kind

The EmailSent model, its migration and a full status-transition manager all exist, but no code ever creates a row. Mailjet's returned message IDs are discarded, there is no inbound webhook, and the de-duplication guard that reads this table is therefore a permanent no-op.

07How a change reaches production today

Merge requestGitLab, reviewedvia Anshul GitLab CIlint · type-checktest · build Build scriptmanual, from a laptoptags + pushes to ECR Deploy scriptscp compose + .envthen ssh On the EC2 boxECR login · prunepull · up -d Livemigrations run inthe entrypoint CI does not deploy. There is no deploy stage, no environments, no rules and no manual jobs in .gitlab-ci.yml. Everything from the build step onward is run by hand by whoever holds the AWS credentials and the .pem key. Rollback = redeploy a tag.
The client is separately building CI/CD on their side: demo auto-deploy on merge to a development branch, production on merging development into main, both branches protected. That is not in this repository yet.

08Where the written documentation disagrees with the code

This matters for the handover: anyone onboarding from the docs alone will build a wrong mental model. Every row below was checked against the files.

The documentation saysThe code saysWhere
Frontend is frontend/, three npm workspaces, API client generated from OpenAPIDeleted in April 2026. The frontend is a design-tool export with a hand-written axios client and no codegen script.commit ad09a47b; Dockerfile.frontend
Django 4.2Django 5.2.3backend/pyproject.toml
Backend lint is ruffblack. ruff is not a dependency at all.pyproject.toml poe tasks
CI stages are fetch-secrets → lint → type-check → testlint → type-check → test → build. No fetch-secrets stage..gitlab-ci.yml
A deploy/ directory holds compose files and certsDoes not exist. Compose files sit at the repo root; deploy scripts under scripts/deploy/.repo root
scripts/build_docker_containers.sh, scripts/deploy_application.shReal names are build-docker-containers.sh and deploy-demo-version.sh. There is no deploy_application.sh.scripts/
Vite dev server proxies /api to the backendNo proxy is configured. The SPA calls the API base URL directly.vite.config.ts
poetry poe serve starts an HTTPS dev serverPlain runserver over HTTP on port 8000.pyproject.toml