docs: sync from backend 8fc2309 — M43/M44 missing FKs + H37 dispute enums

This commit is contained in:
Siavash Sameni
2026-06-07 07:16:02 +04:00
parent a2967ec594
commit 0bb60dbc98
24 changed files with 3428 additions and 906 deletions

View File

@@ -1,24 +1,34 @@
---
title: User
tags: [data-model, mongoose, postgres, dual-write]
tags: [data-model, postgres, drizzle]
aliases: [User Model, IUser, Account]
---
# User
> **Last updated:** 2026-06-03added Postgres/Drizzle schema, `guard` role (migration 0017), dual-write status. Previous update: 2026-05-29 (see [Doc vs Code Audit Report](../09%20-%20Audits/Doc%20vs%20Code%20Audit%20Report%20-%202026-05-29.md))
> **Last updated:** 2026-06-06MongoDB fully removed; PostgreSQL + Drizzle is the only database layer (backend v2.9.12). Previous update: 2026-06-03 (dual-write status, guard role).
The core identity document for every actor in the marketplace: buyers, sellers, and admins. Stores credentials (password + WebAuthn passkeys), profile/preference data, referral bookkeeping, point balances, and a soft-delete status flag. Almost every other model carries an `ObjectId` (Mongo) or `uuid` (Postgres) reference back to `User`, so this collection is the relational hub of the system.
The core identity document for every actor in the marketplace: buyers, sellers, and admins. Stores credentials (password + WebAuthn passkeys), profile/preference data, referral bookkeeping, point balances, and a soft-delete status flag. Almost every other model carries a `uuid` (Postgres) reference back to `User`, so this table is the relational hub of the system.
> [!info] Migration status: DUAL-WRITE
> Writes go to **both** MongoDB (`User` collection) and Postgres (`users` table) via `DualWriteUserRepo`.
> Reads still come from **MongoDB** — PG reads are not yet enabled.
> Repositories: `DrizzleUserRepo`, `MongoUserRepo`, `DualWriteUserRepo`
> [!info] Migration status: COMPLETE
> MongoDB and Mongoose have been fully removed from the backend runtime. PostgreSQL + Drizzle ORM is the sole database layer (19 migrations landed, 00000019, 32 tables).
> Repository: `DrizzleUserRepo` (returned exclusively by the repository factory)
> Postgres table: **`users`** — `backend/src/db/schema/users.ts`
---
## Postgres Table: `users`
## ID Duality
| Field | Storage | Purpose |
| --- | --- | --- |
| `id` (PG column) / `pgId` (domain object) | `uuid`, PG primary key | Used for all marketplace foreign keys: `offer.sellerId`, `purchaseRequest.buyerId`, `payment.buyerId/sellerId`, etc. |
| `legacy_object_id` (PG column) / `_id` (domain/auth tokens) | `text`, 24-hex ObjectId string | Kept for backward compatibility with socket rooms (rooms keyed by legacy id) and auth tokens issued before migration. Partial-unique index WHERE NOT NULL. |
> [!warning] Always match marketplace FKs on `pgId` (UUID), not on `legacy_object_id`. Notifications and socket rooms use the legacy id string.
---
## PostgreSQL Schema (Drizzle): `users`
> [!note] Source
> `backend/src/db/schema/users.ts`
@@ -27,8 +37,8 @@ The core identity document for every actor in the marketplace: buyers, sellers,
| Column | PG Type | Nullable | Default | Notes |
| --- | --- | --- | --- | --- |
| `id` | `uuid` | no | `gen_random_uuid()` | Primary key |
| `legacy_object_id` | `text` | yes | — | Mongo ObjectId; partial-unique index WHERE NOT NULL; used for idempotent backfill upserts |
| `id` | `uuid` | no | `gen_random_uuid()` | Primary key (`pgId` in domain objects) |
| `legacy_object_id` | `text` | yes | — | 24-hex ObjectId string; partial-unique index WHERE NOT NULL; kept for socket rooms and legacy auth token compatibility |
| `email` | `varchar(255)` | yes | — | Partial-unique index WHERE NOT NULL |
| `password` | `varchar(255)` | yes | — | Hashed |
| `first_name` | `text` | yes | — | — |
@@ -62,7 +72,7 @@ The core identity document for every actor in the marketplace: buyers, sellers,
### Child Tables
**`user_passkeys`** — WebAuthn credentials extracted from the embedded array:
**`user_passkeys`** — WebAuthn credentials:
| Column | Type | Notes |
| --- | --- | --- |
@@ -74,14 +84,14 @@ The core identity document for every actor in the marketplace: buyers, sellers,
| `device_name` | `text` | Optional human label |
| `created_at` | `timestamptz` | — |
**`user_refresh_tokens`** — Active JWT refresh tokens extracted from the Mongo array:
**`user_refresh_tokens`** — Active JWT refresh tokens:
| Column | Type | Notes |
| --- | --- | --- |
| `token` | `text` (PK) | The refresh token string |
| `user_id` | `uuid FK→users CASCADE` | Owner |
### Indexes (Postgres)
### Indexes
| Index | Type | Condition |
| --- | --- | --- |
@@ -102,11 +112,7 @@ The core identity document for every actor in the marketplace: buyers, sellers,
---
## MongoDB Collection: `User` (legacy — reads still active)
> [!note] Source
> `backend/src/models/User.ts:70` — schema definition
> `backend/src/models/User.ts:257` — model export
## Field Reference
> [!note] Email change re-verification
> When a profile update (`PUT /api/user/profile`, `userController.updateUserProfile`) changes `email` to a new value, the controller sets `isEmailVerified = false`, generates a **6-digit** `emailVerificationCode` (valid 15 minutes), stores it on `emailVerificationCode` / `emailVerificationCodeExpires`, and emails the code to the new address. The user must then confirm via `POST /api/user/profile/email/verify` (or request a new code with `POST /api/user/profile/email/resend-verification`).
@@ -114,99 +120,73 @@ The core identity document for every actor in the marketplace: buyers, sellers,
> [!note] Wallet ownership proof
> `PATCH /api/user/wallet-address` accepts both EVM and TON wallets. EVM addresses require an EIP-191 signature (`ethers.verifyMessage`); TON addresses are format-validated and may include an optional TonProof. A successful proof sets `profile.walletProofVerified = true` and `profile.walletProofTimestamp`.
### Schema
| Field | Type | Required | Default | Validation | Index | Description |
| --- | --- | --- | --- | --- | --- | --- |
| `email` | String | no | — | lowercase, trim | unique, sparse | Primary email login identifier. Nullable for Telegram-only accounts. |
| `password` | String | no | — | minlength 6 | — | Hashed password. Optional to support passkey-only, Google, and Telegram accounts. |
| `firstName` | String | no | `"کاربر"` | trim | — | Persian default ("user"). |
| `lastName` | String | no | `"جدید"` | trim | — | Persian default ("new"). |
| `role` | String | yes | `"buyer"` | enum: `admin` / `buyer` / `seller` / `resolver` / `guard` | yes | Authorisation tier. `resolver` (commit `fce8a19`): can view/resolve disputes and bypass chat membership checks. `guard` (migration 0017): added in PG schema; purpose TBD. |
| `isEmailVerified` | Boolean | no | `false` | — | — | Set to true after the email verification code is consumed. Warning: Changing the email via `PUT /api/user/profile` **resets this to `false`** and dispatches a fresh **6-digit** verification code to the new address. |
| `authProvider` | String | yes | `"email"` | enum: `email` / `google` / `telegram` | yes | Provider used to create the account. Existing email/password accounts remain `email`; Telegram-only users are `telegram`. |
| `telegramVerified` | Boolean | no | `false` | — | — | Set when Telegram identity has been signature-verified and linked through `TelegramLink`. |
| `emailVerificationToken` | String | no | — | — | — | Legacy token-based email verification. |
| `emailVerificationCode` | String | no | — | — | — | OTP code for email verification. |
| `emailVerificationCodeExpires` | Date | no | — | — | — | Expiry for `emailVerificationCode`. |
| `passwordResetToken` | String | no | — | — | — | Token for reset link flow. |
| `passwordResetExpires` | Date | no | — | — | — | Expiry of `passwordResetToken`. |
| `passwordResetCode` | String | no | — | — | — | OTP reset code. |
| `passwordResetCodeExpires` | Date | no | — | — | — | Expiry for OTP reset code. |
| `passkeys[]` | Subdocument array | no | `[]` | — | — | WebAuthn credentials. Extracted to `user_passkeys` table in PG. |
| `passkeys[].id` | String | yes | — | — | — | Credential ID. |
| `passkeys[].publicKey` | String | yes | — | — | — | Stored public key. |
| `passkeys[].counter` | Number | yes | `0` | — | — | Signature counter. |
| `passkeys[].deviceType` | String | yes | — | enum: `platform` / `cross-platform` | — | Authenticator class. |
| `passkeys[].deviceName` | String | no | — | — | — | Optional human label. |
| `passkeys[].createdAt` | Date | no | `Date.now` | — | — | Registration timestamp. |
| `profile.avatar` | String | no | — | — | — | Avatar URL. |
| `profile.photoURL` | String | no | — | — | — | Alternative photo URL. |
| `profile.phone` | String | no | — | — | — | Contact phone. |
| `profile.address.street` | String | no | — | — | — | Inline address (separate from Address book). |
| `profile.address.city` | String | no | — | — | — | — |
| `profile.address.state` | String | no | — | — | — | — |
| `profile.address.zipCode` | String | no | — | — | — | — |
| `profile.address.country` | String | no | — | — | — | — |
| `profile.bio` | String | no | — | — | — | Free-form bio. |
| `profile.website` | String | no | — | — | — | Personal website URL. |
| `profile.walletAddress` | String | no | — | — | — | On-chain wallet address (EVM `0x…` or TON). Set via `PATCH /api/user/wallet-address`. |
| `profile.walletType` | String | no | — | enum: `evm` / `ton` | — | Which chain family the stored `walletAddress` belongs to. |
| `profile.walletProvider` | String | no | — | — | — | Wallet provider label (e.g. `evm`, `telegram-wallet`). Defaults to `telegram-wallet` for TON, `evm` otherwise. |
| `profile.walletProofVerified` | Boolean | no | — | — | — | True when ownership was proven — EIP-191 signature for EVM, or a verified TonProof for TON. |
| `profile.walletProofTimestamp` | Date | no | — | — | — | When the wallet proof was last verified (only set when `walletProofVerified` is true). |
| `profile.isPublic` | Boolean | no | `false` | — | — | Whether the profile is publicly visible. |
| `preferences.language` | String | no | `"en"` | — | — | UI language. |
| `preferences.currency` | String | no | `"USD"` | — | — | Display currency. |
| `preferences.notifications.email` | Boolean | no | `true` | — | — | Opt-in for email notifications. |
| `preferences.notifications.sms` | Boolean | no | `false` | — | — | Opt-in for SMS notifications. |
| `preferences.notifications.push` | Boolean | no | `true` | — | — | Opt-in for push notifications. |
| `status` | String | no | `"active"` | enum: `active` / `suspended` / `deleted` | yes | Soft-delete and moderation flag. |
| `lastLoginAt` | Date | no | — | — | — | Updated by auth middleware. |
| `refreshTokens[]` | String[] | no | `[]` | — | — | Array of currently active JWT refresh tokens. Warning: Reset to `[]` on password change and on password reset, invalidating every outstanding session. Extracted to `user_refresh_tokens` table in PG. |
| `referralCode` | String | no | — | — | unique, sparse | **Not yet implemented** — planned for referral programme. |
| `referredBy` | ObjectId -> User | no | — | — | yes | **Not yet implemented** — planned for referral programme. |
| `points.total` | Number | no | `0` | — | — | **Not yet implemented** — planned for loyalty system. |
| `points.available` | Number | no | `0` | — | — | **Not yet implemented.** |
| `points.used` | Number | no | `0` | — | — | **Not yet implemented.** |
| `points.level` | Number | no | `1` | — | yes | **Not yet implemented** — planned for LevelConfig lookup. |
| `referralStats.totalReferrals` | Number | no | `0` | — | — | **Not yet implemented.** |
| `referralStats.activeReferrals` | Number | no | `0` | — | — | **Not yet implemented.** |
| `referralStats.totalEarned` | Number | no | `0` | — | — | **Not yet implemented.** |
| `createdAt` | Date | auto | — | — | — | Mongoose timestamp. |
| `updatedAt` | Date | auto | — | — | — | Mongoose timestamp. |
### Virtuals
| Virtual | Returns | Definition |
| Field (domain / camelCase) | PG Column | Notes |
| --- | --- | --- |
| `fullName` | `${firstName} ${lastName}` | `backend/src/models/User.ts:238` |
| `id` / `pgId` | `id` (uuid PK) | Used for all marketplace FKs |
| `_id` / `legacyObjectId` | `legacy_object_id` | 24-hex string; socket rooms + legacy auth tokens |
| `email` | `email` | Primary email login; nullable for Telegram-only accounts |
| `password` | `password` | Hashed; optional for passkey/Google/Telegram accounts |
| `firstName` | `first_name` | Persian default "کاربر" |
| `lastName` | `last_name` | Persian default "جدید" |
| `role` | `role` | enum: `admin` / `buyer` / `seller` / `resolver` / `guard` |
| `isEmailVerified` | `is_email_verified` | Reset to false on email change |
| `authProvider` | `auth_provider` | enum: `email` / `google` / `telegram` |
| `telegramVerified` | `telegram_verified` | Set after Telegram signature-verify + link |
| `emailVerificationToken` | `email_verification_token` | Legacy token flow |
| `emailVerificationCode` | `email_verification_code` | OTP code |
| `emailVerificationCodeExpires` | `email_verification_code_expires` | — |
| `passwordResetToken` | `password_reset_token` | Token for reset link flow |
| `passwordResetExpires` | `password_reset_expires` | — |
| `passwordResetCode` | `password_reset_code` | OTP reset code |
| `passwordResetCodeExpires` | `password_reset_code_expires` | — |
| `passkeys[]` | `user_passkeys` child table | WebAuthn credentials |
| `passkeys[].id` | `user_passkeys.id` | Credential ID (PK) |
| `passkeys[].publicKey` | `user_passkeys.public_key` | Stored public key |
| `passkeys[].counter` | `user_passkeys.counter` | Signature counter |
| `passkeys[].deviceType` | `user_passkeys.device_type` | enum: `platform` / `cross-platform` |
| `passkeys[].deviceName` | `user_passkeys.device_name` | Optional human label |
| `passkeys[].createdAt` | `user_passkeys.created_at` | Registration timestamp |
| `profile.avatar` | `profile` jsonb | Avatar URL |
| `profile.photoURL` | `profile` jsonb | Alternative photo URL |
| `profile.phone` | `profile` jsonb | Contact phone |
| `profile.address.*` | `profile` jsonb | street, city, state, zipCode, country |
| `profile.bio` | `profile` jsonb | Free-form bio |
| `profile.website` | `profile` jsonb | Personal website URL |
| `profile.walletAddress` | `profile` jsonb | EVM `0x…` or TON address; set via `PATCH /api/user/wallet-address` |
| `profile.walletType` | `profile` jsonb | enum: `evm` / `ton` |
| `profile.walletProvider` | `profile` jsonb | e.g. `evm`, `telegram-wallet` |
| `profile.walletProofVerified` | `profile` jsonb | True when ownership proven (EIP-191 or TonProof) |
| `profile.walletProofTimestamp` | `profile` jsonb | Last verified timestamp |
| `profile.isPublic` | `profile` jsonb | Whether profile is publicly visible |
| `preferences.language` | `preferences` jsonb | UI language; default `"en"` |
| `preferences.currency` | `preferences` jsonb | Display currency; default `"USD"` |
| `preferences.notifications.email` | `preferences` jsonb | Opt-in email notifications; default `true` |
| `preferences.notifications.sms` | `preferences` jsonb | Opt-in SMS notifications; default `false` |
| `preferences.notifications.push` | `preferences` jsonb | Opt-in push notifications; default `true` |
| `status` | `status` | enum: `active` / `suspended` / `deleted` |
| `lastLoginAt` | `last_login_at` | Updated by auth middleware |
| `refreshTokens[]` | `user_refresh_tokens` child table | Active JWT refresh tokens; reset on password change/reset |
| `referralCode` | `referral_code` | Planned referral programme |
| `referredBy` | `referred_by_id` (uuid FK) | Planned referral programme |
| `points.total` | `points_total` | Planned loyalty system |
| `points.available` | `points_available` | Planned loyalty system |
| `points.used` | `points_used` | Planned loyalty system |
| `points.level` | `points_level` | Planned LevelConfig lookup |
| `referralStats.totalReferrals` | `referral_stats_total` | Planned |
| `referralStats.activeReferrals` | `referral_stats_active` | Planned |
| `referralStats.totalEarned` | `referral_stats_total_earned` | Planned |
| `createdAt` | `created_at` | Drizzle timestamp |
| `updatedAt` | `updated_at` | Drizzle timestamp |
### Indexes (MongoDB)
### Computed / Virtual
Defined explicitly:
| Virtual | Returns | Notes |
| --- | --- | --- |
| `fullName` | `${firstName} ${lastName}` | Computed in domain layer (was Mongoose virtual) |
- `{ email: 1 }` unique sparse — allows multiple Telegram-only users without email while preserving uniqueness for email-bearing users.
- `{ role: 1 }``backend/src/models/User.ts:178`
- `{ status: 1 }``backend/src/models/User.ts:179`
- `{ authProvider: 1 }` — supports provider-level account reporting and cleanup.
### Serialisation
> [!warning] Missing indexes in Mongo schema
> The schema currently defines only `role` and `status` indexes. The `referralCode`, `referredBy`, and `points.level` indexes documented below are **not yet present** in `User.ts`.
### Pre/Post Hooks
None declared at the schema level.
### Instance Methods
| Signature | Purpose |
| --- | --- |
| `toJSON(): object` | Strips `password`, `refreshTokens`, all `emailVerification*` and `passwordReset*` fields before serialisation. Defined at `backend/src/models/User.ts:243`. |
### Static Methods
None defined on the schema.
`toJSON()` strips `password`, `refreshTokens`, all `emailVerification*` and `passwordReset*` fields before serialisation.
---
@@ -218,16 +198,13 @@ None defined on the schema.
| `buyer` | original | Place purchase requests, confirm delivery |
| `seller` | original | Submit offers, manage shop |
| `resolver` | commit `fce8a19` | View/resolve disputes; bypass chat membership checks; no other admin privileges |
| `guard` | migration 0017 (PG only) | Purpose TBD — defined in `user_role` PG enum, not yet in Mongo schema |
> [!warning] Role enum drift
> The Postgres `user_role` enum includes `guard`; the Mongo schema enum does not. Until the Mongo schema is updated, any `guard`-role user created through PG will not be representable in Mongo and will break dual-write for that record.
| `guard` | migration 0017 | Defined in `user_role` PG enum; purpose TBD |
---
## Relationships
- **References**: User (self, via `referredBy` / `referred_by_id`).
- **References**: User (self, via `referred_by_id`).
- **Referenced by**: PurchaseRequest (`buyerId`, `preferredSellerIds`, `deliveryInfo.deliveryCodeUsedBy`, `deliveryInfo.deliveryAttempts[].sellerId`), SellerOffer (`sellerId`), Payment (`buyerId`, `sellerId`), Chat (`participants[].userId`, `messages[].senderId`, `metadata.createdBy`), Notification (`userId` as string), RequestTemplate (`sellerId`), Dispute (`buyerId`, `sellerId`, `adminId`), BlogPost (`author.id`), Address (`userId`), Review (`sellerId`, `reviewerId`), PointTransaction (`user`, `referredUser`), ShopSettings (`sellerId`).
## State Transitions
@@ -244,32 +221,24 @@ stateDiagram-v2
## Common Queries
```ts
// Mongo — Find by email (login)
User.findOne({ email: email.toLowerCase() });
// Mongo — Active sellers
User.find({ role: 'seller', status: 'active' });
// Mongo — Validate referral
User.findOne({ referralCode: code });
// Mongo — Leaderboard by points
User.find({ status: 'active' }).sort({ 'points.total': -1 }).limit(10);
// Mongo — Promote level
User.updateOne({ _id: id }, { $set: { 'points.level': newLevel } });
```
```sql
-- PG — Find by email
-- Find by email (login)
SELECT * FROM users WHERE email = lower($1) AND email IS NOT NULL;
-- PG — Active sellers
-- Active sellers
SELECT * FROM users WHERE role = 'seller' AND status = 'active';
-- PG — Leaderboard by points
-- Validate referral code
SELECT * FROM users WHERE referral_code = $1 AND referral_code IS NOT NULL;
-- Leaderboard by points
SELECT * FROM users WHERE status = 'active' ORDER BY points_total DESC LIMIT 10;
-- Promote level
UPDATE users SET points_level = $1, updated_at = now() WHERE id = $2;
-- Lookup by legacy ObjectId (socket rooms / auth token migration)
SELECT * FROM users WHERE legacy_object_id = $1;
```
Related: TempVerification, LevelConfig, PointTransaction, ShopSettings.