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

# Organizational Data Structure Guide

> This guide documents the organizational data structure across the Encore OS Platform. It defines when to use each entity, how they relate, and best practices f…

**Version:** 1.0.0\
**Last Updated:** 2025-12-31\
**Owner:** Platform Foundation (PF)

***

## Purpose

This guide documents the organizational data structure across the Encore OS Platform. It defines when to use each entity, how they relate, and best practices for implementation.

**Related Documents:**

* **Constitution:** `constitution.md` Section 5.2.2
* **AI Guide:** `AI_GUIDE.md` Section "Organizational Data Management"
* **Unified Analysis:** `specs/pf/UNIFIED_ORGANIZATIONAL_DATA_ANALYSIS.md`
* **Implementation Plan:** `specs/pf/ORGANIZATIONAL_DATA_IMPLEMENTATION_PLAN.md`

***

## Platform Foundation Organizational Entities

### `pf_organizations`

**Purpose:** Top-level tenants in the multi-tenant system.

**Usage:**

* Every business table includes `organization_id` for tenant isolation
* RLS policies enforce organization boundaries
* Users can belong to multiple organizations

**When to Use:**

* Always include `organization_id` in business tables
* Reference in RLS policies for tenant isolation

***

### `pf_sites`

**Purpose:** Physical work locations within organizations.

**Fields:**

* `id`, `organization_id`, `name`, `slug`
* `tax_jurisdiction` - For payroll tax calculation
* `address_line_1`, `address_line_2`, `city`, `state`, `zip_code`, `country`
* `timezone` - For time-based policies

**When to Use:**

* ✅ **Always include `site_id`** when entity is location-specific:
  * Residences, work orders, assets
  * Site-specific policies, forms, training
  * Site-based operations (episodes, attendance)
* ❌ **Do NOT include `site_id`** when entity is organization-wide:
  * Strategic goals, vision statements
  * Organization-level settings
  * Cross-site teams (some cases)

**Best Practices:**

* Use `primary_site_id` for employee work location (NOT `work_location` TEXT)
* Enhance sites with tax jurisdiction for payroll
* Use site timezone for time-based policies

***

### `pf_departments`

**Purpose:** Unified organizational units for both HR and Finance.

**Fields:**

* `id`, `organization_id`, `site_id`
* `name`, `code`, `parent_department_id` (hierarchical)
* `department_type` - 'operational' | 'cost\_center' | 'both'
* HR fields: `department_head_id`, `is_clinical`
* FA fields: `cost_center`, `cost_allocation_method`

**When to Use:**

* ✅ **Always use `pf_departments`** (NOT `hr_departments` or `fa_departments`)
* ✅ For employee organization (HR)
* ✅ For cost allocation (FA)
* ✅ For department-based policies (GR)
* ✅ For department-based access control

**Best Practices:**

* Set `department_type` based on usage:
  * 'operational' - Used for HR/employee organization
  * 'cost\_center' - Used for FA/cost allocation
  * 'both' - Used for both purposes
* Use hierarchical structure via `parent_department_id`
* Link to `pf_sites` for site-specific departments

***

### `pf_levels`

**Purpose:** Employee classification for policy assignment and access control.

**Fields:**

* `id`, `organization_id`
* `level_name` - 'Executive', 'Manager', 'Individual Contributor'
* `level_code` - 'EXEC', 'MGR', 'IC'
* `level_rank` - 1-10 (1 = highest, 10 = lowest)

**When to Use:**

* ✅ For level-based policy assignment (spend policies, access)
* ✅ For reporting and analytics (compensation by level)
* ✅ For formula fields (e.g., "all employees with level\_rank \<= 3")
* ✅ For access control (executives get different access)

**Best Practices:**

* Assign `level_id` to all employees
* Use `level_rank` for ordering and comparisons
* Create default levels: Executive (1), Manager (5), Individual Contributor (10)

***

### `pf_positions`

**Purpose:** Job title library for consistency across modules.

**Fields:**

* `id`, `organization_id`
* `title`, `code`, `description`
* `is_clinical` - For credential requirements

**When to Use:**

* ✅ For employee job titles (HR)
* ✅ For training assignments (GR)
* ✅ For form field lookups (FW)
* ✅ For reporting and analytics

**Best Practices:**

* Maintain position library for consistency
* Use `is_clinical` to drive credential requirements
* Reference in `hr_employees.position_id`

***

### `pf_teams`

**Purpose:** Cross-functional groups for projects and collaboration.

**Fields:**

* `id`, `organization_id`
* `name`, `description`
* `team_lead_id` - References `hr_employees`

**When to Use:**

* ✅ For cross-functional projects (HR, GR, FW, LO)
* ✅ For team-based policies (GR)
* ✅ For form access control (FW)
* ✅ For goal assignment (LO)

**Best Practices:**

* Use for temporary or project-based groups
* Link to `pf_departments` if team is department-specific
* Reference via `hr_team_members` junction table

***

## Module-Specific Organizational Entities

### `rh_programs` (Recovery Housing)

**Purpose:** Operational/resident programs for phase management.

**Fields:**

* `id`, `organization_id`, `site_id`
* `name`, `program_type`, `duration_baseline_days`
* `capacity_limit`, `eligibility_criteria`

**When to Use:**

* ✅ For resident program structure
* ✅ For phase management
* ✅ For program-specific forms and workflows

**Relationship:**

* Optional: `fa_programs.rh_program_id` for financial tracking

***

### `fa_programs` (Finance)

**Purpose:** Financial/cost reporting programs for Medicaid and grants.

**Fields:**

* `id`, `organization_id`
* `code`, `name`, `department_id`
* `is_revenue_generating`

**When to Use:**

* ✅ For Medicaid cost reporting
* ✅ For grant tracking
* ✅ For revenue/expense allocation

**Relationship:**

* Optional: `rh_program_id` to link to operational programs

***

### `fa_funds` (Finance)

**Purpose:** Fund accounting (restricted/unrestricted).

**Fields:**

* `id`, `organization_id`
* `fund_code`, `name`, `fund_type`

**When to Use:**

* ✅ For fund accounting
* ✅ For grant management
* ✅ For financial reporting

***

## Integration Patterns

### Policy Assignment

**Level-Based Policies:**

```typescript theme={null}
// Assign spend policy based on employee level
const { data: employee } = useEmployee(employeeId);
const { data: level } = useLevel(employee.level_id);

if (level.level_rank <= 3) {
  // Executive-level spend policy
}
```

**Site-Based Policies:**

```typescript theme={null}
// Assign holiday policy based on site
const { data: site } = useSite(siteId);
const { data: policy } = useHolidayPolicy(site.tax_jurisdiction);
```

**Department-Based Policies:**

```typescript theme={null}
// Assign access policy based on department
const { data: department } = useDepartment(departmentId);
if (department.is_clinical) {
  // Clinical department access rules
}
```

***

### Access Control

**Level-Based Access:**

```typescript theme={null}
// Check if user has executive access
const { data: userLevel } = useUserLevel(userId);
const hasExecutiveAccess = userLevel.level_rank <= 3;
```

**Site-Based Access:**

```typescript theme={null}
// Site managers see only their site
const { data: userSites } = useUserSites(userId);
const canAccessSite = userSites.includes(siteId);
```

**Department-Based Access:**

```typescript theme={null}
// Department managers see only their department
const { data: userDepartment } = useUserDepartment(userId);
const canAccessDepartment = userDepartment.id === departmentId;
```

***

### Financial Integration

**Department Cost Allocation:**

```typescript theme={null}
// Use department for GL mapping
const { data: department } = useDepartment(departmentId);
if (department.department_type === 'cost_center' || department.department_type === 'both') {
  // Use for cost allocation
  const glAccount = mapDepartmentToGLAccount(department.cost_center);
}
```

**Program Financial Tracking:**

```typescript theme={null}
// Link operational program to financial program
const { data: rhProgram } = useRHProgram(programId);
const { data: faProgram } = useFAProgram(rhProgram.fa_program_id);
// Track financial metrics for operational program
```

***

## Migration Guide

### From Duplicate Departments

**Before:**

* `hr_departments` for employee organization
* `fa_departments` for cost centers
* No integration between them

**After:**

* `pf_departments` unified table
* `department_type` field distinguishes usage
* Single source of truth

**Migration Steps:**

1. Create `pf_departments` table
2. Migrate `hr_departments` → `pf_departments` (type: 'operational')
3. Migrate `fa_departments` → `pf_departments` (type: 'cost\_center' or 'both' if duplicate)
4. Update foreign keys
5. Create backward-compatible views

***

### From Work Location TEXT

**Before:**

* `hr_employees.work_location TEXT` (unstructured)
* `hr_employees.primary_site_id` (structured)

**After:**

* `hr_employees.primary_site_id` only
* `pf_sites` enhanced with address, tax jurisdiction

**Migration Steps:**

1. Enhance `pf_sites` with address fields
2. Create sites from unique `work_location` TEXT values
3. Update `primary_site_id` to reference new sites
4. Deprecate `work_location` TEXT field

***

## Best Practices

### When Creating New Features

1. **Always use Platform Foundation entities:**
   * `pf_departments` (not core-specific)
   * `pf_sites` (not TEXT fields)
   * `pf_levels` (for policy assignment)
   * `pf_positions` (for job titles)
   * `pf_teams` (for cross-functional groups)

2. **Include `site_id` when location matters:**
   * Residences, work orders, assets
   * Site-specific policies, forms, training
   * Site-based operations

3. **Consider organizational context:**
   * Policy assignment (level, site, department)
   * Access control (level, site, department)
   * Financial integration (department, program)

4. **Document relationships:**
   * Optional relationships (e.g., `fa_programs.rh_program_id`)
   * Hierarchical structures (e.g., `parent_department_id`)
   * Many-to-many relationships (e.g., `hr_team_members`)

***

## Common Patterns

### Employee Organizational Context

```typescript theme={null}
// Get employee's full organizational context
const { data: employee } = useEmployee(employeeId);
const { data: department } = useDepartment(employee.department_id);
const { data: level } = useLevel(employee.level_id);
const { data: position } = usePosition(employee.position_id);
const { data: site } = useSite(employee.primary_site_id);

// Use for policy assignment
const policies = getPoliciesForContext({
  level: level.level_rank,
  department: department.id,
  site: site.id
});
```

### Department Hierarchy

```typescript theme={null}
// Build department hierarchy
const { data: departments } = useDepartmentList({ buildHierarchy: true });

// Use for org chart
<OrgChart departments={departments} />
```

### Site-Based Filtering

```typescript theme={null}
// Filter records by site
const { data: records } = useRecords({
  siteId: currentSite.id,
  organizationId: currentOrg.id
});
```

***

## References

* **Constitution:** `constitution.md` Section 5.2.2
* **AI Guide:** `AI_GUIDE.md` Section "Organizational Data Management"
* **Unified Analysis:** `specs/pf/UNIFIED_ORGANIZATIONAL_DATA_ANALYSIS.md`
* **Implementation Plan:** `specs/pf/ORGANIZATIONAL_DATA_IMPLEMENTATION_PLAN.md`
* **HR-01 Spec:** `specs/hr/HR-01-employee-directory.md`
* **FA-01 Spec:** `specs/fa/FA-01-chart-of-accounts.md`
* **PF-01 Spec:** `specs/pf/PF-01-organization-site-management.md`

***

**Last Updated:** 2025-01-27
