Case building¶
The Case shell is the per-matter workspace: documents and their OCR text,
highlights, the timeline of facts, witnesses, labels, and
search inside the matter. It is one Django app, apps/case, with one
sub-package per tab, plus apps/search (the sidebar search across
matters). The
AI tab is documented on its own pages; this page only links to them.
Where the code is¶
| Path | What it holds |
|---|---|
apps/case/views.py, apps/case/urls.py |
The shell: tab switching, matter selection, every case: route |
apps/case/tabs.py, apps/case/registrations.py |
The tab registry, and what the case app registers at start-up: its tabs, its semantic-index kinds, its matter lookups |
apps/case/services.py |
The public surface the apps above the case builder import from (with models.py); see Module boundaries |
apps/case/semantic.py |
The semantic index: chunking, embedding, the kind registry, save-time re-indexing, semantic_entries() |
apps/case/models.py |
Label, Document, Highlight, Fact, Witness |
apps/case/documents/ |
Documents tab, upload, duplicate detection, mbox import, OCR task, viewer |
apps/drive/ |
Migrations only: the shell that drops the removed Drive mirror's tables and, after it, the removed Files integration's (see Google Drive is removed and The AI chat is retired) |
apps/case/highlights/ |
Highlights tab and the viewer's highlight endpoints |
apps/case/facts/, apps/case/witnesses/ |
Timeline and Witnesses tabs, the Timeline PDF |
apps/case/labels/ |
Labels tab and the apply-labels modal used by every tab |
apps/case/search/, apps/case/search_config.py |
Search inside a matter; watson registration |
apps/search/ |
The sidebar search across matters, contacts and intakes |
apps/accounts/middleware.py, apps/accounts/access.py |
Matter membership enforced from the URL |
templates/case/ |
One folder per tab; viewer.html is a standalone page |
static/pdfjs/ |
pdf.js, installed by scripts/update_pdfjs.py; web/viewer.html is customised |
Data model¶
Every model carries AuditMixin (created_by, updated_by, timestamps)
and simple_history. Importance is one scale everywhere, 1 (Lowest) to 7
(Highest), 4 by default; apps/case/highlights/importance.py is the one
definition and parse_importance() the one parser.
Document:matter(CASCADE),category(Correspondence, Discovery, Evidence, Record),proceeding(SET_NULL),file,labels, the OCR fields (ocr_status,ocr_text,page_count,ocr_pages_done),search_vector,importance,ai_context(auto, always, never),summaryand the fingerprints (content_hash,page_fingerprint).save()runsfull_clean(), enforces the proceeding rule and fingerprints a file that has no hash yet. History excludesocr_textandsearch_vector: a status-only save was snapshotting megabytes of text per write.Label:matternullable; null means a global label. Unique on (matter,name).Highlight: on adocument, withpage_numberandcoordinates(PDF rectangles). Six colours,labels,witnesses.Fact:matter,date,time,description(150 characters), optional rowcolor,documentsandhighlightsas sources,labels.Witness:matter, contact fields,alignment(friendly, neutral, hostile),knowledge.
The proceeding rule lives in Document.save(): a document with a
proceeding is Record unless it is Discovery. Every path that writes
category and proceeding together respects it (the row menus refuse with a
toast, the form clears the proceeding), but a bulk update() bypasses
save() and must keep the pair consistent itself.
How it works¶
Switching it off¶
The case file is a firm-wide feature an administrator switches under
Settings > Features (Firm.case_file_enabled, read through
apps/settings/features/__init__.py). Off, PermissionMiddleware
answers 404 under /case/ (less the MCP API under /case/api/); the
sidebar and the matter header's cross-link read the same switch.
Nothing is deleted.
The shell¶
The case file is one of the two sides of a matter (the other is the
record under /matters/<id>/); Case in the sidebar opens /case/,
which reopens the last matter on its last tab, and the matter header
links each side to the other. Inside, case-nav.html is the tab bar;
each tab link GETs case:tab-content into .detail-body and pushes the
tab's own index URL. views.tab_content stores the tab in the session
(set_last_tab, keyed by matter) and _get_case_tab_data() calls the
tab's registered data function, which the tab's own index and list
views also call, so a full page load and an HTMX swap build the same
context.
The tabs are a registry, apps/case/tabs.py. Each Tab names its index
and list URLs, its template, its data function, its order, whether this
server and user can open it (available) and whether the nav lists it
(listed, defaulting to available), and the wrapper id and HTMX
trigger its list answers to. The case app registers its own tabs in
apps/case/registrations.py, and the Emails tab by apps/mail/apps.py
(available once Google sign-in is set up or the matter holds synced
emails). tab_available(user, tab, matter_id) is the registry's answer,
so a remembered tab that has gone falls back to Documents, and the Case
Law tab is listed only while AI is off (see
AI is optional). The nav is rendered by
the case_tabs template tag (apps/case/templatetags/case_tags.py).
case-content.html and case-tab-content.html include tab-wrapper.html,
which wraps the tab in a div that re-fetches its list on a *Changed event from body
(documentsChanged, highlightsChanged, and so on); mutating views
answer 204 with that HX-Trigger rather than rendering. Filters, sort
keys, pagination and multi-select state all live in the session under
matter-scoped keys from get_session_key() (see
Session state).
Documents¶
documents_add accepts .pdf and .mbox only. For a PDF it fingerprints
the upload (fingerprint.py: SHA-256 of the bytes, and for PDFs a digest
of the page content streams and XObject data that ignores metadata), looks
for matches across every matter the user may see, and renders the form
back with the matches once; a second Submit with duplicate_ok uploads
anyway. The save is two-phase (row first, for the primary key the storage
path needs), then _file_under_chosen_matter() honours the form's Matter
field, _drop_other_matters_labels() strips another matter's labels, and
OCR is queued. An .mbox goes through mbox.py: parse_mbox_file()
reads the first message, generate_email_pdf() renders
templates/case/documents/email_pdf.html with WeasyPrint through a URL
fetcher that only allows the template's own font hosts, and the document's
date and description come from the email.
documents_edit takes a replacement file and a change of matter; a
move copies the file to the new matter's path. Bulk actions read the
selection from the session and pass it through _selected_on_matter(),
which keeps only ids on the matter in the URL, because the membership
check covered that matter and not the selection. bulk_documents_matter
resolves the target through target_matter_for_user() because the target
arrives in the POST body.
download_document serves the file as an attachment under the document's
name (date-prefixed for Record documents); serve_document streams it
inline for the viewer, so the browser never needs the storage bucket's
origin. access.py holds open_matters_for_user(), the choice list for
the Matter field: the user's Open matters plus the record's own matter
whatever its status, because a select with no blank choice would otherwise
move the record on Submit.
OCR¶
tasks.process_document_ocr (Django-Q, group ocr_processing) reads the
file, extracts any text layer with pypdf, and if that is over
TEXT_THRESHOLD (500 characters) stores it with status extracted.
Otherwise it runs ocrmypdf with force_ocr=True, replaces the stored
file with the OCR'd PDF, and stores the result as completed. A
progress-bar plugin (ocr_progress.DatabaseProgressBar) writes
ocr_pages_done so the badge can show pages. Afterwards the search vector
is set from the first 900k characters (Postgres rejects a tsvector input
over 1MB) and, when ai_enabled(), generate_document_summary is queued. Failures set failed
and ocr_error; retry_ocr re-queues a failed document, accept_ocr
promotes extracted to completed, and force_ocr re-runs with
force=True for a document whose text layer was wrong. The badge
(templates/case/documents/ocr-badge.html) re-fetches itself with HTMX
while the status is pending or processing.
The viewer¶
document_viewer renders templates/case/viewer.html: a standalone page
with pdf.js in an iframe (static/pdfjs/web/viewer.html, loading
case:serve) and a highlights sidebar. The two halves talk by
postMessage (viewerReady, selectionChanged, scrollToHighlight,
setHighlights); a new highlight POSTs to add_highlight and the card is
built client-side. scripts/update_pdfjs.py installs a pdf.js release
from npm into static/pdfjs/ and preserves the customised
web/viewer.html across the update; web/viewer-custom.css is not
touched either. Highlights reach the page's script through
json_for_script(), which escapes what HTML would read, because a
highlight's text is whatever was selected in a PDF from outside the firm.
Highlights¶
A highlight is made in one of the two viewers. The Highlights tab
(get_highlights_data) lists both kinds for the matter, filters by
document, witness, keyword, importance and source type, and sorts by a
key validated with with_valid_sort(). highlight_link is the View
Source menu item: it redirects to the document viewer at the page and
highlight, or to the case-law viewer. HighlightForm shows
paragraph_number for document highlights and page_number for case-law
ones; Highlight.citation builds a Bluebook-style cite from either.
edit_highlight answers JSON when called with ?context=viewer and an
HX-Trigger otherwise.
Timeline and witnesses¶
get_facts_data orders by date, time by default and accepts the sort
keys of FactsFilter, through sorting.py: filterset_sort_keys()
derives the legal keys from the filter's order_by field,
stored_sort_key() reads the session key or falls back, and
with_valid_sort() drops a stale key so the rest of the filter still
applies. The same three functions serve highlights, witnesses and saved
cases. Facts link to documents and highlights as sources;
facts/access.py (source_for_fact, label_for_matter) rejects a
source or label posted from another matter. Bulk operations follow the
session selection pattern (toggle_fact_select, select_all_facts over
the visible list, bulk_facts_*). facts_pdf prints exactly what is on
screen: generate_facts_pdf() takes the filtered, sorted list and a
filter_summary from describe_facts_filter() so a partial timeline
says so. Witnesses mirror the pattern and additionally link to highlights
through the apply-witnesses modal.
Labels¶
A label is global (matter null) or the matter's own. _labels_for() in
apps/case/labels/views.py is the one definition of what may go on a
matter's material: the global labels plus that matter's. The apply modal
and add_label_to resolve the posted label id through it, so another
matter's label cannot be attached; remove_label_from resolves through
obj.labels so a leftover label can always be taken off. On a move
between matters (_drop_other_matters_labels()) the leaving matter's
labels stay behind and global labels
travel with the document.
Search¶
Search inside a matter (apps/case/search/views.py) is hybrid:
watson.search(query) over the whole index (the case models are
registered in apps/case/search_config.py), keeping the document,
highlight and fact hits on this matter, then meaning matches from
the pgvector index (apps/case/semantic.py, semantic_entries())
appended and marked semantic (none without a Gemini key, which the
embeddings need). The importance
filter means "at least this important", as on the other tabs. The sidebar
search (apps/search/)
runs watson over matters, contacts and intakes with synonym
expansion, matches proceedings by normalised case number, and shows only
matters the user may open; apps/search/api.py exposes the same search to
the MCP server.
Background work¶
| Task | Queued by | On failure |
|---|---|---|
apps.case.documents.tasks.process_document_ocr |
upload, file replacement, mbox import, retry and force | ocr_status="failed", ocr_error set, badge offers retry |
apps.case.documents.tasks.generate_document_summary |
the OCR task, only with AI configured | logged, document keeps no summary |
The post_save signal in apps/case/documents/signals.py also queues OCR
on a document created with its file in the first save. Schedules are
listed in the schedules reference.
Access¶
Everything under /case/ passes PermissionMiddleware.process_view,
which resolves every id in the URL (matter, document, highlight, fact,
witness, label, and the object_type/object_id pairs of the
label and witness modals) to a matter through MATTER_LOOKUPS in
apps/accounts/access.py and refuses a user who is not a member of all of
them. The tab views therefore carry only @login_required (the shell
views in views.py that take a matter id also carry
@matter_access_required). What the URL
cannot see is checked in the app: a matter in a form or POST body
(documents/access.py), a source or label id in a body
(facts/access.py, labels/views.py), and lists that would reach across
matters (documents_for_user() on the duplicate warning). The
matrix is in the permissions reference.
Things that bite¶
- A new kind of id in a
/case/route needs a line inMATTER_LOOKUPS. Without it the middleware has nothing to check and the view is open to any signed-in user. Document.save()is the only place the proceeding rule runs.queryset.update()skips it (andfull_clean()and history). Write category and proceeding together.- Fingerprints describe the uploaded bytes, not the stored file. OCR
replaces the file with the OCR'd PDF but leaves
content_hashalone, so a re-upload of the original still matches. A path that replaces bytes on purpose must clear the hash or callset_fingerprints(). - The OCR signal never sees a two-phase upload. The first save has no
file, so the signal marks it
not_applicable; the view must queue OCR itself after the file save, asdocuments_adddoes. watson.search()in the matter search is not scoped. It searches the whole index and the view filters by matter afterwards; a big index makes every matter search cost the same.- Sort keys from the session reach
order_by(). A stored key the list does not know would 500 every load; usesorting.pyfor any new sortable list.
Related¶
- Guide: Documents, Timeline, witnesses and highlights
- Admin: Storage
- Subsystems: Matters, AI context, Drafts, Email and intakes (the Emails tab), MCP (the case JSON API), Operations
- Conventions: HTMX and Alpine, Session state