Files
professional_management/professional_management_platform_rest_plan.md
T
2026-08-27 21:52:21 -04:00

3164 lines
42 KiB
Markdown

# 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:
```text
/api/v1
```
GraphQL is not part of v1.
---
## 3. High-Level Architecture
```text
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:
```text
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:
```text
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:
```text
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:
```text
Dashboard
Clients
Projects
Project Phases
Project Team
Sites
Designs
Design Reviews
Inspections
Specifications
Tasks
Documents
Timesheets
Billing
Reports
Administration
```
### Legal Frontend
Suggested navigation:
```text
Dashboard
Clients
Matters
Cases
Hearings
Courts
Deadlines
Documents
Conflict Checks
Time Tracking
Retainers
Billing
Reports
Administration
```
### Healthcare Frontend
Suggested navigation:
```text
Dashboard
Patients
Appointments
Practitioners
Encounters
Clinical Records
Diagnoses
Prescriptions
Insurance
Documents
Billing
Reports
Administration
```
### Platform Admin Frontend
Suggested functions:
```text
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:
```text
/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:
```text
/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:
```text
/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:
```text
/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:
```http
Authorization: Bearer <access-token>
X-Organization-Id: org_123
Content-Type: application/json
```
Every tenant-scoped request requires organization context.
The server must verify:
1. user is authenticated
2. organization exists
3. membership exists
4. membership is active
5. required permission is present
6. resource belongs to the organization
7. resource policy permits access
8. profession-specific rules pass
---
## 9. Standard Response Format
Single resource:
```json
{
"data": {
"id": "project_123",
"name": "Central Tower"
}
}
```
Collection:
```json
{
"data": [],
"meta": {
"pagination": {
"nextCursor": null,
"hasMore": false
}
}
}
```
Error:
```json
{
"error": {
"code": "PROJECT_NOT_FOUND",
"message": "Project not found.",
"details": {}
}
}
```
Clients should rely on `error.code`, not human-readable messages.
---
## 10. HTTP Status Rules
```text
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:
```text
/api/v1
```
Breaking changes require:
```text
/api/v2
```
Additive fields generally do not require a new version.
---
## 12. Authentication
Initial authentication:
```text
Email
+
Password
+
Access Token
+
Refresh Token
```
Endpoints:
```http
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:
```text
core/
├── auth/
├── users/
├── organizations/
├── memberships/
├── roles/
├── permissions/
├── authorization/
├── documents/
├── billing/
├── notifications/
├── audit/
└── events/
```
Dependency rule:
```text
Profession module → Core
```
Never:
```text
Core → Profession module
```
---
## 14. Organizations
Organizations are tenants.
Examples:
```text
Atlas Structural Engineering
Smith & Associates Law
North Shore Medical Practice
```
Suggested fields:
```text
id
name
slug
status
country_code
timezone
currency_code
created_at
updated_at
```
---
## 15. Profession Enablement
Use:
```text
organization_professions
```
Suggested fields:
```text
organization_id
profession
enabled_at
configuration
```
Possible professions:
```text
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.
```text
User
Membership
Organization
```
Suggested `users` fields:
```text
id
email
first_name
last_name
phone
avatar_url
status
created_at
updated_at
```
Suggested `memberships` fields:
```text
id
organization_id
user_id
status
joined_at
created_at
updated_at
```
---
## 17. Membership Invitations
Keep invitations separate from memberships.
Suggested table:
```text
membership_invitations
```
Fields:
```text
id
organization_id
email
invited_by_user_id
expires_at
accepted_at
revoked_at
created_at
```
Flow:
```text
Invitation
Accepted
User
Membership
```
---
## 18. Authorization
Use:
```text
RBAC
+
Resource Policies
+
Professional Qualifications
```
Decision flow:
```text
Authenticated User
Organization Membership
Roles
Permissions
Permission Scope
Resource Policy
Professional Qualification Rule
Domain State Rule
ALLOW / DENY
```
Default decision:
```text
DENY
```
---
## 19. Roles and Permissions
Example roles:
```text
Owner
Administrator
Project Manager
Engineer
Lawyer
Paralegal
Doctor
Nurse
Billing Manager
Viewer
```
Example permissions:
```text
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:
```text
assigned
organization
```
Examples:
```text
Engineer:
engineering.projects.read = assigned
Principal Engineer:
engineering.projects.read = organization
```
Potential future scopes:
```text
owned
team
department
restricted
```
Do not implement until required.
---
## 21. Professional Credentials
Professional qualification is separate from RBAC.
Suggested table:
```text
professional_profiles
```
Fields:
```text
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:
```text
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:
```text
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:
```text
organization_id
```
Examples:
```text
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:
```text
engineering_projects
organization_id
client_id
```
references:
```text
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:
```text
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:
```text
id
organization_id
client_type
display_name
legal_name
contact_name
email
phone
status
created_at
updated_at
```
REST:
```http
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:
```text
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:
```http
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:
```text
id
organization_id
project_id
user_id
project_role
joined_at
left_at
```
REST:
```http
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:
```text
id
organization_id
project_id
name
sequence
status
start_date
end_date
created_at
updated_at
```
Typical phases:
```text
Concept
Preliminary Design
Detailed Design
Construction
Inspection
Closeout
```
REST:
```http
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:
```text
id
organization_id
project_id
name
address
latitude
longitude
created_at
updated_at
```
REST:
```http
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:
```text
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:
```http
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:
```text
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:
```text
draft
under_review
changes_requested
approved
superseded
```
REST:
```http
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`:
```text
id
design_id
version_number
document_id
created_by_user_id
created_at
```
`engineering_design_reviews`:
```text
id
organization_id
design_id
reviewer_user_id
status
comments
reviewed_at
```
Possible review statuses:
```text
pending
approved
changes_requested
rejected
```
---
## 35. Engineering Inspections
Suggested fields:
```text
id
organization_id
project_id
site_id
inspection_type
inspector_user_id
status
scheduled_at
performed_at
summary
created_at
updated_at
```
REST:
```http
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:
```text
id
inspection_id
severity
description
status
resolved_at
```
Possible severities:
```text
observation
minor
major
critical
```
REST:
```http
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:
```text
id
organization_id
project_id
specification_number
title
version
status
document_id
created_at
updated_at
```
---
## 38. Engineering Change Requests
Suggested fields:
```text
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:
```text
id
organization_id
project_id
user_id
work_date
duration_minutes
description
billable
billing_rate_minor
currency_code
created_at
updated_at
```
REST:
```http
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:
```text
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:
```text
/api/v1/legal
```
Examples:
```http
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:
```text
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:
```text
id
organization_id
matter_id
case_number
court_id
jurisdiction
case_type
status
filed_date
created_at
updated_at
```
---
## 43. Legal Hearings
Suggested fields:
```text
id
organization_id
case_id
hearing_type
scheduled_at
courtroom
judge
status
notes
```
---
## 44. Legal Conflict Checks
Suggested fields:
```text
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:
```text
healthcare_patients
healthcare_practitioners
healthcare_appointments
healthcare_encounters
healthcare_clinical_records
healthcare_diagnoses
healthcare_prescriptions
healthcare_insurance
healthcare_allergies
healthcare_medications
```
REST namespace:
```text
/api/v1/healthcare
```
Examples:
```http
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:
```text
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:
```text
id
organization_id
user_id
specialty
license_number
license_jurisdiction
credential_status
created_at
updated_at
```
---
## 48. Healthcare Appointments
Suggested fields:
```text
id
organization_id
patient_id
practitioner_id
appointment_type
starts_at
ends_at
status
reason
created_at
updated_at
```
---
## 49. Healthcare Encounters
Suggested fields:
```text
id
organization_id
patient_id
practitioner_id
appointment_id
encounter_type
started_at
ended_at
status
```
---
## 50. Clinical Records
Suggested fields:
```text
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:
```text
documents
document_versions
```
Actual binary files:
```text
S3-compatible Object Storage
```
Suggested `documents` fields:
```text
id
organization_id
name
mime_type
size_bytes
created_by_user_id
created_at
updated_at
```
Suggested `document_versions` fields:
```text
id
document_id
version_number
storage_key
checksum
size_bytes
uploaded_by_user_id
created_at
```
---
## 52. Document Upload Flow
```text
Frontend
Request upload URL
Backend authorizes
Signed upload URL
Frontend uploads to object storage
Backend finalizes document
Virus/security scan
Document becomes available
```
REST:
```http
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:
```text
engineering_project_documents
engineering_design_documents
engineering_inspection_documents
```
Legal:
```text
legal_matter_documents
legal_case_documents
```
Healthcare:
```text
healthcare_patient_documents
healthcare_encounter_documents
```
This gives stronger foreign-key integrity than generic polymorphic document links.
---
## 54. Billing
Shared financial core:
```text
invoices
invoice_items
payments
```
Profession-specific modules may extend billing workflows.
Engineering examples:
```text
project billing
hourly billing
milestone billing
```
Legal examples:
```text
matter billing
time billing
retainers
trust accounting
```
Healthcare examples:
```text
insurance
claims
patient billing
```
REST:
```http
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:
```json
{
"amountMinor": 12550,
"currency": "USD"
}
```
Meaning:
```text
$125.50
```
Never use floating point for money.
---
## 56. Audit Logging
Table:
```text
audit_events
```
Suggested fields:
```text
id
organization_id
actor_user_id
action
resource_type
resource_id
request_id
ip_address
user_agent
metadata
occurred_at
```
Examples:
```text
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:
```http
GET /api/v1/audit-events
```
No public create/update/delete endpoints.
---
## 57. Domain Events and Transactional Outbox
Profession modules produce internal domain events.
Examples:
```text
engineering.project.created
engineering.inspection.completed
legal.hearing.scheduled
healthcare.appointment.created
invoice.issued
```
Consumers:
```text
notifications
webhooks
analytics
search
integrations
background workflows
```
Use:
```text
outbox_events
```
Transaction pattern:
```text
BEGIN
business update
audit event
outbox event
COMMIT
```
Worker processes outbox events after commit.
---
## 58. Background Jobs
Workers handle:
```text
Email
SMS
Notifications
Report generation
PDF generation
File scanning
Document processing
Imports
Exports
Webhook delivery
Search indexing
Large data operations
```
Architecture:
```text
API
Queue
Worker
```
---
## 59. Redis
Use Redis for:
```text
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:
```http
GET /api/v1/engineering/projects?limit=25
```
Response:
```json
{
"data": [],
"meta": {
"pagination": {
"nextCursor": "...",
"hasMore": true
}
}
}
```
Maximum page size:
```text
100
```
---
## 61. Filtering
Use explicit resource-specific filters.
Examples:
```http
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:
```http
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:
```text
project number
project name
client name
```
Legal:
```text
matter number
client
case number
```
Healthcare:
```text
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:
```json
{
"id": "project_123",
"version": 6
}
```
Update:
```json
{
"version": 6,
"name": "Central Tower Phase II"
}
```
If the current database version differs:
```text
409 CONCURRENT_MODIFICATION
```
---
## 65. Domain-Oriented REST
Important state transitions use explicit command endpoints.
Good:
```http
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:
```http
PATCH /resource/{id}
{
"status": "approved"
}
```
when the change has significant rules or side effects.
---
## 66. Transaction Boundaries
Create project:
```text
BEGIN
create project
assign project manager
write audit event
write outbox event
COMMIT
```
Approve design:
```text
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:
```text
RequestContext
{
requestId
userId
sessionId
organizationId
membershipId
permissions
}
```
Profession modules consume this context.
---
## 68. Request IDs
Every request has:
```http
X-Request-Id
```
If missing, the server generates one.
Use it in:
- logs
- audit context
- error diagnostics
- asynchronous correlation
---
## 69. OpenAPI
Maintain:
```text
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:
```text
Request DTO
Response DTO
```
A database migration should not accidentally change the public API.
---
## 71. Backend Module Structure
Recommended:
```text
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:
```text
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:
```text
HTTP
authentication context
input DTO parsing
application command/query invocation
response mapping
```
Controllers should not contain:
```text
business rules
raw SQL
role logic
transaction orchestration
email sending
audit implementation
```
---
## 74. Commands and Queries
Mutations use commands.
Examples:
```text
CreateEngineeringProjectCommand
ApproveEngineeringDesignCommand
CloseLegalMatterCommand
CompleteHealthcareEncounterCommand
```
Reads use queries.
Examples:
```text
GetEngineeringProjectQuery
ListLegalMattersQuery
GetHealthcarePatientQuery
```
---
## 75. Repositories
Use domain-specific repositories.
Examples:
```text
EngineeringProjectRepository
LegalMatterRepository
HealthcarePatientRepository
```
Avoid one massive generic repository abstraction that eventually needs dozens of flags.
---
## 76. Security Baseline
Minimum controls:
```text
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
```text
marketing configuration
```
### Internal
```text
organization settings
tasks
```
### Confidential
```text
engineering documents
legal matters
billing
```
### Highly Sensitive
```text
clinical records
professional credentials
authentication secrets
```
---
## 78. Healthcare Security
Before healthcare production use, define:
```text
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:
```text
structured logs
metrics
distributed tracing
request IDs
```
Recommended:
```text
OpenTelemetry
```
Track:
```text
API latency
error rate
database latency
database connections
queue depth
worker failures
authentication failures
authorization denials
external service failures
```
---
## 80. Logging
Useful fields:
```text
request_id
route
method
status
duration
user_id when appropriate
organization_id when appropriate
```
Never log:
```text
passwords
tokens
clinical record text
full sensitive documents
payment secrets
```
---
## 81. Testing Strategy
### Unit Tests
Test:
```text
domain rules
authorization policies
calculations
state transitions
```
### Integration Tests
Test:
```text
repositories
PostgreSQL constraints
transactions
```
### API Tests
Test:
```text
routes
validation
authentication
authorization
error responses
```
### End-to-End Tests
Test complete professional workflows.
---
## 82. Tenant Security Tests
For every major resource, attempt:
```text
Organization A resource
using Organization B context
```
Test:
```text
read
update
delete/action
list filtering
search
documents
```
Expected result:
```text
404 / denied
```
---
## 83. Engineering MVP
Engineering is the first vertical.
Initial features:
```text
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:
```text
advanced CAD integration
BIM integration
full document markup
advanced resource planning
procurement
complex accounting
AI design analysis
IoT integrations
```
---
## 84. Engineering MVP Workflow
```text
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:
```text
Domain design
Database conventions
REST conventions
Authorization rules
Repository structure
Engineering workflows
```
### Phase 1: Shared Platform Core
Build:
```text
Auth
Users
Organizations
Organization professions
Membership invitations
Memberships
Roles
Permissions
Authorization
Audit
Outbox
```
### Phase 2: Engineering CRM
Build:
```text
engineering_clients
```
### Phase 3: Engineering Projects
Build:
```text
engineering_projects
engineering_project_members
engineering_project_phases
```
### Phase 4: Work Management
Build:
```text
engineering_tasks
engineering_sites
```
### Phase 5: Documents
Build:
```text
documents
document_versions
object storage
signed uploads
engineering document links
```
### Phase 6: Designs
Build:
```text
engineering_designs
engineering_design_versions
engineering_design_reviews
approval rules
credential-aware authorization
```
### Phase 7: Inspections
Build:
```text
engineering_inspections
engineering_inspection_findings
follow-ups
attachments
```
### Phase 8: Time and Billing
Build:
```text
engineering_time_entries
invoices
invoice_items
payments
```
### Phase 9: Notifications
Build:
```text
in-app notifications
email
worker processing
```
### Phase 10: Reporting
Initial reports:
```text
project status
overdue tasks
inspection status
billable time
revenue
outstanding invoices
```
---
## 86. Legal Expansion
Only after engineering proves the shared platform assumptions.
Build:
```text
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:
```text
development
testing
staging
production
```
Each environment has independent:
```text
database
object storage
secrets
queues
API keys
```
---
## 89. Initial Deployment Architecture
```text
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:
```text
automated backups
point-in-time recovery
tested restores
```
Object storage:
```text
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:
```text
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:
```text
TypeScript
NestJS or Fastify-based architecture
```
Database:
```text
PostgreSQL
```
ORM/query layer candidates:
```text
Prisma
Drizzle
Kysely
```
Frontend:
```text
React / Next.js
```
Queue:
```text
Redis + BullMQ
```
Storage:
```text
S3-compatible storage
```
Observability:
```text
OpenTelemetry
```
Containers:
```text
Docker
```
---
## 93. REST API Milestones
### Milestone 1: Platform Access
```http
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:
```text
Create account
Create organization
Invite team
Assign roles
```
### Milestone 2: Engineering Clients
```http
POST /engineering/clients
GET /engineering/clients
GET /engineering/clients/{id}
PATCH /engineering/clients/{id}
```
### Milestone 3: Engineering Projects
```http
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
```http
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:
```text
engineering sites
signed file uploads
project document links
```
### Milestone 6: Designs and Inspections
Build:
```text
designs
reviews
approvals
inspections
findings
```
### Milestone 7: Commercial Workflows
Build:
```text
time entries
invoices
payments
reports
```
---
## 94. Architecture Rules to Freeze
1. REST is the primary frontend and integration API.
2. Base path is `/api/v1`.
3. GraphQL is not part of v1.
4. One shared backend platform.
5. Separate frontend application for each profession.
6. Each profession owns its database tables.
7. Shared modules contain infrastructure, not profession-specific semantics.
8. Every tenant-owned row has `organization_id`.
9. Tenant isolation is enforced by both application and database.
10. Authorization is always server-side.
11. Roles and professional credentials are different concepts.
12. Profession-specific permissions use namespaces.
13. PostgreSQL is the source of truth.
14. Files live in object storage.
15. Important business transitions use explicit REST command endpoints.
16. Important mutations are audited.
17. Domain events use a transactional outbox.
18. Background side effects run through workers.
19. Start as a modular monolith.
20. Do not start with microservices.
21. Do not replace proper domain modeling with JSON blobs.
22. Do not hard-delete important professional or financial records without explicit retention rules.
23. Database models and public API DTOs are separate contracts.
24. The frontend never determines authorization.
25. Healthcare receives stricter security treatment than ordinary CRM data.
26. Engineering is the first implemented vertical.
27. Legal follows after engineering validates the platform.
28. Healthcare follows after security and compliance requirements are explicitly designed.
29. OpenAPI is the source of truth for the REST contract.
30. Reconsider GraphQL only if a demonstrated client-composition problem justifies the added complexity.
---
## 95. Required Design Artifacts
Prepare and maintain:
```text
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
```text
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:
```text
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.