@apotech-os/support-kit 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/index.cjs CHANGED
@@ -283,33 +283,110 @@ function formatDate(iso) {
283
283
  function toNameMap(rows) {
284
284
  return new Map(rows.map((r) => [r.id, r.name]));
285
285
  }
286
- function windowCutoffIso(days) {
287
- return new Date(Date.now() - days * 24 * 60 * 60 * 1e3).toISOString();
288
- }
289
286
 
290
287
  // src/ui/dashboard/dashboard-stats.ts
291
- function sumCounts(rows, countField = "count") {
292
- return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
293
- }
294
- function countFor(rows, groupField, value, countField = "count") {
295
- const row = rows.find((r) => r[groupField] === value);
296
- return row ? Number(row[countField]) || 0 : 0;
297
- }
298
288
  function bucketDay(row) {
299
289
  return String(row["bucket"]).slice(0, 10);
300
290
  }
301
- function mergeDailySeries(sentRows, heldRows) {
291
+ var EMPTY_TOTALS = {
292
+ auto: 0,
293
+ human: 0,
294
+ inProgress: 0,
295
+ noReplyNeeded: 0,
296
+ failed: 0
297
+ };
298
+ function outcomeOf(status, autoSendDecision) {
299
+ if (status === "sent") return "auto";
300
+ if (status === "no_reply_needed") return "noReplyNeeded";
301
+ if (status === "failed") return "failed";
302
+ if (status === "invalidated" || status === "expired") return "human";
303
+ return autoSendDecision === "hold" ? "human" : "inProgress";
304
+ }
305
+ function foldOutcomes(rows) {
306
+ const totals = { ...EMPTY_TOTALS };
307
+ for (const row of rows) {
308
+ totals[outcomeOf(row["status"], row["autoSendDecision"])] += Number(row["count"]) || 0;
309
+ }
310
+ return totals;
311
+ }
312
+ function settledCount(totals) {
313
+ return totals.auto + totals.human;
314
+ }
315
+ function autonomyRate(totals) {
316
+ const settled = settledCount(totals);
317
+ return settled > 0 ? totals.auto / settled : Number.NaN;
318
+ }
319
+ function foldDailyOutcomes(rows) {
302
320
  const byDay = /* @__PURE__ */ new Map();
303
- for (const row of sentRows) {
321
+ for (const row of rows) {
304
322
  const day = bucketDay(row);
305
- byDay.set(day, { sent: Number(row["count"]) || 0, held: byDay.get(day)?.held ?? 0 });
323
+ const totals = byDay.get(day) ?? { ...EMPTY_TOTALS };
324
+ totals[outcomeOf(row["status"], row["autoSendDecision"])] += Number(row["count"]) || 0;
325
+ byDay.set(day, totals);
306
326
  }
307
- for (const row of heldRows) {
308
- const day = bucketDay(row);
309
- const existing = byDay.get(day);
310
- byDay.set(day, { sent: existing?.sent ?? 0, held: Number(row["count"]) || 0 });
327
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
328
+ day,
329
+ auto: totals.auto,
330
+ human: totals.human,
331
+ rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
332
+ }));
333
+ }
334
+ function fillMissingDays(series, fromIso, toIso) {
335
+ const from = Date.parse(fromIso.slice(0, 10));
336
+ const to = Date.parse(toIso.slice(0, 10));
337
+ if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
338
+ const measured = new Map(series.map((point) => [point.day, point]));
339
+ const filled = [];
340
+ for (let t = from; t <= to; t += 864e5) {
341
+ const day = new Date(t).toISOString().slice(0, 10);
342
+ filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
343
+ }
344
+ return filled;
345
+ }
346
+ function ratePoints(rate, compareRate) {
347
+ return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
348
+ }
349
+ var SIGNAL_MIN_VOLUME = 20;
350
+ var SIGNAL_MIN_POINTS = 3;
351
+ function dashboardSignals(totals, compare) {
352
+ const signals = [];
353
+ const settled = settledCount(totals);
354
+ const rate = autonomyRate(totals);
355
+ if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
356
+ const points = ratePoints(rate, autonomyRate(compare));
357
+ if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
358
+ const move = points < 0 ? "recule" : "progresse";
359
+ signals.push({
360
+ level: points < 0 ? "creuser" : "info",
361
+ text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
362
+ });
363
+ }
364
+ }
365
+ if (totals.failed > 0) {
366
+ signals.push({
367
+ level: "creuser",
368
+ text: `${totals.failed} g\xE9n\xE9ration${totals.failed > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${totals.failed > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon.`
369
+ });
370
+ }
371
+ if (totals.inProgress > 0) {
372
+ signals.push({
373
+ level: "info",
374
+ text: `${totals.inProgress} r\xE9ponse${totals.inProgress > 1 ? "s sont" : " est"} encore en cours : ${totals.inProgress > 1 ? "elles ne comptent" : "elle ne compte"} dans aucun des deux camps.`
375
+ });
311
376
  }
312
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, counts]) => ({ day, ...counts }));
377
+ if (totals.noReplyNeeded > 0) {
378
+ signals.push({
379
+ level: "info",
380
+ text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
381
+ });
382
+ }
383
+ if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
384
+ signals.push({
385
+ level: "info",
386
+ text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
387
+ });
388
+ }
389
+ return signals;
313
390
  }
314
391
  var DEFAULT_TOP_N = 6;
315
392
  function foldCategoryBreakdown(rows, categoryNames, topN = DEFAULT_TOP_N) {
@@ -322,186 +399,335 @@ function foldCategoryBreakdown(rows, categoryNames, topN = DEFAULT_TOP_N) {
322
399
  const tail = measured.slice(topN).reduce((sum, bar) => sum + bar.value, 0);
323
400
  return [...measured.slice(0, topN), { label: "Autres", value: tail }];
324
401
  }
325
- var WINDOW_OPTIONS = [7, 14, 30];
326
- var RECENT_ACTIVITY_LIMIT = 8;
402
+ var POINTS_FORMAT = new Intl.NumberFormat("fr-FR", {
403
+ maximumFractionDigits: 1,
404
+ signDisplay: "exceptZero"
405
+ });
327
406
  function formatRate(value) {
328
- return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)}%`;
407
+ return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)} %`;
329
408
  }
330
- function rateOrNaN(numerator, denominator) {
331
- return denominator > 0 ? numerator / denominator : Number.NaN;
409
+ function AutonomyHero({
410
+ rate,
411
+ compareRate,
412
+ caption
413
+ }) {
414
+ const points = ratePoints(rate, compareRate);
415
+ return /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { className: "border-primary/25 bg-gradient-to-br from-primary/10 via-card to-card", children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-1 p-4", children: [
416
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground", children: [
417
+ /* @__PURE__ */ jsxRuntime.jsx("span", { "aria-hidden": true, className: "inline-block size-2 rounded-full bg-primary" }),
418
+ "Taux d\u2019autonomie"
419
+ ] }),
420
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-4xl font-semibold leading-tight tabular-nums text-foreground", children: formatRate(rate) }),
421
+ points !== null && // Direction is in the sign as well as the colour — `KpiCard`'s own
422
+ // rule, restated here because this card does not go through it.
423
+ /* @__PURE__ */ jsxRuntime.jsxs(
424
+ "p",
425
+ {
426
+ className: `text-xs font-semibold tabular-nums ${points < 0 ? "text-status-blocked" : "text-status-success"}`,
427
+ children: [
428
+ POINTS_FORMAT.format(points),
429
+ " pts",
430
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "ml-1 font-normal text-muted-foreground", children: [
431
+ "vs ",
432
+ formatRate(compareRate)
433
+ ] })
434
+ ]
435
+ }
436
+ ),
437
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "pt-1 text-xs text-muted-foreground", children: caption })
438
+ ] }) });
332
439
  }
333
- function TriageHealthTone({ enabled }) {
334
- return /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Badge, { variant: enabled ? "success" : "danger", children: enabled ? "Actif" : "Coup\xE9" });
440
+ var DASHBOARD_PRESETS = [
441
+ { key: "last7", label: "7 derniers jours" },
442
+ { key: "last30", label: "30 derniers jours" }
443
+ ];
444
+ var WEEKLY_BUCKET_FROM_DAYS = 46;
445
+ var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
446
+ var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
447
+ function startOfDayIso(day) {
448
+ return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
449
+ }
450
+ function endOfDayIso(day) {
451
+ return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : (/* @__PURE__ */ new Date()).toISOString();
452
+ }
453
+ function dayCount(bounds) {
454
+ const from = Date.parse(bounds.fromIso);
455
+ const to = Date.parse(bounds.toIso);
456
+ if (Number.isNaN(from) || Number.isNaN(to)) return 0;
457
+ return Math.max(1, Math.round((to - from) / 864e5));
458
+ }
459
+ function periodBoundsOf(value) {
460
+ const current = {
461
+ fromIso: startOfDayIso(value.range.from),
462
+ toIso: endOfDayIso(value.range.to)
463
+ };
464
+ const compare = value.compare === "none" ? void 0 : value.compareRange ?? uiSdk.comparisonRange(value.preset, value.range, value.compare);
465
+ const days = dayCount(current);
466
+ return {
467
+ current,
468
+ previous: compare === void 0 ? null : { fromIso: startOfDayIso(compare.from), toIso: endOfDayIso(compare.to) },
469
+ days,
470
+ interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
471
+ };
472
+ }
473
+ function defaultPeriod(today = /* @__PURE__ */ new Date()) {
474
+ const to = today.toISOString().slice(0, 10);
475
+ const start = new Date(today);
476
+ start.setUTCDate(start.getUTCDate() - 29);
477
+ const range = { from: start.toISOString().slice(0, 10), to };
478
+ const compareRange = uiSdk.comparisonRange("last30", range, "previous_period");
479
+ return {
480
+ preset: "last30",
481
+ range,
482
+ compare: "previous_period",
483
+ ...compareRange === void 0 ? {} : { compareRange }
484
+ };
485
+ }
486
+ var OUTCOME_METRICS = [{ op: "count", as: "count" }];
487
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision"];
488
+ function formatCount(value) {
489
+ return Number.isNaN(value) ? "\u2026" : value.toLocaleString("fr-FR");
490
+ }
491
+ function dayLabel(day) {
492
+ const parsed = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
493
+ return Number.isNaN(parsed.getTime()) ? day : parsed.toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", timeZone: "UTC" });
335
494
  }
336
495
  function DashboardPage() {
337
496
  const { appSlug } = uiSdk.useAppContext();
338
- const [windowDays, setWindowDays] = react.useState(WINDOW_OPTIONS[0]);
339
- const { settings, error: settingsError } = uiSdk.useAppSettings();
497
+ const [period, setPeriod] = react.useState(() => defaultPeriod());
498
+ const { settings } = uiSdk.useAppSettings();
340
499
  const timezone = settings?.statsTimezone ?? "UTC";
341
- const cutoffIso = react.useMemo(() => windowCutoffIso(windowDays), [windowDays]);
342
- const { rows: statusCounts, isLoading: statusLoading, error: statusError } = useAggregate("generated-response", {
343
- filter: { generatedAt: { gte: cutoffIso } },
344
- groupBy: ["status"],
345
- metrics: [{ op: "count", as: "count" }]
500
+ const periodKey = JSON.stringify(period);
501
+ const bounds = react.useMemo(() => periodBoundsOf(JSON.parse(periodKey)), [periodKey]);
502
+ const currentFilter = { generatedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } };
503
+ const previousBounds = bounds.previous ?? bounds.current;
504
+ const {
505
+ rows: dailyRows,
506
+ isLoading: dailyLoading,
507
+ error: dailyError
508
+ } = useAggregate("generated-response", {
509
+ filter: currentFilter,
510
+ groupBy: OUTCOME_GROUP_BY,
511
+ bucket: { field: "generatedAt", interval: bounds.interval, tz: timezone },
512
+ metrics: OUTCOME_METRICS
346
513
  });
347
- const { rows: autoSendCounts, isLoading: autoSendLoading } = useAggregate("generated-response", {
348
- filter: { generatedAt: { gte: cutoffIso } },
349
- groupBy: ["autoSendDecision"],
350
- metrics: [{ op: "count", as: "count" }]
514
+ const { rows: previousRows, isLoading: previousLoading } = useAggregate("generated-response", {
515
+ filter: { generatedAt: { gte: previousBounds.fromIso, lte: previousBounds.toIso } },
516
+ groupBy: OUTCOME_GROUP_BY,
517
+ metrics: OUTCOME_METRICS
351
518
  });
352
- const { rows: escalatedRows, isLoading: escalatedLoading, error: escalatedError } = useAggregate("triage-decision", {
353
- filter: { escalated: { eq: true } },
354
- metrics: [{ op: "count", as: "count" }]
355
- });
356
- const { rows: categoryCounts, isLoading: categoryLoading, error: categoryError } = useAggregate("triage-decision", {
357
- filter: { decidedAt: { gte: cutoffIso } },
519
+ const {
520
+ rows: categoryCounts,
521
+ isLoading: categoryLoading,
522
+ error: categoryError
523
+ } = useAggregate("triage-decision", {
524
+ filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
358
525
  groupBy: ["categoryId"],
359
- metrics: [{ op: "count", as: "count" }]
360
- });
361
- const { rows: dailySent, error: dailySentError } = useAggregate("generated-response", {
362
- filter: { generatedAt: { gte: cutoffIso }, status: { eq: "sent" } },
363
- bucket: { field: "generatedAt", interval: "day", tz: timezone },
364
- metrics: [{ op: "count", as: "count" }]
526
+ metrics: OUTCOME_METRICS
365
527
  });
366
- const { rows: dailyHeld, error: dailyHeldError } = useAggregate("generated-response", {
367
- filter: { generatedAt: { gte: cutoffIso }, autoSendDecision: { eq: "hold" } },
368
- bucket: { field: "generatedAt", interval: "day", tz: timezone },
369
- metrics: [{ op: "count", as: "count" }]
370
- });
371
- const dailySeriesError = dailySentError !== void 0 || dailyHeldError !== void 0;
372
528
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
373
529
  const categoryNames = react.useMemo(() => toNameMap(categories), [categories]);
374
- const {
375
- rows: recentActivity,
376
- isLoading: activityLoading,
377
- error: activityError
378
- } = useRecordList(
379
- "triage-decision",
380
- { sort: [{ field: "decidedAt", direction: "desc" }], limit: RECENT_ACTIVITY_LIMIT },
381
- toTriageDecision
530
+ const totals = react.useMemo(() => foldOutcomes(dailyRows), [dailyRows]);
531
+ const compareTotals = react.useMemo(
532
+ () => bounds.previous === null ? null : foldOutcomes(previousRows),
533
+ [bounds.previous, previousRows]
382
534
  );
383
- const totalGenerated = sumCounts(statusCounts);
384
- const sentCount = countFor(statusCounts, "status", "sent");
385
- const heldCount = countFor(autoSendCounts, "autoSendDecision", "hold");
386
- const escalatedTotal = escalatedRows[0] ? Number(escalatedRows[0]["count"]) || 0 : 0;
535
+ const daily = react.useMemo(() => {
536
+ const folded = foldDailyOutcomes(dailyRows);
537
+ return bounds.interval === "day" ? fillMissingDays(folded, bounds.current.fromIso, bounds.current.toIso) : folded;
538
+ }, [dailyRows, bounds]);
539
+ const rate = autonomyRate(totals);
540
+ const compareRate = compareTotals === null ? Number.NaN : autonomyRate(compareTotals);
541
+ const settled = settledCount(totals);
542
+ const signals = react.useMemo(() => dashboardSignals(totals, compareTotals), [totals, compareTotals]);
387
543
  const categoryBars = foldCategoryBreakdown(categoryCounts, categoryNames);
388
- const dailySeries = mergeDailySeries(dailySent, dailyHeld);
389
- const alarming = settingsError !== void 0 || settings !== void 0 && settings.triageEnabled === false;
390
- const healthBand = /* @__PURE__ */ jsxRuntime.jsxs("section", { "data-testid": "dashboard-health", children: [
391
- /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground", children: "Sant\xE9" }),
392
- /* @__PURE__ */ jsxRuntime.jsx("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-3", children: settingsError !== void 0 ? /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { className: "sm:col-span-3", children: /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { className: "p-4 text-sm text-destructive", children: "\xC9tat du triage indisponible." }) }) : settings === void 0 ? /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { className: "sm:col-span-3", children: /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { className: "p-4 text-sm text-muted-foreground", children: "Chargement de l'\xE9tat du triage\u2026" }) }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
393
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-1 p-4", children: [
394
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Triage" }),
395
- /* @__PURE__ */ jsxRuntime.jsx(TriageHealthTone, { enabled: settings.triageEnabled === true })
396
- ] }) }),
397
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-1 p-4", children: [
398
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Cadence" }),
399
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium", children: settings.triageIntervalMinutes ? `Toutes les ${settings.triageIntervalMinutes} minutes` : "\u2014" })
400
- ] }) }),
401
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-1 p-4", children: [
402
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Escalades" }),
403
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium", children: escalatedLoading ? "\u2026" : escalatedError ? "Indisponible" : `${escalatedTotal} au total` })
404
- ] }) })
405
- ] }) })
406
- ] });
407
- const columns = [
408
- { key: "ticketId", header: "Ticket", cell: (row) => row.ticketId },
409
- { key: "category", header: "Cat\xE9gorie", cell: (row) => row.categoryId && categoryNames.get(row.categoryId) || "\u2014" },
410
- {
411
- key: "escalated",
412
- header: "Escalade",
413
- cell: (row) => row.escalated ? /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Badge, { variant: "warning", children: "Escalad\xE9" }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground", children: "Non escalad\xE9" })
414
- },
415
- { key: "decidedAt", header: "Date", cell: (row) => formatDate(row.decidedAt) }
416
- ];
544
+ const loading = dailyLoading || previousLoading;
545
+ const chartData = daily.map((point) => ({ ...point, jour: dayLabel(point.day) }));
546
+ const bucketWord = bounds.interval === "day" ? "jour" : "semaine";
547
+ const aCreuser = signals.find((signal) => signal.level === "creuser");
548
+ const lead = loading ? null : settled === 0 ? {
549
+ alert: false,
550
+ title: "Aucune demande r\xE9gl\xE9e sur cette p\xE9riode",
551
+ detail: "Choisis une autre p\xE9riode, ou v\xE9rifie que le triage tourne (Param\xE8tres \u203A Triage)."
552
+ } : aCreuser !== void 0 ? { alert: true, title: "Un point m\xE9rite ton attention", detail: aCreuser.text } : {
553
+ alert: false,
554
+ title: `${formatRate(rate)} des demandes r\xE9gl\xE9es sans personne`,
555
+ detail: `${formatCount(totals.auto)} r\xE9ponses envoy\xE9es par l\u2019IA, ${formatCount(totals.human)} reprises par un humain, sur ${formatCount(settled)} demandes r\xE9gl\xE9es.`
556
+ };
417
557
  return /* @__PURE__ */ jsxRuntime.jsxs(PageShell, { children: [
418
558
  /* @__PURE__ */ jsxRuntime.jsx(
419
559
  PageHeader,
420
560
  {
421
561
  title: "Tableau de bord",
422
- description: "Les chiffres cl\xE9s et les graphiques couvrent la fen\xEAtre choisie ; la sant\xE9 annonce la sienne.",
423
- actions: /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3", children: [
424
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
425
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: "Fen\xEAtre :" }),
426
- WINDOW_OPTIONS.map((days) => /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
427
- days,
428
- " j"
429
- ] }, days))
430
- ] }),
562
+ description: "Ce que l\u2019IA a r\xE9gl\xE9 seule sur la p\xE9riode, et ce qui est retomb\xE9 sur un humain.",
563
+ actions: /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
564
+ /* @__PURE__ */ jsxRuntime.jsx(
565
+ uiSdk.DateRangeCompare,
566
+ {
567
+ value: period,
568
+ onChange: setPeriod,
569
+ comparable: true,
570
+ presets: DASHBOARD_PRESETS,
571
+ align: "end"
572
+ }
573
+ ),
431
574
  /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Link, { href: `/espace/${appSlug}/pipeline`, children: "Voir le pipeline complet" })
432
- ] }) })
575
+ ] })
433
576
  }
434
577
  ),
435
- alarming && healthBand,
436
- /* @__PURE__ */ jsxRuntime.jsxs("div", { "data-testid": "dashboard-kpis", className: "grid grid-cols-1 gap-4 sm:grid-cols-3", children: [
437
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
438
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.KpiCard, { label: "G\xE9n\xE9r\xE9", value: statusLoading ? Number.NaN : totalGenerated, formatValue: (v) => Number.isNaN(v) ? "\u2026" : String(v) }),
439
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-1 px-1 text-xs text-muted-foreground", children: "R\xE9ponses g\xE9n\xE9r\xE9es sur la fen\xEAtre choisie, tous statuts confondus (en attente, envoy\xE9es, \xE9chou\xE9es\u2026)." })
440
- ] }),
441
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
442
- /* @__PURE__ */ jsxRuntime.jsx(
443
- uiSdk.KpiCard,
444
- {
445
- label: "Taux d'envoi auto",
446
- value: statusLoading || autoSendLoading ? Number.NaN : rateOrNaN(sentCount, totalGenerated),
447
- formatValue: formatRate
448
- }
449
- ),
450
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-1 px-1 text-xs text-muted-foreground", children: "Part des r\xE9ponses g\xE9n\xE9r\xE9es sur la fen\xEAtre dont le statut est \xAB Envoy\xE9e \xBB." })
451
- ] }),
578
+ lead !== null && /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "flex items-start gap-3 p-4", children: [
579
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Badge, { variant: lead.alert ? "warning" : "brand", children: lead.alert ? "\xC0 creuser" : "Cap" }),
452
580
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
453
- /* @__PURE__ */ jsxRuntime.jsx(
454
- uiSdk.KpiCard,
455
- {
456
- label: "Taux de blocage",
457
- value: statusLoading || autoSendLoading ? Number.NaN : rateOrNaN(heldCount, totalGenerated),
458
- formatValue: formatRate,
459
- lowerIsBetter: true
460
- }
461
- ),
462
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-1 px-1 text-xs text-muted-foreground", children: "Part des r\xE9ponses g\xE9n\xE9r\xE9es sur la fen\xEAtre que la politique d'envoi a retenues (\xE9tat \xAB Bloqu\xE9 \xBB)." })
581
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-base font-semibold leading-snug", children: lead.title }),
582
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-1 text-sm leading-relaxed text-muted-foreground", children: lead.detail })
463
583
  ] })
464
- ] }),
465
- statusError !== void 0 && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
466
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [
467
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "p-4", children: [
468
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mb-3 text-sm font-medium", children: "R\xE9partition par cat\xE9gorie" }),
469
- categoryLoading ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : categoryError !== void 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer la r\xE9partition par cat\xE9gorie." }) : categoryBars.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun volume calcul\xE9 pour l'instant sur cette fen\xEAtre." }) : /* @__PURE__ */ jsxRuntime.jsx(uiSdk.BarChart, { data: categoryBars, x: "label", series: [{ key: "value", label: "Volume", colorIndex: 0 }] })
470
- ] }) }),
471
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "p-4", children: [
472
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mb-3 text-sm font-medium", children: "\xC9volution par jour" }),
473
- dailySeriesError ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer l'\xE9volution par jour." }) : dailySeries.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune journ\xE9e mesur\xE9e sur cette fen\xEAtre." }) : /* @__PURE__ */ jsxRuntime.jsx(
474
- uiSdk.StackedBarChart,
475
- {
476
- data: dailySeries,
477
- x: "day",
478
- label: "\xC9volution par jour",
479
- series: [
480
- { key: "sent", label: "Envoy\xE9es", colorIndex: 0 },
481
- { key: "held", label: "Bloqu\xE9es", colorIndex: 1 }
482
- ]
483
- }
484
- )
485
- ] }) })
486
- ] }),
487
- !alarming && healthBand,
488
- /* @__PURE__ */ jsxRuntime.jsxs("section", { children: [
489
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-2 flex items-baseline justify-between gap-4", children: [
490
- /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-xs font-semibold uppercase tracking-wider text-muted-foreground", children: "Activit\xE9 r\xE9cente" }),
491
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Link, { href: `/espace/${appSlug}/tickets`, children: "Ouvrir le suivi des demandes" })
492
- ] }),
584
+ ] }) }),
585
+ /* @__PURE__ */ jsxRuntime.jsxs(
586
+ "div",
587
+ {
588
+ "data-testid": "dashboard-kpis",
589
+ className: "grid grid-cols-1 gap-4 sm:grid-cols-[1.3fr_1fr_1fr]",
590
+ children: [
591
+ /* @__PURE__ */ jsxRuntime.jsx(
592
+ AutonomyHero,
593
+ {
594
+ rate: loading ? Number.NaN : rate,
595
+ compareRate,
596
+ caption: loading ? "Calcul en cours\u2026" : `${formatCount(totals.auto)} r\xE9gl\xE9es par l\u2019IA sur ${formatCount(settled)} demandes r\xE9gl\xE9es.`
597
+ }
598
+ ),
599
+ /* @__PURE__ */ jsxRuntime.jsx(
600
+ uiSdk.KpiCard,
601
+ {
602
+ label: "R\xE9gl\xE9 par l\u2019IA",
603
+ value: loading ? Number.NaN : totals.auto,
604
+ ...compareTotals === null ? {} : { compareValue: compareTotals.auto },
605
+ formatValue: formatCount
606
+ }
607
+ ),
608
+ /* @__PURE__ */ jsxRuntime.jsx(
609
+ uiSdk.KpiCard,
610
+ {
611
+ label: "Repris par un humain",
612
+ value: loading ? Number.NaN : totals.human,
613
+ ...compareTotals === null ? {} : { compareValue: compareTotals.human },
614
+ formatValue: formatCount,
615
+ lowerIsBetter: true
616
+ }
617
+ )
618
+ ]
619
+ }
620
+ ),
621
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-3", children: [
493
622
  /* @__PURE__ */ jsxRuntime.jsx(
494
- uiSdk.DataTable,
623
+ uiSdk.KpiCard,
495
624
  {
496
- columns,
497
- rows: recentActivity,
498
- rowId: (row) => row.id,
499
- manual: true,
500
- loading: activityLoading,
501
- error: activityError ? "Erreur lors du chargement de l\u2019activit\xE9 r\xE9cente." : void 0,
502
- empty: "Aucune d\xE9cision de triage enregistr\xE9e pour l\u2019instant."
625
+ label: "Encore en cours",
626
+ value: loading ? Number.NaN : totals.inProgress,
627
+ formatValue: formatCount
628
+ }
629
+ ),
630
+ /* @__PURE__ */ jsxRuntime.jsx(
631
+ uiSdk.KpiCard,
632
+ {
633
+ label: "Sans r\xE9ponse n\xE9cessaire",
634
+ value: loading ? Number.NaN : totals.noReplyNeeded,
635
+ formatValue: formatCount
636
+ }
637
+ ),
638
+ /* @__PURE__ */ jsxRuntime.jsx(
639
+ uiSdk.KpiCard,
640
+ {
641
+ label: "\xC9checs techniques",
642
+ value: loading ? Number.NaN : totals.failed,
643
+ ...compareTotals === null ? {} : { compareValue: compareTotals.failed },
644
+ formatValue: formatCount,
645
+ lowerIsBetter: true
503
646
  }
504
647
  )
648
+ ] }),
649
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs leading-relaxed text-muted-foreground", children: "Le taux d\u2019autonomie rapporte les r\xE9ponses envoy\xE9es par l\u2019IA \xE0 ces m\xEAmes r\xE9ponses plus celles qu\u2019un humain a reprises \u2014 bloqu\xE9es, escalad\xE9es, invalid\xE9es parce qu\u2019un agent avait d\xE9j\xE0 r\xE9pondu, ou expir\xE9es. \xB7 Une escalade est compt\xE9e UNE fois, du c\xF4t\xE9 humain : c\u2019est un motif de blocage, pas un camp de plus. \xB7 Les demandes encore en cours, celles sans r\xE9ponse n\xE9cessaire et les \xE9checs techniques sont hors du taux \u2014 les compter d\u2019un c\xF4t\xE9 ou de l\u2019autre le fausserait dans les deux sens. \xB7 Le d\xE9nominateur ne couvre que les demandes mises en file : un ticket escalad\xE9 avant toute g\xE9n\xE9ration n\u2019y figure pas." }),
650
+ dailyError !== void 0 && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
651
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [
652
+ /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Card, { children: [
653
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardHeader, { children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardTitle, { className: "text-sm", children: [
654
+ "Automatique ou humain, ",
655
+ bucketWord,
656
+ " par ",
657
+ bucketWord
658
+ ] }) }),
659
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { children: dailyError !== void 0 ? /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-sm text-destructive", children: [
660
+ "Impossible de calculer l\u2019\xE9volution par ",
661
+ bucketWord,
662
+ "."
663
+ ] }) : chartData.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune journ\xE9e mesur\xE9e sur cette p\xE9riode." }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
664
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mb-1 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: "Part r\xE9gl\xE9e par l\u2019IA" }),
665
+ /* @__PURE__ */ jsxRuntime.jsx(
666
+ uiSdk.AreaChart,
667
+ {
668
+ data: chartData,
669
+ x: "jour",
670
+ series: [{ key: "rate", label: "Taux d\u2019autonomie" }],
671
+ formatValue: formatRate,
672
+ height: 150,
673
+ hideLegend: true
674
+ }
675
+ ),
676
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mb-1 mt-4 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: "Demandes r\xE9gl\xE9es, en volume" }),
677
+ /* @__PURE__ */ jsxRuntime.jsx(
678
+ uiSdk.StackedBarChart,
679
+ {
680
+ data: chartData,
681
+ x: "jour",
682
+ label: `Demandes r\xE9gl\xE9es par ${bucketWord}`,
683
+ series: [
684
+ { key: "auto", label: "R\xE9gl\xE9 par l\u2019IA", colorIndex: 0 },
685
+ { key: "human", label: "Repris par un humain", colorIndex: 1 }
686
+ ],
687
+ formatValue: formatCount,
688
+ height: 150
689
+ }
690
+ ),
691
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "mt-3 text-xs leading-relaxed text-muted-foreground", children: [
692
+ "La courbe est la ",
693
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "part" }),
694
+ " r\xE9gl\xE9e sans personne ; les barres sont le",
695
+ " ",
696
+ /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "volume" }),
697
+ " qu\u2019elle recouvre. Un ",
698
+ bucketWord,
699
+ " \xE0 100 % sur deux demandes n\u2019est pas la m\xEAme nouvelle qu\u2019un ",
700
+ bucketWord,
701
+ " \xE0 80 % sur deux cents."
702
+ ] }),
703
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "mt-1 text-xs leading-relaxed text-muted-foreground", children: [
704
+ "Un trou dans la courbe veut dire \xAB rien de r\xE9gl\xE9 ce ",
705
+ bucketWord,
706
+ "-l\xE0 \xBB, jamais \xAB 0 % \xBB : sans d\xE9nominateur, il n\u2019y a pas de taux \xE0 tracer."
707
+ ] })
708
+ ] }) })
709
+ ] }),
710
+ /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Card, { children: [
711
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardHeader, { children: /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardTitle, { className: "text-sm", children: "R\xE9partition par cat\xE9gorie" }) }),
712
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { children: categoryLoading ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : categoryError !== void 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer la r\xE9partition par cat\xE9gorie." }) : categoryBars.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun volume calcul\xE9 pour l'instant sur cette p\xE9riode." }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
713
+ /* @__PURE__ */ jsxRuntime.jsx(
714
+ uiSdk.BarChart,
715
+ {
716
+ data: categoryBars,
717
+ x: "label",
718
+ series: [{ key: "value", label: "Volume", colorIndex: 0 }]
719
+ }
720
+ ),
721
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mt-3 text-xs leading-relaxed text-muted-foreground", children: "Les d\xE9cisions de triage de la p\xE9riode, par cat\xE9gorie \u2014 le volume qui entre, avant toute id\xE9e de qui l\u2019a r\xE9gl\xE9." })
722
+ ] }) })
723
+ ] })
724
+ ] }),
725
+ /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Card, { children: [
726
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardHeader, { children: /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardTitle, { className: "text-sm", children: "Signaux \xE0 surveiller" }) }),
727
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { children: signals.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Rien de notable sur cette p\xE9riode \u2014 ou pas assez de demandes r\xE9gl\xE9es pour qu\u2019une comparaison veuille dire quelque chose." }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
728
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Badge, { variant: signal.level === "creuser" ? "warning" : "neutral", children: signal.level === "creuser" ? "\xC0 creuser" : "Info" }),
729
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm leading-relaxed", children: signal.text })
730
+ ] }, signal.text)) }) })
505
731
  ] })
506
732
  ] });
507
733
  }
@@ -1217,7 +1443,7 @@ function computePipelineStats(rows, timezone = "UTC") {
1217
1443
  }
1218
1444
  var STATS_PAGE_SIZE = 200;
1219
1445
  var TABLE_PAGE_SIZE = 200;
1220
- var WINDOW_OPTIONS2 = [7, 14, 30];
1446
+ var WINDOW_OPTIONS = [7, 14, 30];
1221
1447
  var DECISION_OPTIONS = [
1222
1448
  { value: "", label: "Tous" },
1223
1449
  { value: "sent", label: "Envoy\xE9s auto" },
@@ -1245,7 +1471,7 @@ function buildTableFilter(decision, status) {
1245
1471
  function countOrEllipsis(value) {
1246
1472
  return Number.isNaN(value) ? "\u2026" : String(value);
1247
1473
  }
1248
- function windowCutoffIso2(days) {
1474
+ function windowCutoffIso(days) {
1249
1475
  return new Date(Date.now() - days * 24 * 60 * 60 * 1e3).toISOString();
1250
1476
  }
1251
1477
  function ConfidenceCell({ confidence }) {
@@ -1333,7 +1559,7 @@ function PipelinePage() {
1333
1559
  const toast = uiSdk.useToast();
1334
1560
  const [isTriaging, setIsTriaging] = react.useState(false);
1335
1561
  const isTriagingRef = react.useRef(false);
1336
- const [windowDays, setWindowDays] = react.useState(WINDOW_OPTIONS2[0]);
1562
+ const [windowDays, setWindowDays] = react.useState(WINDOW_OPTIONS[0]);
1337
1563
  const [decisionFilter, setDecisionFilter] = react.useState("");
1338
1564
  const [statusFilter, setStatusFilter] = react.useState("");
1339
1565
  const [verdictFilter, setVerdictFilter] = react.useState("");
@@ -1368,7 +1594,7 @@ function PipelinePage() {
1368
1594
  const categoryNames = react.useMemo(() => toNameMap(categories), [categories]);
1369
1595
  const agentNames = react.useMemo(() => toNameMap(agents), [agents]);
1370
1596
  const windowedStatsRows = react.useMemo(() => {
1371
- const cutoff = windowCutoffIso2(windowDays);
1597
+ const cutoff = windowCutoffIso(windowDays);
1372
1598
  return statsRows.filter((row) => row.generatedAt !== null && row.generatedAt >= cutoff);
1373
1599
  }, [statsRows, windowDays]);
1374
1600
  const stats = react.useMemo(
@@ -1463,7 +1689,7 @@ function PipelinePage() {
1463
1689
  ),
1464
1690
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1465
1691
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: "Fen\xEAtre :" }),
1466
- WINDOW_OPTIONS2.map((days) => /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
1692
+ WINDOW_OPTIONS.map((days) => /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
1467
1693
  days,
1468
1694
  " j"
1469
1695
  ] }, days))
@@ -5289,7 +5515,7 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
5289
5515
  globalNotes: promptWarningNodes.length > 0 ? [{ ...PROMPT_403_NOTE, nodes: promptWarningNodes }] : []
5290
5516
  };
5291
5517
  }
5292
- function windowCutoffIso3(days, now = Date.now()) {
5518
+ function windowCutoffIso2(days, now = Date.now()) {
5293
5519
  return new Date(now - days * 24 * 60 * 60 * 1e3).toISOString();
5294
5520
  }
5295
5521
  function totalOf(rows) {
@@ -5303,7 +5529,7 @@ function totalOf(rows) {
5303
5529
  return total;
5304
5530
  }
5305
5531
  function useGraphTraffic(windowDays) {
5306
- const cutoffIso = react.useMemo(() => windowCutoffIso3(windowDays), [windowDays]);
5532
+ const cutoffIso = react.useMemo(() => windowCutoffIso2(windowDays), [windowDays]);
5307
5533
  const triaged = useAggregate("triage-decision", {
5308
5534
  filter: { decidedAt: { gte: cutoffIso } },
5309
5535
  metrics: [{ op: "count", as: "count" }]