Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
paths: - "packages/database/supabase/migrations/" - "apps/erp/app/modules/sales/" - "apps/erp/app/modules/purchasing/**"
Customer & Supplier Database Schema
Customer and supplier data live in PostgreSQL (Supabase). The two families are near-mirrors of each other (customer* gated by sales_*, supplier* gated by purchasing_*), but with a few intentional asymmetries — see "Gotchas". When in doubt, the generated types at packages/database/src/types.ts are the source of truth; migrations are timestamped and the newest one wins.
Core tables
customer / supplier (main entities)
Key columns (both, unless noted):
idTEXT PK (defaultuuid_generate_v4())readableIdTEXT NOT NULL — human-readable id (CUS/SUPprefix, size 6), per-company unique (<entity>_readableId_companyId_unique). Auto-filled by a BEFORE INSERT trigger viaget_next_sequence(...)only when blank, so explicit values (CSV import) win — and an explicit value in the sequence's format moves the counter past it (sync_advance_document_sequence).nameTEXT NOT NULL — unique per company (<entity>_name_unique)customerTypeId/supplierTypeIdTEXT →customerType/supplierType- Status differs by entity (asymmetric):
customer.customerStatusIdTEXT →customerStatustable (FK)supplier.supplierStatus— enum columnsupplierStatusType='Active' | 'Inactive' | 'Pending' | 'Rejected'. There is nosupplierStatustable anymore (dropped in20260309211117_supplier-status-enums.sql).
- Default contact pointer:
customer.salesContactId/supplier.purchasingContactId→<entity>Contact.id(ON DELETE RESTRICT). There is NOinvoicingContactId— it was added then dropped (20260304112615_purchasing-info.sql). defaultCcTEXT[] — default CC email recipientstaxId,taxPercentNUMERIC(10,5) (0..1),currencyCode→currencyCode.codeaccountManagerId,assignee→user.idlogo,website,tagsTEXT[],customFieldsJSONBsupplieralso hasembedding halfvec(384)(semantic search)- Legacy
phone/faxcolumns still exist on the tables but are superseded — the views now derive phone/fax from the primary linked contact (see Views). externalIdis no longer a column — external integration ids moved to theexternalIntegrationMappingtable (20260130005853); the views recompute it as a JSONB aggregate.- Audit:
companyIdNOT NULL →company.id,createdAt/By,updatedAt/By.
customerType / supplierType
id (default uuid_generate_v4()), name (unique per company), protected BOOLEAN, standard audit + customFields.
customerStatus (table) — customer only
id (default xid()), name (unique per company), audit + customFields. Supplier's equivalent is the enum above, not a table.
Relationship tables (customer ↔ contact ↔ location)
contact (shared by both families)
id (default xid()), firstName, lastName, fullName (GENERATED firstName || ' ' || lastName STORED), email (nullable since 20251224160904), title, mobilePhone, homePhone, workPhone, fax, notes, isCustomer BOOLEAN NOT NULL DEFAULT TRUE, companyId.
isCustomerdistinguishes a contact as customer-side (true) vs supplier-side (false); set at insert time.- Contact has no address fields —
addressLine1/city/state/postalCode/countryCode/birthdaywere dropped (20240813152858). Addresses live in theaddresstable. - Email is not uniquely constrained.
20260112120041meant to drop the partial unique index but named it unquoted, so Postgres lower-cased the name andIF EXISTSdropped nothing;20261027162653drops it for real. - A contact lives through its
customerContact/supplierContactrows. Usually there is one, but Paperless Parts reuses a contact found by email and links it to more customers. When the LAST link goes (deleted directly, by cascade when its customer or supplier is deleted, or moved to another contact by an UPDATE), thesync_delete_unlinked_contactafter-interceptor on both link tables deletes the contact. It locks the contact before checking for other links, so a concurrent re-link survives, and it does nothing underapp.sync_in_progress(dataset wipes and restores manage contacts themselves). Before it, a deleted customer left its contacts behind, invisible in the app.
customerContact / supplierContact (join: entity ↔ contact)
id (default xid()), customerId/supplierId → entity (ON DELETE CASCADE), contactId → contact (CASCADE), customerLocationId/supplierLocationId → location (nullable, SET NULL), userId → user (nullable), tags, customFields.
insertCustomerContact(sales.service.ts) andinsertSupplierContact(purchasing.service.ts) write thecontactrow and its link in ONE Kysely transaction, after checking the customer or supplier and the location belong to the company. Two separate writes left an orphaned contact whenever the link insert failed.
customerLocation / supplierLocation (join: entity ↔ address)
id (default xid()), customerId/supplierId (CASCADE), addressId → address (CASCADE), name TEXT NOT NULL (20240813213122), tags, supplierLocation.externalId JSONB, customFields.
- Unique per
(addressId, <entity>Id)(20250913172116). - Code inserts an
addressrow first, then the location (name,addressId, ...).
address
id (default xid()), addressLine1/2, city, state, postalCode, countryCode INTEGER → country.id, phone, fax, companyId.
customerPayment / supplierPayment (1:1, PK = entityId)
invoice<Entity>Id (can differ for billing), invoice<Entity>LocationId, invoice<Entity>ContactId, paymentTermId, currencyCode, audit. (These invoice-contact pointers are separate from and unrelated to the dropped invoicingContactId.)
customerShipping / supplierShipping (1:1, PK = entityId)
shipping<Entity>Id, shipping<Entity>LocationId, shipping<Entity>ContactId, shippingTermId, shippingMethodId, audit.
customerAccount / supplierAccount (external portal users)
Composite PK (id, companyId); id → user.id, <entity>Id → entity.
Views: customers / suppliers
SECURITY_INVOKER=true. Expose entity columns plus: type (from type table), status (customer: customerStatus.name; supplier: the enum value directly), orderCount (sales/purchase orders), supplier-only partCount (supplierPart), phone/fax derived from the primary linked contact's workPhone/fax, and a recomputed externalId JSONB from externalIntegrationMapping.
RLS
RLS is gated by company employee permissions (newest standardized policies in 20250201181148_rls-refactor.sql for customer/contact, 20260228000000_rls-refactor-3.sql for supplier):
customer,customerContact,customerLocation:sales_view/create/update/delete. Customer-side SELECT also OR-in external-portal access viaget_customer_ids_with_customer_permission(...).supplier,supplierContact,supplierLocation:purchasing_view/create/update/delete(employee-only).contact: union ofsales_*andpurchasing_*(a contact can be either side).customerPayment/customerShipping/supplierPayment/supplierShipping: payment gated by the family's primary perm, shipping bypurchasing_*(notecustomerShippinghistorically usedpurchasing_*).- Child tables derive
companyIdfrom the parent viaget_company_id_from_foreign_key("<entity>Id", '<entity>').
Triggers / side effects
- Inserting a
customer/supplierauto-creates its*Payment+*Shippingrows and an orggroup+membership. These are now event-system interceptors (sync_create_*_entries,attach_event_trigger('customer'/'supplier', ...)in20260410031801), not the legacycreate_*_entriestriggers. - Changes to a linked
contact/addressbump the parent entity'supdatedAt(sync_contact_to_parent/sync_address_to_parent,20260210171712).
Gotchas
- No
invoicingContactIdoncustomer/supplier— onlysalesContactId/purchasingContactId. Don't reintroduce it. - Status is asymmetric: customer = FK table, supplier = inline enum. Don't assume a
supplierStatustable exists. contact.emailis nullable and not unique. Don't assume NOT NULL or a unique constraint.externalIdis not a column — queryexternalIntegrationMapping(or the view's computed field).- Some migration filenames are misleading:
20251114222648_supplier_id.sqlis about non-conformance, and20250125121403_add-customer-and-supplier-custom-fields.sqltouchesattributeDataType, not customer/supplier. - The legacy
phone/faxcolumns oncustomer/supplierpersist but are not the display source; the views use the primary contact's phone/fax.