# PEOPLEFLOW — Database Architecture & ERD

## 1. Core Data Modeling Principles

1. **Group-Wide Employee Identity vs. Company-Scoped Employment Assignments**:
   - A person (`Employee`) exists **once** across SMC Cement Group (`globalEmployeeCode`, e.g., `SMC-000142`).
   - Their employment within **ECC**, **NCC**, or **SCII** is modeled as `EmploymentAssignment` (carrying `companyId`, company-specific `companyEmployeeNo`, `departmentId`, `positionId`, `managerAssignmentId`, `workLocation`, `costCenter`, `startDate`, `endDate`, `status`, `isPrimary`).
   - **Why this matters**: When an employee transfers from **ECC** to **NCC**, PEOPLEFLOW does **not** duplicate the person. Instead, the ECC `EmploymentAssignment` closes with status `TRANSFERRED` and a new NCC `EmploymentAssignment` opens as `ACTIVE`, preserving complete employment, asset, access, and audit history under one identity.
2. **Immutable Lifecycle & Approval History**:
   - Lifecycle requests (`OnboardingRequest`, `OffboardingRequest`, `MovementRequest`), `ApprovalHistory`, `Task`, `AssetAssignment`, and `AuditLog` are **never hard-deleted** upon separation.
3. **Immutable Workflow Snapshots**:
   - When a lifecycle request triggers a published `WorkflowVersion`, the engine binds the request to that exact `workflowVersionId`. Editing a workflow later creates a new Draft version and never mutates in-flight requests.
4. **Auditability**:
   - Every core table tracks `createdAt`, `updatedAt`, `createdById`, `updatedById`.
   - Critical state transitions run inside `prisma.$transaction(...)` together with `AuditLog` creation.

---

## 2. Entity-Relationship Diagram (ERD)

```mermaid
erDiagram
    Company ||--o{ Department : has
    Company ||--o{ Position : defines
    Company ||--o{ EmploymentAssignment : employs
    Company ||--o{ UserCompanyAccess : grants
    Company ||--o{ Asset : owns
    Company ||--o{ Workflow : scopes

    Department ||--o{ Position : contains
    Department ||--o{ EmploymentAssignment : assigns
    Department ||--o{ Task : owns

    User ||--o{ UserRole : has
    Role ||--o{ UserRole : assigned_to
    Role ||--o{ RolePermission : grants
    Permission ||--o{ RolePermission : mapped_to
    User ||--o{ UserCompanyAccess : scoped_to
    User ||--o| Employee : linked_identity

    Employee ||--o{ EmploymentAssignment : holds
    EmploymentAssignment ||--o{ EmploymentAssignment : manages
    Employee ||--o{ EmployeeApplicationAccess : has
    AccessProfile ||--o{ EmployeeApplicationAccess : templates

    Employee ||--o{ OnboardingRequest : subject_of
    Employee ||--o{ OffboardingRequest : subject_of
    Employee ||--o{ MovementRequest : subject_of

    Workflow ||--o{ WorkflowVersion : versions
    WorkflowVersion ||--o{ WorkflowStage : contains
    WorkflowStage ||--o{ WorkflowTaskTemplate : defines
    WorkflowVersion ||--o{ OnboardingRequest : drives
    WorkflowVersion ||--o{ OffboardingRequest : drives
    WorkflowVersion ||--o{ MovementRequest : drives

    OnboardingRequest ||--o{ Task : generates
    OffboardingRequest ||--o{ Task : generates
    MovementRequest ||--o{ Task : generates
    Task ||--o{ TaskDependency : depends_on
    Task ||--o{ TaskComment : has
    Task ||--o{ TaskAssignment : assigned_to

    OnboardingRequest ||--o{ Approval : requires
    OffboardingRequest ||--o{ Approval : requires
    MovementRequest ||--o{ Approval : requires
    Approval ||--o{ ApprovalHistory : logs

    Asset ||--o{ AssetAssignment : tracks
    Employee ||--o{ AssetAssignment : holds
    AssetAssignment ||--o| AssetReturn : closed_by

    Employee ||--o{ Document : owns
    Integration ||--o{ IntegrationLog : records
    User ||--o{ Notification : receives
    User ||--o{ AuditLog : performs
```

---

## 3. Core Entity Specification

### A. Identity, RBAC & Company Scope
| Entity | Key Columns & Constraints | Purpose |
| :--- | :--- | :--- |
| `Company` | `id`, `code` (`ECC`\|`NCC`\|`SCII`, unique), `name`, `legalName`, `isActive` | Multi-company tenant root |
| `User` | `id`, `email` (unique), `entraObjectId` (unique nullable), `passwordHash` (dev only), `name`, `isActive`, `hasGroupWideAccess`, `employeeId` (unique nullable) | Authenticated application account |
| `Role` | `id`, `code` (unique), `name`, `description`, `isSystem` | 9 enterprise RBAC roles |
| `Permission` | `id`, `code` (unique, e.g. `onboarding.create`, `employee.pii.read`), `module`, `action`, `description` | Granular capability atoms |
| `UserRole` | `(userId, roleId)` unique | Many-to-many user-role assignment |
| `RolePermission` | `(roleId, permissionId)` unique | Role capability matrix |
| `UserCompanyAccess` | `(userId, companyId)` unique | Restricts user visibility to authorized companies |

### B. Organization & Employee Master Data
| Entity | Key Columns & Constraints | Purpose |
| :--- | :--- | :--- |
| `Department` | `id`, `companyId`, `code`, `name`, `headEmployeeId`, unique `(companyId, code)` | Company departments & dept heads |
| `Position` | `id`, `companyId`, `departmentId`, `code`, `title`, `employmentLevel` | Job roles & default access profiles |
| `Employee` | `id`, `globalEmployeeCode` (unique), `firstName`, `middleName`, `lastName`, `suffix`, `dateOfBirth` (PII), `gender` (optional), `personalEmail` (PII), `contactNumber` (PII), `corporateEmail` (unique nullable), `lifecycleStatus` | Group-wide canonical employee identity |
| `EmploymentAssignment` | `id`, `employeeId`, `companyId`, `companyEmployeeNo`, `departmentId`, `positionId`, `managerAssignmentId`, `employmentType`, `employmentClassification`, `workLocation`, `costCenter`, `dateHired`, `effectiveStartDate`, `effectiveEndDate`, `status`, `isPrimary`, unique `(companyId, companyEmployeeNo)` | Company-specific active & historical employment assignments |
| `AccessProfile` | `id`, `companyId` (nullable for group-wide), `name`, `entitlementsJson` | Reusable IT access bundles (M365, Ramco, Freshservice, VPN) |
| `EmployeeApplicationAccess` | `id`, `employeeId`, `companyId`, `applicationName`, `externalAccountId`, `accessStatus` (`PENDING`\|`ACTIVE`\|`DISABLED`\|`REVOKED`\|`FAILED`), `lastVerifiedAt`, `lastVerificationResultJson` | Live & verified record of external system accounts |

### C. Lifecycle Requests
| Entity | Key Columns & Constraints | Purpose |
| :--- | :--- | :--- |
| `OnboardingRequest` | `id`, `requestNumber` (unique), `companyId`, `employeeId`, `assignmentId`, `workflowVersionId`, `status`, `startDate`, `itRequirementsJson`, `equipmentRequirementsJson`, `specialInstructions`, `requestedById`, `idempotencyKey` (unique nullable), `completedAt` | Full onboarding request & requirements |
| `OffboardingRequest` | `id`, `requestNumber` (unique), `companyId`, `employeeId`, `assignmentId`, `workflowVersionId`, `status`, `separationType`, `isEmergency`, `resignationDate`, `lastWorkingDate`, `scheduledDeactivationAt`, `separationReason` (restricted HR PII), `handoverEmployeeId`, `specialInstructions`, `requestedById`, `idempotencyKey`, `completedAt` | Controlled & emergency separation lifecycle |
| `MovementRequest` | `id`, `requestNumber` (unique), `employeeId`, `movementType` (`DEPT_TRANSFER`\|`POSITION_CHANGE`\|`PROMOTION`\|`MANAGER_CHANGE`\|`LOCATION_CHANGE`\|`COMPANY_TRANSFER`), `sourceCompanyId`, `targetCompanyId`, `sourceAssignmentId`, `targetAssignmentId`, `workflowVersionId`, `effectiveDate`, `proposedChangesJson`, `accessReviewStatus`, `status`, `requestedById`, `completedAt` | Intra-company & inter-company transfers |

### D. Workflow Engine, Tasks & Approvals
| Entity | Key Columns & Constraints | Purpose |
| :--- | :--- | :--- |
| `Workflow` | `id`, `code` (unique), `name`, `lifecycleType` (`ONBOARDING`\|`OFFBOARDING`\|`MOVEMENT`), `companyId` (nullable = group template), `isActive` | Workflow template container |
| `WorkflowVersion` | `id`, `workflowId`, `versionNumber`, `status` (`DRAFT`\|`PUBLISHED`\|`ARCHIVED`), `dateReferenceField`, `publishedAt`, `publishedById`, unique `(workflowId, versionNumber)` | Immutable versioned workflow blueprint |
| `WorkflowStage` | `id`, `workflowVersionId`, `name`, `sortOrder`, `colorToken` | Visual stage grouping (`Pre-Start`, `Day 1`, `Week 1`, etc.) |
| `WorkflowTaskTemplate` | `id`, `stageId`, `title`, `description`, `nodeType` (`TASK`\|`APPROVAL`\|`FORM`\|`MEETING`\|`TRAINING`\|`DOCUMENT_REQUEST`\|`CONDITION`\|`DELAY`\|`WEBHOOK`\|`INTEGRATION_ACTION`\|`NOTIFICATION`), `assignedDepartmentRole`, `defaultAssigneeUserId`, `relativeDueDays`, `dueTime`, `isRequired`, `conditionJson`, `configJson`, `dependsOnTemplateIdsJson`, `sortOrder` | Executable node definition |
| `Task` | `id`, `companyId`, `requestType`, `onboardingRequestId`, `offboardingRequestId`, `movementRequestId`, `employeeId`, `templateId`, `stageName`, `title`, `description`, `nodeType`, `assignedDepartment`, `assignedUserId`, `priority`, `status` (`PENDING`\|`IN_PROGRESS`\|`WAITING_APPROVAL`\|`BLOCKED`\|`COMPLETED`\|`CANCELLED`), `isRequired`, `dueDate`, `completedAt`, `completedById`, `externalVerificationStatus`, `externalResponseJson` | Concrete executable task instance |
| `TaskDependency` | `(taskId, dependsOnTaskId)` unique | Blocks downstream task until prerequisite completes |
| `TaskComment` | `id`, `taskId`, `authorId`, `body`, `createdAt` | Threaded task collaboration & evidence notes |
| `Approval` | `id`, `companyId`, `requestType`, `onboardingRequestId`, `offboardingRequestId`, `movementRequestId`, `stepOrder`, `approvalRole`, `approverUserId`, `status` (`PENDING`\|`APPROVED`\|`REJECTED`\|`CANCELLED`), `decidedAt`, `remarks` | Structured multi-step approval gates |
| `ApprovalHistory` | `id`, `approvalId`, `actorId`, `action`, `remarks`, `createdAt` | Immutable log of approval actions/reassignments |

### E. Assets, Documents, Integrations & Governance
| Entity | Key Columns & Constraints | Purpose |
| :--- | :--- | :--- |
| `Asset` | `id`, `companyId`, `assetTag` (unique), `serialNumber`, `category`, `brand`, `model`, `location`, `condition`, `status` (`AVAILABLE`\|`ASSIGNED`\|`UNDER_MAINTENANCE`\|`FOR_DISPOSAL`\|`RETURNED`\|`LOST`\|`DAMAGED`) | Company physical & IT equipment registry |
| `AssetAssignment` | `id`, `assetId`, `employeeId`, `companyId`, `assignedAt`, `assignedById`, `conditionAtIssue`, `status`, `notes` | Active & historical employee asset accountability |
| `AssetReturn` | `id`, `assetAssignmentId` (unique), `offboardingRequestId`, `returnedAt`, `receivedById`, `conditionAtReturn`, `damageNotes`, `clearanceVerified` | Structured asset return & condition verification |
| `Document` | `id`, `companyId`, `employeeId`, `requestType`, `requestId`, `taskId`, `category`, `fileName`, `mimeType`, `sizeBytes`, `storageKey`, `version`, `accessLevel`, `retentionUntil`, `uploadedById` | Access-controlled metadata for private files |
| `Integration` | `id`, `companyId` (nullable = group), `provider` (`MICROSOFT_GRAPH`\|`FRESHSERVICE`\|`RAMCO_ERP`\|`SMTP`), `mode` (`MOCK`\|`LIVE`), `isEnabled`, `encryptedConfig`, `lastSyncAt`, `lastHealthStatus` | Integration configuration & mode control |
| `IntegrationLog` | `id`, `integrationId`, `companyId`, `requestType`, `requestId`, `taskId`, `operation`, `externalRefId`, `status` (`SUCCESS`\|`FAILED`\|`RETRYING`), `requestPayloadRedacted`, `responsePayloadRedacted`, `errorMessage`, `retryCount`, `executedAt` | Full traceability for external API calls & verification |
| `Notification` | `id`, `userId`, `companyId`, `type`, `title`, `body`, `linkUrl`, `isRead`, `readAt`, `createdAt` | In-app notifications (mirrored to email when configured) |
| `BackgroundJob` | `id`, `jobType`, `payloadJson`, `status` (`PENDING`\|`RUNNING`\|`COMPLETED`\|`FAILED`), `runAt`, `attempts`, `maxAttempts`, `lastError`, `lockedAt` | Transactional async & scheduled job queue |
| `AuditLog` | `id`, `companyId`, `actorUserId`, `actorRoles`, `action`, `entityType`, `entityId`, `beforeJson`, `afterJson`, `ipAddress`, `userAgent`, `createdAt` | Append-only compliance audit trail |

---

## 4. Indexing & Integrity Strategy

- **Composite indexes** on all high-frequency filtered views:
  - `EmploymentAssignment(companyId, status)`
  - `Task(companyId, status, dueDate)` and `Task(assignedUserId, status)`
  - `Approval(approverUserId, status)` and `Approval(companyId, status)`
  - `OnboardingRequest(companyId, status, startDate)`
  - `OffboardingRequest(companyId, status, lastWorkingDate)`
  - `AuditLog(companyId, entityType, entityId, createdAt)`
  - `BackgroundJob(status, runAt)`
- **Duplicate prevention**:
  - `unique(companyId, companyEmployeeNo)` prevents duplicate employee IDs within a company.
  - Partial/application-level check prevents multiple concurrent `OPEN` onboarding or offboarding requests for the same `EmploymentAssignment`.
  - `idempotencyKey` prevents double-click / network-retry duplicate submissions.
