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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
description: How user, employee, employeeJob, company membership, and permissions/claims relate in Carbon's auth identity graph paths: - "packages/database/supabase/migrations/" - "packages/auth/src/services/" - "apps/erp/app/modules/users/" - "apps/erp/app/modules/resources/"
User / Employee / EmployeeJob / Permission identity graph
Carbon's identity is multi-tenant: one user can belong to many companies, with a
per-company role and per-company employee record. "Job" in employeeJob means an
employee's job title/role within a company — NOT a production/manufacturing job (that
is the separate job table from 20240909194622_jobs.sql).
Core tables (PK + key columns; newest migrations applied)
user— global identity,idmatches Supabaseauth.users.id. PKid.email,firstName,lastName,fullName(GENERATEDfirstName || ' ' || lastName, STORED),about(default''),avatarUrl,active(default TRUE),phone,admin,developer,isConsoleOperator,flagsJSONB,acknowledgedITAR,externalIdJSONB,createdAt,updatedAt.- No FKs to other app tables.
fullNameis generated and never null when names are set; prefer it directly.
userToCompany— the membership join table. PK(userId, companyId).role "role"whereCREATE TYPE "role" AS ENUM ('customer','employee','supplier'). This is how a user belongs to multiple companies (one row per company, role can differ per company).employee— per-company employee record. PK(id, companyId);id → user.id.employeeTypeId → employeeType.id(RESTRICT),companyId → company.id,active BOOLEAN DEFAULT FALSE,pin(console mode). Added in20241208004151_invites.sql.employeeJob— job title / org placement. PK(id, companyId);id → user.id.title,startDate DATE,locationId → location.id,departmentId → department.id,shiftId → shift.id,managerId → user.id,tags TEXT[],customFieldsJSONB,updatedAt,updatedBy → user.id. Created20230224035103_shifts.sql;departmentId/tagsadded later. (workCellIdexisted briefly, then dropped in20240819115702_work-centers.sql.)employeeType— per-company role definition. PKid.name,companyId → company.id,protected BOOLEAN.employeeTypePermission— permissions granted by an employee type. PK(employeeTypeId, module).module "module"(enum), andview/create/update/delete TEXT[](each is an array of company IDs;"0"= all companies).employeeTypeId → employeeType.id.userPermission— the effective, flattened per-user permission set. PKid(id → user.id).permissions JSONB DEFAULT '{}'keyed like<module>_<action>→ array of company IDs.
How permissions / claims are derived
- Membership:
userToCompanygives the user'srolein a company. - Grants:
employee.employeeTypeId → employeeType → employeeTypePermissiondefines what each employee type can do per module/action, scoped to company IDs. - Flattened: those grants are materialized into
userPermission.permissions(JSONB,<module>_<action>→ company-ID array). - Claims: SQL
get_claims(uid, company)(latest:20260925121735_rpc-function-guards.sql) readsrolefromuserToCompanyandpermissionsfromuserPermission, then returns(jsonb_build_object('role', role) || permissions). Called through the API it answers only for the caller's ownuid, or for someone in a company where the caller holdsusers_vieworusers_update; service role and direct connections are unrestricted. RLS helpers likeget_companies_with_employee_role(), andget_companies_with_employee_permission('<module>_<action>')enforce this in policies (helpers re-defined in later migrations — read the newest). - App layer (
packages/auth/src/services/):getUserClaims()caches claims in Redis atpermissions:${userId}(falls back to the RPC);makePermissionsFromClaims()(users.ts) parses them into{ permissions, role };requirePermissions(request, { view?, create?, update?, delete?, role? })inauth.server.tsis the route gate. Active company comes from acompanyIdcookie viagetCompanyId/setCompanyId(company.server.ts).
Views (read-only joins)
employees— newest in20260529160000_employees-view-status.sql. Joinsuser+employee(+employeeJob/locationforlocationId,locationName). AliasesfullName AS "name". Adds a computedstatus('Active' | 'Invited' | 'Inactive') fromemployee.activeand theinvitetable. Filter isWHERE u.active = TRUE(on user, not employee), so inactive employees of an active user still appear — filter onactive/statuswhen you only want active employees.employeeSummary—20240103010721_employee-summary.sql.user+employee+ LEFT JOINemployeeJob/location/department/manageruser. Returnsid, name, avatarUrl, companyId, title, startDate, departmentName, locationName, managerName.employeesAcrossCompanies—20260526091437_employee-location.sql. AggregatescompanyIdper user (array_agg) for users across companies.
Gotchas
userRLS is company-scoped (20260924153817_user-rls-company-scope.sql). A caller sees themselves, users who share auserToCompanycompany, and, as an employee, users with anemployee/customerAccount/supplierAccountrow in their company (pending invites, deactivated people). Another user's row is writable only withusers_updatein a company where that user has an activeuserToCompanyrow. INSERT and DELETE are revoked fromanon/authenticated, so they go through the service role. A BEFORE UPDATE trigger (guard_user_identity_columns) rejects any API-role change toid,email,active,admin,developerorisConsoleOperator. Sending those columns unchanged is fine. Deleting a user also deletes its identitygroup(sync_delete_user_identity_group).employeeandemployeeJobshare composite PK(id, companyId)andid → user.id— always scope queries by both id and companyId. A user has one employee/employeeJob row per company.userToCompany.role(membership type) is distinct fromemployeeType(which permission set); don't conflate "role" the enum with "role" the job title (employeeJob.title).- Permission company-ID array
"0"means "all companies" — don't string-match a literal company id only. - Deactivating an employee (
deactivateEmployeeinpackages/auth/src/services/users.server.ts) removes the company fromuserPermission.permissions, deletes theuserToCompanyrow and everymembershipin groups owned by that company, and setsemployee.active = false. It does not clearuser.active, delete theemployeeoremployeeJobrows, or scrub stored userId references (assignee columns,workCenterEmployee, notification-group settings arrays). - The claims cache is invalidated by the deactivate* functions themselves, not by their
callers.
deactivateEmployee/Customer/Suppliereachredis.del(getPermissionCacheKey(userId))on success, anddeactivateUserdeletes it again after delegating. That matters becauserequirePermissionsreads the cache (1h TTL) before the database, and thecreate*Accountrollback paths in the ERP call the role-specific functions directly rather than going throughdeactivateUser— a caller that skipped the invalidation would leave revoked grants live.employeeJobis kept on purpose — it is org placement, not access — so title, start date, department, shift, manager, location, tags and custom fields survive a deactivate/re-invite round trip. Group memberships do not: acceptance restores only the employee-type group, so a re-invited person must be added back to any custom group by hand. Because the row survives, a reader ofemployeeJobthat means "current staff" must also checkemployee.active(getScheduledEmployeesTodaydoes;employeeJobhas no FK toemployeeto embed). - Planning stores more user ids the deactivation does not scrub:
itemPlanning.responsibleEmployee,location.responsibleEmployee,companySettings.defaultResponsibleEmployee,itemPostingGroupResponsibility.responsibleEmployeeandplanningAction.assignee(allTEXT REFERENCES "user"("id"), so the database accepts any user's id, including another company's). A route saves one only afterisActiveCompanyEmployee(client, companyId, userId)(apps/erp/app/modules/shared/shared.service.ts), which fails closed on a read error. - Re-adding a deactivated person through Add Account (
createEmployeeAccount) reuses the surviving rows rather than failing: it refuses only when the existingemployeerow isactive. A person whose invite is still pending is re-added the same way, which issues a new code and invalidates the link already emailed. The reuse path (reinviteDeactivatedEmployee) is one Kysely transaction: it locks theemployeerow and re-checksactiveunder the lock, updatesemployeeTypeId, upsertsemployeeJob(onlylocationId,updatedByandupdatedAton conflict) and upserts theinviteon(email, companyId)— so the invite's permissions and the row's employee type cannot diverge, and a failed write leaves no redeemable invite. It never inserts a first-timeemployeerow; that stays under the caller's RLS client. - The re-add writes outside RLS, so it checks what RLS would have. The route requires only
users_create, but a first-time add insertsemployeeandemployeeJobunder the caller's client, whose INSERT policies requireusers_updateandpeople_create. Before the reuse transaction,createEmployeeAccountreads the inviter's claims (getUserClaims) and refuses unless both are held — otherwise ausers_create-only admin could re-add someone they could never have added. The writes stamp the inviter inupdatedBy(employeeJob,invite) because the Kysely connection has noauth.uid()for the audit log;employeehas no audit columns. - A re-used invite row restarts
createdAt(insertInviteand the reuse path both set it). The controlled-environment expiry (isControlledInviteExpired) counts from it, and the reused row is the person's original invite, so keeping it expired the new invite on arrival. - Re-activation happens on invite acceptance —
acceptInvite(apps/erp/app/modules/users/users.service.ts) restores the employee-typemembershipthe deactivation removed (thesync_add_employee_to_type_grouptrigger fires on INSERT only, so an UPDATE cannot rely on it), flipsactiveback to true, and stampsacceptedAtin one Kysely transaction, so a failed restore leaves the invite unaccepted and retryable rather than an active employee outside their type's group. TheacceptedAtupdate also requiresrevokedAt IS NULL, so a revoke that commits after the invite was looked up still wins. Before merginguserPermission, the transaction locks theuserrowFOR NO KEY UPDATE(migrateUserToSsodoes the same), so two first acceptances for one user in different companies cannot drop each other's grants. The membership insert usesON CONFLICT ("groupId", "memberUserId") DO NOTHINGagainstmembership_groupId_memberUserId_key(20261015074817), which is what makes it safe against the trigger racing the same insert. - Every writer of a user membership must tolerate that index. Before it,
uq_membership(groupId, memberGroupId, memberUserId) never deduped user memberships (memberGroupIdis NULL on all of them), so duplicates were silent. The insert interceptors (sync_add_employee_to_type_group,sync_add_customer_account_to_group,sync_add_supplier_account_to_group) useON CONFLICT … DO NOTHING, andsync_update_employee_type_membershipdrops the old membership instead of moving it when the user is already in the new type's group (20261015075112). A new writer needs the same, or a leftover membership fails the insert or update that fired it. - Notification fan-out (
notify.tsresolve-recipientsinpackages/jobs) filters resolved recipients againstuserToCompanyfor the notification's company — a missing membership row (i.e. a deactivated user) is dropped before any in-app/email/Slack delivery, regardless of how the recipient list was built. - Permission/claims helper SQL functions are redefined across many migrations — always read the newest.