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

# Procedure Analytics & Compliance Effectiveness — Integration Contracts

> Feature ID: GR-13 Feature Status: ✅ Complete | Downstream Integrations: 📝 Planned Last Updated: 2026-03-07 Owning Core: GR (Governance & Compliance) Constitut…

**Feature ID:** GR-13\
**Feature Status:** ✅ Complete | **Downstream Integrations:** 📝 Planned
**Last Updated:** 2026-03-07\
**Owning Core:** GR (Governance & Compliance)\
**Constitution Reference:** §1 Architecture — no direct core-to-core imports; cross-core via Platform Integration Layer and events.

***

## Overview

GR-13 provides read-only procedure execution analytics layered on top of GR-11 (Procedures Management) data. It integrates downstream with GR-07 (Quality Improvement) for gap export and PF-12 (Reporting) for accreditation report generation.

**Architectural pattern:** GR-13 is analytics-only (reads data within the GR core boundary, emits a single event for GR-07). It does not own any business entity tables; it creates one materialized view and one SECURITY DEFINER wrapper function.

**Related documents:**

* [GR-INTEGRATION.md](./GR-INTEGRATION.md) — GR module integration anchor
* [CROSS\_CORE\_INTEGRATIONS.md](./CROSS_CORE_INTEGRATIONS.md) — integration matrix
* [EVENT\_CONTRACTS.md](./EVENT_CONTRACTS.md) — event payload schemas

***

## Integration Summary

| Integration               | Pattern                                    | From → To                                       | Status                               |
| ------------------------- | ------------------------------------------ | ----------------------------------------------- | ------------------------------------ |
| GR-11 execution data      | Data (same core, DB read)                  | GR-13 reads `gr_procedure_executions`           | Implicit                             |
| GR-03 regulatory domains  | Data (same core, DB read)                  | GR-13 reads `gr_regulatory_requirements`        | Implicit                             |
| GR-07 QI project creation | Event (`fw_domain_events`) → Edge Function | GR-13 → GR-07 (via `gr-procedure-gap-consumer`) | ✅ Complete (GR-13-EN-01, 2026-04-19) |
| PF-12 report export       | Platform Layer                             | GR-13 → `@/platform/reports`                    | 📝 Planned                           |
| PF-10 notifications       | Platform Layer                             | GR-13 → `@/platform/notifications`              | 📝 Planned                           |
| PF-30 permissions         | Platform Layer                             | GR-13 checks `gr.procedure-analytics.*`         | 📝 Planned                           |

***

## Events Published by GR-13

### `procedure_gap_identified`

* **Channel:** `gr_events`
* **Publisher:** GR-13 (triggered when user clicks "Export to QI" in the analytics dashboard)
* **Subscribers:** GR-07 (create QI project candidate) — consumer shipped in **GR-13-EN-01** (2026-04-19)
* **Purpose:** Notifies GR-07 that a procedure execution gap was identified and a QI project should be created.
* **Status:** ✅ Complete (publisher + consumer)

**Payload Schema:**

```typescript theme={null}
{
  organization_id: string;       // UUID — required for tenant routing
  procedure_id: string;          // UUID — GR-11 procedure
  procedure_title: string;       // Human-readable name
  category: string;              // Procedure category (from gr_procedures.category)
  completion_rate_pct: number;   // 0.0–100.0 — computed from materialized view
  overdue_count: number;         // Count of overdue executions
  exported_by: string;           // UUID — auth.uid() of acting user
  exported_at: string;           // ISO 8601 timestamp
}
```

**Security note:** Payload contains no PHI/PII. Payload is procedural data only (organizational records, not patient records).

***

## Events Consumed by GR-13

*None.* GR-13 is analytics-only and does not consume events from other cores.

***

## API Contracts

### SECURITY DEFINER Wrapper Function (Internal)

**Function:** `gr_get_procedure_execution_summary(p_org_id UUID)`\
**Pattern:** Direct DB RPC (not HTTP API)\
**Auth:** `SECURITY DEFINER` — validates `pf_has_org_access(p_org_id, auth.uid())`\
**Returns:** SETOF `gr_procedure_execution_summary`\
**Consumers:** GR-13 frontend hooks via Supabase `rpc()`

```typescript theme={null}
// Usage in hook
const { data } = await supabase.rpc('gr_get_procedure_execution_summary', {
  p_org_id: orgId
});
```

### Edge Function (Internal Cron)

**Function:** `gr-refresh-procedure-analytics`\
**Pattern:** HTTP POST — internal cron via pg\_cron\
**Auth:** Service role key (internal only; `verify_jwt=false`)\
**Schedule:** `0 2 * * *` (2 AM UTC daily)\
**Purpose:** `REFRESH MATERIALIZED VIEW CONCURRENTLY gr_procedure_execution_summary`

> **Security:** This function MUST NOT be exposed to public callers. The `verify_jwt=false` setting is intentional for cron invocation; the service role key is required in the Authorization header.

***

## Platform Integration Layers Used

| Layer               | Import Path                                      | Usage                                             |
| ------------------- | ------------------------------------------------ | ------------------------------------------------- |
| PF-10 Notifications | `@/platform/notifications`                       | Overdue count alert when threshold exceeded       |
| PF-12 Reports       | `@/platform/reports`                             | Procedure compliance effectiveness PDF/CSV export |
| PF-30 Permissions   | `useHasPermission` from `@/platform/permissions` | Guards analytics dashboard and export actions     |
| PF-01 Organizations | `useCurrentUser` from `@/platform/auth`          | Provides `organization_id` for all queries        |

***

## GR-07 Integration Detail

The "Export to QI" action in the GR-13 analytics dashboard triggers an interaction with GR-07 (Quality Improvement). Per architecture rules, GR-13 does not import GR-07 directly; it uses `@/platform/workflow` to launch the GR-07 new-project creation sheet.

**Pre-fill contract (GR-13 → GR-07 new project sheet):**

```typescript theme={null}
interface GR07QIProjectPreFill {
  name: string;              // "Improve: [procedure title]"
  category: string;          // Procedure category
  description: string;       // Auto-generated gap description with execution rate + overdue count
  priority: 'high' | 'medium' | 'low';  // 'high' if overdue > 0; 'medium' if rate < 60%; 'low' otherwise
  source_procedure_id: string; // UUID — traceability back to GR-11 procedure
}
```

**Cross-core field note:** `source_procedure_id` must be confirmed with GR-07 spec as a supported pre-fill field. If GR-07 does not yet accept `source_procedure_id`, this field is stored only in the `procedure_gap_identified` event payload and not in the GR-07 project record until GR-07 adds the field.

**Pending contract:** See `docs/architecture/integrations/PENDING_CONTRACTS.md` — add row for GR-13 ↔ GR-07 `source_procedure_id` field when GR-07 spec is updated.

***

## Tenant Isolation

* All analytics queries routed through `gr_get_procedure_execution_summary(p_org_id)` SECURITY DEFINER function.
* SECURITY DEFINER function calls `pf_has_org_access(p_org_id, auth.uid())` before returning rows.
* No direct client access to `gr_procedure_execution_summary` materialized view via PostgREST.
* Organization ID is always sourced from `useCurrentUser()` in frontend hooks — never user-supplied.

***

## Contract Validation Checklist

Per `docs/architecture/integrations/CONTRACT_VALIDATION_CHECKLIST.md`:

* [x] Integration patterns documented (Platform Layer, Event)
* [x] Event payload schema defined (no PHI confirmed)
* [x] SECURITY DEFINER function signature documented
* [x] Tenant isolation mechanism described
* [x] Edge function auth strategy documented (`verify_jwt=false` for cron; service role required)
* [ ] GR-07 `source_procedure_id` field confirmed (pending GR-07 spec update — see PENDING\_CONTRACTS.md)
* [ ] PF-12 report template ID `gr_procedure_compliance_effectiveness` registered (pending Phase 3)
