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

# HR-IT Offboarding Integration

> Version: 1.0 Created: 2026-01-21 Last Updated: 2026-01-21 Status: Active Spec: HR-03 Employee Lifecycle, IT-08 Onboarding/Offboarding

**Version:** 1.0\
**Created:** 2026-01-21\
**Last Updated:** 2026-01-21\
**Status:** Active\
**Spec:** HR-03 Employee Lifecycle, IT-08 Onboarding/Offboarding

## Overview

Documents the integration between HR employee termination/offboarding and IT deprovisioning.

## Integration Flow

```
┌──────────────────────────┐
│  HR Start Offboarding    │
│  (StartOffboardingDialog)│
└──────────┬───────────────┘
           │ 1. Creates HR offboarding instance
           │ 2. Auto-creates IT offboarding →
           ▼
┌──────────────────────────┐
│  useOffboardingMutation  │
│  (Enhanced)              │
└──────────┬───────────────┘
           │ Creates it_onboarding_instances
           │ with workflow_type: 'offboarding'
           ▼
┌──────────────────────────┐
│  IT Module Dashboard     │
│  (/it/offboarding)       │
└──────────────────────────┘

         ┌────────────────────────────┐
         │  Fallback: Edge Function   │
         │  hr-employee-terminated-   │
         │  handler                   │
         └──────────┬─────────────────┘
                    │ If IT offboarding missing,
                    │ creates one automatically
                    ▼
         ┌────────────────────────────┐
         │  IT Offboarding Instance   │
         │  (Urgent Priority)         │
         └────────────────────────────┘
```

## Data Flow

### 1. Start Offboarding Dialog

HR initiates offboarding with:

| Field              | Type    | Description                                                 |
| ------------------ | ------- | ----------------------------------------------------------- |
| `employee_id`      | UUID    | Employee being terminated                                   |
| `termination_date` | date    | Last day of employment                                      |
| `termination_type` | enum    | voluntary, involuntary, retirement, end\_contract, transfer |
| `reason`           | string? | Optional termination reason                                 |

### 2. Offboarding Mutation (Enhanced)

The `useOffboardingMutation` hook now:

1. Creates HR offboarding instance via `create_default_offboarding` RPC
2. Checks if IT offboarding already exists for employee
3. If not, creates IT offboarding instance with:

| Column          | Value                                         |
| --------------- | --------------------------------------------- |
| `employee_id`   | Link to terminated employee                   |
| `workflow_type` | `'offboarding'`                               |
| `status`        | `'pending'`                                   |
| `priority`      | `'high'` (security-critical)                  |
| `target_date`   | Employee termination date                     |
| `notes`         | Termination details + access revocation notes |

### 3. IT Offboarding Tasks

IT receives offboarding with tasks for:

* Email account deactivation
* Network/VPN access revocation
* Application access removal
* Equipment return tracking
* Security badge deactivation

## Fallback: Edge Function Handler

The `hr-employee-terminated-handler` edge function serves as a fallback:

1. Triggered by `employee_terminated` event
2. Checks if IT offboarding exists for the employee
3. If missing, creates one with `priority: 'urgent'`
4. Logs to audit trail

This ensures IT deprovisioning happens even if the UI flow was bypassed.

## Event Contract

| Event                          | Publisher | Subscriber                     | Trigger                                |
| ------------------------------ | --------- | ------------------------------ | -------------------------------------- |
| `employee_offboarding_started` | HR-03     | IT-08                          | StartOffboardingDialog completion      |
| `employee_terminated`          | HR-03     | hr-employee-terminated-handler | Employment status change to terminated |

### Event Payload Schema

**`employee_offboarding_started` Event:**

```json theme={null}
{
  "event_id": "uuid",           // Unique event ID for idempotency
  "event_version": "1.0",       // Event schema version
  "organization_id": "uuid",    // Tenant identifier
  "employee_id": "uuid",        // Terminated employee
  "termination_date": "date",   // Last day of employment
  "termination_type": "enum",   // voluntary, involuntary, retirement, end_contract, transfer
  "reason": "string?",          // Optional termination reason
  "actor_id": "uuid",           // User who initiated offboarding
  "timestamp": "iso8601"        // Event creation timestamp
}
```

**`employee_terminated` Event:**

```json theme={null}
{
  "event_id": "uuid",           // Unique event ID for idempotency
  "event_version": "1.0",       // Event schema version
  "organization_id": "uuid",    // Tenant identifier
  "employee_id": "uuid",        // Terminated employee
  "termination_date": "date",   // Last day of employment
  "termination_type": "enum",   // voluntary, involuntary, retirement, end_contract, transfer
  "actor_id": "uuid",           // System or user who triggered termination
  "timestamp": "iso8601"        // Event creation timestamp
}
```

### Idempotency Guarantees

* **Event ID:** Each event includes a unique `event_id` (UUID) that must be checked before processing
* **Duplicate Handling:** Subscribers must check for existing processing of `event_id` before creating IT offboarding instances
* **Exactly-Once Processing:** Events are processed exactly once per `event_id` to prevent duplicate IT offboarding instances

### Event Versioning

* **Current Version:** `1.0`
* **Versioning Strategy:** Schema changes require new version number
* **Backward Compatibility:** Subscribers must handle multiple event versions gracefully

### Delivery Guarantees

* **At-Least-Once Delivery:** Events may be delivered multiple times; idempotency handling required
* **Retry Policy:** Failed event processing triggers automatic retry with exponential backoff
* **Dead Letter Queue:** Events that fail after maximum retries are logged for manual review

### Event Ordering

* **Per-Employee Ordering:** Events for the same `employee_id` are processed in timestamp order
* **Cross-Employee:** No ordering guarantees across different employees
* **Concurrent Processing:** Multiple events may be processed concurrently; idempotency ensures correctness

### HIPAA Compliance Notes

* **Exactly-Once Processing:** Critical for PHI access revocation to prevent duplicate or missed revocations
* **Audit Logging:** All event processing must be logged with `event_id`, `actor_id`, and `timestamp`
* **Access Revocation:** PHI access revocation must be logged immediately upon event processing

## Integration Points

### HR Side (Publisher)

* **Hook:** `src/cores/hr/hooks/useOffboardingMutation.ts`
* **Hook:** `src/cores/hr/hooks/useITOffboardingIntegration.ts`
* **Dialog:** `src/cores/hr/components/StartOffboardingDialog.tsx`
* **Edge Function:** `supabase/functions/hr-employee-terminated-handler/index.ts`

### IT Side (Subscriber)

* **Table:** `it_onboarding_instances` (workflow\_type = 'offboarding')
* **Dashboard:** `/it/offboarding`
* **Hook:** `useITOnboardingInstances` (existing)

## Security Considerations

### Access Controls

1. **RLS Policies:** IT offboarding instances protected by organization-level RLS
2. **Permission Check:** Only users with `hr.employees.terminate` or `hr.offboarding.create` can trigger
3. **Audit Trail:** All IT instances include `created_by` for accountability
4. **Priority Escalation:** Offboarding defaults to `urgent` priority for security (standardized terminology)

### Access Revocation Timelines

The system supports two termination workflows with different access revocation timelines:

**Immediate Termination:**

* PHI access revoked immediately upon termination
* Email and network access revoked immediately
* Financial system access (SOX-controlled) revoked immediately
* All access revocations logged to audit trail

**Scheduled Termination:**

* Access allowed until termination date with enhanced monitoring
* PHI access revoked on termination date (not before)
* Email and network access revoked on termination date
* Financial system access revoked on termination date
* Enhanced monitoring logs all access attempts during notice period

**Fallback Rule:**

* Any termination date in the past triggers an alert and immediate manual review
* System automatically revokes all access for past-dated terminations
* Manual review required to confirm and document revocation

### Data Classification

1. **Access Revocation:** See [Access Revocation Timelines](#access-revocation-timelines) above
2. **Equipment Tracking:** Hardware return tracked independently
3. **Access Audit:** Full audit trail of deprovisioning actions

### Compliance

1. **HIPAA:** PHI access must be revoked immediately upon termination (see [Access Revocation Timelines](#access-revocation-timelines))
2. **SOX:** Financial system access follows the same immediate-revocation rules as PHI for immediate terminations. For scheduled terminations, access is revoked on termination date with enhanced monitoring.
3. **Data Retention:** IT offboarding records retained per policy

## Related Integration: Quick Add Employee → IT Onboarding

> **Note:** This section documents the onboarding flow (opposite of offboarding). For complete onboarding integration details, see `HR_IT_ONBOARDING.md`.

The `EmployeeFormDialog` (quick add) also creates IT onboarding:

1. After employee creation succeeds
2. Auto-creates IT onboarding with:
   * Email account requested: true
   * Network access requested: true
   * Default hardware/applications: none
3. IT receives provisioning task immediately

This ensures all employees get IT setup regardless of onboarding path.

## Testing

1. Start offboarding via dialog → Verify IT offboarding created
2. Terminate employee directly → Verify edge function creates IT offboarding
3. Add employee via quick add → Verify IT onboarding created
4. Check both IT dashboard views populate correctly

### Security & Compliance Testing

**Test Scenarios Checklist:**

* [ ] **Multi-tenancy isolation:** Verify Organization A cannot view/modify Organization B offboarding and RLS prevents cross-tenant leakage
* [ ] **Permission enforcement:** Verify users without `hr.employees.terminate` are denied and role-based dashboard access is enforced
* [ ] **PHI/HIPAA checks:** Confirm PHI access is revoked after offboarding and immediate-termination timelines are honored, and audit trail captures revocations
* [ ] **Priority & timing:** Validate `urgent` vs `high` handling, past termination dates trigger immediate review, scheduled vs immediate flows
* [ ] **Resilience:** Test edge function failure/retry, UI fallback, and idempotent handling of duplicate events
* [ ] **Audit trail/SOX completeness:** Ensure `created_by` is recorded and all actions are logged

**Detailed Test Scenarios:**

**Multi-Tenancy Isolation:**

* Create offboarding for Employee A in Organization 1
* Attempt to access offboarding from Organization 2 user account
* Verify RLS policies prevent cross-tenant access
* Verify IT dashboard only shows offboarding for user's organization

**Permission Enforcement:**

* Attempt to trigger offboarding without `hr.employees.terminate` permission
* Verify access denied with appropriate error message
* Verify IT dashboard only accessible to users with appropriate permissions

**PHI/HIPAA Checks:**

* Create immediate termination offboarding
* Verify PHI access revocation logged immediately
* Verify audit trail includes `event_id`, `actor_id`, and `timestamp`
* Create scheduled termination with past date
* Verify alert triggered and immediate manual review required

**Priority & Timing:**

* Create immediate termination → Verify `urgent` priority set
* Create scheduled termination → Verify `high` priority set (or appropriate priority)
* Create termination with past date → Verify alert and immediate review
* Verify scheduled vs immediate flows handle access revocation correctly

**Resilience:**

* Simulate edge function failure during IT offboarding creation
* Verify retry mechanism works correctly
* Verify UI shows appropriate error state
* Send duplicate event with same `event_id` → Verify idempotent handling (no duplicate IT offboarding)

**Audit Trail/SOX Completeness:**

* Verify all IT offboarding instances include `created_by`
* Verify all access revocations logged with full context
* Verify event processing logged with `event_id` and `timestamp`
* Verify SOX-controlled financial system access revocations logged separately
