> ## 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 Overview

> Overview of the Platform Foundation in Encore OS — identity, settings, and shared services.

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

## How the platform is layered

Every domain core depends only on Platform Foundation — never on each other. PF provides multi-tenant isolation (organizations → sites), Supabase Auth + RBAC enforced through RLS, a dynamic module registry, and shared services (notifications, documents, reporting, audit).

```mermaid theme={null}
flowchart TD
  Auth["Auth & RBAC<br/>(Supabase Auth · roles ·<br/>has_org_access / has_role)"] --> PF
  Tenancy["Multi-tenancy<br/>(organizations → sites · RLS)"] --> PF
  Services["Shared services<br/>(notifications · documents ·<br/>reporting · audit)"] --> PF
  PF["Platform Foundation"] --> Registry["Module registry<br/>(role-aware loading)"]
  Registry --> Cores["Domain cores<br/>(CL · PM · FA · RH · HR ·<br/>CE · GR · FW · FM · IT · LO)"]
```

<Frame caption="Platform identity and SSO — Microsoft Entra integration settings.">
  <img src="https://mintcdn.com/encoreos/FHgwdEuPbyKq-W7P/images/pf/pf-63-en-02-entra-settings.png?fit=max&auto=format&n=FHgwdEuPbyKq-W7P&q=85&s=3f9a22fe1fca74857ce0c232f7af082b" alt="Platform Foundation identity and SSO settings" width="1440" height="2324" data-path="images/pf/pf-63-en-02-entra-settings.png" />
</Frame>

## Explore the platform foundation

<CardGroup cols={2}>
  <Card title="Multi-tenancy" icon="sitemap" href="#multi-tenancy-model">
    Organizations, sites, and RLS-based tenant isolation.
  </Card>

  <Card title="Auth & RBAC" icon="lock" href="#authentication--authorization">
    Supabase Auth, role hierarchy, and permission checks.
  </Card>

  <Card title="Module registry" icon="puzzle-piece" href="#module-registry">
    Dynamic, role-aware module loading and the app launcher.
  </Card>

  <Card title="Notifications" icon="bell" href="/pf/notifications-guide">
    In-app, email, and SMS notification preferences.
  </Card>

  <Card title="Documents" icon="folder-open" href="/pf/document-management-guide">
    Uploading and organizing documents.
  </Card>

  <Card title="Reporting" icon="chart-column" href="/pf/reporting-guide">
    Creating and running reports.
  </Card>
</CardGroup>

## 📚 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

```text theme={null}
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

```text theme={null}
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**](/pf/notifications-guide) - Managing notifications and preferences
* [**Document Management Guide**](/pf/document-management-guide) - Uploading and organizing documents
* [**Reporting Guide**](/pf/reporting-guide) - 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**](https://github.com/Encore-OS/encoreos/blob/development/tests/README.md) - Writing RLS security tests
* [**Integration Documentation**](/architecture/integrations/index) - Cross-module communication
* [**Constitution**](https://github.com/Encore-OS/encoreos/blob/development/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
