Data model
ContentsVision stores everything in a single SQLite database (storage/inventory.db) through SQLAlchemy 2's async ORM. The models live in backend/app/models/. This page is the reference for every table and relationship.
Entity relationships
The parent-child links inside a claim (Room.claim_id, ProcessingJob.room_id, InventoryItem.job_id, ItemPhoto.item_id, StagedPhoto.job_id) are real SQLAlchemy ForeignKey columns. The ownership links team_id (on users and claims) and Claim.created_by_user_id are plain indexed strings, not database-level foreign keys. Team scoping is enforced in the application layer, not by the database.
Tables
teams
The organization. Auto-created on first login from the SSO token.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at | datetime | |
external_id | int, nullable | The AdjustSquare team id. |
name | string | Team display name. |
team_token | string, indexed | The team's Adjust Square API token, used as the bearer token when submitting claims. |
contents_estimation_key | string | The team's Contents Estimation intake key (cek_...), captured from the SSO JWT like team_token. Makes the Contents Estimation send per-team. See Contents Estimation authentication. |
credit_rate | float, nullable | Dollars of revenue per credit, for the media-processing Slack notification. NULL (the default) means use the global DEFAULT_TEAM_CREDIT_RATE. |
organization_id / business_unit_id | string, indexed | Where the team sits in the configuration hierarchy ("" = not placed). See configuration and access. |
users
A person. Auto-provisioned on first login.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at | datetime | |
external_id | string, nullable, unique, indexed | The identity-provider user id: a Contents Estimation UUID, or a legacy Adjust Square integer stored as text. It becomes the adjuster id on submission when it is numeric. Databases created before the column was text still have it as INTEGER (ALTER TABLE users ADD COLUMN external_id INTEGER). Those values are read back as text (ExternalUserId in models/user.py), so a numeric id cannot fail a string response field. Team ids stay integers (teams.external_id). |
email | string, unique, indexed | |
name | string | |
team_id | string, indexed | The owning team's id. |
is_active | bool | Defaults to true and nothing sets it false. Not read at sign-in. Whether a person may open ContentsVision at all is product_access, not this. |
last_seen_at | datetime, nullable, indexed | When the user last made an authenticated request. Stamped by get_current_user (at most once a minute per user); powers the admin "Active Users (live)" stat. |
timezone | string | IANA zone picked on Settings > Profile ("" = browser local). Display preference only; storage stays UTC. |
product_access
One person's product access on one ContentsEstimation team, as pushed by ContentsEstimation on an Enterprise deployment (models/product_access.py). See product access. Empty on every SMB deployment. Only the push routes write it.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
ce_team_id | string, indexed | ContentsEstimation's team UUID. Unique together with email. |
ce_user_id | string, indexed | ContentsEstimation's user UUID (what users.external_id holds for a person who signed in through it). |
ce_team_legacy_id | int, nullable, indexed | The integer team id this app knows (teams.external_id). NULL when the push did not carry it: the record then applies on any team the person signs in on. |
email | string, indexed | Lower case. There is deliberately no link to users: a record can exist before the person has ever signed in. |
enterprise | bool | False for an SMB person: stored, never enforced, never shown. |
active | bool | The whole account. False refuses the person. |
capture_app, capture_admin, vision, estimation | bool | The four switches. vision false refuses the person; the others only shape the product switcher. |
url_estimation, url_vision, url_capture_admin | string | That deployment's own addresses, which the switcher links to. "" when none was sent. |
version | int | Only ever increases for a person and team. A push that is not newer is ignored. |
updated_at | datetime | When ContentsEstimation last changed the record (UTC). |
received_at | datetime | When this app stored it (UTC). |
component_visibility
Admin-controlled show/hide overrides for UI components (currently training). One row per override; resolution is team override > global override (team_id="") > the registry default in services/component_visibility.py (training defaults to HIDDEN). See GET /api/admin/components and the admin Teams tab.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
updated_at | datetime | |
component | string, indexed | Key from the component registry, e.g. training. |
team_id | string, indexed | "" = the global row; otherwise the team this override applies to. |
visible | bool |
claims
The top-level unit of work.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at / updated_at | datetime | created_at indexed. |
claim_number | string, indexed | |
date_of_loss | date | |
zip_code | string | The loss site's US ZIP (10001) or Canadian postal code (M5V 3L9). One field for both: the two formats cannot be confused, so app/core/postal.py tells them apart, validates, and stores the canonical form. Sent onward as zip either way. |
policy_limit / policy_deductible | float | |
insured_name / adjuster_name | string | |
loss_type / coverage_type / claim_type | string | Human-readable; mapped to Adjust Square codes on submit. |
team_id | string, indexed | Owning team. |
is_training | bool, indexed | Training sandbox flag: uploads complete instantly with fixture items (no AI, no credits) and submission is a dry run. Seeded per learner from a training module's fixture claims (the Academy's is created by the Training hub). See training. |
training_module_key / training_fixture_ref | string, default "" | For sandbox claims: the module and fixture claim ref that seeded it (scratch = the learner created it during a lesson). Blank module = an Academy claim from before modules. |
source | string, indexed, default upload | Where the claim came from: upload, contents_capture, contents_estimation or training (services/claim_source.py). Stamped where each kind of claim is created; the importer re-stamps any non-training claim it lands media in as contents_capture. Claims older than the column were backfilled once (CLAIM_SOURCE_BACKFILL_SQL, recorded as claim_source_backfill_2026_11_11 in data_migrations) from is_training, the "Created claim from ContentsEstimation" activity row and import_batches.claim_id. Drives the Dashboard's Source column. |
capture_assignment_status | string | The ContentsCapture assignment status behind the claim, as last heard from Capture: read from the assignment tree on every import, and from assignment.status_changed / assignment.archived webhook events. Blank for a claim not fed by Capture (and for Capture claims imported before the column existed, until their next import or status event). draft or active makes the computed status capturing. |
capture_status_at | datetime, nullable | When capture_assignment_status was last set. An event whose occurredAt is older is ignored, so a late redelivery cannot undo a newer status. |
created_by_user_id | string, indexed | The users.id of the member who created the claim. That user's external_id is the Adjust Square user id. |
created_by_external_name / created_by_external_email | string | For a claim auto-created from ContentsCapture whose assignment creator has no ContentsVision account: their name and email (shown as Created By, with a ContentsCapture marker). created_by_user_id then stays the connection owner as the technical owner. Blank otherwise. See ContentsCapture: who a claim is credited to. |
assigned_to_user_id / assigned_at | string, indexed / datetime | Who is working the claim now ("" = unassigned), separate from the creator. New claims start assigned to their creator (a before_insert hook); older claims were backfilled once (claim_assigned_to_backfill_2026_11_12). Changed only through POST /api/claims/assign, which writes claim_assignment_changes. |
adjust_square_claim_key | string | Set after the first submission. |
adjust_square_claim_id | int | The integer claim id on Adjust Square. |
submitted_at | datetime, nullable | |
contents_estimation_claim_key / contents_estimation_claim_id | string | The linked Contents Estimation claim, set by the first send or at birth by an import. Once set, every send appends to that claim. See Contents Estimation. |
contents_estimation_submitted_at | datetime, nullable | When the claim was first sent to Contents Estimation. |
contents_estimation_items_unlocked | bool | Admin escape hatch for a claim sent by mistake: re-opens its sent items for editing (POST /api/claims/{id}/contents-estimation-item-lock). Never cleared by a later send. |
contents_estimation_item_offset | int | For a claim imported from Contents Estimation: the highest item number that claim already held there, so numbering here continues above it. 0 otherwise. |
manual_status / manual_status_basis / manual_status_note / manual_status_by / manual_status_at | string / string / text / string / datetime | A status picked by hand (POST /api/claims/status), with the computed status it was picked against. It shows only while the computed status still equals manual_status_basis; once the claim moves on by itself they are cleared. Blank = automatic. See claim status. |
is_archived | bool, indexed | Soft-hide flag. Archived claims drop out of the default GET /api/claims list. Nothing is ever deleted by hand; archiving is the only removal path. A claim that has been submitted (submitted_at set) is locked and cannot be archived. |
archived_at | datetime, nullable | When the claim was archived (null when active). The daily purge permanently deletes anything archived more than 30 days ago; restoring clears this. |
Hierarchy, configuration, access, views, tags
Documented in full in configuration and access:
| Table | Holds |
|---|---|
organizations, business_units | The levels above teams. |
config_settings | One value of one registered key at one level (scope_type, scope_id, key, value JSON, locked, updated_by_user_id). Unique per scope and key. |
access_profiles | Custom permission profiles owned by a team or org (name, description, permissions list). |
claim_assignment_changes | Append-only history of who a claim was assigned to: from_user_id / from_user_name, to_user_id / to_user_name ("" = unassigned), note, changed_by_user_id / changed_by_name. Names are snapshotted. |
saved_views, saved_view_pins | Named grid configurations (resource, owner_user_id, scope, config JSON) and each user's pinned ones (view_id, order, optional label; max 10). Pinned views are the custom dashboards. |
tags, claim_tags | Team tags (name, case-insensitive name_key, color) and which claims carry them (claim_id, tag_id). |
claim_status_changes
Append-only history of hand-made status changes on a claim. The live override sits on the claim (manual_status).
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
claim_id | string, indexed | |
created_at | datetime, indexed | |
from_status / to_status | string | to_status is "" for a hand-back to the automatic status. |
note | text | Optional, up to 2000 characters. |
user_id / user_name | string | Who changed it. |
rooms
A labeled bucket inside a claim.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
claim_id | string, FK to claims.id, indexed | |
created_at / updated_at | datetime | |
name | string | e.g. "Master Bedroom". |
is_archived | bool, indexed | Soft-hide flag. Archived rooms drop out of the default room list and their items stop counting toward the claim. A room that contains any submitted item is locked and cannot be archived. |
archived_at | datetime, nullable | When the room was archived (null when active). Drives the 30-day purge. |
sort_order | int, nullable | The room's place in the claim's room order, lowest first, set by PUT /api/claims/{id}/rooms/order. NULL on a claim that was never reordered (rooms then list newest first). A room created on a reordered claim gets min - 1, so it lands on top. room_display_order() in models/room.py is the one ORDER BY every room list uses. |
Room photos and the room cover have no columns here. A room's scoping media is read from where the ContentsCapture import left it (services/room_media.py): staged_photos rows with intent = 'scoping' and deleted = false on the room's photo jobs, and the room's video jobs with processing_jobs.intent = 'scoping'. The cover is the first four of those photos, ordered by job (created_at, oldest first) then file name. Who captured each one and when is on the matching uploads row (meta.capturedBy, meta.capturedAt). None of it has an inventory_items row, which is why it never counts toward an item total, an export, or a send. See Room photos.
processing_jobs
One upload and its processing run.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
room_id | string, FK to rooms.id, indexed | |
source_type | string | video, photo, or audio. |
filename / file_path | string | The original file (or photos dir). |
file_size_bytes | int | |
duration_seconds | float | Drives video/audio billing. |
loss_type / claim_number | string | Copied from the claim at creation. |
notes | text | Free-text notes on the upload. |
uploaded_by | string | Who put this here, as a label to show: an adjuster's User.name, or the homeowner's email address when it arrived through their own link. Free text, because the two sources have nothing in common to key on. Blank on anything predating the column. |
origin | string, indexed | "" (the adjuster's own upload), insured_list (a list the homeowner TYPED: no file, already complete, no cost), or insured_media. The UI branches on this rather than guessing from a filename. |
status | string | pending, importing_pdf, awaiting_grouping, awaiting_confirmation, extracting, transcribing, segmenting, analyzing, synthesizing, complete, error. |
progress_pct | int | 0-100, streamed to the UI. |
current_stage | string | Human-readable current step. |
error_message | text | Set on failure. |
total_frames / rooms_detected / items_found | int | Processing metadata. |
transcript / transcript_segments / transcript_language | text / JSON / string | Transcription output. |
room_segments | JSON | Time-chunk ranges. |
completed_at | datetime, nullable | |
billed_cost_usd | float | Credits charged (name kept for backward compatibility). |
billed_blocks | float | The billing unit for video and audio: whole 20 second blocks, rounded up. |
billed_minutes | float | Clip length in whole minutes. No longer what the charge is derived from (billed_blocks is); kept so analytics on it stay comparable. |
photo_request_count | int | AI calls made (photo jobs). |
billing_charged | bool | Whether credits were spent up front against the external billing service (only when ENABLE_BILLING). false otherwise. |
billing_txn_id | string | The billing service's transaction id for the up-front spend, when one was made. |
billing_amount | float | Credits spent up front, so a refund can return the exact amount. |
billing_refunded | bool | true once the up-front charge was refunded because processing failed. |
recovery_attempts | int | How many times the self-healing sweep requeued this job after an interruption (restart, crash, hang). One retry is allowed; a second interruption fails and refunds the job. See troubleshooting. |
ai_cost_usd | float | Our internal OpenRouter spend in dollars (token counts priced at the model's per-million rates), copied from the in-memory observability counters when the job finishes. Separate from customer credit billing. Jobs predating this stay at 0. |
ai_input_tokens / ai_output_tokens / ai_api_calls | int | The token counts and AI call count behind ai_cost_usd. |
pdf_template_label | string | The recognised PDF layout, e.g. Encircle contents list. Not shown to the user; kept for the pipeline log and the support email when an import goes wrong. Blank for non-PDF jobs. |
intent | string | Capture intent of a whole-file job: scoping for a video from ContentsCapture that documents the room (never analyzed, zero credits, completes with zero items), otherwise items. Photo jobs stay items; their intent is per photo on staged_photos.intent. |
groups_may_hold_several_items | bool | Whether a multi-photo group may hold several items rather than several angles of one. Set on the grouping screen and defaulted on for a PDF import; picks which prompt each multi-photo group is analyzed with. |
photo_truncated_groups | JSON | Photo groups whose answer ran out of room, so items in them were never read. One entry per group: {"group_index", "passes", "found": [names]}. passes counts the AI calls that group has had (capped at PHOTO_MAX_PASSES); found is what has been read out of it, sent back on the next pass so only what is missing comes back. Empty on nearly every job. See the AI pipeline. |
job_log_archives
The durable copy of a job's pipeline log lines. While a job runs its logs live in the in-memory ring buffer (see observability); when the job reaches complete or error the buffer is copied here so the detail survives restarts and stays readable on the Logs page. One row per job, upserted.
| Column | Type | Notes |
|---|---|---|
job_id | string, FK to processing_jobs.id | Primary key. |
created_at | datetime | |
logs | JSON | The full list of structured log entries (ts, level, msg, stage, elapsed). |
submissions
One "Send for Estimation" event for a claim (a claim can be submitted several times; later submissions add the new items to the same Adjust Square claim).
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key; shown as the submission id in the UI. |
claim_id | string, indexed | |
created_at | datetime | |
items_count / photos_count | int | What the submission carried. |
adjust_square_claim_key | string | The portal claim it landed on. |
is_resubmit | bool | False for the claim-creating first submission. |
is_dry_run | bool | Training claims: recorded, sent nowhere. |
status | string | processing while background item/photo uploads run, then complete. |
processing_seconds | float | End to end: request start to background finish. |
api_request_logs
One outbound AI API call (OpenRouter), for the admin "API Requests" inspector on the Logs page. The request JSON is stored with base64 images redacted to size placeholders; the response is stored in full.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at | datetime, indexed | |
job_id | string, indexed | Derived from the per-job pipeline logger. |
service / method / url / model | string | openrouter, POST, the endpoint, and the model id. |
status_code / duration_ms / attempts | int / float / int | Final outcome and total time across retries. |
input_tokens / output_tokens / cost_usd | int / int / float | From the response usage block (OpenRouter reports real cost). |
request_json / response_json | JSON | Redacted request; full response. |
error | text | Set when the call ultimately failed. |
model_examples
One photo the vision model was shown, and the item it answered with. Kept so a self-hosted model can be trained from real claims. Written when the photo pipeline saves an AI item. Not written for a training claim, an item the user named by hand (no AI call), or a marked-photo placeholder the model did not identify. A claim on the Adjust Square account is written too, at the lowest rank: nobody reviews those claims, but the answer came from a frontier model and is still a useful example. That account is a team named Adjust Square (including "Adjust Square (Local Dev)"), or a team whose users all have an @adjustsquare.com email. A customer team that also has a staff user stays a customer team.
The photo bytes are copied to storage/model-examples/photos/<sha256>.<ext>, outside the job folder, so the 30-day archive purge does not delete them. The row is not foreign-keyed to the item: deleting the claim does not delete the example. api_request_logs redacts the image and is not tied to one item, and the activity log only keeps its newest 500 rows, so neither table is the training set by itself.
Older photo items can be compiled once with backend/scripts/backfill_model_examples.py, then picked up by the pending export. It keeps an item only when the photo file is still in the job folder. The label is the item as it stands now. When the API log's answer matches that item on its own, that answer is the prediction. Otherwise the prediction is a copy of the label and the row carries prediction_unrecovered. A file that is only the later crop (item_####.jpg) is kept and marked crop_only. Claims whose folder the archive purge already deleted cannot be rebuilt. Video and audio items are not included. An item that already has an example is left alone.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at / updated_at | datetime, indexed | updated_at moves when the label, quality, or superseded flag changes. An export does not move it. |
item_id | string, unique | The inventory item. Kept after the item is deleted. |
job_id / team_id / claim_id | string | Where it came from. |
model | string | The OpenRouter model id at the time of the call. |
prompt_kind | string | photo_unmerged, photo_merged, photo_group_multi, photo_segment, or photo_marked. |
continuation | bool | True when the item came from a "read the rest" pass. |
photos | JSON | The images that were sent, in order. Each entry is {sha256, file}. file is the name under the photo store. A marked photo stores the original and the copy with the marks drawn on it. |
prediction | JSON | The model's answer, frozen. Includes item_name, quantity, brand, model_number, serial_number, notes, condition, damage_type, visual_evidence, confidence, and the room the photo was filed under. |
label | JSON | The answer we currently trust. Starts as a copy of the prediction. |
quality | string, indexed | high, standard, or unchecked. |
signals | JSON | Sorted list. customer_edit when a customer changed a detail. customer_sent when a customer sent the item to Contents Estimation. |
edited_by_user_id / edited_at | string / datetime | The customer edit that last raised it. |
sent_by_user_id / sent_at | string / datetime | The customer send. |
superseded | bool, indexed | True once the item was merged into another. The example is no longer a standalone item. |
exported_at | datetime, nullable, indexed | Set when an export included the row. Cleared when the row changes, so the next pending export picks it up. |
high means a user who is not on the admin allowlist and whose email is not @adjustsquare.com either edited a detail (item_name, quantity, brand, model_number, serial_number, sku, notes, condition, damage_type, age_years, age_months) or sent the item to Contents Estimation. The label is then what they left it as. Moving a room, approving for Adjust Square, and an auto-approve do not raise it. A staff edit does not raise it and does not change the label. An admin impersonating a customer is authenticated as that customer, so the edit counts as the customer's.
standard is a customer claim left as the model wrote it. Still exported. Less certain than high.
unchecked is a claim on the Adjust Square account. Nobody reviewed it. Still exported, at rank 0, and weighted lowest. The answer is from a frontier model, which is ahead of the open source model being trained.
Export is GET /api/admin/model-examples/export or backend/scripts/export_model_examples.py. The zip is examples.jsonl (one example per line, rank 2 then 1 then 0), manifest.json, and photos/. Each line's claim is a one-way code for its claim (falls back to the job), so training can hold whole claims back for its test without the export naming a claim. --claim-map writes {example id: {claim, prediction}} for every row instead: the claim code and the model's original answer (no labels, no photos, nothing stamped). Rank 0 is an Adjust Square account example: keep it. A merged-away row has superseded true and a null rank: skip it. The nightly run is --pending, which stamps exported_at: see Nightly model training.
inventory_items
A single line of the inventory.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
job_id | string, FK to processing_jobs.id, indexed | |
source_type | string | Copied from the job, except an item typed in by hand (add_item, add_room_item): that is always form, whatever job it sits on. The tables show it as a FORM badge. A startup backfill relabels older items on Added by hand (origin="manual") jobs. "Add item from this photo" is form too (since 2026-10-20; the one-time photo_added_items_form_2026_10_20 migration relabelled earlier ones, found through their add_item activity entries). The tables show four tags only: PHOTO, VIDEO, AUDIO, FORM (a narrated video item is just VIDEO). |
uploaded_by | string | Copied from the job for the same reason source_type is. An item an adjuster types by hand carries THEIR name, even when the job around it came from the homeowner. |
item_name | string | Searchable retail-style name. |
quantity | int | Identical items are grouped. |
room | string | Room name (denormalized for convenience). |
condition | string | New / Above Average / Average / Below Average. |
age_years / age_months | int | Set by the AI only from a spoken age (video narration, audio). Always 0 from photos, and never estimated from appearance. |
notes | text | |
brand / model_number / serial_number / sku | string | |
damage_type | string | smoke / water / heat / impact / mold. |
estimated_value | float | |
confidence | float | 0.0-1.0. |
audio_evidence / visual_evidence | text | What was said / what was seen. |
audio_start_seconds / audio_end_seconds | float | The recording slice (audio items). |
photo_path / crop_photo_path / photo_context_path / source_photo_path | string | Legacy photo columns, kept as a safety net. |
photo_frame_time | float | Timestamp in the video. |
photo_frames | text (JSON) | All analyzed frame URLs. |
reviewed / flagged / approved | bool | Human review state. |
mark_numbers | string | JSON list of the numbers of the specialist's marks this item was found at ([2], or [1, 4] for identical items sharing one entry). Blank unless found through an include mark. |
marked_photo_path | string | URL of the copy of the source photo with the specialist's marks drawn on it. Set on every item from a marked photo and on items a desk user adds from one. Blank otherwise. |
outside_marks | bool | A desk user added this item from a marked photo. Review labels it "Outside the specialist's marks". |
partly_in_frame | bool | The AI said the item is cut off by the edge of its photo with less than about half visible, and the team's edge items setting was flag. Saved together with flagged = true; review shows "Partly visible, confirm" while the item is flagged and not approved. Kept afterwards as the record of why. |
is_archived | bool, indexed | Soft-hide flag. Archived items drop out of the inventory lists, counts, exports, and Adjust Square submission, but keep their item_number (no renumbering on archive) so unarchiving restores the exact slot. Submitted items cannot be archived. Archiving is the only way to remove an item; there is no manual delete. |
archived_at | datetime, nullable | When the item was archived (null when active). Drives the 30-day purge. |
sort_order | int | |
item_number | int, indexed | Unique per claim. On a claim imported from Contents Estimation it starts above Claim.contents_estimation_item_offset (that claim's highest number there). |
submitted | bool, indexed | Sent to Adjust Square. |
adjust_square_item_id | int | Remote item id after submission. |
photo_uploaded_at | datetime, nullable | When the item's photo landed on Adjust Square. NULL on a submitted item means its photo is still pending (or failed); drives photo-upload-status and the retry. |
contents_estimation_sent_at | datetime, nullable | When the item was sent to Contents Estimation; never cleared. A send offers and charges only items without it, and it is what freezes the item. Separate from submitted (the Adjust Square lock). |
photos | relationship | The item_photos rows (source of truth for images). |
item_photos
Photos attached to a finished item. The source of truth for item imagery (the legacy photo_path columns on the item are kept for compatibility).
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
item_id | string, FK to inventory_items.id, CASCADE delete, indexed | |
path / crop_path / context_path | string | |
is_primary | bool | The primary thumbnail. Setting it via PUT /api/inventory/item/{id}/photos/{photo_id} demotes every other photo on the item AND copies the photo onto InventoryItem.photo_path, which is what the inventory table and the export actually read. ItemPhotosModal is the user-facing way to set it. Guided Review's frame pick sets it too, through photo_path on PUT /api/inventory/item/{id}. |
photo_order | int | "order" is reserved in SQL, hence the name. |
staged_photos
Raw uploaded photos waiting to be grouped before AI runs.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
job_id | string, FK to processing_jobs.id, CASCADE delete, indexed | |
filename | string | File on disk under <storage>/<job_id>/photos/ (a synthetic orig_####.jpg sequence, or pdf_####.jpg for a photo pulled out of a PDF, so the two can never overwrite each other). |
original_filename | string | The photo's real upload name (e.g. IMG_1234.jpg). The on-disk filename is synthetic, so this is the only record of the real name; grouping's "Sort by name" re-orders on it. Blank for manual segments and for rows created before the column existed. |
captured_at | string | When the photo was taken (YYYY-MM-DDTHH:MM:SS), read from EXIF in the browser at upload (the re-encode strips EXIF, so it must be captured before then); falls back to the file's modified time. Powers grouping's "Sort by date". Blank when unknown and for manual segments. |
group_index | int, indexed | Photos sharing a group become one item. Manual segments use a high range (>= 1_000_000) so they never collide with photo groups. |
photo_order | int | |
deleted | bool, indexed | Soft-delete; file removed on Process. |
is_segment | bool | True for a crop the user drew from a parent photo during grouping (a known item the AI never re-splits). |
quantity | int | User-set quantity for a described or segment item (e.g. 4 for four boxed rolls of tape). 1 by default. |
manual_name | string | User-typed name for the item (a whole photo / merged group, or a segment). When set, the AI is skipped for it (no request, no credits). Blank means the AI names it. |
source_filename | string | The whole photo a segment was cropped from, so "clear segments" can restore it. |
bbox | string | JSON [x, y, w, h] (normalized) of the box on the source photo, kept for re-editing. |
source_description | text | For a photo imported from a PDF: the note printed beside it, lifted verbatim off the page (e.g. Charred barber products). Kept exactly as printed, however poor, because it is the source record. It is never the item's name: it is passed to the AI as a hint when the photo is analyzed, and saved onto the finished item's notes. Blank otherwise. |
source_room | string | For a PDF import: the room heading the photo was printed under. A claim-level import uses it to pick the room's job. Blank otherwise. |
source_item_key | string | The vendor's own label on the page (Item 42). Photos printed under ONE label are one item, so they are staged sharing a group_index and arrive already merged. Blank otherwise. |
intent | string | Capture intent from ContentsCapture: items (the default, and the value for every photo from any other source) or scoping. A scoping photo documents the room: the pipeline never sends it to the AI, it costs no credit, and its row and file stay on the job as a room photo. See capture intent. |
marks | text | JSON text of the pins and boxes the field specialist drew on the photo in ContentsCapture, as sent. Blank for none, and blank while the photo's intent is scoping. Read by the photo pipeline for a lone photo: include marks return only marked items, exclude marks remove what is in them. See marked photos. |
pdf_templates
One learned recipe for reading a vendor's PDF page layout, so the AI is asked once per FORMAT rather than once per file. Deliberately global, not team-scoped: these rows hold layout rules only (coordinates, regexes), never claim content, so the first upload of a new format teaches the whole app. signature_json keeps the page furniture lines the fingerprint was built from, so a vendor that prints the insured's name in that furniture (which changes the hash per claim) is still recognised by a near match rather than re-learned. See PDF import.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
fingerprint | string, unique, indexed | Hash of the layout signature: the lines repeating on most pages with digits masked, plus page size and producing application. Stable across two exports from the same tool, distinct between vendors. |
label | string | The model's human name for the format, e.g. Encircle contents list. Shown to the user. |
recipe_json | text | The recipe. Always re-validated through Recipe.from_dict() before use: a stored recipe is data, never code, and a bad one degrades rather than raising. |
source | string | ai when the model wrote it, builtin for one we ship. |
created_by_team_id | string | The team whose upload first taught us this format. Kept for support; not used to scope lookups. |
signature_json | text | The page furniture lines behind the fingerprint, compared when the hash misses so a near match still reuses the recipe. Blank on rows learned before it existed. |
use_count / last_photo_count / last_used_at | int / int / datetime | How often the recipe has been reused and how well it did last time. A recipe that keeps finding nothing is the signal to re-derive it. |
activity_log
One row per meaningful action, powering the Settings activity log and its Restore button. Covered in observability.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at | datetime, indexed | |
user_id / user_name | string | Who did it. |
team_id | string, indexed | The team the action belongs to. The log and Restore are team-scoped. |
action_type | string | Machine code the restore logic dispatches on. |
action_label / target | string | Human-readable text. |
entity_type / entity_id | string | What was acted on. |
snapshot | JSON, nullable | Everything needed to undo the action. |
restorable / restored / restored_at | bool / bool / datetime | Restore state. |
training_progress
One row per user per training module lesson; the source of truth for points, badges (lesson complete = badge earned), and whether a module is passed. See training.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at / updated_at | datetime | |
user_id / team_id | string, indexed | Who is training, and their team (for the leaderboard). |
module_key | string, indexed, default academy | The module the row belongs to. Rows from before modules are the Academy's. |
mission_key | string, indexed | The lesson key within the module, e.g. messy-claim (historical column name). |
module_version | int, default 0 | Module version the lesson was completed against (0 = before versioning). |
status | string | in_progress or complete. |
quiz_score / quiz_total / quiz_attempts | int | Best quiz result and attempt count. |
checks_passed | JSON | Check keys that passed on the latest grading run. |
check_attempts | int | |
points | int | Banked once at completion: mission base + quiz bonus. |
completed_at | datetime, nullable |
training_modules
The training module library: one row per version of a custom or imported module. Builtin modules ship as JSON in backend/app/training_modules/ and are not stored here unless edited. See training.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
created_at | datetime | |
key | string, indexed | Module slug. The highest non-archived version is live. |
version | int | Assigned by the server on save; never reused. |
title | string | Copied from the document for listings. |
source | string | custom (builder) or imported (JSON file). |
team_id | string, indexed | Owning team, "" for the shared library. |
created_by_user_id | string | |
document | JSON | The full validated cv.training.module document. |
is_archived | bool | Archived versions are ignored (archiving a builtin's edits reverts it). |
training_certificates
Issued certifications, publicly verifiable by code. See training.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
code | string, unique, indexed | Shareable verification code, e.g. CV-3F9A-C24D-71BE. |
user_id / team_id | string, indexed | |
holder_name / team_name | string | Snapshotted at issue time so the public page stays stable. |
level | string | Certified Contents Specialist. |
score_pct / points | int | Overall quiz accuracy and total points at issue time. |
issued_at | datetime | |
revoked | bool | Invalidates the certificate while keeping the code resolvable. |
insured_links
One invitation sent to the INSURED (the homeowner), letting them build their own inventory for exactly one claim through a public link. See Insured inventory link.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
claim_id | string, FK to claims.id, CASCADE delete, indexed | The one claim this link can reach. Checked on every public request. |
team_id / created_by_user_id | string, indexed | Denormalised from the claim so the adjuster-side ownership check is one query. |
token_hash | string, unique, indexed | SHA-256 of the raw token. The raw token is never stored, so a database leak yields no working links. It exists only in the emailed URL. |
insured_email | string, indexed | The address the adjuster sent it to. |
insured_name | string | What the person typed on arrival. Neither this nor the email is a gate: whoever holds the link may use it. Both exist so the record shows who entered the inventory. |
expires_at | datetime, indexed | INSURED_LINK_TTL_DAYS from creation (30 by default). |
revoked_at | datetime, nullable | Manual kill switch. Bites on the holder's next request. |
email_status | string | Furthest state Mailgun reported: "", not_configured, failed, sent, delivered, opened, clicked. |
email_message_id | string, indexed | Mailgun's message id. |
email_error | text | Why a send or delivery failed, shown to the adjuster. |
email_sent_at / email_delivered_at / email_opened_at / email_clicked_at | datetime, nullable | From the Mailgun webhook. An email "open" fires on a tracking pixel that Apple Mail loads regardless of whether a human looked, so treat it as weak evidence. |
send_count | int | How many times it was sent. A resend rotates token_hash, so the earlier email's URL stops working. |
link_first_opened_at / link_last_opened_at / open_count | datetime, int | Measured on our own server when the page is fetched. This is the signal worth trusting, unlike an email open. |
started_at | datetime, nullable | First time they entered anything. |
submitted_at | datetime, nullable | When they pressed Submit. A submitted link becomes read-only. |
submitted_item_count / submitted_photo_count / submitted_video_count | int | What the submit produced. |
uploaded_bytes | int | Lifetime total across every request, enforced against INSURED_LINK_MAX_TOTAL_MB. Deleting an upload does not credit it back, so upload-then-delete cannot push unlimited bytes. |
status is a derived property (revoked / submitted / expired / in_progress / opened / sent), not a column.
insured_draft_rooms
A room the HOMEOWNER added, before submit. The adjuster sets up the rooms they know about; the homeowner knows their own home and can add the loft, the shed, the spare room nobody mentioned.
These are drafts rather than real rooms because adding one is a single tap and abandoning it costs nothing, so creating a Room on the spot would fill the adjuster's claim with empty rooms somebody typed and thought better of. A drafted room reaches the claim at the same moment its contents do: on submit, and only if it has contents to bring.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. Draft rows point at this in their room_id until submit. |
link_id | string, FK to insured_links.id, CASCADE delete, indexed | |
name | string | Matched case-insensitively against the claim's rooms at submit, so a "Garage" the adjuster made meanwhile is adopted rather than duplicated. |
position | int | Order the homeowner added them in. |
room_id | string, indexed | The rooms.id it became. Blank while still a draft. A materialised draft room is never listed again: the real room is on the claim by then. |
insured_draft_items
One typed row in the homeowner's table: a draft until a submit sends it, then kept in place, locked. Every column maps onto an InventoryItem field, which is where the row lands.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
link_id | string, FK to insured_links.id, CASCADE delete, indexed | |
room_id | string, indexed | Either a real rooms.id (a room the adjuster set up) or an insured_draft_rooms.id (one the homeowner added). Submit resolves the second into the first and rewrites this column. |
position | int | Order within the room; drives the "Item No." the homeowner sees. The real claim-unique item_number is assigned at submit. |
item_name | string | Title. The only required text field, and only at submit. |
quantity | int | Positive integer, minimum 1. |
brand / model_number / notes | string / text | Optional. |
estimated_value | float | Non-negative. |
age_years / age_months | int | Non-negative. Months of 12 or more are folded into years (18 months becomes 1 year 6 months). |
first_saved_at | datetime, nullable | Set once, the first time a save leaves the row non-blank; the submission history shows it as when the item was added. Separate from created_at, which the submit backfills compare against. |
submitted_at | datetime, nullable | NULL while a draft; stamped by the submit that sent it. A link can be submitted more than once, so locking is per row: a sent row stays visible but locked, and anything added later is a fresh draft. |
insured_draft_files
One photo or video the homeowner uploaded, before submit. The bytes are written to <storage>/insured/<link_id>/ on arrival, so a flaky connection never costs a re-upload; only the row that becomes a StagedPhoto waits for submit.
| Column | Type | Notes |
|---|---|---|
id | string (UUID) | Primary key. |
link_id | string, FK to insured_links.id, CASCADE delete, indexed | |
room_id | string, indexed | |
draft_item_id | string, indexed | Set only for kind = "item_photo": the typed row it belongs to. |
kind | string | room_photo, room_video, or item_photo. |
filename | string | Synthetic name on disk. Photos are re-encoded to JPEG right after the upload replies (a background task; see batched photo upload), which strips EXIF (so a phone photo never carries the homeowner's GPS location onto the claim) after baking the EXIF orientation into the pixels (upright_rgb in services/image_encode.py), so a portrait phone photo stays upright without the tag. |
original_filename | string | What their phone called it. |
content_type / size_bytes | string / int | |
group_key | string, indexed | Photos the homeowner grouped as ONE item (different angles). Blank = on its own. At submit a group becomes a shared StagedPhoto.group_index, so it costs one AI call and comes back as one item. |
note | text | The homeowner's note about this one file ("the TV is behind the boxes on the left"). At submit it becomes StagedPhoto.source_description and reaches the AI through the same path as a PDF caption. For a video it becomes ProcessingJob.notes instead. |
position | int | |
submitted_at | datetime, nullable | As on insured_draft_items: NULL while a draft, stamped when sent. |
Media integrations (ContentsCapture)
Four tables in models/integration.py, documented in full in Contents Capture. Team scoping is a plain indexed team_id string, like claims.
| Table | Holds |
|---|---|
storage_connections | One configured provider per team (kind = contents_capture): name, status (active, disabled, error), the Capture org id (external_account_id), non-secret config, the org token (api_token; secret_ref is the upgrade path to a secret manager), last_synced_at, error_message. |
uploads | One piece of source media with provenance: connection_id, source, import_batch_id, external_media_id, storage_key, media_type, mime_type, size_bytes, sha256, local_path, meta (the capture tree snapshot), target claim_id / room_id, the job_id it became, status and imported_at. |
import_batches | One import run: connection_id (blank for a contents-list PDF import, which shares this table), assignment_id, the selection manifest, status (pending, expanding, importing, complete, partial, failed), the claim_id it landed in, counters (total_media, imported_count, skipped_count, failed_count), created_job_ids and finished_at. Polled through GET /api/integrations/imports/{batch_id}. |
capture_auto_events | The automatic-processing queue: one row per synced Capture media item waiting for its room to settle (connection_id, assignment_id, location_id, media_id, media_type, event_id, received_at). pending, then consumed (imported in batch_id) or dropped. |
How the schema is created and migrated
There is no migration tool (no Alembic). On startup, core/database.py's init_db() (serialized across the web processes and the worker by a lock file next to the database, since they all boot together):
- Calls
Base.metadata.create_allto create any missing tables. - Runs a list of idempotent
ALTER TABLE ... ADD COLUMNstatements, each wrapped in a try/except so an already-existing column is silently skipped. This is how new columns are added to existing databases. - Runs backfills. The self-limiting ones (a fixed row stops matching) run every boot: assigning sequential
item_numbers to old items per claim, repairingcrop_photo_pathfor old photo items, and seedingitem_photosrows for items that predate the multi-photo model. Any data migration that is not provably self-limiting goes through_run_once, which records its name in adata_migrationstable (name,applied_at) and never runs it again; a failure is logged and not recorded, so it retries on the next boot. Examples:claim_source_backfill_2026_11_11,claim_assigned_to_backfill_2026_11_12,photo_added_items_form_2026_10_20.
To add a column: add it to the model and append an ALTER TABLE ... ADD COLUMN line in init_db(). create_all only creates whole new tables; it never alters an existing one, so without the ALTER line the column exists in the model but not in an already-deployed database.