Skip to content

Data model

Generated at build time from 0001_init.sql 0002_search.sql 0003_email_outbox_lease.sql 0004_ticket_down_intervals.sql 0005_idempotency_keys.sql 0006_search_keyed.sql 0007_activity_message_id.sql 0008_google_contacts.sql in packages/db/migrations(45 tables) and workers/auth/migrations. Only cemco-api reads and writes the CRM database; everything else goes through operations.

Conventions

  • Ids are UUID text. Money is integer cents. Days are YYYY-MM-DD, instants are ISO 8601 UTC text.
  • Booleans are 0/1; lists are JSON text. Columns are snake_case; the API is camelCase.
  • Every foreign key has an index. Every write appends to audit_log.
  • Search uses the FTS5 table search_index, kept current by triggers.
  • A new change is a new numbered migration file. Never edit a migration that has been applied.

System: staff users

users

ColumnTypeConstraints
idTEXTPRIMARY KEY
emailTEXTNOT NULL COLLATE NOCASE UNIQUE
nameTEXTNOT NULL
roleTEXTNOT NULL DEFAULT 'viewer' CHECK (role IN ('admin', 'editor', 'viewer'))
activeINTEGERNOT NULL DEFAULT 1 CHECK (active IN (0, 1))
auth_user_idTEXTUNIQUE
last_seen_atTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Customers

accounts

ColumnTypeConstraints
idTEXTPRIMARY KEY
nameTEXTNOT NULL
normalized_nameTEXTNOT NULL
segmentTEXTNOT NULL DEFAULT 'concrete_producer' CHECK (segment IN ('concrete_producer', 'multiservice'))
statusTEXTNOT NULL DEFAULT 'active' CHECK (status IN ('active', 'prospect', 'inactive'))
phoneTEXT
websiteTEXT
hq_line1TEXT
hq_line2TEXT
hq_cityTEXT
hq_stateTEXT
hq_postal_codeTEXT
hq_countryTEXT
hubspot_company_idTEXTUNIQUE
owner_user_idTEXTreferences users.id ON DELETE SET NULL
notesTEXT
last_contacted_atTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_accounts_normalized_name (normalized_name) idx_accounts_owner (owner_user_id) idx_accounts_status (status) idx_accounts_last_contacted (last_contacted_at)

contacts

ColumnTypeConstraints
idTEXTPRIMARY KEY
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
first_nameTEXTNOT NULL
last_nameTEXTNOT NULL DEFAULT ''
roleTEXT
emailTEXTCOLLATE NOCASE
mobileTEXT
phoneTEXT
preferred_channelTEXTNOT NULL DEFAULT 'email' CHECK (preferred_channel IN ('email', 'phone', 'text'))
is_primaryINTEGERNOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1))
hubspot_contact_idTEXTUNIQUE
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_contacts_account (account_id) unique idx_contacts_email_unique (email) WHERE email IS NOT NULL

sites

ColumnTypeConstraints
idTEXTPRIMARY KEY
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
nameTEXTNOT NULL
line1TEXT
line2TEXT
cityTEXT
stateTEXT
postal_codeTEXT
countryTEXTDEFAULT 'US'
latitudeREAL
longitudeREAL
power_sourceTEXT
water_sourceTEXT
active_fromTEXT
active_toTEXT
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_sites_account (account_id) idx_sites_state (state)

site_readiness

ColumnTypeConstraints
site_idTEXTreferences sites.id NOT NULL ON DELETE CASCADE
itemTEXTNOT NULL CHECK (item IN ('pad', 'power', 'water', 'access', 'aggregate_supply'))
confirmedINTEGERNOT NULL DEFAULT 0 CHECK (confirmed IN (0, 1))
confirmed_onTEXT
confirmed_by_user_idTEXTreferences users.id ON DELETE SET NULL
confirmed_by_nameTEXT
noteTEXT
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Table constraints: PRIMARY KEY (site_id, item)

Indexes: idx_site_readiness_user (confirmed_by_user_id)

Products (equipment price list)

products

ColumnTypeConstraints
idTEXTPRIMARY KEY
skuTEXTNOT NULL UNIQUE
nameTEXTNOT NULL
categoryTEXTNOT NULL CHECK (category IN ('plant', 'mixer', 'accessory', 'option'))
modelTEXT
machine_typeTEXTCHECK (machine_type IS NULL OR machine_type IN ('plant', 'mixer', 'silo', 'feeder', 'power_pack'))
descriptionTEXT
price_centsINTEGERNOT NULL CHECK (price_cents >= 0)
price_listTEXTNOT NULL DEFAULT '2026.11'
activeINTEGERNOT NULL DEFAULT 1 CHECK (active IN (0, 1))
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_products_category (category)

Documents (bytes live in R2 bucket cemco-documents)

documents

ColumnTypeConstraints
idTEXTPRIMARY KEY
kindTEXTNOT NULL CHECK (kind IN ('signed_quote', 'quote', 'purchase_order', 'drawing', 'manual', 'inspection_report', 'photo', 'training_record', 'invoice', 'email_attachment', 'export', 'other'))
titleTEXTNOT NULL
filenameTEXTNOT NULL
content_typeTEXTNOT NULL DEFAULT 'application/octet-stream'
size_bytesINTEGERNOT NULL DEFAULT 0
statusTEXTNOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'stored'))
r2_keyTEXTNOT NULL UNIQUE
sha256TEXT
account_idTEXTreferences accounts.id ON DELETE SET NULL
customer_visibleINTEGERNOT NULL DEFAULT 0 CHECK (customer_visible IN (0, 1))
sourceTEXTNOT NULL DEFAULT 'upload' CHECK (source IN ('upload', 'email', 'portal', 'system', 'import'))
uploaded_by_user_idTEXT
uploaded_by_nameTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_documents_account (account_id) idx_documents_kind (kind)

ColumnTypeConstraints
document_idTEXTreferences documents.id NOT NULL ON DELETE CASCADE
entity_typeTEXTNOT NULL
entity_idTEXTNOT NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Table constraints: PRIMARY KEY (document_id, entity_type, entity_id)

Indexes: idx_document_links_entity (entity_type, entity_id)

Orders

orders

ColumnTypeConstraints
idTEXTPRIMARY KEY
order_numberTEXTNOT NULL UNIQUE
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
site_idTEXTreferences sites.id ON DELETE SET NULL
titleTEXT
stageTEXTNOT NULL DEFAULT 'received' CHECK (stage IN ('received', 'in_build', 'ready_to_ship', 'shipped', 'delivered', 'set_up', 'commissioned', 'trained', 'closed'))
signed_quote_document_idTEXTreferences documents.id ON DELETE SET NULL
signed_quote_received_onTEXT
total_centsINTEGERNOT NULL DEFAULT 0 CHECK (total_cents >= 0)
balance_remaining_centsINTEGERCHECK (balance_remaining_cents IS NULL OR balance_remaining_cents >= 0)
is_validINTEGERGENERATED ALWAYS AS ( signed_quote_document_id IS NOT NULL AND signed_quote_received_on IS NOT NULL AND balance_remaining_cents IS NOT NULL ) STORED
financing_partnerTEXTNOT NULL DEFAULT 'none' CHECK (financing_partner IN ('none', 'commercial_capital', 'northland_capital', 'other'))
financing_statusTEXTNOT NULL DEFAULT 'not_applicable' CHECK (financing_status IN ('not_applicable', 'pending', 'approved', 'declined', 'funded'))
financing_notesTEXT
po_numberTEXT
expected_ship_onTEXT
owner_user_idTEXTreferences users.id ON DELETE SET NULL
notesTEXT
received_onTEXT
in_build_onTEXT
ready_to_ship_onTEXT
shipped_onTEXT
delivered_onTEXT
set_up_onTEXT
commissioned_onTEXT
trained_onTEXT
closed_onTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Table constraints: CHECK (stage = 'received' OR (signed_quote_document_id IS NOT NULL AND signed_quote_received_on IS NOT NULL AND balance_remaining_cents IS NOT NULL))

Indexes: idx_orders_account (account_id) idx_orders_site (site_id) idx_orders_stage (stage) idx_orders_signed_quote (signed_quote_document_id) idx_orders_owner (owner_user_id) idx_orders_valid (is_valid)

order_lines

ColumnTypeConstraints
idTEXTPRIMARY KEY
order_idTEXTreferences orders.id NOT NULL ON DELETE CASCADE
product_idTEXTreferences products.id ON DELETE SET NULL
skuTEXT
descriptionTEXTNOT NULL
quantityINTEGERNOT NULL DEFAULT 1 CHECK (quantity >= 1)
unit_price_centsINTEGERNOT NULL DEFAULT 0 CHECK (unit_price_cents >= 0)
total_centsINTEGERNOT NULL DEFAULT 0 CHECK (total_cents >= 0)
positionINTEGERNOT NULL DEFAULT 0
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_order_lines_order (order_id) idx_order_lines_product (product_id)

order_events

ColumnTypeConstraints
idTEXTPRIMARY KEY
order_idTEXTreferences orders.id NOT NULL ON DELETE CASCADE
from_stageTEXT
to_stageTEXTNOT NULL
occurred_onTEXTNOT NULL
noteTEXT
actor_user_idTEXT
actor_nameTEXTNOT NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_order_events_order (order_id)

Installed base

machines

ColumnTypeConstraints
idTEXTPRIMARY KEY
serial_numberTEXTNOT NULL UNIQUE
serial_normalizedTEXTNOT NULL
typeTEXTNOT NULL CHECK (type IN ('plant', 'mixer', 'silo', 'feeder', 'power_pack'))
modelTEXTNOT NULL
configurationTEXT
optionsTEXTNOT NULL DEFAULT '[]'
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
site_idTEXTreferences sites.id ON DELETE SET NULL
order_idTEXTreferences orders.id ON DELETE SET NULL
product_idTEXTreferences products.id ON DELETE SET NULL
statusTEXTNOT NULL DEFAULT 'in_build' CHECK (status IN ('in_build', 'in_transit', 'operating', 'down', 'idle', 'retired'))
built_onTEXT
shipped_onTEXT
commissioned_onTEXT
warranty_startTEXT
warranty_endTEXT
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_machines_serial_normalized (serial_normalized) idx_machines_account (account_id) idx_machines_site (site_id) idx_machines_order (order_id) idx_machines_product (product_id) idx_machines_status (status) idx_machines_warranty_end (warranty_end)

machine_locations

ColumnTypeConstraints
idTEXTPRIMARY KEY
machine_idTEXTreferences machines.id NOT NULL ON DELETE CASCADE
site_idTEXTreferences sites.id NOT NULL ON DELETE CASCADE
moved_in_onTEXTNOT NULL
moved_out_onTEXT
noteTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_machine_locations_machine (machine_id) idx_machine_locations_site (site_id)

machine_owners

ColumnTypeConstraints
idTEXTPRIMARY KEY
machine_idTEXTreferences machines.id NOT NULL ON DELETE CASCADE
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
from_dateTEXTNOT NULL
to_dateTEXT
noteTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_machine_owners_machine (machine_id) idx_machine_owners_account (account_id)

service_plans

ColumnTypeConstraints
idTEXTPRIMARY KEY
machine_idTEXTreferences machines.id NOT NULL ON DELETE CASCADE
nameTEXTNOT NULL
interval_daysINTEGERNOT NULL CHECK (interval_days >= 1)
last_done_onTEXT
next_due_onTEXTNOT NULL
recommended_part_idsTEXTNOT NULL DEFAULT '[]'
notesTEXT
activeINTEGERNOT NULL DEFAULT 1 CHECK (active IN (0, 1))
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_service_plans_machine (machine_id) idx_service_plans_next_due (next_due_on)

service_contracts

ColumnTypeConstraints
idTEXTPRIMARY KEY
machine_idTEXTreferences machines.id NOT NULL ON DELETE CASCADE
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
plan_nameTEXTNOT NULL
starts_onTEXTNOT NULL
renews_onTEXTNOT NULL
price_centsINTEGERNOT NULL DEFAULT 0 CHECK (price_cents >= 0)
statusTEXTNOT NULL DEFAULT 'active' CHECK (status IN ('active', 'expired', 'cancelled'))
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_service_contracts_machine (machine_id) idx_service_contracts_account (account_id) idx_service_contracts_renews (renews_on)

training_records

ColumnTypeConstraints
idTEXTPRIMARY KEY
machine_idTEXTreferences machines.id NOT NULL ON DELETE CASCADE
order_idTEXTreferences orders.id ON DELETE SET NULL
set_up_onTEXT
first_batch_onTEXT
trained_onTEXTNOT NULL
trainer_nameTEXTNOT NULL
traineesTEXTNOT NULL DEFAULT '[]'
topicsTEXT
punch_listTEXTNOT NULL DEFAULT '[]'
customer_signoff_nameTEXT
customer_signed_onTEXT
signoff_document_idTEXTreferences documents.id ON DELETE SET NULL
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_training_records_machine (machine_id) idx_training_records_order (order_id) idx_training_records_document (signoff_document_id)

Tasks (before check-ins, which point at them)

tasks

ColumnTypeConstraints
idTEXTPRIMARY KEY
typeTEXTNOT NULL DEFAULT 'task' CHECK (type IN ('task', 'call', 'visit', 'delivery', 'commissioning', 'service', 'check_in'))
titleTEXTNOT NULL
notesTEXT
statusTEXTNOT NULL DEFAULT 'open' CHECK (status IN ('open', 'done', 'cancelled'))
due_onTEXTNOT NULL
starts_atTEXT
ends_atTEXT
locationTEXT
assigned_to_user_idTEXTreferences users.id ON DELETE SET NULL
account_idTEXTreferences accounts.id ON DELETE CASCADE
contact_idTEXTreferences contacts.id ON DELETE SET NULL
order_idTEXTreferences orders.id ON DELETE SET NULL
machine_idTEXTreferences machines.id ON DELETE SET NULL
ticket_idTEXT
site_idTEXTreferences sites.id ON DELETE SET NULL
check_in_idTEXT
google_event_idTEXT
google_calendar_idTEXT
sync_stateTEXTNOT NULL DEFAULT 'pending' CHECK (sync_state IN ('not_synced', 'pending', 'synced', 'error'))
synced_atTEXT
sync_errorTEXT
completed_atTEXT
created_by_user_idTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_tasks_assigned (assigned_to_user_id) idx_tasks_account (account_id) idx_tasks_contact (contact_id) idx_tasks_order (order_id) idx_tasks_machine (machine_id) idx_tasks_ticket (ticket_id) idx_tasks_site (site_id) idx_tasks_check_in (check_in_id) idx_tasks_due (status, due_on) idx_tasks_sync (sync_state) unique idx_tasks_google_event (google_event_id) WHERE google_event_id IS NOT NULL

calendar_tombstones

Google events to remove after a synced task was deleted.

ColumnTypeConstraints
idTEXTPRIMARY KEY
task_idTEXTNOT NULL
google_event_idTEXTNOT NULL
google_calendar_idTEXT
assigned_to_user_idTEXTreferences users.id ON DELETE SET NULL
titleTEXT
deleted_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_calendar_tombstones_user (assigned_to_user_id)

check_ins

ColumnTypeConstraints
idTEXTPRIMARY KEY
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
machine_idTEXTreferences machines.id ON DELETE CASCADE
order_idTEXTreferences orders.id ON DELETE SET NULL
kindTEXTNOT NULL CHECK (kind IN ('day_30', 'day_90', 'day_365', 'pre_season', 'ad_hoc'))
due_onTEXTNOT NULL
statusTEXTNOT NULL DEFAULT 'scheduled' CHECK (status IN ('scheduled', 'completed', 'skipped'))
completed_onTEXT
outcomeTEXT
task_idTEXTreferences tasks.id ON DELETE SET NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_check_ins_account (account_id) idx_check_ins_machine (machine_id) idx_check_ins_order (order_id) idx_check_ins_task (task_id) idx_check_ins_due (status, due_on) unique idx_check_ins_auto_unique (order_id, machine_id, kind) WHERE kind IN ('day_30', 'day_90', 'day_365') AND order_id IS NOT NULL AND machine_id IS NOT NULL

Parts and stock

parts

ColumnTypeConstraints
idTEXTPRIMARY KEY
part_numberTEXTNOT NULL UNIQUE COLLATE NOCASE
descriptionTEXTNOT NULL
categoryTEXT
unitTEXTNOT NULL DEFAULT 'each'
price_centsINTEGERNOT NULL DEFAULT 0 CHECK (price_cents >= 0)
price_list_dateTEXTNOT NULL
fits_modelsTEXTNOT NULL DEFAULT '[]'
on_handINTEGERNOT NULL DEFAULT 0
reorder_pointINTEGERNOT NULL DEFAULT 0 CHECK (reorder_point >= 0)
reorder_quantityINTEGERNOT NULL DEFAULT 0 CHECK (reorder_quantity >= 0)
bin_locationTEXT
recommended_spareINTEGERNOT NULL DEFAULT 0 CHECK (recommended_spare IN (0, 1))
activeINTEGERNOT NULL DEFAULT 1 CHECK (active IN (0, 1))
low_stock_alerted_atTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_parts_category (category) idx_parts_price_list_date (price_list_date)

Service

tickets

ColumnTypeConstraints
idTEXTPRIMARY KEY
ticket_numberTEXTNOT NULL UNIQUE
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
machine_idTEXTreferences machines.id NOT NULL ON DELETE RESTRICT
contact_idTEXTreferences contacts.id ON DELETE SET NULL
titleTEXTNOT NULL
descriptionTEXT
categoryTEXTNOT NULL DEFAULT 'other' CHECK (category IN ('mechanical', 'electrical', 'controls', 'hydraulic', 'pneumatic', 'structural', 'calibration', 'operator_training', 'other'))
priorityTEXTNOT NULL DEFAULT 'normal' CHECK (priority IN ('low', 'normal', 'high', 'down'))
statusTEXTNOT NULL DEFAULT 'new' CHECK (status IN ('new', 'diagnosing', 'parts_on_order', 'scheduled', 'waiting_on_customer', 'resolved', 'follow_up_complete'))
root_causeTEXTCHECK (root_cause IS NULL OR root_cause IN ('component_failure', 'manufacturing_defect', 'wear', 'operator_error', 'installation', 'shipping_damage', 'environment', 'design', 'unknown'))
resolutionTEXT
sourceTEXTNOT NULL DEFAULT 'staff' CHECK (source IN ('staff', 'portal', 'email', 'agent'))
assigned_to_user_idTEXTreferences users.id ON DELETE SET NULL
is_warrantyINTEGERNOT NULL DEFAULT 0 CHECK (is_warranty IN (0, 1))
onsite_hoursREALNOT NULL DEFAULT 0
travel_hoursREALNOT NULL DEFAULT 0
travel_milesREALNOT NULL DEFAULT 0
opened_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
scheduled_forTEXT
resolved_atTEXT
down_sinceTEXT
down_untilTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_tickets_account (account_id) idx_tickets_machine (machine_id) idx_tickets_contact (contact_id) idx_tickets_assigned (assigned_to_user_id) idx_tickets_status (status, priority) idx_tickets_opened (opened_at)

parts_orders

ColumnTypeConstraints
idTEXTPRIMARY KEY
order_numberTEXTNOT NULL UNIQUE
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
contact_idTEXTreferences contacts.id ON DELETE SET NULL
machine_idTEXTreferences machines.id ON DELETE SET NULL
ticket_idTEXTreferences tickets.id ON DELETE SET NULL
statusTEXTNOT NULL DEFAULT 'quote' CHECK (status IN ('quote', 'ordered', 'shipped', 'delivered', 'cancelled'))
subtotal_centsINTEGERNOT NULL DEFAULT 0 CHECK (subtotal_cents >= 0)
shipping_centsINTEGERNOT NULL DEFAULT 0 CHECK (shipping_cents >= 0)
tax_centsINTEGERNOT NULL DEFAULT 0 CHECK (tax_cents >= 0)
total_centsINTEGERNOT NULL DEFAULT 0 CHECK (total_cents >= 0)
quoted_onTEXTNOT NULL
quote_valid_untilTEXT
ordered_onTEXT
shipped_onTEXT
delivered_onTEXT
carrierTEXT
tracking_numberTEXT
ship_to_nameTEXT
ship_to_addressTEXT
customer_poTEXT
notesTEXT
created_by_user_idTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_parts_orders_account (account_id) idx_parts_orders_contact (contact_id) idx_parts_orders_machine (machine_id) idx_parts_orders_ticket (ticket_id) idx_parts_orders_status (status)

parts_order_lines

ColumnTypeConstraints
idTEXTPRIMARY KEY
parts_order_idTEXTreferences parts_orders.id NOT NULL ON DELETE CASCADE
part_idTEXTreferences parts.id NOT NULL ON DELETE RESTRICT
part_numberTEXTNOT NULL
descriptionTEXTNOT NULL
quantityINTEGERNOT NULL DEFAULT 1 CHECK (quantity >= 1)
unit_price_centsINTEGERNOT NULL DEFAULT 0 CHECK (unit_price_cents >= 0)
total_centsINTEGERNOT NULL DEFAULT 0 CHECK (total_cents >= 0)
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_parts_order_lines_order (parts_order_id) idx_parts_order_lines_part (part_id)

stock_movements

ColumnTypeConstraints
idTEXTPRIMARY KEY
part_idTEXTreferences parts.id NOT NULL ON DELETE RESTRICT
typeTEXTNOT NULL CHECK (type IN ('receive', 'adjust', 'ship', 'return'))
quantityINTEGERNOT NULL CHECK (quantity <> 0)
balance_afterINTEGERNOT NULL
reasonTEXT
parts_order_idTEXTreferences parts_orders.id ON DELETE SET NULL
ticket_idTEXTreferences tickets.id ON DELETE SET NULL
unit_cost_centsINTEGER
actor_user_idTEXT
actor_nameTEXTNOT NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_stock_movements_part (part_id, created_at) idx_stock_movements_parts_order (parts_order_id) idx_stock_movements_ticket (ticket_id)

ticket_parts

ColumnTypeConstraints
idTEXTPRIMARY KEY
ticket_idTEXTreferences tickets.id NOT NULL ON DELETE CASCADE
part_idTEXTreferences parts.id NOT NULL ON DELETE RESTRICT
part_numberTEXTNOT NULL
descriptionTEXTNOT NULL
quantityINTEGERNOT NULL DEFAULT 1 CHECK (quantity >= 1)
unit_price_centsINTEGERNOT NULL DEFAULT 0 CHECK (unit_price_cents >= 0)
covered_by_warrantyINTEGERNOT NULL DEFAULT 0 CHECK (covered_by_warranty IN (0, 1))
stock_movement_idTEXTreferences stock_movements.id ON DELETE SET NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_ticket_parts_ticket (ticket_id) idx_ticket_parts_part (part_id) idx_ticket_parts_movement (stock_movement_id)

ticket_time_entries

ColumnTypeConstraints
idTEXTPRIMARY KEY
ticket_idTEXTreferences tickets.id NOT NULL ON DELETE CASCADE
work_dateTEXTNOT NULL
onsite_hoursREALNOT NULL DEFAULT 0
travel_hoursREALNOT NULL DEFAULT 0
travel_milesREALNOT NULL DEFAULT 0
technician_nameTEXTNOT NULL
noteTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_ticket_time_entries_ticket (ticket_id)

warranty_claims

ColumnTypeConstraints
idTEXTPRIMARY KEY
claim_numberTEXTNOT NULL UNIQUE
ticket_idTEXTreferences tickets.id NOT NULL ON DELETE CASCADE
machine_idTEXTreferences machines.id NOT NULL ON DELETE RESTRICT
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
statusTEXTNOT NULL DEFAULT 'submitted' CHECK (status IN ('submitted', 'approved', 'denied', 'credited'))
descriptionTEXT
amount_claimed_centsINTEGERNOT NULL DEFAULT 0 CHECK (amount_claimed_cents >= 0)
credit_centsINTEGERNOT NULL DEFAULT 0 CHECK (credit_cents >= 0)
submitted_onTEXTNOT NULL
decided_onTEXT
notesTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_warranty_claims_ticket (ticket_id) idx_warranty_claims_machine (machine_id) idx_warranty_claims_account (account_id)

Activity

activities

ColumnTypeConstraints
idTEXTPRIMARY KEY
typeTEXTNOT NULL CHECK (type IN ('call', 'email', 'text', 'visit', 'note', 'system'))
directionTEXTCHECK (direction IS NULL OR direction IN ('outbound', 'inbound'))
subjectTEXTNOT NULL
bodyTEXT
occurred_atTEXTNOT NULL
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
contact_idTEXTreferences contacts.id ON DELETE SET NULL
order_idTEXTreferences orders.id ON DELETE SET NULL
machine_idTEXTreferences machines.id ON DELETE SET NULL
ticket_idTEXTreferences tickets.id ON DELETE SET NULL
external_refTEXT
external_thread_idTEXT
from_addressTEXT
to_addressesTEXTNOT NULL DEFAULT '[]'
duration_minutesINTEGER
logged_by_user_idTEXT
logged_by_nameTEXTNOT NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
rfc822_message_idTEXT

Indexes: unique idx_activities_external_ref (external_ref) WHERE external_ref IS NOT NULL idx_activities_account (account_id, occurred_at) idx_activities_contact (contact_id) idx_activities_order (order_id) idx_activities_machine (machine_id) idx_activities_ticket (ticket_id) unique idx_activities_rfc822_message_id (rfc822_message_id) WHERE rfc822_message_id IS NOT NULL

activity_documents

ColumnTypeConstraints
activity_idTEXTreferences activities.id NOT NULL ON DELETE CASCADE
document_idTEXTreferences documents.id NOT NULL ON DELETE CASCADE

Table constraints: PRIMARY KEY (activity_id, document_id)

Indexes: idx_activity_documents_document (document_id)

Opportunities

opportunities

ColumnTypeConstraints
idTEXTPRIMARY KEY
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
titleTEXTNOT NULL
descriptionTEXT
product_idTEXTreferences products.id ON DELETE SET NULL
machine_idTEXTreferences machines.id ON DELETE SET NULL
estimated_value_centsINTEGERCHECK (estimated_value_cents IS NULL OR estimated_value_cents >= 0)
statusTEXTNOT NULL DEFAULT 'open' CHECK (status IN ('open', 'handed_to_sales', 'won', 'lost'))
handed_to_sales_onTEXT
sales_contactTEXT
notesTEXT
created_by_user_idTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
updated_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_opportunities_account (account_id) idx_opportunities_product (product_id) idx_opportunities_machine (machine_id) idx_opportunities_status (status)

Import

import_runs

ColumnTypeConstraints
idTEXTPRIMARY KEY
entityTEXTNOT NULL CHECK (entity IN ('accounts', 'contacts', 'sites', 'products', 'parts', 'machines'))
sourceTEXTNOT NULL DEFAULT 'google_sheet'
source_nameTEXT
statusTEXTNOT NULL DEFAULT 'dry_run' CHECK (status IN ('dry_run', 'applying', 'applied', 'failed'))
mappingTEXTNOT NULL DEFAULT '{}'
columnsTEXTNOT NULL DEFAULT '[]'
defaultsTEXTNOT NULL DEFAULT '{}'
on_duplicateTEXTNOT NULL DEFAULT 'skip' CHECK (on_duplicate IN ('skip', 'update'))
total_rowsINTEGERNOT NULL DEFAULT 0
create_countINTEGERNOT NULL DEFAULT 0
update_countINTEGERNOT NULL DEFAULT 0
duplicate_countINTEGERNOT NULL DEFAULT 0
error_countINTEGERNOT NULL DEFAULT 0
created_by_user_idTEXT
created_by_nameTEXTNOT NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
applied_atTEXT

Indexes: idx_import_runs_status (status)

import_rows

ColumnTypeConstraints
run_idTEXTreferences import_runs.id NOT NULL ON DELETE CASCADE
row_numberINTEGERNOT NULL
actionTEXTNOT NULL CHECK (action IN ('create', 'update', 'skip_duplicate', 'error'))
dataTEXTNOT NULL DEFAULT '{}'
errorsTEXTNOT NULL DEFAULT '[]'
duplicate_of_idTEXT
duplicate_of_nameTEXT
result_idTEXT

Table constraints: PRIMARY KEY (run_id, row_number)

Portal

customer_users

ColumnTypeConstraints
idTEXTPRIMARY KEY
auth_user_idTEXTNOT NULL UNIQUE
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
contact_idTEXTreferences contacts.id ON DELETE SET NULL
emailTEXTNOT NULL COLLATE NOCASE UNIQUE
nameTEXTNOT NULL
activeINTEGERNOT NULL DEFAULT 1 CHECK (active IN (0, 1))
last_seen_atTEXT
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_customer_users_account (account_id) idx_customer_users_contact (contact_id)

portal_invites

ColumnTypeConstraints
idTEXTPRIMARY KEY
account_idTEXTreferences accounts.id NOT NULL ON DELETE CASCADE
contact_idTEXTreferences contacts.id ON DELETE SET NULL
emailTEXTNOT NULL COLLATE NOCASE
nameTEXTNOT NULL
token_hashTEXTNOT NULL UNIQUE
statusTEXTNOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'accepted', 'revoked', 'expired'))
expires_atTEXTNOT NULL
invited_by_user_idTEXT
invited_by_nameTEXTNOT NULL
accepted_atTEXT
customer_user_idTEXTreferences customer_users.id ON DELETE SET NULL
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))

Indexes: idx_portal_invites_account (account_id) idx_portal_invites_contact (contact_id) idx_portal_invites_customer_user (customer_user_id) idx_portal_invites_email (email, status)

Calendar feeds, audit log, email outbox, counters

calendar_feeds

ColumnTypeConstraints
idTEXTPRIMARY KEY
user_idTEXTreferences users.id NOT NULL UNIQUE ON DELETE CASCADE
tokenTEXTNOT NULL UNIQUE
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
last_accessed_atTEXT

audit_log

ColumnTypeConstraints
idTEXTPRIMARY KEY
atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
actor_kindTEXTNOT NULL CHECK (actor_kind IN ('staff', 'customer', 'agent', 'system'))
actor_user_idTEXTNOT NULL
actor_emailTEXTNOT NULL
actor_nameTEXTNOT NULL
operationTEXTNOT NULL
entity_typeTEXT
entity_idTEXT
account_idTEXT
summaryTEXT
detailTEXT
request_idTEXT

Indexes: idx_audit_log_at (at) idx_audit_log_entity (entity_type, entity_id) idx_audit_log_account (account_id, at) idx_audit_log_actor (actor_user_id, at) idx_audit_log_operation (operation, at)

email_outbox

ColumnTypeConstraints
idTEXTPRIMARY KEY
templateTEXTNOT NULL
to_addressTEXTNOT NULL
subjectTEXTNOT NULL
body_textTEXTNOT NULL
body_htmlTEXT
statusTEXTNOT NULL DEFAULT 'queued' CHECK (status IN ('queued', 'sent', 'failed', 'skipped'))
account_idTEXTreferences accounts.id ON DELETE SET NULL
entity_typeTEXT
entity_idTEXT
dedupe_keyTEXTUNIQUE
errorTEXT
attemptsINTEGERNOT NULL DEFAULT 0
created_atTEXTNOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))
sent_atTEXT
lease_untilTEXT

Indexes: idx_email_outbox_status (status, created_at) idx_email_outbox_account (account_id) idx_email_outbox_entity (entity_type, entity_id)

counters

Sequences for order, ticket, parts order and claim numbers.

ColumnTypeConstraints
nameTEXTPRIMARY KEY
valueINTEGERNOT NULL DEFAULT 0

Other

ticket_down_intervals

Earlier downtime intervals of a ticket. tickets.down_since/down_until hold the current (or last) interval; when a resolved down ticket is reopened as down, its finished interval is moved here first so the time the machine ran between the two is not counted as downtime.

ColumnTypeConstraints
idTEXTPRIMARY KEY
ticket_idTEXTreferences tickets.id NOT NULL ON DELETE CASCADE
machine_idTEXTreferences machines.id NOT NULL ON DELETE RESTRICT
account_idTEXTreferences accounts.id NOT NULL ON DELETE RESTRICT
started_atTEXTNOT NULL
ended_atTEXTNOT NULL
created_atTEXTNOT NULL

Indexes: idx_ticket_down_intervals_ticket (ticket_id) idx_ticket_down_intervals_machine (machine_id) idx_ticket_down_intervals_account (account_id)

idempotency_keys

Idempotency keys for POST /v1/ops/{name}. A client that may send the same write twice (the app's offline outbox after a dropped connection, two tabs replaying the same outbox) sends an Idempotency-Key header; the first request claims the key, and a repeat gets the stored answer instead of applying the write again. Keys belong to the caller and are purged after 7 days.

ColumnTypeConstraints
actor_idTEXTNOT NULL
keyTEXTNOT NULL
operationTEXTNOT NULL
stateTEXTNOT NULL CHECK (state IN ('pending', 'done'))
responseTEXT
created_atTEXTNOT NULL

Table constraints: PRIMARY KEY (actor_id, key)

Indexes: idx_idempotency_keys_created (created_at)

search_indexfts5 virtual table

Full-text search (FTS5) over the records the one search box covers (FR-26). Kept current by triggers; `reindexSearch()` in @cemco/db rebuilds it by touching rows.

ColumnTypeConstraints
entity_typetextUNINDEXED
entity_idtextUNINDEXED
account_idtextUNINDEXED
titletext
subtitletext
bodytext

Table constraints: content = 'search_docs' content_rowid = 'id' tokenize = 'unicode61 remove_diacritics 2' prefix = '2 3 4'

Two-way Google Contacts sync, per staff user. A CRM contact is linked to one Google contact (resource name) in each connected user's Google account. `pushed_at` is the contact's updated_at last sent to or taken from Google, so a later CRM edit is pushed again. state 'removed': the user deleted it in Google; it is not pushed again.

ColumnTypeConstraints
user_idTEXTreferences users.id NOT NULL ON DELETE CASCADE
contact_idTEXTreferences contacts.id NOT NULL ON DELETE CASCADE
resource_nameTEXTNOT NULL
etagTEXT
stateTEXTNOT NULL DEFAULT 'linked' CHECK (state IN ('linked', 'removed'))
pushed_atTEXT
synced_atTEXTNOT NULL

Table constraints: PRIMARY KEY (user_id, contact_id)

Indexes: unique idx_google_contact_links_resource (user_id, resource_name)

google_contact_sync

ColumnTypeConstraints
user_idTEXTreferences users.id PRIMARY KEY ON DELETE CASCADE
sync_tokenTEXT
last_synced_atTEXT
last_errorTEXT

Now the indexed text lives in an ordinary table, search_docs, unique on (entity_type,

search_docs

ColumnTypeConstraints
idINTEGERPRIMARY KEY
entity_typeTEXTNOT NULL
entity_idTEXTNOT NULL
account_idTEXT
titleTEXT
subtitleTEXT
bodyTEXT

Table constraints: UNIQUE (entity_type, entity_id)

Auth database

cemco-auth is owned by the auth Worker and holds sign-in data only (users, sessions, API keys and OAuth clients as the auth service adds them). The CRM links to it through users.auth_user_id andcustomer_users.

auth_events

cemco-auth database. The better-auth tables (user, session, account, verification, apikey, oauth clients and tokens) are added by later migrations in this folder. This first migration adds a small sign-in event log (who signed in, refused sign-ins) for the auth build-out to write to. Nothing writes to it yet.

id TEXT at TEXT kind TEXT email TEXT detail TEXT

user

id TEXT name TEXT email TEXT emailVerified INTEGER image TEXT createdAt DATE updatedAt DATE userType TEXT disabled INTEGER lastSignInAt DATE

session

id TEXT expiresAt DATE token TEXT createdAt DATE updatedAt DATE ipAddress TEXT userAgent TEXT userId TEXT

account

id TEXT accountId TEXT providerId TEXT userId TEXT accessToken TEXT refreshToken TEXT idToken TEXT accessTokenExpiresAt DATE refreshTokenExpiresAt DATE scope TEXT password TEXT createdAt DATE updatedAt DATE

verification

id TEXT identifier TEXT value TEXT expiresAt DATE createdAt DATE updatedAt DATE

apikey

id TEXT configId TEXT name TEXT start TEXT referenceId TEXT prefix TEXT key TEXT refillInterval INTEGER refillAmount INTEGER lastRefillAt DATE enabled INTEGER rateLimitEnabled INTEGER rateLimitTimeWindow INTEGER rateLimitMax INTEGER requestCount INTEGER remaining INTEGER lastRequest DATE expiresAt DATE createdAt DATE updatedAt DATE permissions TEXT metadata TEXT

jwks

id TEXT publicKey TEXT privateKey TEXT createdAt DATE expiresAt DATE alg TEXT crv TEXT

oauthClient

id TEXT clientId TEXT clientSecret TEXT clientDiscoveryId TEXT disabled INTEGER skipConsent INTEGER enableEndSession INTEGER subjectType TEXT scopes TEXT clientCredentialsScopes TEXT userId TEXT createdAt DATE updatedAt DATE name TEXT uri TEXT icon TEXT contacts TEXT tos TEXT policy TEXT softwareId TEXT softwareVersion TEXT softwareStatement TEXT redirectUris TEXT postLogoutRedirectUris TEXT backchannelLogoutUri TEXT backchannelLogoutSessionRequired INTEGER tokenEndpointAuthMethod TEXT applicationType TEXT jwks TEXT jwksUri TEXT grantTypes TEXT responseTypes TEXT requirePKCE INTEGER dpopBoundAccessTokens INTEGER referenceId TEXT metadata TEXT

oauthResource

id TEXT identifier TEXT name TEXT accessTokenTtl INTEGER refreshTokenTtl INTEGER signingAlgorithm TEXT signingKeyId TEXT allowedScopes TEXT customClaims TEXT dpopBoundAccessTokensRequired INTEGER disabled INTEGER createdAt DATE updatedAt DATE policyVersion INTEGER metadata TEXT

oauthClientResource

id TEXT clientId TEXT resourceId TEXT metadata TEXT createdAt DATE

oauthRefreshToken

id TEXT token TEXT clientId TEXT sessionId TEXT userId TEXT referenceId TEXT authorizationCodeId TEXT resources TEXT requestedUserInfoClaims TEXT expiresAt DATE createdAt DATE revoked DATE rotatedAt DATE rotationReplayResponse TEXT rotationReplayExpiresAt DATE authTime DATE confirmation TEXT scopes TEXT

oauthAccessToken

id TEXT token TEXT clientId TEXT sessionId TEXT userId TEXT referenceId TEXT authorizationCodeId TEXT resources TEXT requestedUserInfoClaims TEXT refreshId TEXT expiresAt DATE createdAt DATE revoked DATE confirmation TEXT scopes TEXT

oauthConsent

id TEXT clientId TEXT userId TEXT referenceId TEXT resources TEXT requestedUserInfoClaims TEXT scopes TEXT createdAt DATE updatedAt DATE

oauthClientAssertion

id TEXT expiresAt DATE

rateLimit

id TEXT key TEXT count INTEGER lastRequest BIGINT