> ## Documentation Index
> Fetch the complete documentation index at: https://docs.encoreos.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Platform Foundation Documentation

> The Platform Foundation provides the core infrastructure and shared services for the Encore Health OS platform.

The Platform Foundation provides the core infrastructure and shared services for the Encore Health OS platform.

## 📚 Table of Contents

* [Architecture Overview](#architecture-overview)
* [Multi-Tenancy Model](#multi-tenancy-model)
* [Authentication & Authorization](#authentication--authorization)
* [Module Registry](#module-registry)
* [User Guides](#user-guides)

***

## Architecture Overview

### Core Responsibilities

The Platform Foundation (PF) provides:

1. **Multi-Tenant Infrastructure**
   * Organization and site management
   * Tenant isolation via RLS
   * Cross-tenant security enforcement

2. **Authentication & Authorization**
   * User authentication via Supabase Auth
   * Role-Based Access Control (RBAC)
   * Permission enforcement at data and UI levels

3. **Shared Services**
   * Notifications (in-app, email, SMS)
   * Document management
   * Reporting engine
   * Audit logging
   * Form analytics

4. **Developer Infrastructure**
   * Module registry for dynamic navigation
   * Error handling and monitoring
   * Testing utilities
   * Shared UI components

### Module Architecture

```
Platform Foundation (PF) - Core Services
├── RH (Recovery Housing)
├── FA (Finance & Accounting)
├── HR (Workforce Management)
├── GR (Governance & Compliance)
├── FW (Forms & Workflow)
└── FM (Facilities Management)
```

**Key Principle:** Modules depend ONLY on Platform Foundation, NEVER on each other.

***

## Multi-Tenancy Model

### Organization Hierarchy

```
Platform
└── Organizations (pf_organizations)
    └── Sites (pf_sites)
        └── Sub-sites (hierarchical)
```

### Tenant Isolation

Every business table includes:

* `organization_id` - Required, references `pf_organizations`
* `site_id` - Optional, references `pf_sites`

**RLS Enforcement:**

```sql theme={null}
CREATE POLICY "tenant_isolation" ON table_name
  FOR SELECT USING (
    has_org_access(auth.uid(), organization_id)
  );
```

### Security Functions

**`has_org_access(user_id, org_id)`**

* SECURITY DEFINER function (bypasses RLS recursion)
* Checks if user has ANY role in the organization
* Used by all RLS policies for tenant isolation

**`has_role(user_id, required_role, org_id, site_id)`**

* Verifies user has required role level or higher
* Respects role hierarchy (platform\_admin > org\_admin > site\_admin > manager > staff)

***

## Authentication & Authorization

### Authentication Flow

1. User signs in via email/password or OAuth
2. Supabase Auth creates session with JWT
3. JWT contains `auth.uid()` used by RLS policies
4. User's roles and permissions fetched from `pf_user_role_assignments` (V2 permissions system)

### Role Hierarchy

| Role                | Access Level        | Typical Permissions                     |
| ------------------- | ------------------- | --------------------------------------- |
| **platform\_admin** | All organizations   | System configuration, user management   |
| **org\_admin**      | Single organization | Org settings, user roles, module config |
| **site\_admin**     | Single site         | Site operations, staff management       |
| **manager**         | Department/program  | Workflow approvals, reports             |
| **staff**           | Daily operations    | Data entry, form submissions            |

### Permission Checks

**Backend (RLS):**

```sql theme={null}
CREATE POLICY "policy_name" ON table_name
  FOR operation USING (
    has_role(auth.uid(), 'required_role', organization_id, site_id)
  );
```

**Frontend (UI):**

```typescript theme={null}
import { useRole } from '@/shared/lib/hooks/use-role';

const { hasRole } = useRole();

if (hasRole('org_admin')) {
  // Show admin features
}
```

***

## Module Registry

### Dynamic Module Loading

Modules register themselves at app startup:

```typescript theme={null}
// src/cores/rh/index.ts
import { registerModule } from '@/platform/registry';

registerModule({
  id: 'rh',
  name: 'Recovery Housing',
  icon: Home,
  description: 'Census and bed management',
  route: '/rh',
  requiredRole: 'staff',
  component: lazy(() => import('./RHDashboard'))
});
```

### Benefits

* ✅ No hardcoded module lists
* ✅ Role-based visibility
* ✅ Lazy loading (performance)
* ✅ Easy to add/remove modules

### App Launcher

The App Launcher displays available modules based on:

1. User's role
2. Module's `requiredRole`
3. Module enablement in org settings

***

## User Guides

### For End Users

* **[Notifications Guide](./notifications-guide.md)** - Managing notifications and preferences
* **[Document Management Guide](./document-management-guide.md)** - Uploading and organizing documents
* **[Reporting Guide](./reporting-guide.md)** - Creating and running reports

### For Administrators

* **Organization Setup** - Configuring organizations and sites
* **User Management** - Adding users and assigning roles
* **Module Configuration** - Enabling/disabling modules per org

### For Developers

* **[Testing Guide](../../tests/README.md)** - Writing RLS security tests
* **[Integration Documentation](../architecture/integrations/index.md)** - Cross-module communication
* **[Constitution](../../constitution.md)** - Architecture guardrails

***

## Database Naming Conventions

All Platform Foundation tables follow these patterns:

| Pattern                    | Example            | Purpose                    |
| -------------------------- | ------------------ | -------------------------- |
| `pf_*`                     | `pf_organizations` | Platform Foundation tables |
| `*_id`                     | `organization_id`  | Foreign key columns        |
| `created_at`, `updated_at` | Timestamps         | Audit trail                |
| `created_by`, `updated_by` | User references    | User tracking              |
| `custom_fields`            | JSONB              | Extensibility              |
| `deleted_at`               | Nullable timestamp | Soft delete                |

***

## Key Technologies

* **Backend:** Supabase (PostgreSQL + Auth + Storage)
* **Frontend:** React + TypeScript + Tailwind CSS
* **State Management:** TanStack Query (React Query)
* **Routing:** React Router v6
* **Forms:** React Hook Form + Zod
* **Testing:** Vitest + Testing Library

***

## Support & Resources

* **Internal Documentation:** `/docs/`
* **Specifications:** `/specs/pf/`
* **Implementation Logs:** `/specs/pf/IMPLEMENTATION_LOG.md`
* **Test Coverage:** `/tests/README.md`

***

## Security Best Practices

1. **Always use RLS policies** - Never trust client-side checks alone
2. **Use SECURITY DEFINER functions** - Avoid RLS recursion issues
3. **Validate all inputs** - Use Zod schemas for API inputs
4. **Test multi-tenant isolation** - Every table needs RLS tests
5. **Scrub PII/PHI from logs** - No sensitive data in error messages
6. **Audit critical actions** - All data changes logged in `pf_audit_logs`

***

**Version:** 3.0.0\
**Last Updated:** 2025-11-29
