Bluewoo HRMS

Micro-Step Build Plan

155-step implementation guide for HRMS with exact commands, code, and verification gates

HRMS Micro-Step Build Plan

This document defines the complete implementation plan for the HRMS system using a micro-step approach. Each step is designed to be completed in under 60 minutes with clear verification.


Two Repositories

This plan involves TWO separate repositories:

RepositoryPurposeWhat Happens Here
hrms-docsDocumentationCreate phase files with detailed steps
hrmsCodeExecute the steps, build the actual HRMS

Workflow Between Repositories

hrms-docs (this repo)              hrms (code repo)
─────────────────────              ─────────────────
                                   
1. Create phase-00.mdx ──────────► 2. Execute Steps 01-08
   (detailed instructions)            (follow instructions exactly)
                                      
3. Update status to ✅  ◄────────── 4. All gates pass
   Delete old building blocks         Commit code changes
                                      
5. Create phase-01.mdx ──────────► 6. Execute Steps 09-24
   ...                                ...

Git & Deployment Workflow

All changes follow the branch protection workflow:

Feature Branch → PR (Preview) → Merge → Staging → [Manual] → Production

See Development Workflow for complete guide.

Commit Messages & Versioning

All commits must use Conventional Commits format:

<type>: <description>
TypeVersion BumpExample
featMinor (0.X.0)feat: add employee dashboard
fixPatch (0.0.X)fix: resolve login timeout
docsPatchdocs: update API guide
chorePatchchore: update dependencies

Versions are auto-bumped on merge to main via semantic-release. Non-conforming commits are rejected by CI.

See Constraints for full details.


Philosophy

Core Principles

  • One step = One thing that works and can be verified in under 60 minutes
  • If a step takes more than 60 minutes → stop, something is wrong
  • If a gate fails → fix it before moving on. No exceptions.
  • All code uses our documented schema from Database Schema

Step Structure

Every step has exactly four components:

ComponentDescription
InputWhat must exist before starting this step
TaskExactly what to build (specific files, specific code)
GateHow to verify it works (specific command, specific output)
LockWhat files become untouchable after this step

Rules

  • Never skip a gate
  • Never start the next step until current gate passes
  • Never modify locked files without following the Correction Protocol
  • Always fix issues found during gate verification
  • Always document deviations using the Correction Protocol

Correction Protocol

If during ANY step you discover that our documented approach doesn't work:

  • Schema model doesn't fit the use case
  • Library doesn't work as expected
  • Architecture pattern causes issues
  • Technology choice is wrong

DO NOT:

  • Hack around it
  • Create workarounds
  • Continue with a broken foundation
  • Make undocumented changes

INSTEAD, Follow These 6 Steps:

1. STOP

  • Halt current step immediately
  • Document what doesn't work and why
  • Do not write any more code

2. DECIDE

  • Discuss the correct approach
  • Consider impact on existing steps
  • Agree on the new solution
  • Create ADR (Architecture Decision Record) if significant

3. DOCUMENT FIRST

  • Update the relevant documentation:
    • database-schema.mdx for schema changes
    • service-patterns.mdx for pattern changes
    • technology-stack.mdx for library changes
    • Use case files if behavior changes
  • Documentation is the source of truth
  • No code changes until docs are updated

4. VALIDATE PREVIOUS STEPS

  • Review ALL completed steps (01 → current)
  • For each step, ask: "Does this change affect this step?"
  • Mark affected steps for re-execution
  • Create list of steps to redo

5. REDO AFFECTED STEPS

  • Re-execute each affected step in order
  • Update code to match new documentation
  • Run gate verification again
  • Update lock list if files changed

6. CONTINUE

  • Only after all affected steps pass their gates
  • Resume from the step where issue was discovered
  • Use the newly documented approach

Correction Log Format

When a correction happens, log it:

## Correction Log

### Correction #1 (Step XX)
- **Issue**: [What didn't work]
- **Root Cause**: [Why it didn't work]
- **Decision**: [What we decided]
- **Docs Updated**: [List of files]
- **Steps Redone**: [List of step numbers]
- **ADR**: [Link if created]
- **Date**: [When]

Important: This Plan Replaces Building Blocks

The 10 phase files will COMPLETELY REPLACE the current 17 building block files.

Why Replace?

Current Building Blocks (17 files)New Micro-Step Phases (10 files)
Theoretical checklistsExact commands and code to copy
Vague "implement X" tasksStep-by-step with verification
No verification gatesEvery step has a testable gate
Overlapping contentSequential, no overlap
Easy to get lost60-minute max = clear progress
Files can be modified anytimeLocked files prevent regressions

Legacy Files Status

Deleted (replaced by phase files):

  • 01-database-setup.mdx → phase-00
  • 02-authentication.mdx → phase-01
  • 03-rbac-implementation.mdx → phase-01
  • 04-multi-tenancy.mdx → phase-01
  • 05-api-foundation.mdx → phase-00, phase-02
  • 06-frontend-foundation.mdx → phase-00, phase-02
  • 07-ai-service-setup.mdx → phase-09
  • 11-employee-management.mdx → phase-02, phase-03
  • 12-time-off-tracking.mdx → phase-05
  • 13-document-management.mdx → phase-06
  • 14-analytics-dashboard.mdx → phase-08

Kept (not covered by phases):

  • 08-deployment.mdx → Separate concern
  • 09-redis-caching.mdx → Future enhancement (Month 2)
  • 10-bullmq-events.mdx → Future enhancement (Month 4)
  • 11-notifications-audit.mdx → Future enhancement (Post-MVP)
  • 15-team-communication.mdx → ADD-ON feature (Month 5)
  • 16-goals-okr.mdx → ADD-ON feature (Month 5-6)
  • 17-advanced-rbac.mdx → ADD-ON feature (Month 6)

How to Use This Plan

Workflow: One Phase at a Time

┌─────────────────────────────────────────────────────────────────┐
│  For each phase (0 → 9):                                        │
│                                                                 │
│  1. CREATE detailed phase file (e.g., phase-00-empty-shell.mdx) │
│     └── Full Input/Task/Gate/Lock for every step                │
│     └── Exact code to copy-paste                                │
│     └── Specific verification commands                          │
│                                                                 │
│  2. EXECUTE in hrms code repository                             │
│     └── Follow each step exactly                                │
│     └── Run gate verification after each step                   │
│     └── Do NOT proceed if gate fails                            │
│                                                                 │
│  3. VERIFY phase completion gate                                │
│     └── All services running                                    │
│     └── All endpoints responding                                │
│                                                                 │
│  4. DELETE old building block files that phase replaces         │
│                                                                 │
│  5. COMMIT and move to next phase                               │
└─────────────────────────────────────────────────────────────────┘

Current Status

PhaseStatusDetailed FileSteps
00✅ Documentedphase-00-empty-shell.mdx01-08
01✅ Documentedphase-01-multi-tenant-auth.mdx01-16
01.5✅ Documentedphase-01.5-design-system.mdx01-08
02✅ Documentedphase-02-employee-entity.mdx01-18
03✅ Documentedphase-03-org-structure.mdx01-20
04✅ Documentedphase-04-org-visualization.mdx01-10
05✅ Documentedphase-05-time-off.mdx01-20
06✅ Documentedphase-06-document-management.mdx01-16
07✅ Documentedphase-07-tags-custom-fields.mdx01-14
08✅ Documentedphase-08-dashboard.mdx01-16
09✅ Documentedphase-09-ai-integration.mdx01-17
10✅ Documentedphase-10-platform-admin.mdx01-10
10.5✅ Documentedphase-10.5-pre-launch.mdx01-10
11✅ Documentedphase-11-production-deployment.mdx01-20

Note: Each phase uses its own step numbering (01, 02, 03...). Reference as "Phase 02.3" for Phase 2, Step 3.

Next Action

All phases documented! Ready to execute in hrms code repo.

Execute Phase 00: Begin implementation in hrms code repo.


Phase 0: Empty Shell (Steps 01-08)

Goal: Three applications that start and connect. Nothing works yet except "hello world" level responses.

Completion Gate: All three services running, health endpoint returns JSON with database connection status.

StepTitleGate
01Create monorepo structurels apps/web apps/api packages/database shows all folders
02Create Next.js app shellnpm run dev shows Next.js default page
03Create NestJS app shellcurl localhost:3001 returns "HRMS API Running"
04Create database package with Prismacat prisma/schema.prisma shows HealthCheck model
05Create Docker Compose for PostgreSQLdocker compose ps shows hrms-postgres running
06Connect Prisma to PostgreSQLnpx prisma studio opens and shows HealthCheck table
07Connect API to databaseAPI starts without database connection errors
08Create health endpointcurl localhost:3001/health returns {"status":"ok","database":"connected"}

Locked Files After Phase 0:

  • package.json (workspaces configuration)
  • docker-compose.yml
  • apps/api/nest-cli.json
  • apps/api/tsconfig.json
  • apps/api/src/prisma/*
  • apps/api/src/health/*
  • packages/database/package.json

Phase 1: Multi-Tenant Auth (Steps 09-24)

Goal: Full authentication with SystemRole-based access control per our documented schema.

Completion Gate: User can login via Google, session contains tenantId and systemRole, API endpoints are protected by tenant and role guards.

StepTitleGate
09Add Tenant model to schemaPrisma studio shows Tenant table with TenantStatus enum
10Add User model with SystemRole enumUser table with SYSTEM_ADMIN/HR_ADMIN/MANAGER/EMPLOYEE
11Add Auth.js tables (Account, Session, VerificationToken)All auth tables exist in database
12Install Auth.js in Next.jsnpm run dev starts without errors
13Configure Auth.js with Google providercurl localhost:3000/api/auth/providers returns JSON
14Create login page/login shows Google sign-in button
15Create protected dashboard layout/dashboard redirects to /login if not authenticated
16Add logout functionalityLogout button clears session and redirects
17Create tenant on first loginNew user automatically gets tenant with role=SYSTEM_ADMIN
18Add tenant and systemRole to sessionsession.user.tenantId and session.user.systemRole exist
19Display tenant info on dashboardDashboard shows organization name and user role
20Add TenantId decorator to API@TenantId() extracts tenant from X-Tenant-ID header
21Add TenantGuard to APIRequests without X-Tenant-ID header return 400
22Add SystemRoleGuard to APIEndpoints can require specific roles
23Create tenant endpointcurl -H "X-Tenant-ID: ..." localhost:3001/tenant returns tenant info
24Connect frontend to API with tenant headerDashboard shows "API Status: Connected"

Locked Files After Phase 1:

  • All Phase 0 locks, plus:
  • packages/database/prisma/schema.prisma (Tenant, User, Auth.js tables)
  • apps/web/auth.ts
  • apps/web/app/api/auth/[...nextauth]/route.ts
  • apps/web/types/next-auth.d.ts
  • apps/web/lib/db.ts
  • apps/web/lib/api.ts
  • apps/api/src/tenant/*

Phase 2: Employee Entity (Steps 25-42)

Goal: Full Employee CRUD with our documented schema (all enums, soft delete, tenant isolation).

Completion Gate: Complete CRUD operations work via API and frontend, employee data is tenant-isolated.

StepTitleGate
25Add EmploymentType enumFULL_TIME, PART_TIME, CONTRACT, INTERN in schema
26Add WorkMode enumONSITE, REMOTE, HYBRID in schema
27Add EmployeeStatus enumONBOARDING, ACTIVE, ON_LEAVE, TERMINATED in schema
28Add Employee model (full schema)All fields from database-schema.mdx
29Link User to Employee (optional 1:1)User.employeeId relation works
30Run migrationnpm run db:push succeeds, Employee table exists
31Create CreateEmployeeDtoclass-validator decorators for all required fields
32Create UpdateEmployeeDtoPartialType with all optional fields
33Create EmployeeRepositoryTenant-filtered queries with soft delete support
34Create EmployeeServiceCRUD operations with NotFoundException handling
35Create EmployeeControllerGET/POST/PUT/DELETE with TenantGuard
36Register EmployeeModulenpm run build succeeds in API
37Test Employee CRUD via curlCreate, read, update, delete all return expected responses
38Create employee list page (frontend)/dashboard/employees shows table with employees
39Create employee form componentForm with all Employee fields
40Create new employee page/dashboard/employees/new form submits and creates employee
41Create edit employee page/dashboard/employees/[id] loads data and updates work
42Add delete functionalitySoft delete removes employee from list

Locked Files After Phase 2:

  • All Phase 1 locks, plus:
  • Employee model in schema.prisma
  • apps/api/src/employees/*
  • apps/web/app/dashboard/employees/*

Phase 3: Org Structure (Steps 43-62)

Goal: Flexible organizational relationships per domain model (multi-manager support, teams, departments).

Completion Gate: Employees can have primary manager, dotted-line managers, belong to multiple departments and teams.

StepTitleGate
43Add Department modelWith departmentHeadId, parentDepartmentId
44Add Team modelWith teamLeadId
45Add OrgRole modelJob roles within tenant
46Add EmployeeOrgRelations modelPrimary manager, primary department, primary team
47Add EmployeeDottedLine modelSecondary reporting relationships
48Add EmployeeAdditionalManager modelThird-level manager assignments
49Add EmployeeDepartment junctionMany-to-many with isPrimary flag
50Add EmployeeTeam junctionMany-to-many with teamRole
51Add EmployeeRole junctionMany-to-many with assignedAt
52Run migration for org structureAll junction tables exist
53Create DepartmentRepositoryCRUD with tenant filtering
54Create DepartmentServiceWith hierarchy validation (no cycles)
55Create DepartmentControllerGET/POST/PUT/DELETE endpoints
56Create Team Repository/Service/ControllerFull Team CRUD
57Create OrgService getDirectReportsReturns employee's direct reports
58Create OrgService getManagersReturns all managers (primary + dotted + additional)
59Create OrgService setManagerWith circular reference prevention
60Create manager assignment endpointPOST /employees/:id/manager works
61Create department assignment endpointPOST /employees/:id/departments works
62Create team assignment endpointPOST /employees/:id/teams works

Locked Files After Phase 3:

  • All Phase 2 locks, plus:
  • All org models in schema.prisma
  • apps/api/src/departments/*
  • apps/api/src/teams/*
  • apps/api/src/org/*

Phase 4: Org Visualization (Steps 63-72)

Goal: Interactive org chart visualization using React Flow.

Completion Gate: Org chart renders, supports zoom/pan, clicking shows employee details, drag-and-drop reassigns managers.

StepTitleGate
63Install React FlowPackage installed and importable
64Create org chart data fetcherAPI endpoint returns hierarchical org data
65Create EmployeeNode componentCard renders with name, title, avatar
66Create OrgChart componentRenders employee tree structure
67Add org chart to dashboard/dashboard/org displays org chart
68Add zoom and pan controlsUser can navigate large org structures
69Add click-to-view employeeClicking node opens employee profile
70Add drag-to-reassign managerDragging employee to new manager updates relationship
71Add department filterCan filter org chart by department
72Add search in org chartCan find and highlight employee in tree

Locked Files After Phase 4:

  • All Phase 3 locks, plus:
  • apps/web/app/dashboard/org/*
  • apps/web/components/org-chart/*

Phase 5: Time-Off System (Steps 73-92)

Goal: Complete time-off management per domain model (policy → balance → request → approval).

Completion Gate: Employees can request time-off, managers can approve/reject, balances update correctly.

StepTitleGate
73Add TimeOffType enumVACATION, SICK, PERSONAL, PARENTAL, BEREAVEMENT, etc.
74Add LeaveType enumPAID, UNPAID, SPECIAL
75Add AccrualSchedule enumANNUAL, MONTHLY, NONE
76Add RequestStatus enumPENDING, APPROVED, REJECTED, CANCELLED
77Add TimeOffPolicy modelWith all fields from schema
78Add TimeOffBalance modelPer employee per policy per year
79Add TimeOffRequest modelWith approverId, comments, dates
80Run migrationAll time-off tables exist
81Create TimeOffPolicyRepositoryCRUD operations
82Create TimeOffPolicyServiceWith validation rules
83Create TimeOffPolicyControllerAdmin-only endpoints
84Create TimeOffBalanceServiceCalculate available = total - used - pending
85Create TimeOffRequestRepositoryWith status filtering
86Create TimeOffRequestServiceSubmit, approve, reject with balance updates
87Create TimeOffRequestControllerEmployee and manager endpoints
88Create time-off request form (frontend)Select policy, start/end dates
89Create my requests pageList user's own time-off requests
90Create pending approvals pageManager sees team's pending requests
91Add approve/reject actionsManager can approve or reject with comments
92Create leave calendar viewVisual calendar showing team time-off

Locked Files After Phase 5:

  • All Phase 4 locks, plus:
  • All time-off models in schema.prisma
  • apps/api/src/time-off/*
  • apps/web/app/dashboard/time-off/*

Phase 6: Documents (Steps 93-108)

Goal: Document management with visibility levels and access control per use cases.

Completion Gate: Users can upload documents, set visibility, share with specific users/teams, access control enforced.

StepTitleGate
93Add DocumentCategory enumPOLICY, CONTRACT, PERSONAL, TEMPLATE, etc.
94Add DocumentVisibility enumPRIVATE, TEAM, DEPARTMENT, MANAGERS, COMPANY, CUSTOM
95Add AccessType enumUSER, TEAM, DEPARTMENT, ROLE
96Add DocumentPermission enumVIEW, DOWNLOAD, EDIT
97Add Document modelWith all fields from schema
98Add DocumentAccess modelFine-grained sharing with expiration
99Run migrationDocument tables exist
100Setup GCS bucketBucket created and accessible from API
101Create upload serviceUploads files to GCS, returns signed URL
102Create DocumentRepositoryQueries filtered by visibility
103Create DocumentAccessServiceCheck canView, canDownload, canEdit
104Create DocumentServiceCRUD + access control enforcement
105Create DocumentControllerUpload, list, share, download endpoints
106Create document upload page (frontend)Form with file input, visibility selector
107Create document list pageShows documents user can access
108Create share document modalGrant access to users/teams/departments

Locked Files After Phase 6:

  • All Phase 5 locks, plus:
  • All document models in schema.prisma
  • apps/api/src/documents/*
  • apps/web/app/dashboard/documents/*

Phase 7: Tags & Custom Fields (Steps 109-122)

Goal: Flexible categorization and tenant-defined metadata fields.

Completion Gate: Tags can be created, assigned to employees/documents. Custom fields can be defined and values stored.

StepTitleGate
109Add TagCategory modelWith assetTypes array (employee, document, goal)
110Add Tag modelWith category relation
111Add TagStatus enumACTIVE, ARCHIVED
112Add TagPermission modelRole-based tag assignment permissions
113Add EmployeeTag junctionTag employees with assignedBy
114Add DocumentTag junctionTag documents with assignedBy
115Run migrationTag tables exist
116Create TagServiceWith permission checking
117Create TagControllerCRUD + assign/remove endpoints
118Add CustomFieldDefinition modelField schema per entity type
119Add CustomFieldValue modelActual values per entity
120Add FieldType, FieldVisibility enumsTEXT, NUMBER, DROPDOWN, etc.
121Create CustomFieldServiceCRUD definitions + get/set values
122Add custom fields to employee formDynamic fields render based on definitions

Locked Files After Phase 7:

  • All Phase 6 locks, plus:
  • All tag/custom field models in schema.prisma
  • apps/api/src/tags/*
  • apps/api/src/custom-fields/*

Phase 8: Dashboard System (Steps 123-138)

Goal: Widget-based customizable dashboards per dashboard-system.mdx specification.

Completion Gate: Users can create dashboards, add widgets, drag-and-drop layout, layouts persist.

StepTitleGate
123Add DashboardType enumSYSTEM, PERSONAL, SHARED
124Add ShareType, SharePermission enumsUSER, TEAM, DEPARTMENT / VIEW, EDIT
125Add Dashboard model (no relations)With config JSON column
126Add DashboardShare modelSharing configuration
127Add DashboardLayout model + ALL relationsRelations to Dashboard, User, Tenant
128Run migrationDashboard tables exist
129Create widget registry typesTypes + registry class
130Create DashboardServiceCRUD + sharing logic
131Create DashboardController/api/v1/dashboards endpoints
132Install react-grid-layoutPackage installed
133Create DashboardContainer componentMain orchestrator + queries
134Create GridLayout wrapperDrag-and-drop with responsive breakpoints
135Create WidgetGallery componentModal to browse and add widgets
136Create HeadcountWidgetFirst real widget + definitions
137Create layout persistenceAuto-save to localStorage + API
138Create dashboard pageList + detail pages

Locked Files After Phase 8:

  • All Phase 7 locks, plus:
  • All dashboard models in schema.prisma
  • apps/api/src/dashboards/*
  • apps/web/features/dashboard/*
  • apps/web/app/dashboard/dashboards/*
  • apps/web/lib/queries/dashboards.ts

Phase 9: AI Integration (Steps 139-155)

Goal: AI service with RAG for document search and chat tools.

Completion Gate: AI chat widget works, can search documents, explain org structure, check time-off balance.

StepTitleGate
139Create AI service (separate Express app)Starts on port 3002
140Setup MongoDB for AIConnection works
141Install LangChainPackage installed
142Create document chunking serviceSplits documents for RAG
143Create embedding serviceGenerates embeddings via OpenAI
144Create vector store serviceStores and queries embeddings
145Create RAG query endpointPOST /ai/query returns relevant docs
146Create chat tools registryTool definitions for AI
147Implement employee_search toolFind employees by query
148Implement document_search toolRAG-powered doc search
149Implement org_explain toolExplain org relationships
150Implement timeoff_balance toolGet user's time-off balance
151Create chat endpointPOST /ai/chat with tool use
152Create AI chat widget (frontend)Floating chat button
153Create chat message componentsUser and assistant messages
154Create tool result renderersInfo cards, confirmation cards
155Integrate chat with dashboardChat available on all dashboard pages

Locked Files After Phase 9:

  • All Phase 8 locks, plus:
  • apps/ai/*
  • apps/web/features/ai-chat/*

Summary

PhaseStepsFeaturesEst. Time
008Monorepo, Next.js, NestJS, Prisma, Docker4-6 hours
0116Auth, Tenant, SystemRole, Guards8-12 hours
01.58Design System Setup6-8 hours
0218Employee CRUD (full schema)8-12 hours
0320Org structure (multi-manager)10-14 hours
0410Org chart (React Flow)5-8 hours
0520Time-off (policy/balance/request)10-14 hours
0616Documents (visibility/access)8-12 hours
0714Tags + Custom Fields7-10 hours
0816Dashboard (widget system)8-12 hours
0917AI (RAG/chat)10-14 hours
1010Platform Admin12-14 hours
10.510Pre-Launch (email, onboarding)17-24 hours
1120Production Deployment (GCP)12-16 hours
TOTAL~203Complete HRMS + Deployment~127-176 hours

Next Steps

Documentation Complete (All Phases) ✅

✅ Phase 00: phase-00-empty-shell.mdx ✅ Phase 01: phase-01-multi-tenant-auth.mdx ✅ Phase 01.5: phase-01.5-design-system.mdx ✅ Phase 02: phase-02-employee-entity.mdx ✅ Phase 03: phase-03-org-structure.mdx ✅ Phase 04: phase-04-org-visualization.mdx ✅ Phase 05: phase-05-time-off.mdx ✅ Phase 06: phase-06-document-management.mdx ✅ Phase 07: phase-07-tags-custom-fields.mdx ✅ Phase 08: phase-08-dashboard.mdx ✅ Phase 09: phase-09-ai-integration.mdx ✅ Phase 10: phase-10-platform-admin.mdx ✅ Phase 10.5: phase-10.5-pre-launch.mdx ✅ Phase 11: phase-11-production-deployment.mdx

All phases documented. Ready for implementation.

Next (Code - hrms repo)

  1. Execute Phases 00-10.5 in the hrms code repository
    • Follow each step exactly
    • Run gate after each step
    • Do NOT proceed if gate fails