42 KiB
Professional Management Platform
Full REST-First System Design Plan
1. Product Vision
Build one shared backend platform that powers multiple profession-specific management applications.
Initial professions:
- Engineering
- Legal
- Healthcare
Future professions may include accounting, architecture, consulting, property management, veterinary practices, financial advisory, and other regulated or professional-service industries.
The core design principle is:
Share infrastructure, not domain meaning.
Engineering projects, legal matters, and medical patients are fundamentally different concepts and should not be forced into the same universal business table.
2. Core Architecture Decision
The platform will use:
- REST
- JSON
- OpenAPI
- Versioned endpoints
- PostgreSQL
- Modular monolith backend
- Profession-specific frontends
- Profession-specific database tables
- Shared identity, security, billing, documents, audit, and infrastructure
Base API path:
/api/v1
GraphQL is not part of v1.
3. High-Level Architecture
FRONTENDS
┌──────────────────┼──────────────────┐
│ │ │
Engineering Web Legal Web Healthcare Web
│ │ │
└──────────────────┼──────────────────┘
│
▼
REST API
/api/v1
│
┌───────────┼───────────┐
│ │ │
Core Engineering Legal
│ │ │
│ Healthcare │
│ │ │
└───────────┼───────────┘
│
PostgreSQL
│
┌───────────────┼────────────────┐
│ │ │
Shared Tables Profession Tables Audit/Event Tables
Shared infrastructure:
PostgreSQL
Redis
Object Storage
Queue / Workers
Audit
Notifications
Billing
Observability
4. System Architecture Strategy
Start with a modular monolith.
Do not start with microservices.
Initial deployment:
Frontend Apps
│
▼
Backend API
│
├── PostgreSQL
├── Redis
├── Object Storage
└── Worker Queue
Benefits:
- simpler transactions
- easier development
- easier deployment
- clearer domain boundaries
- lower operational burden
- easier refactoring
- future service extraction remains possible
5. Repository Structure
Recommended monorepo:
professional-platform/
│
├── apps/
│ ├── engineering-web/
│ ├── legal-web/
│ ├── healthcare-web/
│ ├── platform-admin/
│ ├── api/
│ └── workers/
│
├── packages/
│ ├── ui/
│ ├── api-client/
│ ├── auth-client/
│ ├── validation/
│ ├── types/
│ ├── config/
│ └── testing/
│
├── database/
│ ├── migrations/
│ ├── seeds/
│ └── scripts/
│
├── infrastructure/
│ ├── docker/
│ ├── deployment/
│ └── monitoring/
│
└── docs/
├── architecture/
├── api/
├── security/
└── domains/
6. Frontend Strategy
Every profession receives its own frontend application.
Avoid one giant frontend filled with profession checks.
Engineering Frontend
Suggested navigation:
Dashboard
Clients
Projects
Project Phases
Project Team
Sites
Designs
Design Reviews
Inspections
Specifications
Tasks
Documents
Timesheets
Billing
Reports
Administration
Legal Frontend
Suggested navigation:
Dashboard
Clients
Matters
Cases
Hearings
Courts
Deadlines
Documents
Conflict Checks
Time Tracking
Retainers
Billing
Reports
Administration
Healthcare Frontend
Suggested navigation:
Dashboard
Patients
Appointments
Practitioners
Encounters
Clinical Records
Diagnoses
Prescriptions
Insurance
Documents
Billing
Reports
Administration
Platform Admin Frontend
Suggested functions:
Organizations
Users
Profession Modules
Subscriptions
System Health
Audit
Support
Global Configuration
Platform administrators and organization administrators are separate concepts.
7. REST API Structure
Shared endpoints:
/api/v1/auth
/api/v1/me
/api/v1/organizations
/api/v1/memberships
/api/v1/membership-invitations
/api/v1/roles
/api/v1/permissions
/api/v1/documents
/api/v1/invoices
/api/v1/payments
/api/v1/audit-events
Engineering:
/api/v1/engineering/clients
/api/v1/engineering/projects
/api/v1/engineering/project-members
/api/v1/engineering/phases
/api/v1/engineering/sites
/api/v1/engineering/tasks
/api/v1/engineering/designs
/api/v1/engineering/inspections
/api/v1/engineering/specifications
/api/v1/engineering/time-entries
Legal:
/api/v1/legal/clients
/api/v1/legal/matters
/api/v1/legal/cases
/api/v1/legal/hearings
/api/v1/legal/deadlines
/api/v1/legal/conflict-checks
/api/v1/legal/retainers
/api/v1/legal/time-entries
Healthcare:
/api/v1/healthcare/patients
/api/v1/healthcare/practitioners
/api/v1/healthcare/appointments
/api/v1/healthcare/encounters
/api/v1/healthcare/clinical-records
/api/v1/healthcare/diagnoses
/api/v1/healthcare/prescriptions
/api/v1/healthcare/insurance
8. REST Conventions
All APIs use JSON.
Typical headers:
Authorization: Bearer <access-token>
X-Organization-Id: org_123
Content-Type: application/json
Every tenant-scoped request requires organization context.
The server must verify:
- user is authenticated
- organization exists
- membership exists
- membership is active
- required permission is present
- resource belongs to the organization
- resource policy permits access
- profession-specific rules pass
9. Standard Response Format
Single resource:
{
"data": {
"id": "project_123",
"name": "Central Tower"
}
}
Collection:
{
"data": [],
"meta": {
"pagination": {
"nextCursor": null,
"hasMore": false
}
}
}
Error:
{
"error": {
"code": "PROJECT_NOT_FOUND",
"message": "Project not found.",
"details": {}
}
}
Clients should rely on error.code, not human-readable messages.
10. HTTP Status Rules
200 Success
201 Created
202 Accepted
204 No Content
400 Bad Request
401 Unauthorized
403 Forbidden
404 Not Found
409 Conflict
422 Validation Error
429 Too Many Requests
500 Internal Server Error
Cross-tenant resource access should return 404.
11. API Versioning
Current API:
/api/v1
Breaking changes require:
/api/v2
Additive fields generally do not require a new version.
12. Authentication
Initial authentication:
Email
+
Password
+
Access Token
+
Refresh Token
Endpoints:
POST /api/v1/auth/register
POST /api/v1/auth/login
POST /api/v1/auth/refresh
POST /api/v1/auth/logout
GET /api/v1/me
Access tokens:
- short-lived
- signed
- identify user/session
Refresh tokens:
- rotated
- revocable
- stored hashed
Future:
- MFA
- passkeys
- SSO
- OAuth
- enterprise identity providers
13. Shared Core Backend
Recommended modules:
core/
├── auth/
├── users/
├── organizations/
├── memberships/
├── roles/
├── permissions/
├── authorization/
├── documents/
├── billing/
├── notifications/
├── audit/
└── events/
Dependency rule:
Profession module → Core
Never:
Core → Profession module
14. Organizations
Organizations are tenants.
Examples:
Atlas Structural Engineering
Smith & Associates Law
North Shore Medical Practice
Suggested fields:
id
name
slug
status
country_code
timezone
currency_code
created_at
updated_at
15. Profession Enablement
Use:
organization_professions
Suggested fields:
organization_id
profession
enabled_at
configuration
Possible professions:
engineering
legal
healthcare
An organization may eventually enable more than one profession module.
16. Users and Memberships
Users are global identities.
A user gains tenant access through membership.
User
│
▼
Membership
│
▼
Organization
Suggested users fields:
id
email
first_name
last_name
phone
avatar_url
status
created_at
updated_at
Suggested memberships fields:
id
organization_id
user_id
status
joined_at
created_at
updated_at
17. Membership Invitations
Keep invitations separate from memberships.
Suggested table:
membership_invitations
Fields:
id
organization_id
email
invited_by_user_id
expires_at
accepted_at
revoked_at
created_at
Flow:
Invitation
↓
Accepted
↓
User
↓
Membership
18. Authorization
Use:
RBAC
+
Resource Policies
+
Professional Qualifications
Decision flow:
Authenticated User
↓
Organization Membership
↓
Roles
↓
Permissions
↓
Permission Scope
↓
Resource Policy
↓
Professional Qualification Rule
↓
Domain State Rule
↓
ALLOW / DENY
Default decision:
DENY
19. Roles and Permissions
Example roles:
Owner
Administrator
Project Manager
Engineer
Lawyer
Paralegal
Doctor
Nurse
Billing Manager
Viewer
Example permissions:
clients.read
clients.create
clients.update
documents.read
documents.upload
billing.read
invoices.issue
payments.record
engineering.projects.read
engineering.projects.manage
engineering.designs.approve
legal.matters.read
legal.matters.manage
healthcare.records.read
healthcare.records.write
20. Permission Scopes
Initial scopes:
assigned
organization
Examples:
Engineer:
engineering.projects.read = assigned
Principal Engineer:
engineering.projects.read = organization
Potential future scopes:
owned
team
department
restricted
Do not implement until required.
21. Professional Credentials
Professional qualification is separate from RBAC.
Suggested table:
professional_profiles
Fields:
organization_id
user_id
profession
title
license_number
registration_number
jurisdiction
status
expiry_date
A user having a permission does not automatically mean they are professionally qualified to perform every regulated action.
22. Database Architecture
Use PostgreSQL.
Start with:
One database
+
Shared schema
+
Profession-specific tables
Do not begin with database-per-profession or database-per-customer unless compliance or residency requirements force that choice.
23. Shared Tables
Recommended shared tables:
organizations
organization_professions
users
user_credentials
sessions
memberships
membership_invitations
roles
permissions
role_permissions
membership_roles
professional_profiles
documents
document_versions
invoices
invoice_items
payments
notifications
notification_deliveries
audit_events
outbox_events
24. Multi-Tenancy Rule
Every tenant-owned row must contain:
organization_id
Examples:
engineering_projects.organization_id
legal_matters.organization_id
healthcare_patients.organization_id
Enforce tenant boundaries at:
- API layer
- authorization layer
- repository/query layer
- database constraints
25. Tenant-Safe Foreign Keys
Use composite tenant-aware foreign keys when possible.
Example:
engineering_projects
organization_id
client_id
references:
engineering_clients
organization_id
id
This prevents linking a resource from one organization to another organization's data.
Engineering Domain
26. Engineering Tables
Initial tables:
engineering_clients
engineering_projects
engineering_project_members
engineering_project_phases
engineering_sites
engineering_tasks
engineering_designs
engineering_design_versions
engineering_design_reviews
engineering_inspections
engineering_inspection_findings
engineering_specifications
engineering_change_requests
engineering_time_entries
27. Engineering Clients
Suggested fields:
id
organization_id
client_type
display_name
legal_name
contact_name
email
phone
status
created_at
updated_at
REST:
POST /api/v1/engineering/clients
GET /api/v1/engineering/clients
GET /api/v1/engineering/clients/{clientId}
PATCH /api/v1/engineering/clients/{clientId}
POST /api/v1/engineering/clients/{clientId}/archive
28. Engineering Projects
Suggested fields:
id
organization_id
client_id
project_number
name
description
discipline
stage
status
project_manager_user_id
start_date
expected_completion_date
completed_date
budget_minor
currency_code
created_at
updated_at
version
REST:
POST /api/v1/engineering/projects
GET /api/v1/engineering/projects
GET /api/v1/engineering/projects/{projectId}
PATCH /api/v1/engineering/projects/{projectId}
POST /api/v1/engineering/projects/{projectId}/activate
POST /api/v1/engineering/projects/{projectId}/close
29. Engineering Project Members
Suggested fields:
id
organization_id
project_id
user_id
project_role
joined_at
left_at
REST:
GET /api/v1/engineering/projects/{projectId}/members
POST /api/v1/engineering/projects/{projectId}/members
PATCH /api/v1/engineering/projects/{projectId}/members/{memberId}
DELETE /api/v1/engineering/projects/{projectId}/members/{memberId}
30. Engineering Project Phases
Suggested fields:
id
organization_id
project_id
name
sequence
status
start_date
end_date
created_at
updated_at
Typical phases:
Concept
Preliminary Design
Detailed Design
Construction
Inspection
Closeout
REST:
GET /api/v1/engineering/projects/{projectId}/phases
POST /api/v1/engineering/projects/{projectId}/phases
PATCH /api/v1/engineering/projects/{projectId}/phases/{phaseId}
POST /api/v1/engineering/projects/{projectId}/phases/{phaseId}/complete
31. Engineering Sites
Suggested fields:
id
organization_id
project_id
name
address
latitude
longitude
created_at
updated_at
REST:
POST /api/v1/engineering/projects/{projectId}/sites
GET /api/v1/engineering/projects/{projectId}/sites
GET /api/v1/engineering/sites/{siteId}
PATCH /api/v1/engineering/sites/{siteId}
32. Engineering Tasks
Suggested fields:
id
organization_id
project_id
title
description
status
priority
created_by_user_id
assigned_to_user_id
due_at
completed_at
created_at
updated_at
version
REST:
POST /api/v1/engineering/tasks
GET /api/v1/engineering/tasks
GET /api/v1/engineering/tasks/{taskId}
PATCH /api/v1/engineering/tasks/{taskId}
POST /api/v1/engineering/tasks/{taskId}/complete
POST /api/v1/engineering/tasks/{taskId}/reopen
POST /api/v1/engineering/tasks/{taskId}/cancel
33. Engineering Designs
Suggested fields:
id
organization_id
project_id
design_number
title
description
discipline
status
prepared_by_user_id
approved_by_user_id
created_at
updated_at
version
Possible statuses:
draft
under_review
changes_requested
approved
superseded
REST:
POST /api/v1/engineering/projects/{projectId}/designs
GET /api/v1/engineering/projects/{projectId}/designs
GET /api/v1/engineering/designs/{designId}
PATCH /api/v1/engineering/designs/{designId}
POST /api/v1/engineering/designs/{designId}/submit-review
POST /api/v1/engineering/designs/{designId}/request-changes
POST /api/v1/engineering/designs/{designId}/approve
Important approvals use explicit commands, not generic status PATCH operations.
34. Design Versions and Reviews
engineering_design_versions:
id
design_id
version_number
document_id
created_by_user_id
created_at
engineering_design_reviews:
id
organization_id
design_id
reviewer_user_id
status
comments
reviewed_at
Possible review statuses:
pending
approved
changes_requested
rejected
35. Engineering Inspections
Suggested fields:
id
organization_id
project_id
site_id
inspection_type
inspector_user_id
status
scheduled_at
performed_at
summary
created_at
updated_at
REST:
POST /api/v1/engineering/projects/{projectId}/inspections
GET /api/v1/engineering/projects/{projectId}/inspections
GET /api/v1/engineering/inspections/{inspectionId}
PATCH /api/v1/engineering/inspections/{inspectionId}
POST /api/v1/engineering/inspections/{inspectionId}/start
POST /api/v1/engineering/inspections/{inspectionId}/complete
36. Inspection Findings
Suggested fields:
id
inspection_id
severity
description
status
resolved_at
Possible severities:
observation
minor
major
critical
REST:
POST /api/v1/engineering/inspections/{inspectionId}/findings
PATCH /api/v1/engineering/inspection-findings/{findingId}
POST /api/v1/engineering/inspection-findings/{findingId}/resolve
37. Engineering Specifications
Suggested fields:
id
organization_id
project_id
specification_number
title
version
status
document_id
created_at
updated_at
38. Engineering Change Requests
Suggested fields:
id
organization_id
project_id
request_number
title
description
status
requested_by_user_id
approved_by_user_id
estimated_cost_minor
created_at
updated_at
39. Engineering Time Entries
Suggested fields:
id
organization_id
project_id
user_id
work_date
duration_minutes
description
billable
billing_rate_minor
currency_code
created_at
updated_at
REST:
POST /api/v1/engineering/time-entries
GET /api/v1/engineering/time-entries
GET /api/v1/engineering/time-entries/{id}
PATCH /api/v1/engineering/time-entries/{id}
Store duration as integer minutes.
Legal Domain
40. Legal Tables
Initial tables:
legal_clients
legal_matters
legal_matter_members
legal_cases
legal_case_parties
legal_courts
legal_hearings
legal_deadlines
legal_documents
legal_time_entries
legal_retainers
legal_conflict_checks
REST namespace:
/api/v1/legal
Examples:
GET /api/v1/legal/clients
POST /api/v1/legal/matters
GET /api/v1/legal/matters/{id}
POST /api/v1/legal/matters/{id}/close
GET /api/v1/legal/cases
POST /api/v1/legal/hearings
POST /api/v1/legal/conflict-checks
41. Legal Matters
Suggested fields:
id
organization_id
client_id
matter_number
title
practice_area
responsible_lawyer_user_id
status
opened_date
closed_date
created_at
updated_at
42. Legal Cases
Suggested fields:
id
organization_id
matter_id
case_number
court_id
jurisdiction
case_type
status
filed_date
created_at
updated_at
43. Legal Hearings
Suggested fields:
id
organization_id
case_id
hearing_type
scheduled_at
courtroom
judge
status
notes
44. Legal Conflict Checks
Suggested fields:
id
organization_id
potential_client_name
related_parties
requested_by_user_id
reviewed_by_user_id
status
result
created_at
reviewed_at
Healthcare Domain
45. Healthcare Tables
Initial tables:
healthcare_patients
healthcare_practitioners
healthcare_appointments
healthcare_encounters
healthcare_clinical_records
healthcare_diagnoses
healthcare_prescriptions
healthcare_insurance
healthcare_allergies
healthcare_medications
REST namespace:
/api/v1/healthcare
Examples:
GET /api/v1/healthcare/patients
POST /api/v1/healthcare/patients
POST /api/v1/healthcare/appointments
POST /api/v1/healthcare/encounters
GET /api/v1/healthcare/clinical-records/{id}
POST /api/v1/healthcare/prescriptions
Healthcare must have stricter privacy, auditing, retention, and credential checks.
46. Healthcare Patients
Suggested fields:
id
organization_id
patient_number
first_name
middle_name
last_name
date_of_birth
sex
phone
email
address
status
created_at
updated_at
47. Healthcare Practitioners
Suggested fields:
id
organization_id
user_id
specialty
license_number
license_jurisdiction
credential_status
created_at
updated_at
48. Healthcare Appointments
Suggested fields:
id
organization_id
patient_id
practitioner_id
appointment_type
starts_at
ends_at
status
reason
created_at
updated_at
49. Healthcare Encounters
Suggested fields:
id
organization_id
patient_id
practitioner_id
appointment_id
encounter_type
started_at
ended_at
status
50. Clinical Records
Suggested fields:
id
organization_id
patient_id
encounter_id
author_practitioner_id
record_type
content
created_at
updated_at
Sensitive clinical content may require application-level encryption.
Shared Platform Services
51. Documents
Use shared object storage.
Database:
documents
document_versions
Actual binary files:
S3-compatible Object Storage
Suggested documents fields:
id
organization_id
name
mime_type
size_bytes
created_by_user_id
created_at
updated_at
Suggested document_versions fields:
id
document_id
version_number
storage_key
checksum
size_bytes
uploaded_by_user_id
created_at
52. Document Upload Flow
Frontend
↓
Request upload URL
↓
Backend authorizes
↓
Signed upload URL
↓
Frontend uploads to object storage
↓
Backend finalizes document
↓
Virus/security scan
↓
Document becomes available
REST:
POST /api/v1/documents/upload-url
POST /api/v1/documents/{documentId}/complete-upload
GET /api/v1/documents/{documentId}
GET /api/v1/documents/{documentId}/download-url
POST /api/v1/documents/{documentId}/versions
53. Profession-Specific Document Links
Use explicit tables where possible.
Engineering:
engineering_project_documents
engineering_design_documents
engineering_inspection_documents
Legal:
legal_matter_documents
legal_case_documents
Healthcare:
healthcare_patient_documents
healthcare_encounter_documents
This gives stronger foreign-key integrity than generic polymorphic document links.
54. Billing
Shared financial core:
invoices
invoice_items
payments
Profession-specific modules may extend billing workflows.
Engineering examples:
project billing
hourly billing
milestone billing
Legal examples:
matter billing
time billing
retainers
trust accounting
Healthcare examples:
insurance
claims
patient billing
REST:
POST /api/v1/invoices
GET /api/v1/invoices
GET /api/v1/invoices/{invoiceId}
PATCH /api/v1/invoices/{invoiceId}
POST /api/v1/invoices/{invoiceId}/issue
POST /api/v1/invoices/{invoiceId}/void
POST /api/v1/invoices/{invoiceId}/payments
POST /api/v1/payments/{paymentId}/refund
55. Money Representation
Use integer minor units:
{
"amountMinor": 12550,
"currency": "USD"
}
Meaning:
$125.50
Never use floating point for money.
56. Audit Logging
Table:
audit_events
Suggested fields:
id
organization_id
actor_user_id
action
resource_type
resource_id
request_id
ip_address
user_agent
metadata
occurred_at
Examples:
engineering.project.created
engineering.design.approved
legal.matter.created
legal.document.viewed
healthcare.record.viewed
invoice.issued
membership.role_changed
Audit logs are append-only.
REST:
GET /api/v1/audit-events
No public create/update/delete endpoints.
57. Domain Events and Transactional Outbox
Profession modules produce internal domain events.
Examples:
engineering.project.created
engineering.inspection.completed
legal.hearing.scheduled
healthcare.appointment.created
invoice.issued
Consumers:
notifications
webhooks
analytics
search
integrations
background workflows
Use:
outbox_events
Transaction pattern:
BEGIN
business update
audit event
outbox event
COMMIT
Worker processes outbox events after commit.
58. Background Jobs
Workers handle:
Email
SMS
Notifications
Report generation
PDF generation
File scanning
Document processing
Imports
Exports
Webhook delivery
Search indexing
Large data operations
Architecture:
API
↓
Queue
↓
Worker
59. Redis
Use Redis for:
job queue
rate limiting
short-lived caching
distributed locks
optional session support
PostgreSQL remains the authoritative source of truth.
60. Pagination
Use cursor pagination.
Example:
GET /api/v1/engineering/projects?limit=25
Response:
{
"data": [],
"meta": {
"pagination": {
"nextCursor": "...",
"hasMore": true
}
}
}
Maximum page size:
100
61. Filtering
Use explicit resource-specific filters.
Examples:
GET /api/v1/engineering/projects?status=active&discipline=structural
GET /api/v1/engineering/tasks?status=todo&assignedToUserId=user_123
Do not build a generic query DSL in v1.
62. Sorting
Examples:
GET /api/v1/engineering/projects?sort=createdAt
GET /api/v1/engineering/projects?sort=-createdAt
Only explicitly supported fields may be sorted.
63. Search
Start with PostgreSQL search.
Engineering search may cover:
project number
project name
client name
Legal:
matter number
client
case number
Healthcare:
patient number
patient identity
Healthcare search requires tighter privacy controls.
Do not introduce Elasticsearch/OpenSearch until PostgreSQL is genuinely insufficient.
64. Optimistic Concurrency
Important mutable resources should use a version field.
Example:
{
"id": "project_123",
"version": 6
}
Update:
{
"version": 6,
"name": "Central Tower Phase II"
}
If the current database version differs:
409 CONCURRENT_MODIFICATION
65. Domain-Oriented REST
Important state transitions use explicit command endpoints.
Good:
POST /engineering/projects/{id}/close
POST /engineering/designs/{id}/approve
POST /engineering/tasks/{id}/complete
POST /engineering/inspections/{id}/complete
POST /invoices/{id}/issue
Avoid:
PATCH /resource/{id}
{
"status": "approved"
}
when the change has significant rules or side effects.
66. Transaction Boundaries
Create project:
BEGIN
create project
assign project manager
write audit event
write outbox event
COMMIT
Approve design:
BEGIN
validate permission
validate project access
validate credentials
validate design state
create review result
mark approved
write audit event
write outbox event
COMMIT
67. Request Context
Every authenticated request should resolve:
RequestContext
{
requestId
userId
sessionId
organizationId
membershipId
permissions
}
Profession modules consume this context.
68. Request IDs
Every request has:
X-Request-Id
If missing, the server generates one.
Use it in:
- logs
- audit context
- error diagnostics
- asynchronous correlation
69. OpenAPI
Maintain:
openapi.yaml
OpenAPI should define:
- routes
- request DTOs
- response DTOs
- authentication
- error schemas
- pagination
- filters
- examples
Generate frontend API clients when practical.
70. DTO Rule
Database models are not public API contracts.
Use:
Request DTO
Response DTO
A database migration should not accidentally change the public API.
71. Backend Module Structure
Recommended:
src/
├── core/
│ ├── auth/
│ ├── organizations/
│ ├── memberships/
│ ├── authorization/
│ ├── documents/
│ ├── billing/
│ ├── audit/
│ └── events/
│
├── engineering/
│ ├── clients/
│ ├── projects/
│ ├── project-members/
│ ├── phases/
│ ├── sites/
│ ├── tasks/
│ ├── designs/
│ ├── inspections/
│ └── specifications/
│
├── legal/
│ ├── clients/
│ ├── matters/
│ ├── cases/
│ ├── hearings/
│ ├── conflicts/
│ └── retainers/
│
└── healthcare/
├── patients/
├── practitioners/
├── appointments/
├── encounters/
├── records/
└── prescriptions/
72. Internal Module Structure
Example:
projects/
├── domain/
│ ├── project.entity.ts
│ ├── project-status.ts
│ └── project.errors.ts
│
├── application/
│ ├── commands/
│ │ ├── create-project.ts
│ │ ├── update-project.ts
│ │ └── close-project.ts
│ │
│ └── queries/
│ ├── get-project.ts
│ └── list-projects.ts
│
├── infrastructure/
│ └── project.repository.ts
│
└── api/
├── project.controller.ts
├── project.request.ts
└── project.response.ts
73. Controllers
Controllers should handle:
HTTP
authentication context
input DTO parsing
application command/query invocation
response mapping
Controllers should not contain:
business rules
raw SQL
role logic
transaction orchestration
email sending
audit implementation
74. Commands and Queries
Mutations use commands.
Examples:
CreateEngineeringProjectCommand
ApproveEngineeringDesignCommand
CloseLegalMatterCommand
CompleteHealthcareEncounterCommand
Reads use queries.
Examples:
GetEngineeringProjectQuery
ListLegalMattersQuery
GetHealthcarePatientQuery
75. Repositories
Use domain-specific repositories.
Examples:
EngineeringProjectRepository
LegalMatterRepository
HealthcarePatientRepository
Avoid one massive generic repository abstraction that eventually needs dozens of flags.
76. Security Baseline
Minimum controls:
TLS everywhere
strong password hashing
secure refresh token storage
rate limiting
RBAC
tenant isolation
input validation
SQL injection protection
signed object-storage URLs
audit trails
secret management
encryption at rest
dependency scanning
security headers
session revocation
77. Data Classification
Suggested classes:
Public
marketing configuration
Internal
organization settings
tasks
Confidential
engineering documents
legal matters
billing
Highly Sensitive
clinical records
professional credentials
authentication secrets
78. Healthcare Security
Before healthcare production use, define:
privacy model
clinical access model
audit policy
retention policy
credential model
jurisdiction requirements
encryption strategy
consent requirements
data residency requirements
Healthcare should be treated as a stricter security tier.
79. Observability
Use:
structured logs
metrics
distributed tracing
request IDs
Recommended:
OpenTelemetry
Track:
API latency
error rate
database latency
database connections
queue depth
worker failures
authentication failures
authorization denials
external service failures
80. Logging
Useful fields:
request_id
route
method
status
duration
user_id when appropriate
organization_id when appropriate
Never log:
passwords
tokens
clinical record text
full sensitive documents
payment secrets
81. Testing Strategy
Unit Tests
Test:
domain rules
authorization policies
calculations
state transitions
Integration Tests
Test:
repositories
PostgreSQL constraints
transactions
API Tests
Test:
routes
validation
authentication
authorization
error responses
End-to-End Tests
Test complete professional workflows.
82. Tenant Security Tests
For every major resource, attempt:
Organization A resource
using Organization B context
Test:
read
update
delete/action
list filtering
search
documents
Expected result:
404 / denied
83. Engineering MVP
Engineering is the first vertical.
Initial features:
Authentication
Organization management
Users / memberships / roles
Engineering clients
Projects
Project members
Project phases
Tasks
Sites
Documents
Basic design records
Inspections
Time entries
Basic billing
Audit history
Do not initially build:
advanced CAD integration
BIM integration
full document markup
advanced resource planning
procurement
complex accounting
AI design analysis
IoT integrations
84. Engineering MVP Workflow
User registers
↓
Creates engineering organization
↓
Invites engineer
↓
Assigns role
↓
Creates client
↓
Creates project
↓
Assigns project team
↓
Creates project phases
↓
Creates tasks
↓
Uploads documents
↓
Creates design
↓
Reviews / approves design
↓
Schedules inspection
↓
Records inspection findings
↓
Records engineering time
↓
Creates invoice
↓
Records payment
↓
Closes project
↓
Audit history contains lifecycle
85. Development Phases
Phase 0: Architecture Foundation
Deliver:
Domain design
Database conventions
REST conventions
Authorization rules
Repository structure
Engineering workflows
Phase 1: Shared Platform Core
Build:
Auth
Users
Organizations
Organization professions
Membership invitations
Memberships
Roles
Permissions
Authorization
Audit
Outbox
Phase 2: Engineering CRM
Build:
engineering_clients
Phase 3: Engineering Projects
Build:
engineering_projects
engineering_project_members
engineering_project_phases
Phase 4: Work Management
Build:
engineering_tasks
engineering_sites
Phase 5: Documents
Build:
documents
document_versions
object storage
signed uploads
engineering document links
Phase 6: Designs
Build:
engineering_designs
engineering_design_versions
engineering_design_reviews
approval rules
credential-aware authorization
Phase 7: Inspections
Build:
engineering_inspections
engineering_inspection_findings
follow-ups
attachments
Phase 8: Time and Billing
Build:
engineering_time_entries
invoices
invoice_items
payments
Phase 9: Notifications
Build:
in-app notifications
email
worker processing
Phase 10: Reporting
Initial reports:
project status
overdue tasks
inspection status
billable time
revenue
outstanding invoices
86. Legal Expansion
Only after engineering proves the shared platform assumptions.
Build:
Legal Client
↓
Matter
↓
Case
↓
Hearings / Deadlines / Documents
Do not redesign engineering around legal terminology.
Extract only genuinely reusable infrastructure.
87. Healthcare Expansion
Healthcare comes after:
- core platform is stable
- audit model is proven
- permission model is proven
- tenant isolation is tested
- retention and encryption strategies are defined
Healthcare should be treated as its own security and compliance workstream.
88. Deployment Environments
Use:
development
testing
staging
production
Each environment has independent:
database
object storage
secrets
queues
API keys
89. Initial Deployment Architecture
CDN
│
├── Engineering Web
├── Legal Web
└── Healthcare Web
Load Balancer
│
Backend API
│
├── PostgreSQL
├── Redis
├── Object Storage
└── Queue
│
Workers
Prefer managed infrastructure where practical.
90. Backup Strategy
Database:
automated backups
point-in-time recovery
tested restores
Object storage:
versioning
retention policies
backup or replication where required
A backup strategy is incomplete until restoration is tested.
91. Migration Strategy
Use explicit numbered migrations.
Example:
001_core_organizations
002_core_users
003_core_memberships
004_core_rbac
005_core_audit
006_engineering_clients
007_engineering_projects
008_engineering_project_members
009_engineering_phases
010_engineering_tasks
Do not use automatic ORM schema synchronization in production.
92. Technology Recommendation
Backend:
TypeScript
NestJS or Fastify-based architecture
Database:
PostgreSQL
ORM/query layer candidates:
Prisma
Drizzle
Kysely
Frontend:
React / Next.js
Queue:
Redis + BullMQ
Storage:
S3-compatible storage
Observability:
OpenTelemetry
Containers:
Docker
93. REST API Milestones
Milestone 1: Platform Access
POST /auth/register
POST /auth/login
POST /auth/refresh
GET /me
POST /organizations
GET /me/organizations
POST /membership-invitations
GET /memberships
GET /roles
POST /roles
GET /permissions
Goal:
Create account
↓
Create organization
↓
Invite team
↓
Assign roles
Milestone 2: Engineering Clients
POST /engineering/clients
GET /engineering/clients
GET /engineering/clients/{id}
PATCH /engineering/clients/{id}
Milestone 3: Engineering Projects
POST /engineering/projects
GET /engineering/projects
GET /engineering/projects/{id}
PATCH /engineering/projects/{id}
POST /engineering/projects/{id}/activate
POST /engineering/projects/{id}/close
Milestone 4: Collaboration
POST /engineering/projects/{id}/members
GET /engineering/projects/{id}/members
POST /engineering/tasks
GET /engineering/tasks
POST /engineering/tasks/{id}/complete
Milestone 5: Sites and Documents
Build:
engineering sites
signed file uploads
project document links
Milestone 6: Designs and Inspections
Build:
designs
reviews
approvals
inspections
findings
Milestone 7: Commercial Workflows
Build:
time entries
invoices
payments
reports
94. Architecture Rules to Freeze
- REST is the primary frontend and integration API.
- Base path is
/api/v1. - GraphQL is not part of v1.
- One shared backend platform.
- Separate frontend application for each profession.
- Each profession owns its database tables.
- Shared modules contain infrastructure, not profession-specific semantics.
- Every tenant-owned row has
organization_id. - Tenant isolation is enforced by both application and database.
- Authorization is always server-side.
- Roles and professional credentials are different concepts.
- Profession-specific permissions use namespaces.
- PostgreSQL is the source of truth.
- Files live in object storage.
- Important business transitions use explicit REST command endpoints.
- Important mutations are audited.
- Domain events use a transactional outbox.
- Background side effects run through workers.
- Start as a modular monolith.
- Do not start with microservices.
- Do not replace proper domain modeling with JSON blobs.
- Do not hard-delete important professional or financial records without explicit retention rules.
- Database models and public API DTOs are separate contracts.
- The frontend never determines authorization.
- Healthcare receives stricter security treatment than ordinary CRM data.
- Engineering is the first implemented vertical.
- Legal follows after engineering validates the platform.
- Healthcare follows after security and compliance requirements are explicitly designed.
- OpenAPI is the source of truth for the REST contract.
- Reconsider GraphQL only if a demonstrated client-composition problem justifies the added complexity.
95. Required Design Artifacts
Prepare and maintain:
01_PROJECT_ARCHITECTURE.md
02_DATABASE_CONVENTIONS.md
03_AUTHORIZATION_MODEL.md
04_ENGINEERING_DOMAIN.md
05_ENGINEERING_DATABASE_SCHEMA.md
06_API_CONVENTIONS.md
07_ENGINEERING_API_SPEC.md
08_FRONTEND_ARCHITECTURE.md
09_SECURITY_MODEL.md
10_DEPLOYMENT_ARCHITECTURE.md
11_TESTING_STRATEGY.md
12_MVP_BACKLOG.md
13_OPENAPI.yaml
96. Recommended Implementation Order
Foundation
↓
Authentication
↓
Organizations
↓
Memberships
↓
RBAC
↓
Engineering Clients
↓
Engineering Projects
↓
Project Team
↓
Tasks
↓
Sites
↓
Documents
↓
Designs
↓
Inspections
↓
Time Tracking
↓
Billing
↓
Notifications
↓
Reports
↓
Legal Vertical
↓
Healthcare Vertical
97. Final Design Position
The platform is not a generic management system with profession names painted on top.
It is:
One Shared Platform
│
├── Shared Identity
├── Shared Security
├── Shared Infrastructure
├── Shared Documents
├── Shared Financial Core
├── Shared Audit/Event Platform
│
├── Engineering Product
│ ├── Engineering Frontend
│ ├── Engineering REST APIs
│ └── Engineering Tables
│
├── Legal Product
│ ├── Legal Frontend
│ ├── Legal REST APIs
│ └── Legal Tables
│
└── Healthcare Product
├── Healthcare Frontend
├── Healthcare REST APIs
└── Healthcare Tables
The system shares infrastructure where reuse is valuable while preserving independent domain models where professional workflows differ.