feat(helpdesk): add Risk Radar dashboard with customer risk scoring

New portfolio view scoring customers 0-100 across five dimensions:
- Open pressure (30%): open + critical ticket count
- Trend (25%): net ticket flow (created - closed) in period
- SLA overdue (20%): tickets exceeding escalation targets
- Resolution time (15%): median hours to close (null = neutral)
- Inactivity (10%): age of oldest open ticket

Card grid with score badges (color-coded high/medium/low), metric
pills, driver bars. Click opens detail dialog with all dimensions
and open ticket list. Clientside search filter.

PBI_LV_Tickets with client-driven paging ($skip/$top, hardcap 5000).
Escalation definitions cached separately (30min TTL). Truncated
banner when data is capped.

New: RiskRadarService, getTicketsForRiskRadar(), 13 PHPUnit tests,
permission helpdesk.risk-radar.view, 2 routes, i18n de+en.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-06 00:24:48 +02:00
parent c6c5d06936
commit 5a4974909b
17 changed files with 1487 additions and 5 deletions

View File

@@ -11,10 +11,12 @@ final class HelpdeskAuthorizationPolicy implements AuthorizationPolicyInterface
public const ABILITY_ACCESS = 'helpdesk.access';
public const ABILITY_SETTINGS_MANAGE = 'helpdesk.settings.manage';
public const ABILITY_TEAM_WORKLOAD = 'helpdesk.team-workload.view';
public const ABILITY_RISK_RADAR = 'helpdesk.risk-radar.view';
public const PERMISSION_ACCESS = 'helpdesk.access';
public const PERMISSION_SETTINGS_MANAGE = 'helpdesk.settings.manage';
public const PERMISSION_TEAM_WORKLOAD = 'helpdesk.team-workload.view';
public const PERMISSION_RISK_RADAR = 'helpdesk.risk-radar.view';
public function __construct(
private readonly PermissionService $permissionService
@@ -23,7 +25,7 @@ final class HelpdeskAuthorizationPolicy implements AuthorizationPolicyInterface
public function supports(string $ability): bool
{
return in_array($ability, [self::ABILITY_ACCESS, self::ABILITY_SETTINGS_MANAGE, self::ABILITY_TEAM_WORKLOAD], true);
return in_array($ability, [self::ABILITY_ACCESS, self::ABILITY_SETTINGS_MANAGE, self::ABILITY_TEAM_WORKLOAD, self::ABILITY_RISK_RADAR], true);
}
public function authorize(string $ability, array $context = []): AuthorizationDecision
@@ -37,6 +39,7 @@ final class HelpdeskAuthorizationPolicy implements AuthorizationPolicyInterface
self::ABILITY_ACCESS => self::PERMISSION_ACCESS,
self::ABILITY_SETTINGS_MANAGE => self::PERMISSION_SETTINGS_MANAGE,
self::ABILITY_TEAM_WORKLOAD => self::PERMISSION_TEAM_WORKLOAD,
self::ABILITY_RISK_RADAR => self::PERMISSION_RISK_RADAR,
default => null,
};

View File

@@ -20,14 +20,17 @@ final class HelpdeskLayoutProvider implements LayoutContextProvider
$actorContext = ['actor_user_id' => $userId];
$canManageSettings = $authorizationService->authorize('helpdesk.settings.manage', $actorContext)->isAllowed();
$canViewTeam = $authorizationService->authorize('helpdesk.team-workload.view', $actorContext)->isAllowed();
$canViewRiskRadar = $authorizationService->authorize('helpdesk.risk-radar.view', $actorContext)->isAllowed();
} catch (\Throwable) {
$canManageSettings = false;
$canViewTeam = false;
$canViewRiskRadar = false;
}
return ['helpdesk.nav' => [
'can_manage_settings' => $canManageSettings,
'can_view_team' => $canViewTeam,
'can_view_risk_radar' => $canViewRiskRadar,
]];
}
}

View File

@@ -611,6 +611,56 @@ class BcODataGateway
return $this->extractODataValues($response);
}
/**
* Get tickets across all customers for risk radar aggregation.
*
* Uses PBI_LV_Tickets with client-driven paging ($skip/$top).
* Hardcap: 5000 rows (10 pages × 500 per page).
*
* @return array{tickets: array<int, array<string, mixed>>, truncated: bool}
*/
public function getTicketsForRiskRadar(): array
{
$pageSize = 500;
$maxPages = 10;
$select = 'No,Customer_No,Cust_Name,Escalation_Code,Created_On,Last_Activity_Date,Process_Stage,Ticket_State,Support_User_Name,Category_1_Code,Process_Code';
$allTickets = [];
$truncated = false;
for ($page = 0; $page < $maxPages; $page++) {
$skip = $page * $pageSize;
$url = $this->settingsGateway->buildEntityUrl(self::ENTITY_TICKETS_LV)
. '?$top=' . $pageSize
. '&$skip=' . $skip
. '&$select=' . rawurlencode($select)
. '&$orderby=' . rawurlencode('Created_On desc');
$response = $this->request('GET', $url);
if ($response === null) {
break;
}
$rows = $this->extractODataValues($response);
if ($rows === []) {
break;
}
foreach ($rows as $row) {
$allTickets[] = $row;
}
if (count($rows) < $pageSize) {
break;
}
if ($page === $maxPages - 1) {
$truncated = true;
}
}
return ['tickets' => $allTickets, 'truncated' => $truncated];
}
/**
* Get contracts for a customer by customer number.
*

View File

@@ -87,6 +87,11 @@ final class DebitorCacheControl
return 'module.helpdesk.team.v1.workload.' . $tenantScope;
}
public static function riskRadarKey(string $tenantScope, int $periodDays): string
{
return 'module.helpdesk.risk-radar.v1.' . $tenantScope . '.' . $periodDays;
}
/**
* @return array<int, string>
*/

View File

@@ -0,0 +1,417 @@
<?php
namespace MintyPHP\Module\Helpdesk\Service;
/**
* Risk Radar scoring engine — aggregates tickets per customer and computes
* a 0100 risk score from five weighted dimensions.
*/
final class RiskRadarService
{
// --- Score weights (must sum to 100) ---
private const W_OPEN_PRESSURE = 30;
private const W_TREND = 25;
private const W_SLA_OVERDUE = 20;
private const W_RESOLUTION = 15;
private const W_INACTIVITY = 10;
// --- Level thresholds ---
private const LEVEL_HIGH = 70;
private const LEVEL_MEDIUM = 40;
private const CLOSED_STATES = ['Erledigt', 'Resolved', 'Closed', 'Geschlossen'];
/**
* Build the complete risk radar dataset.
*
* @param array<int, array<string, mixed>> $tickets Raw OData tickets
* @param array<int, array<string, mixed>> $escalationDefs Escalation definitions with Code + Target_Time
* @param int $periodDays One of 30, 90, 180, 365
* @param bool $truncated Whether the ticket set was capped
*
* @return array{summary: array<string, int>, customers: array<int, array<string, mixed>>, meta: array<string, mixed>}
*/
public static function buildRiskRadar(
array $tickets,
array $escalationDefs,
int $periodDays,
bool $truncated = false
): array {
$nowTs = time();
$periodStart = $nowTs - ($periodDays * 86400);
$prevPeriodStart = $periodStart - ($periodDays * 86400);
// Build escalation target map: Code → seconds
$slaTargets = self::buildSlaTargetMap($escalationDefs);
// Aggregate per customer
$customers = [];
foreach ($tickets as $ticket) {
$customerNo = trim((string) ($ticket['Customer_No'] ?? ''));
if ($customerNo === '') {
continue;
}
if (!isset($customers[$customerNo])) {
$customers[$customerNo] = [
'customer_no' => $customerNo,
'customer_name' => trim((string) ($ticket['Cust_Name'] ?? '')),
'open' => 0,
'critical' => 0,
'created_current' => 0,
'closed_current' => 0,
'created_prev' => 0,
'closed_prev' => 0,
'sla_overdue_count' => 0,
'resolution_hours' => [],
'oldest_open_age_hours' => 0,
'open_tickets' => [],
];
}
$state = trim((string) ($ticket['Ticket_State'] ?? ''));
$isClosed = in_array($state, self::CLOSED_STATES, true)
|| (isset($ticket['Process_Stage']) && (int) $ticket['Process_Stage'] === 40);
$createdTs = self::parseTimestamp((string) ($ticket['Created_On'] ?? ''));
$activityTs = self::resolveActivityTimestamp($ticket);
if ($isClosed) {
if ($activityTs !== null && $activityTs >= $periodStart) {
$customers[$customerNo]['closed_current']++;
if ($createdTs !== null && $activityTs > $createdTs) {
$customers[$customerNo]['resolution_hours'][] = intdiv($activityTs - $createdTs, 3600);
}
}
if ($activityTs !== null && $activityTs >= $prevPeriodStart && $activityTs < $periodStart) {
$customers[$customerNo]['closed_prev']++;
}
if ($createdTs !== null && $createdTs >= $periodStart) {
$customers[$customerNo]['created_current']++;
}
if ($createdTs !== null && $createdTs >= $prevPeriodStart && $createdTs < $periodStart) {
$customers[$customerNo]['created_prev']++;
}
} else {
$customers[$customerNo]['open']++;
if ($createdTs !== null && $createdTs >= $periodStart) {
$customers[$customerNo]['created_current']++;
}
if ($createdTs !== null && $createdTs >= $prevPeriodStart && $createdTs < $periodStart) {
$customers[$customerNo]['created_prev']++;
}
// Critical: open > 48h
if ($activityTs !== null) {
$ageHours = intdiv(max(0, $nowTs - $activityTs), 3600);
if ($ageHours > 48) {
$customers[$customerNo]['critical']++;
}
if ($ageHours > $customers[$customerNo]['oldest_open_age_hours']) {
$customers[$customerNo]['oldest_open_age_hours'] = $ageHours;
}
}
// SLA overdue check
$escalationCode = trim((string) ($ticket['Escalation_Code'] ?? ''));
if ($escalationCode !== '' && $createdTs !== null && isset($slaTargets[$escalationCode])) {
$elapsed = $nowTs - $createdTs;
if ($elapsed > $slaTargets[$escalationCode]) {
$customers[$customerNo]['sla_overdue_count']++;
}
}
// Collect open ticket info for detail dialog
$customers[$customerNo]['open_tickets'][] = [
'no' => trim((string) ($ticket['No'] ?? '')),
'state' => $state,
'age_hours' => $activityTs !== null ? intdiv(max(0, $nowTs - $activityTs), 3600) : 0,
'escalation_code' => $escalationCode,
'category' => trim((string) ($ticket['Category_1_Code'] ?? '')),
];
}
}
// Score each customer
$scoredCustomers = [];
$summaryHigh = 0;
$summaryMedium = 0;
$summaryLow = 0;
foreach ($customers as $customerNo => $c) {
$hasActivity = $c['open'] > 0 || $c['created_current'] > 0 || $c['closed_current'] > 0;
if (!$hasActivity) {
continue;
}
$dimensions = self::scoreDimensions($c);
$totalScore = self::computeTotalScore($dimensions);
$level = $totalScore >= self::LEVEL_HIGH ? 'high'
: ($totalScore >= self::LEVEL_MEDIUM ? 'medium' : 'low');
if ($level === 'high') {
$summaryHigh++;
} elseif ($level === 'medium') {
$summaryMedium++;
} else {
$summaryLow++;
}
// Top-3 drivers sorted by weighted contribution
$drivers = $dimensions;
usort($drivers, static fn (array $a, array $b): int => $b['weighted_points'] <=> $a['weighted_points']);
$topDrivers = array_slice($drivers, 0, 3);
// Sort open tickets: critical first, then by age
$openTickets = $c['open_tickets'];
usort($openTickets, static function (array $a, array $b): int {
$aCrit = $a['age_hours'] > 48 ? 1 : 0;
$bCrit = $b['age_hours'] > 48 ? 1 : 0;
if ($aCrit !== $bCrit) {
return $bCrit <=> $aCrit;
}
return $b['age_hours'] <=> $a['age_hours'];
});
$netFlow = $c['created_current'] - $c['closed_current'];
$resolutionMedian = self::median($c['resolution_hours']);
$scoredCustomers[] = [
'customer_no' => $c['customer_no'],
'customer_name' => $c['customer_name'],
'risk_score' => $totalScore,
'risk_level' => $level,
'kpis' => [
'open' => $c['open'],
'critical' => $c['critical'],
'sla_overdue' => $c['sla_overdue_count'],
'net_flow' => $netFlow,
'resolution_median_hours' => $resolutionMedian,
'oldest_open_hours' => $c['oldest_open_age_hours'],
],
'drivers' => $topDrivers,
'dimensions' => $dimensions,
'open_tickets' => array_slice($openTickets, 0, 10),
];
}
// Sort: score desc, sla_overdue desc, open desc, customer_no asc
usort($scoredCustomers, static function (array $a, array $b): int {
if ($a['risk_score'] !== $b['risk_score']) {
return $b['risk_score'] <=> $a['risk_score'];
}
if ($a['kpis']['sla_overdue'] !== $b['kpis']['sla_overdue']) {
return $b['kpis']['sla_overdue'] <=> $a['kpis']['sla_overdue'];
}
if ($a['kpis']['open'] !== $b['kpis']['open']) {
return $b['kpis']['open'] <=> $a['kpis']['open'];
}
return strcmp($a['customer_no'], $b['customer_no']);
});
return [
'summary' => [
'total' => count($scoredCustomers),
'high' => $summaryHigh,
'medium' => $summaryMedium,
'low' => $summaryLow,
],
'customers' => $scoredCustomers,
'meta' => [
'period_days' => $periodDays,
'tickets_total' => count($tickets),
'truncated' => $truncated,
'confidence' => $truncated ? 'medium' : 'high',
],
];
}
/**
* Score all five dimensions for a single customer.
*
* @param array<string, mixed> $c Customer aggregate data
* @return array<int, array{id: string, label: string, raw_value: int|float|null, dimension_score: int, weight: int, weighted_points: float}>
*/
private static function scoreDimensions(array $c): array
{
$open = (int) $c['open'];
$critical = (int) $c['critical'];
$netFlow = (int) $c['created_current'] - (int) $c['closed_current'];
$slaOverdue = (int) $c['sla_overdue_count'];
$resolutionMedian = self::median($c['resolution_hours']);
$oldestAge = (int) $c['oldest_open_age_hours'];
// 1. Open Pressure: min(100, open*8 + critical*18)
$openScore = min(100, $open * 8 + $critical * 18);
// 2. Trend (net flow): <=0:0, 1-2:35, 3-5:70, >=6:100
$trendScore = match (true) {
$netFlow <= 0 => 0,
$netFlow <= 2 => 35,
$netFlow <= 5 => 70,
default => 100,
};
// 3. SLA Overdue: 0:0, 1:50, 2:75, >=3:100
$slaScore = match (true) {
$slaOverdue === 0 => 0,
$slaOverdue === 1 => 50,
$slaOverdue === 2 => 75,
default => 100,
};
// 4. Resolution (median hours): null→neutral, <=24:0, 25-48:35, 49-96:70, >96:100
$resolutionScore = null;
if ($resolutionMedian !== null) {
$resolutionScore = match (true) {
$resolutionMedian <= 24 => 0,
$resolutionMedian <= 48 => 35,
$resolutionMedian <= 96 => 70,
default => 100,
};
}
// 5. Inactivity (oldest open): <=24:0, 25-72:35, 73-168:70, >168:100
$inactivityScore = match (true) {
$oldestAge <= 24 => 0,
$oldestAge <= 72 => 35,
$oldestAge <= 168 => 70,
default => 100,
};
$dimensions = [
['id' => 'open_pressure', 'label' => 'Open pressure', 'raw_value' => $open, 'dimension_score' => $openScore, 'weight' => self::W_OPEN_PRESSURE],
['id' => 'trend', 'label' => 'Trend', 'raw_value' => $netFlow, 'dimension_score' => $trendScore, 'weight' => self::W_TREND],
['id' => 'sla_overdue', 'label' => 'SLA overdue', 'raw_value' => $slaOverdue, 'dimension_score' => $slaScore, 'weight' => self::W_SLA_OVERDUE],
['id' => 'resolution', 'label' => 'Resolution time', 'raw_value' => $resolutionMedian, 'dimension_score' => $resolutionScore, 'weight' => self::W_RESOLUTION],
['id' => 'inactivity', 'label' => 'Inactivity', 'raw_value' => $oldestAge, 'dimension_score' => $inactivityScore, 'weight' => self::W_INACTIVITY],
];
// Compute weighted points; redistribute resolution weight when null
$effectiveWeightSum = 0;
foreach ($dimensions as $d) {
if ($d['dimension_score'] !== null) {
$effectiveWeightSum += $d['weight'];
}
}
foreach ($dimensions as $i => $d) {
if ($d['dimension_score'] === null) {
$dimensions[$i]['weighted_points'] = 0.0;
} else {
$adjustedWeight = $effectiveWeightSum > 0
? ($d['weight'] / $effectiveWeightSum) * 100
: (float) $d['weight'];
$dimensions[$i]['weighted_points'] = round(($d['dimension_score'] / 100) * $adjustedWeight, 1);
}
}
return $dimensions;
}
/**
* Compute total score from dimensions (sum of weighted points, capped at 100).
*
* @param array<int, array<string, mixed>> $dimensions
*/
private static function computeTotalScore(array $dimensions): int
{
$total = 0.0;
foreach ($dimensions as $d) {
$total += (float) ($d['weighted_points'] ?? 0);
}
return min(100, (int) round($total));
}
/**
* @param array<int, array<string, mixed>> $escalationDefs
* @return array<string, int> Code → target seconds
*/
private static function buildSlaTargetMap(array $escalationDefs): array
{
$map = [];
foreach ($escalationDefs as $def) {
$code = trim((string) ($def['Code'] ?? ''));
$targetTime = trim((string) ($def['Target_Time'] ?? ''));
if ($code === '' || $targetTime === '') {
continue;
}
$seconds = self::parseIsoDuration($targetTime);
if ($seconds !== null && $seconds > 0) {
$map[$code] = $seconds;
}
}
return $map;
}
private static function parseIsoDuration(string $value): ?int
{
$value = strtoupper(trim($value));
if ($value === '' || !str_starts_with($value, 'P')) {
return null;
}
if (!preg_match('/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/', $value, $m)) {
return null;
}
$days = isset($m[1]) && $m[1] !== '' ? (int) $m[1] : 0;
$hours = isset($m[2]) && $m[2] !== '' ? (int) $m[2] : 0;
$minutes = isset($m[3]) && $m[3] !== '' ? (int) $m[3] : 0;
$seconds = isset($m[4]) && $m[4] !== '' ? (int) floor((float) $m[4]) : 0;
return ($days * 86400) + ($hours * 3600) + ($minutes * 60) + $seconds;
}
/**
* @param array<int, int> $values
*/
private static function median(array $values): ?float
{
if ($values === []) {
return null;
}
sort($values);
$count = count($values);
$mid = intdiv($count, 2);
return $count % 2 === 0
? round(($values[$mid - 1] + $values[$mid]) / 2, 1)
: (float) $values[$mid];
}
private static function parseTimestamp(string $value): ?int
{
$value = trim($value);
if ($value === '' || str_starts_with($value, '0001-01-01')) {
return null;
}
$ts = strtotime($value);
return is_int($ts) ? $ts : null;
}
/**
* @param array<string, mixed> $ticket
*/
private static function resolveActivityTimestamp(array $ticket): ?int
{
$lastActivity = trim((string) ($ticket['Last_Activity_Date'] ?? ''));
if ($lastActivity !== '' && !str_starts_with($lastActivity, '0001-01-01')) {
$ts = strtotime($lastActivity);
if (is_int($ts)) {
return $ts;
}
}
return self::parseTimestamp((string) ($ticket['Created_On'] ?? ''));
}
}