Apps

Apps · NocoCRM · Development

Data model

This page describes NocoCRM's tables, fields, the relations between records, and how to change the data model. The full field definitions are in server/providers/crm/schema.ts in the repository.

General conventions

  • Tables: each of the six business objects has its own table: crmLeads, crmCompanies, crmContacts, crmOpportunities, crmTasks, crmApprovals.
  • Relations: records refer to each other through id fields. The database has no foreign key constraints; CrmService keeps the relations intact.
  • Field definitions: live in schema.ts. Forms, lists, validation, the API document and import and export are all generated from them.
  • Options: also live in schema.ts and cannot be added or removed in the interface; their display names are in client/locales/crm/. The AI has its own copy of the names of opportunity stages, approval topics, approval statuses and opportunity contact roles, in server/locales/crm-ai/texts/.
  • Database: SQLite by default; PostgreSQL and MySQL are also supported. Table and column names in the database use underscores, for example crm_leads and owner_id.

Relations between records

RecordRelates toFields
ContactCompanycompanyId
OpportunityCompany, the contacts involvedcompanyId, contacts
ApprovalOpportunityopportunityId
TaskLead, company, opportunityleadId, companyId, opportunityId
LeadThe company, contact and opportunity it was converted intoconvertedCompanyId, convertedContactId, convertedOpportunityId
TimelineAny recordentity, recordId

Business objects

Leads

Leads (crmLeads) hold unconfirmed potential deals or potential customers.

FieldDescription
name, phone, email, linkedin, jobTitle, genderThe contact's name, phone, email, LinkedIn, job title and gender
company, website, industry, employees, annualRevenue, currency, country, state, city, address, companyDescriptionThe company's name, website, industry, number of employees, annual revenue and its currency, country / region, state / province, city, address and introduction
message, attachmentsThe original message and files
sourceSource
status, invalidReasonStatus: New, Working, Nurturing, Converted, Invalid; an invalid reason is required when the status is Invalid
convertedAt, convertedCompanyId, convertedContactId, convertedOpportunityIdWhen the lead was converted, and the IDs of the company, contact and opportunity it was converted into

Companies

Companies (crmCompanies) hold the organisations or businesses you have a business relationship with.

FieldDescription
name, website, linkedin, industry, employees, annualRevenue, currency, country, state, city, address, descriptionThe company's name, website, LinkedIn, industry, number of employees, annual revenue and its currency, country / region, state / province, city, address and introduction
typeType: Direct customer, Partner, Reseller, Other
sourceSource
status, churnReasonStatus: Prospect, Qualified, Customer, Inactive, Churned; a churn reason is required when the status is Churned. A company converted from a lead is Qualified, and becomes Customer when one of its opportunities is won
attachmentsFiles
signalsWatched, signalsCheckedAtWhether company signals are watched, and when they were last checked

Contacts

Contacts (crmContacts) hold the people at customer companies.

FieldDescription
name, phone, email, linkedin, jobTitle, genderThe contact's name, phone, email, LinkedIn, job title and gender
companyId, employed, primaryThe company, whether the person still works there, and whether they are the company's primary contact
sourceSource

Opportunities

Opportunities (crmOpportunities) hold deals in progress or already closed, and track the whole process from initial contact to closing.

FieldDescription
nameOpportunity name
companyIdThe company
contactsContacts at the company and their role in this opportunity's decision: Decision maker, Champion, Evaluator, Influencer, End user, Blocker, Other
description, attachmentsDescription and files
stage, lostReason, pauseReason, resumeAt, closedAtStage: Initial contact, Qualification, Validation, Proposal, Negotiation, Contract, Won, Lost, Paused. A lost reason is required when the stage is Lost; a pause reason is required when it is Paused, and a resume date can be given. The close date is recorded when the stage becomes Won or Lost
amount, currency, expectedCloseAtAmount, currency and expected close date; the currency defaults to the one set in the system settings
sourceSource
businessTypeBusiness type: New business, Expansion, Cross-sell, Renewal, Tender, Other

Tasks

Tasks (crmTasks) hold to-dos.

FieldDescription
nameTask title
statusStatus: Not done, Completed, Cancelled
dueAt, completedAtDue time and completion time
leadId, companyId, opportunityIdThe related lead, company and opportunity
internalParticipantsColleagues taking part
description, result, attachmentsDescription, result and files

Approvals

Approvals (crmApprovals) hold approval requests for an opportunity.

FieldDescription
nameApproval title
opportunityIdThe opportunity
topic, description, attachmentsTopic, request details and files; topics: Discount, Payment terms, Contract terms, Commitment, Other
approverIdApprover
statusStatus: Draft, Pending approval, Approved, Rejected, Withdrawn
decisionComment, submittedAt, decidedAt, statusChangedAtThe decision comment, submission time, decision time, and when the status last changed
lifecycleVersion, lifecycleDefinitionThe process version this approval uses

Common fields

All six objects have the following fields, which the tables above leave out. Every object also has a name field, but its meaning differs by object and is described in each table.

FieldDescription
idPrimary key: a 36-character UUID string, not an auto-increment number
ownerIdOwner
createdById, createdAt, updatedAtCreator, creation time and update time

Shared options

  • Source (leads, companies, contacts, opportunities): Website, Marketing, Exhibition, Search engine, AI, Customer referral, Employee referral, Partner, Outbound, Other.
  • Employees: 1-10, 11-50, 51-200, 201-500, 501-1000, 1001-5000, 5000+.
  • Industry: 23 options.
  • Currency: USD, CNY, EUR, GBP, JPY, HKD, SGD, AUD, CAD.

Other tables

Besides the six business objects, NocoCRM has the tables below. Their names all start with crm, and they hold the timeline, attachments, settings, agents' change plans, company signals, WhatsApp and other data. Data about users, permissions, mail, scheduled tasks and the agents themselves is stored and managed by NocoBase plugins and is not in this table.

TableContents
crmHistoryThe timeline: field changes, comments and replies, AI suggestion cards and their status, mail threads, WhatsApp conversations, company signals
crmFiles, crmFileUploadsAttachment file information and who uploaded it. The NocoBase File plugin stores the file contents on a storage drive; records refer to these files by id in attachments, and files no record has referred to for 7 days are cleaned up early every morning
crmSettingsSettings as key-value rows: the business row holds all settings of the General page, the business guidance and the switch for the ask box at the bottom of pages; other rows hold the agent switches, the background agents' models and instructions, the WhatsApp app secret and so on
crmUserPreferencesThe interface language each person last used NocoCRM in, recorded automatically when they open a page; the system uses it when it handles records on that person's behalf while they are away
crmPlans, crmPlanRowsChange plans that an agent proposes and a person confirms, and each step in them
crmAiWatchesFollow-ups, approval suggestions or task preparations that a conversation asked an agent to start are recorded here until they finish; the result is then sent back to that conversation and the row is deleted
crmSignals, crmSignalChecksSignals the company signals agent finds (Funding, Hiring, Executives, Major news, Risk) and a record of each check
crmWa*WhatsApp numbers, contacts and their WhatsApp identities, conversations, messages, and the webhooks received

How mail and WhatsApp relate to records

  • Mail: messages themselves are stored in the Mail plugin's tables and do not point to NocoCRM records. Every minute NocoCRM reads each member's mailbox and writes one mail entry per thread to the timeline of the related records: unconverted leads and contacts are matched by email address, and companies by website domain. When a contact matches, the thread also shows on their company and on the opportunities they take part in. Mail sent from a record is also recorded as a completed task.
  • WhatsApp: a WhatsApp contact relates to a lead or contact through leadId or contactId, and is switched to the new contact on conversion; each conversation writes one whatsapp entry to the timeline.

Changing the data model

Every change to the data model starts with a database migration, under these rules:

  • Migrations are immutable: a merged migration is history, and a correction can only come as a new migration. A migration must be self-contained, spelling out every field and index and its matching down; the exported name must match the file name. Migrations are written by hand; there is no generator command.
  • Running migrations: run pnpm nocobase db apply, or restart pnpm dev. While a migration is not yet merged, you can redo it with pnpm nocobase db redo.
  • Do not edit generated files: database/main/collections/ is generated from the migrations.
  • Testing: test a migration's up and down against a real database; see tests/logic/ai-watches-migration.test.ts.

For how to write migrations, see Create tables and initialize data.

Add a field

Take adding a "Contract no." field contractNo to opportunities as an example:

  1. Write the migration: create a file in database/main/migrations/, following the existing file name format, for example 202612010001_crm_opportunity_contract_no.ts. In up, add the field with builder.alterCollection('crmOpportunities', ...); in down, remove it. Then run the migration.
  2. Add the field definition: add the field to definitions.opportunities.fields in server/providers/crm/schema.ts, with its type, whether it is required, and its options; to show it in the list, also add it to columns. Once this is done, server validation, the API document, the create and edit forms, the list columns and import and export all include it.
  3. Business rules (optional): validation across fields goes in the opportunity branch of CrmService.save. Throw a CrmError with an error code, and add the error message to the interface text.
  4. Detail page: the details section of a record's page is laid out by hand. Add the field to the opportunity's details group in client/pages/crm-entity-detail.tsx; field icons are in client/components/crm/field-icons.tsx.
  5. Text: add contractNo: ['Contract no.', '合同编号'] to fields in client/locales/crm/index.ts, then add an entry to each of the other 10 language files.
  6. AI (optional): form capture and opportunity follow-up only fill the fields in fixed lists. For the AI to recognise or update this field, add it to the field lists in opportunity-capture.ts and opportunity-evaluation.ts. Lead conversion likewise copies only the listed fields; see conversion.ts.
  7. Tests: for the API, see tests/logic/crm.test.ts; for the form and detail page, see tests/components/crm-form.test.tsx.

Permissions need no change: the sales roles' grants on opportunities cover all fields, so the new field is included automatically.

Change options

Options such as source, stage, status and type live in schema.ts and need no migration. To add or remove an option, change the options in the field definition, defaultSettings.options, and the option names in the 12 language files together. For opportunity stages, approval topics or approval statuses, also change the names the AI uses (stageNames, topicNames, statusNames) in the 12 files in server/locales/crm-ai/texts/. Old values in existing records do not change automatically; handle those records before you remove an option.

Opportunity contact roles are the exception: they are not in schema.ts but written separately in the server validation, the form, the detail page and the AI prompts, and the names the AI uses are roleNames. To change them, we recommend handing the job to a coding agent so that it finds every place they are used.

Add a table

First decide what the table is:

It only holds data for its own feature, like the company signals table (crmSignals) or the AI work a conversation waits for (crmAiWatches):

  1. Write a migration that creates the table with builder.createCollection('crm<Name>', ...); the table name starts with crm.
  2. Write a service in server/providers/crm/ that reads and writes the table.
  3. If pages need it, add an API in server/routes/, register it in server/routes/crm.ts, and add its path to server/routes/crm-paths.ts so the sign-in check covers it.

It is a new kind of business object that needs a list, a detail page, permissions and import and export, like leads and opportunities. This is a larger change:

  1. Write a migration that creates the table, with the common fields.
  2. Add it to the Entity type and to definitions in schema.ts. The API, the API document, forms, lists, import and export, and the permission resource are all generated from these definitions.
  3. Add its English name and path parameter to objectNames in server/routes/schemas/records.ts.
  4. Add it and its icon to the list of record pages in client/routes.ts; the details section of its detail page is laid out by hand in client/pages/crm-entity-detail.tsx.
  5. Add it to the object list of the role settings page (client/pages/settings/permission-workspace.ts). Its pages go into crmPages in resources.ts, and on an existing system an administrator also needs to grant them in System settings › Roles & permissions.
  6. Add its name, fields and options to the 12 language files.

Global search, the timeline, the Sales Expert, the inbox and other features also keep lists of the six objects. We recommend handing this to a coding agent and having it use an existing object (approvals, for example) as the model to find every place that needs adding to.

NocoBase docs assistant

Ask anything about NocoBase…

You can ask follow-up questions about recent answers.