# Plan: Chargeability Report

**Date:** 2026-03-13
**Status:** Draft
**Depends on:** Country/SAH, OrgUnit hierarchy, Utilization Categories, Client/WBS, Resource extensions

## Problem

The bi-weekly chargeability report is currently produced in Excel. CapaKraken needs a **live reporting section** in the app that updates in real-time as assignments, resources, and SAH change. The report is not a static file — it is an interactive page that can be **exported** as Excel or PDF on demand.

Core requirements:

- Live FTE-weighted chargeability percentages grouped by org unit hierarchy
- Historical actuals (SAP-imported or tracked) alongside forward forecasts
- Region filtering (GER only vs ALL resource types)
- Target vs actual comparison per management level and chapter
- Business Development % as a separate metric
- Change tracking (delta vs previous forecast snapshot)
- Excel and PDF export of the current view

## Report Structure (from Excel)

The report screenshot shows this layout:

```
Chg Report Content Prod. // - All
Status as of: {date}

| Region | Org Unit (L6) | Chapter (L7) | Ressource Type | FTE | Target ACN | tracked Chg % (SAP) | predicted Chg % (forecast months) |
```

### Row Hierarchy

**GER section** (Production Studios only):

```
GER | Content Production | Content Production | Total        | FTE | Target | Jan | Feb | Mar | Apr | ...
GER | CGI Content       | Art Direction       |              | FTE | Target | ... |
GER | CGI Content       | Capability Dev      |              | FTE | Target | ... |
GER | CGI Content       | CGI Production      |              | FTE | Target | ... |
GER | CGI Content       | Product Data Mgmt   |              | FTE | Target | ... |
GER | CGI Content       | Program/Delivery    |              | FTE | Target | ... |
GER | CGI Content       | CGI Content         | Total        | FTE | Target | ... |  ← L6 subtotal
GER | CGI Technology    | CGI Development     |              | FTE | Target | ... |
GER | CGI Technology    | IT Development      |              | FTE | Target | ... |
GER | CGI Technology    | CGI Technology      | Total        | FTE | Target | ... |
... (Creative Content Production, VFX)
GER | Content Prod.     | Total               | Chg Germany  | FTE | Target | ... |  ← grand total
GER | Content Prod.     | Total               | BD Germany   |     |        | ... |  ← BD% row
```

**PLUS row**: additional CHG for Near&Offshore + ACN FTEs

**ALL row**: combined total

**Change tracking**: previous forecast date + delta rows

### Column Structure

| Column Group | Type | Source |
|---|---|---|
| FTE | number | Sum of resource FTE for the group |
| Target ACN | % | Official target per management level, FTE-weighted |
| Historical months (SAP) | tracked Chg % | Imported actual chargeability from SAP/period data |
| Forecast months | predicted Chg % | FTE-weighted average of individual resource forecasts |

### Key Formulas

**FTE per chapter:**
```
SUM(resource.fte) WHERE resource.orgUnit.level7 = chapter
                   AND resource.resourceType = filter
```

**Chargeability per chapter (forecast):**
```
SUM(resource.fte * resource.forecastChargeability[month])
/ SUM(resource.fte)
```
This is an FTE-weighted average.

**Target per chapter:**
```
SUM(resource.fte * resource.managementLevel.targetPercentage)
/ SUM(resource.fte)
```

**Unassigned hours (implicit):**
```
SAH - sum(all categorized hours)
```

**BD% (Germany):**
```
SUM(resource.fte * resource.bdPercentage[month])
/ SUM(resource.fte)
```

## Data Requirements

### What CapaKraken needs to have (per resource, per month)

| Data Point | Source | Notes |
|---|---|---|
| FTE | Resource.fte | May vary monthly |
| Org Unit (L5/L6/L7) | Resource.orgUnit + tree | Drives row grouping |
| Country / Metro City | Resource.country | Drives region filter (GER vs ALL) |
| Resource Type | Derived or stored | Production Studios / Near&Offshore / Accenture |
| Management Level | Resource.managementLevel | Drives target % |
| Target % | ManagementLevel.targetPercentage | Official chargeability target |
| Forecast Chargeability | **Derived from assignments** | Hours assigned to Chg projects / SAH |
| Forecast BD% | **Derived from assignments** | Hours assigned to BD projects / SAH |
| Tracked Chargeability | **Imported from SAP** or tracked in-app | Actual period data |

### Forecast Chargeability Derivation

This is the key insight: **predicted chargeability can be derived from what CapaKraken already knows**:

```
forecastChg(resource, month) =
  sum(assignment.hoursPerDay * workingDays)
    WHERE assignment.project.utilizationCategory = 'Chg'
    AND assignment overlaps month
  / SAH(resource, month)
```

Similarly for BD, MD&I, etc. — each utilization category's hours divided by SAH.

This means the chargeability report is a **query over existing assignments + SAH**, not a separate data entry.

### Tracked (Actual) Chargeability

For historical data, two options:

1. **Import from SAP**: bulk import of period data (P-1, P-2, etc.) as snapshots
2. **Track in-app**: if CapaKraken becomes the system of record for time tracking

Recommendation: Start with SAP import. Add a `ChargeabilitySnapshot` model for imported actuals.

```prisma
model ChargeabilitySnapshot {
  id            String   @id @default(cuid())
  periodDate    DateTime                     // e.g. 2026-02-28
  periodType    String                       // "PTD" or "MTD"
  orgUnitId     String                       // L7 chapter
  resourceType  String?                      // filter dimension
  fte           Float
  chargeability Float                        // 0.0 to 1.0
  bdPercentage  Float?
  mdiPercentage Float?
  moPercentage  Float?
  recoveryRate  Float?
  importedAt    DateTime @default(now())

  @@unique([periodDate, periodType, orgUnitId, resourceType])
}
```

## API

Location: `packages/api/src/router/chargeability-report.ts`

| Procedure | Access | Description |
|---|---|---|
| `getReport` | manager | Full chargeability report for a date range and region filter |
| `getResourceForecast` | manager | Per-resource monthly forecast data (for the ChgFC-equivalent) |
| `importActuals` | admin | Bulk import SAP period data |
| `getSnapshots` | manager | List imported actuals for a period |
| `getChangeTracking` | manager | Delta between current forecast and a previous snapshot date |

### `getReport` Response Shape

```typescript
interface ChargeabilityReportRow {
  region: string;               // "GER" or "ALL"
  orgUnitL6: string;
  chapter: string;              // L7 name
  resourceType?: string;        // for ALL section sub-rows
  isSubtotal: boolean;
  fte: number;
  targetACN: number;            // FTE-weighted target %
  months: {
    month: string;              // "2026-03"
    dataType: 'SAP' | 'MTD';   // actual vs forecast
    fte: number;
    chargeabilityPercent: number;
  }[];
}

interface ChargeabilityReport {
  statusDate: string;
  gerRows: ChargeabilityReportRow[];
  bdGermany: { month: string; bdPercent: number }[];
  plusRow: { fte: number; months: { month: string; chargeabilityPercent: number }[] };
  allTotalRow: ChargeabilityReportRow;
  changeTracking?: {
    previousDate: string;
    gerDelta: { month: string; delta: number }[];
    allDelta: { month: string; delta: number }[];
  };
}
```

## Engine: Chargeability Calculator

Location: `packages/engine/src/chargeability/calculator.ts`

Pure functions for:

```typescript
// FTE-weighted chargeability for a group
function calculateGroupChargeability(
  resources: { fte: number; chargeability: number }[]
): number;

// Derive forecast chargeability from assignments + SAH
function deriveResourceForecast(
  assignments: { hoursPerDay: number; startDate: Date; endDate: Date; utilizationCategory: string }[],
  sah: SAHResult,
  month: { start: Date; end: Date }
): { chg: number; bd: number; mdi: number; mo: number; pdr: number; unassigned: number };

// FTE-weighted target for a group
function calculateGroupTarget(
  resources: { fte: number; targetPercentage: number }[]
): number;
```

## UI

### Live Reporting Section (`/reports/chargeability`)

This is an **interactive, live-updating page** — not a static export. Data refreshes whenever assignments, resource attributes, or SAH inputs change.

**Layout:**
- Header: title, status date (auto = now), region toggle (GER / ALL)
- Filter bar: resource type toggles (Production Studios / Accenture / Near&Offshore), date range (which months to display)
- Main table: matching the Excel screenshot structure (see Row Hierarchy above)
- Color coding: green background = actual months (SAP data), blue = current month, white = forecast months
- Subtotal rows: bold, darker background
- BD% row: bottom of GER section
- Change tracking section: collapsible, shows delta vs a selectable previous snapshot date
- Sticky first columns (Region, Org Unit, Chapter, Resource Type, FTE, Target) with horizontal scroll for months

**Interactivity:**
- Click on a chapter row → drill down to individual resources in that chapter
- Click on a resource → navigate to resource detail page
- Click on a cell → tooltip showing the contributing assignments and their hours
- Compare mode: select two snapshot dates and see a side-by-side delta view

**Real-time updates:**
- SSE integration: report subscribes to assignment/resource change events
- When an assignment is created/modified/deleted, affected rows recalculate
- Debounced refresh (not per-keystroke, but within seconds of a change)

### Export (on demand)

Export buttons in the page header:

**Excel export:**
- Matches the current Excel report format for stakeholder familiarity
- Includes all visible rows and columns based on current filter state
- Separate sheets for GER and ALL views
- Formulas preserved where possible (e.g. subtotals as SUM formulas)
- Uses the existing PDF/Excel export infrastructure from Phase 6

**PDF export:**
- Landscape layout matching the on-screen table
- Includes header with status date and active filters
- Page breaks per L6 section
- Color coding preserved

## Dependencies

All other plans must land first:
1. **Country/SAH** — provides available hours denominator
2. **OrgUnit hierarchy** — provides row grouping
3. **Utilization Categories** — provides hour bucketing (Chg, BD, etc.)
4. **Client/WBS** — provides project attribution
5. **Resource extensions** — provides management level, resource type, client unit
6. **Management Level model** — provides target percentages

## Phased Delivery

### Phase A: Live forecast report
- Interactive page at `/reports/chargeability`
- Derive chargeability from assignments + SAH (live query, no static file)
- Show FTE and predicted Chg% per chapter per month
- Region filter (GER/ALL) and resource type toggles
- Subtotals and BD% row
- SSE subscription for real-time updates

### Phase B: Target comparison + drill-down
- Add management level targets
- Show Target ACN column with variance highlighting
- Click-to-drill-down into individual resources per chapter
- Cell tooltips showing contributing assignments

### Phase C: Historical actuals + snapshots
- SAP actuals import mechanism
- Show tracked Chg% for past periods (green columns)
- Mixed actual/forecast column display
- Snapshot save/compare for change tracking

### Phase D: Export + client views
- Excel export matching stakeholder format (with formulas)
- PDF export (landscape, color-coded)
- Client-specific report views (e.g. BMW-only filter)
- Compare mode (two snapshots side-by-side)

## Acceptance Criteria

- [ ] Chargeability report page with GER/ALL toggle
- [ ] Rows grouped by L6 → L7 with subtotals
- [ ] FTE-weighted chargeability percentages per chapter per month
- [ ] Forecast derived from assignments + SAH (not manual entry)
- [ ] Target column from management level target percentages
- [ ] Resource type sub-rows in ALL section
- [ ] BD% row for Germany
- [ ] SAP actuals import mechanism
- [ ] Change tracking (delta vs previous snapshot)
- [ ] Excel export
