Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions app/Console/Commands/Support/CertificateKpiReportCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace App\Console\Commands\Support;

use App\Services\Support\CertificateKpiReportService;
use App\Services\Support\SupportJson;
use Illuminate\Console\Command;

class CertificateKpiReportCommand extends Command
{
protected $signature = 'support:certificate-kpi-report
{start : Start date (YYYY-MM-DD or DD.MM.YYYY)}
{end : End date (YYYY-MM-DD or DD.MM.YYYY)}
{--json}';

protected $description = 'Support tool: certificate KPI counts for Organiser, Excellence, and Super Organiser';

public function handle(CertificateKpiReportService $service): int
{
$start = (string) $this->argument('start');
$end = (string) $this->argument('end');
$input = ['start' => $start, 'end' => $end];

try {
$result = $service->report($start, $end);
$payload = SupportJson::ok('certificate_kpi_report', $input, $result);
} catch (\InvalidArgumentException $e) {
$payload = SupportJson::fail('certificate_kpi_report', $input, $e->getMessage());
} catch (\Throwable $e) {
$payload = SupportJson::fail('certificate_kpi_report', $input, $e->getMessage());
}

$this->output->writeln(json_encode($payload, JSON_UNESCAPED_SLASHES));

return $payload['ok'] ? self::SUCCESS : self::FAILURE;
}
}
7 changes: 6 additions & 1 deletion app/Services/Support/Agents/CursorCliTriageProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,12 @@ private function artisanPromptBlock(): string

return <<<BLOCK

Use "artisan_command" only when the fix requires running a server maintenance command.
Use "artisan_command" only when the fix requires running a server maintenance command,
or when staff ask for read-only operational data (e.g. certificate KPI counts for a date range).
For certificate KPI / dashboard / semester statistics requests listing Organiser, Excellence,
and Super Organiser counts between two dates, use case_type "artisan_command" with
"artisan_command_name": "support:certificate-kpi-report" and artisan_args
{"start":"<start date>","end":"<end date>","--json":true}. Dates may be YYYY-MM-DD or DD.MM.YYYY.
Prefer an allowlisted command and put its name in "artisan_command_name" with values in "artisan_args"
(keys = argument/option names, e.g. {"email":"user@example.com","--firstname":"Ada"}).
Allowlisted commands:
Expand Down
20 changes: 20 additions & 0 deletions app/Services/Support/Agents/TriageAgentService.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace App\Services\Support\Agents;

use App\Models\Support\SupportCase;
use App\Services\Support\CertificateKpiRequestParser;
use App\Services\Support\SupportEmailChangeRequestParser;
use App\Services\Support\SupportProfileRequestParser;
use App\Services\Support\SupportRoleRequestParser;
Expand All @@ -15,6 +16,7 @@ public function __construct(
private readonly SupportEmailChangeRequestParser $emailChangeParser,
private readonly CursorCliTriageProvider $aiProvider,
private readonly SupportRoleRequestParser $roleParser,
private readonly CertificateKpiRequestParser $certificateKpiParser,
) {
}

Expand Down Expand Up @@ -62,6 +64,7 @@ private function heuristicTriage(SupportCase $case): array
$profile = $this->profileParser->parse($rawText);
$emailChange = $this->emailChangeParser->parse($rawText);
$roleRequest = $this->roleParser->parse($rawText);
$certificateKpi = $this->certificateKpiParser->parse($rawText);
$hasEmailChangeRequest = $emailChange['from_email'] !== null && $emailChange['to_email'] !== null;
$hasRoleAddRequest = $roleRequest['role'] !== null
&& $roleRequest['operation'] === 'add'
Expand Down Expand Up @@ -103,6 +106,9 @@ private function heuristicTriage(SupportCase $case): array
} elseif (Str::contains($text, ['missing event', 'events missing'])) {
$caseType = 'missing_events';
$runbook = 'missing_events';
} elseif ($certificateKpi['looks_like_kpi_request'] && $certificateKpi['start'] && $certificateKpi['end']) {
$caseType = 'artisan_command';
$runbook = 'certificate_kpi_report';
} elseif (Str::contains($text, ['certificate', 'cert'])) {
$caseType = 'certificate_issue';
$runbook = 'missing_certificate';
Expand Down Expand Up @@ -130,6 +136,9 @@ private function heuristicTriage(SupportCase $case): array
if ($caseType === 'email_change') {
$risk = 'medium';
}
if ($caseType === 'artisan_command' && $runbook === 'certificate_kpi_report') {
$risk = 'low';
}
if ($hasRoleRequest && $this->roleLooksPrivileged((string) $roleRequest['role'])) {
$risk = 'high';
}
Expand Down Expand Up @@ -165,6 +174,17 @@ private function heuristicTriage(SupportCase $case): array
'change_summary' => null,
'change_area' => null,
'cursor_prompt' => null,
'artisan_command_name' => ($caseType === 'artisan_command' && $runbook === 'certificate_kpi_report')
? 'support:certificate-kpi-report'
: null,
'artisan_args' => ($caseType === 'artisan_command' && $runbook === 'certificate_kpi_report')
? [
'start' => (string) $certificateKpi['start'],
'end' => (string) $certificateKpi['end'],
'--json' => true,
]
: [],
'artisan_raw_command' => null,
'triage_source' => 'heuristic',
];
}
Expand Down
12 changes: 12 additions & 0 deletions app/Services/Support/Artisan/ArtisanActionRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ public function all(): array
'arguments' => ['identifier' => ['type' => 'token', 'required' => true]],
'options' => ['--json' => ['type' => 'flag']],
],
'support:certificate-kpi-report' => [
'description' => 'Certificate KPI counts for a date window (Organiser, Excellence, Super Organiser).',
'is_write' => false,
'supports_dry_run' => false,
'arguments' => [
'start' => ['type' => 'date', 'required' => true],
'end' => ['type' => 'date', 'required' => true],
],
'options' => ['--json' => ['type' => 'flag']],
],
'support:user-restore' => [
'description' => 'Restore a soft-deleted user.',
'is_write' => true,
Expand Down Expand Up @@ -93,6 +103,8 @@ public function validateValue(string $type, mixed $value): bool

return match ($type) {
'email' => filter_var(trim($value), FILTER_VALIDATE_EMAIL) !== false,
'date' => (bool) preg_match('/^\d{4}-\d{2}-\d{2}$/', trim($value))
|| (bool) preg_match('/^\d{1,2}[.\/\-]\d{1,2}[.\/\-]\d{4}$/', trim($value)),
// Event codes / identifiers: letters, digits, dot, dash, underscore.
'token' => (bool) preg_match('/^[A-Za-z0-9._-]{1,64}$/', trim($value)),
// Names: no shell metacharacters or control chars.
Expand Down
180 changes: 180 additions & 0 deletions app/Services/Support/CertificateKpiReportService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
<?php

namespace App\Services\Support;

use App\Event;
use App\Excellence;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

/**
* KPI counts for Code Week certificates in a date window.
*
* - organiser: activity organiser certificates (reported events with certificate_url)
* - excellence: Certificate of Excellence rows
* - super_organiser: Super Organiser certificate rows
*/
final class CertificateKpiReportService
{
/**
* @return array<string, mixed>
*/
public function report(string $startInput, string $endInput): array
{
$start = $this->normalizeBoundary($startInput, false);
$end = $this->normalizeBoundary($endInput, true);

if ($start->greaterThan($end)) {
throw new \InvalidArgumentException('start_date_after_end_date');
}

$organiser = $this->countOrganiserCertificates($start, $end);
$excellence = $this->countExcellenceCertificates($start, $end);
$superOrganiser = $this->countSuperOrganiserCertificates($start, $end);

return [
'window' => [
'start' => $start->toDateTimeString(),
'end' => $end->toDateTimeString(),
'start_input' => trim($startInput),
'end_input' => trim($endInput),
],
'counts' => [
'organiser' => $organiser,
'excellence' => $excellence,
'super_organiser' => $superOrganiser,
'total' => $organiser + $excellence + $superOrganiser,
],
'monthly' => [
'organiser' => $this->monthlyOrganiser($start, $end),
'excellence' => $this->monthlyExcellence($start, $end),
'super_organiser' => $this->monthlySuperOrganiser($start, $end),
],
'labels' => [
'organiser' => 'Organiser (reported activity certificates)',
'excellence' => 'Excellence',
'super_organiser' => 'Super Organiser',
],
];
}

public function normalizeBoundary(string $input, bool $endOfDay): Carbon
{
$value = trim($input);
if ($value === '') {
throw new \InvalidArgumentException('empty_date');
}

if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
$date = Carbon::createFromFormat('Y-m-d', $value);

return $endOfDay ? $date->endOfDay() : $date->startOfDay();
}

if (preg_match('/^(\d{1,2})[.\/\-](\d{1,2})[.\/\-](\d{4})$/', $value, $m)) {
$date = Carbon::createFromFormat('Y-m-d', sprintf('%04d-%02d-%02d', (int) $m[3], (int) $m[2], (int) $m[1]));

return $endOfDay ? $date->endOfDay() : $date->startOfDay();
}

throw new \InvalidArgumentException('invalid_date_format');
}

private function countOrganiserCertificates(Carbon $start, Carbon $end): int
{
return Event::query()
->where('status', 'APPROVED')
->whereNotNull('reported_at')
->whereNotNull('certificate_url')
->whereBetween('reported_at', [$start, $end])
->count();
}

private function countExcellenceCertificates(Carbon $start, Carbon $end): int
{
return Excellence::query()
->where('type', 'Excellence')
->whereNotNull('certificate_url')
->whereBetween('created_at', [$start, $end])
->count();
}

private function countSuperOrganiserCertificates(Carbon $start, Carbon $end): int
{
return Excellence::query()
->where('type', 'SuperOrganiser')
->whereNotNull('certificate_url')
->whereBetween('created_at', [$start, $end])
->count();
}

/**
* @return array<string, int>
*/
private function monthlyOrganiser(Carbon $start, Carbon $end): array
{
return $this->monthlyCounts(
Event::query()
->where('status', 'APPROVED')
->whereNotNull('reported_at')
->whereNotNull('certificate_url')
->whereBetween('reported_at', [$start, $end]),
'reported_at'
);
}

/**
* @return array<string, int>
*/
private function monthlyExcellence(Carbon $start, Carbon $end): array
{
return $this->monthlyCounts(
Excellence::query()
->where('type', 'Excellence')
->whereNotNull('certificate_url')
->whereBetween('created_at', [$start, $end]),
'created_at'
);
}

/**
* @return array<string, int>
*/
private function monthlySuperOrganiser(Carbon $start, Carbon $end): array
{
return $this->monthlyCounts(
Excellence::query()
->where('type', 'SuperOrganiser')
->whereNotNull('certificate_url')
->whereBetween('created_at', [$start, $end]),
'created_at'
);
}

/**
* @param \Illuminate\Database\Eloquent\Builder<\Illuminate\Database\Eloquent\Model> $query
* @return array<string, int>
*/
private function monthlyCounts($query, string $column): array
{
$driver = DB::connection()->getDriverName();
$expr = $driver === 'sqlite'
? "strftime('%Y-%m', {$column})"
: "DATE_FORMAT({$column}, '%Y-%m')";

$rows = (clone $query)
->selectRaw("{$expr} as yyyymm, COUNT(*) as cnt")
->groupBy('yyyymm')
->orderBy('yyyymm')
->get();

$out = [];
foreach ($rows as $row) {
if (!empty($row->yyyymm)) {
$out[(string) $row->yyyymm] = (int) $row->cnt;
}
}

return $out;
}
}
67 changes: 67 additions & 0 deletions app/Services/Support/CertificateKpiRequestParser.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<?php

namespace App\Services\Support;

/**
* Extract a certificate KPI date window from support ticket text.
*/
final class CertificateKpiRequestParser
{
private const DATE_PATTERN = '\d{1,2}[.\/\-]\d{1,2}[.\/\-]\d{4}|\d{4}-\d{2}-\d{2}';

/**
* @return array{start: ?string, end: ?string, looks_like_kpi_request: bool}
*/
public function parse(string $text): array
{
$normalized = str_replace("\r\n", "\n", $text);
$lower = mb_strtolower($normalized);

$looksLikeKpi = $this->looksLikeKpiRequest($lower);
[$start, $end] = $this->extractDateRange($normalized);

return [
'start' => $start,
'end' => $end,
'looks_like_kpi_request' => $looksLikeKpi,
];
}

private function looksLikeKpiRequest(string $lower): bool
{
if (!str_contains($lower, 'certificate') && !str_contains($lower, 'cert')) {
return false;
}

return str_contains($lower, 'kpi')
|| str_contains($lower, 'dashboard')
|| str_contains($lower, 'database')
|| str_contains($lower, 'statistics')
|| str_contains($lower, 'stats')
|| str_contains($lower, 'provide the information')
|| str_contains($lower, 'between')
|| str_contains($lower, 'super organiser')
|| str_contains($lower, 'excellence');
}

/**
* @return array{0: ?string, 1: ?string}
*/
private function extractDateRange(string $text): array
{
$patterns = [
'/between\s+('.self::DATE_PATTERN.')\s+(?:and|to)\s+('.self::DATE_PATTERN.')/iu',
'/from\s+('.self::DATE_PATTERN.')\s+(?:to|until|-)\s+('.self::DATE_PATTERN.')/iu',
'/('.self::DATE_PATTERN.')\s*(?:to|–|—|-)\s*('.self::DATE_PATTERN.')/u',
'/data\s+between\s+('.self::DATE_PATTERN.')\s+(?:and|to)\s+('.self::DATE_PATTERN.')/iu',
];

foreach ($patterns as $pattern) {
if (preg_match($pattern, $text, $m)) {
return [trim($m[1]), trim($m[2])];
}
}

return [null, null];
}
}
Loading
Loading