@apotech-os/support-kit 3.1.0 → 3.3.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.js CHANGED
@@ -1,6 +1,6 @@
1
- import { GENERATED_RESPONSE_STATUSES, EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, toTriageDecision, toAgent, toGeneratedResponse, isGeneratedResponseStatus, toCategoryGroup, toResponseComparison, toDiffAnalysis, NODE_NAMES, settingsToProfile, hasNoDraftNode, guardrailBucket, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-SFOPXCD4.js';
1
+ import { GENERATED_RESPONSE_STATUSES, EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, toAgent, toGeneratedResponse, toTriageDecision, isGeneratedResponseStatus, toCategoryGroup, toResponseComparison, toDiffAnalysis, NODE_NAMES, settingsToProfile, hasNoDraftNode, guardrailBucket, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-SFOPXCD4.js';
2
2
  import { useState, useMemo, useRef, useEffect, useCallback, useId } from 'react';
3
- import { useAppContext, useAppSettings, Card, CardContent, Button, Link, KpiCard, BarChart, StackedBarChart, DataTable, Select, useAppApi, useToast, Badge, FunnelChart, Spinner, LineChart, Switch, Input, Checkbox, Textarea, cn, SidePanel, CopyButton, Modal, Tooltip, buttonVariants, CardHeader, CardTitle, AppInvokeError, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
3
+ import { useAppContext, useAppSettings, DateRangeCompare, Link, KpiCard, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, Button, Select, DataTable, useAppApi, useToast, FunnelChart, Spinner, LineChart, Switch, Input, Checkbox, Textarea, comparisonRange, cn, SidePanel, CopyButton, Modal, Tooltip, buttonVariants, AppInvokeError, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
 
6
6
  function useRecordList(objectKey, query, mapper) {
@@ -143,225 +143,631 @@ function formatDate(iso) {
143
143
  function toNameMap(rows) {
144
144
  return new Map(rows.map((r) => [r.id, r.name]));
145
145
  }
146
- function windowCutoffIso(days) {
147
- return new Date(Date.now() - days * 24 * 60 * 60 * 1e3).toISOString();
148
- }
149
146
 
150
147
  // src/ui/dashboard/dashboard-stats.ts
151
- function sumCounts(rows, countField = "count") {
152
- return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
153
- }
154
- function countFor(rows, groupField, value, countField = "count") {
155
- const row = rows.find((r) => r[groupField] === value);
156
- return row ? Number(row[countField]) || 0 : 0;
157
- }
158
148
  function bucketDay(row) {
159
149
  return String(row["bucket"]).slice(0, 10);
160
150
  }
161
- function mergeDailySeries(sentRows, heldRows) {
151
+ var EMPTY_TOTALS = {
152
+ auto: 0,
153
+ human: 0,
154
+ inProgress: 0,
155
+ noReplyNeeded: 0,
156
+ failed: 0
157
+ };
158
+ function outcomeOf(status, autoSendDecision) {
159
+ if (status === "sent") return "auto";
160
+ if (status === "no_reply_needed") return "noReplyNeeded";
161
+ if (status === "failed") return "failed";
162
+ if (status === "invalidated" || status === "expired") return "human";
163
+ return autoSendDecision === "hold" ? "human" : "inProgress";
164
+ }
165
+ function foldOutcomes(rows) {
166
+ const totals = { ...EMPTY_TOTALS };
167
+ for (const row of rows) {
168
+ totals[outcomeOf(row["status"], row["autoSendDecision"])] += Number(row["count"]) || 0;
169
+ }
170
+ return totals;
171
+ }
172
+ function settledCount(totals) {
173
+ return totals.auto + totals.human;
174
+ }
175
+ function autonomyRate(totals) {
176
+ const settled = settledCount(totals);
177
+ return settled > 0 ? totals.auto / settled : Number.NaN;
178
+ }
179
+ function foldDailyOutcomes(rows) {
162
180
  const byDay = /* @__PURE__ */ new Map();
163
- for (const row of sentRows) {
181
+ for (const row of rows) {
164
182
  const day = bucketDay(row);
165
- byDay.set(day, { sent: Number(row["count"]) || 0, held: byDay.get(day)?.held ?? 0 });
183
+ const totals = byDay.get(day) ?? { ...EMPTY_TOTALS };
184
+ totals[outcomeOf(row["status"], row["autoSendDecision"])] += Number(row["count"]) || 0;
185
+ byDay.set(day, totals);
166
186
  }
167
- for (const row of heldRows) {
168
- const day = bucketDay(row);
169
- const existing = byDay.get(day);
170
- byDay.set(day, { sent: existing?.sent ?? 0, held: Number(row["count"]) || 0 });
187
+ return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
188
+ day,
189
+ auto: totals.auto,
190
+ human: totals.human,
191
+ rate: settledCount(totals) > 0 ? autonomyRate(totals) : null
192
+ }));
193
+ }
194
+ function fillMissingDays(series, fromIso, toIso) {
195
+ const from = Date.parse(fromIso.slice(0, 10));
196
+ const to = Date.parse(toIso.slice(0, 10));
197
+ if (Number.isNaN(from) || Number.isNaN(to) || to < from) return series;
198
+ const measured = new Map(series.map((point) => [point.day, point]));
199
+ const filled = [];
200
+ for (let t = from; t <= to; t += 864e5) {
201
+ const day = new Date(t).toISOString().slice(0, 10);
202
+ filled.push(measured.get(day) ?? { day, auto: 0, human: 0, rate: null });
203
+ }
204
+ return filled;
205
+ }
206
+ function ratePoints(rate, compareRate) {
207
+ return Number.isNaN(rate) || Number.isNaN(compareRate) ? null : (rate - compareRate) * 100;
208
+ }
209
+ var SIGNAL_MIN_VOLUME = 20;
210
+ var SIGNAL_MIN_POINTS = 3;
211
+ function dashboardSignals(totals, compare) {
212
+ const signals = [];
213
+ const settled = settledCount(totals);
214
+ const rate = autonomyRate(totals);
215
+ if (compare !== null && settled >= SIGNAL_MIN_VOLUME && settledCount(compare) >= SIGNAL_MIN_VOLUME) {
216
+ const points = ratePoints(rate, autonomyRate(compare));
217
+ if (points !== null && Math.abs(points) >= SIGNAL_MIN_POINTS) {
218
+ const move = points < 0 ? "recule" : "progresse";
219
+ signals.push({
220
+ level: points < 0 ? "creuser" : "info",
221
+ text: `Le taux d\u2019autonomie ${move} de ${Math.abs(Math.round(points))} points par rapport \xE0 la p\xE9riode pr\xE9c\xE9dente.`
222
+ });
223
+ }
224
+ }
225
+ if (totals.failed > 0) {
226
+ signals.push({
227
+ level: "creuser",
228
+ 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.`
229
+ });
230
+ }
231
+ if (totals.inProgress > 0) {
232
+ signals.push({
233
+ level: "info",
234
+ 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.`
235
+ });
236
+ }
237
+ if (totals.noReplyNeeded > 0) {
238
+ signals.push({
239
+ level: "info",
240
+ text: `${totals.noReplyNeeded} demande${totals.noReplyNeeded > 1 ? "s" : ""} ne n\xE9cessitai${totals.noReplyNeeded > 1 ? "ent" : "t"} aucune r\xE9ponse : hors du taux d\u2019autonomie.`
241
+ });
242
+ }
243
+ if (compare !== null && settled > 0 && settledCount(compare) < SIGNAL_MIN_VOLUME) {
244
+ signals.push({
245
+ level: "info",
246
+ text: "La p\xE9riode pr\xE9c\xE9dente compte trop peu de demandes r\xE9gl\xE9es pour que la comparaison veuille dire quelque chose."
247
+ });
171
248
  }
172
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, counts]) => ({ day, ...counts }));
249
+ return signals;
173
250
  }
174
- var DEFAULT_TOP_N = 6;
175
- function foldCategoryBreakdown(rows, categoryNames, topN = DEFAULT_TOP_N) {
176
- const measured = rows.map((row) => {
177
- const id = row["categoryId"];
251
+ function foldHumanReasons(rows) {
252
+ const reasons = { blocked: 0, invalidated: 0, expired: 0 };
253
+ for (const row of rows) {
254
+ if (outcomeOf(row["status"], row["autoSendDecision"]) !== "human") continue;
255
+ const count = Number(row["count"]) || 0;
256
+ if (row["status"] === "invalidated") reasons.invalidated += count;
257
+ else if (row["status"] === "expired") reasons.expired += count;
258
+ else reasons.blocked += count;
259
+ }
260
+ return reasons;
261
+ }
262
+ var CATEGORY_TOP_N = 10;
263
+ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CATEGORY_TOP_N) {
264
+ const byId = /* @__PURE__ */ new Map();
265
+ const barFor = (id) => {
178
266
  const name = typeof id === "string" ? categoryNames.get(id) : void 0;
179
- return name ? { label: name, value: Number(row["count"]) || 0 } : null;
180
- }).filter((bar) => bar !== null).sort((a, b) => b.value - a.value);
181
- if (measured.length <= topN + 1) return measured;
182
- const tail = measured.slice(topN).reduce((sum, bar) => sum + bar.value, 0);
183
- return [...measured.slice(0, topN), { label: "Autres", value: tail }];
267
+ if (name === void 0) return null;
268
+ const existing = byId.get(id);
269
+ if (existing !== void 0) return existing;
270
+ const bar = {
271
+ label: name,
272
+ total: 0,
273
+ auto: 0,
274
+ human: 0,
275
+ noReply: 0,
276
+ undrafted: 0
277
+ };
278
+ byId.set(id, bar);
279
+ return bar;
280
+ };
281
+ for (const row of triageRows) {
282
+ const bar = barFor(row["categoryId"]);
283
+ if (bar !== null) bar.total += Number(row["count"]) || 0;
284
+ }
285
+ for (const row of responseRows) {
286
+ const bar = barFor(row["categoryId"]);
287
+ if (bar === null) continue;
288
+ const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
289
+ const count = Number(row["count"]) || 0;
290
+ if (outcome === "auto") bar.auto += count;
291
+ else if (outcome === "human") bar.human += count;
292
+ else if (outcome === "noReplyNeeded") bar.noReply += count;
293
+ }
294
+ const bars = [...byId.values()].map((bar) => {
295
+ const accounted = bar.auto + bar.human + bar.noReply;
296
+ return {
297
+ ...bar,
298
+ total: Math.max(bar.total, accounted),
299
+ undrafted: Math.max(0, bar.total - accounted)
300
+ };
301
+ }).filter((bar) => bar.total > 0).sort((a, b) => b.total - a.total);
302
+ if (bars.length <= topN + 1) return bars;
303
+ const tail = bars.slice(topN).reduce(
304
+ (sum, bar) => ({
305
+ label: "Autres",
306
+ total: sum.total + bar.total,
307
+ auto: sum.auto + bar.auto,
308
+ human: sum.human + bar.human,
309
+ noReply: sum.noReply + bar.noReply,
310
+ undrafted: sum.undrafted + bar.undrafted
311
+ }),
312
+ { label: "Autres", total: 0, auto: 0, human: 0, noReply: 0, undrafted: 0 }
313
+ );
314
+ return [...bars.slice(0, topN), tail];
184
315
  }
185
- var WINDOW_OPTIONS = [7, 14, 30];
186
- var RECENT_ACTIVITY_LIMIT = 8;
316
+ var POINTS_FORMAT = new Intl.NumberFormat("fr-FR", {
317
+ maximumFractionDigits: 1,
318
+ signDisplay: "exceptZero"
319
+ });
187
320
  function formatRate(value) {
188
- return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)}%`;
321
+ return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)} %`;
189
322
  }
190
- function rateOrNaN(numerator, denominator) {
191
- return denominator > 0 ? numerator / denominator : Number.NaN;
323
+ function AutonomyHero({
324
+ rate,
325
+ compareRate,
326
+ caption
327
+ }) {
328
+ const points = ratePoints(rate, compareRate);
329
+ return /* @__PURE__ */ jsx(Card, { className: "border-primary/25 bg-gradient-to-br from-primary/10 via-card to-card", children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-1 p-4", children: [
330
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground", children: [
331
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "inline-block size-2 rounded-full bg-primary" }),
332
+ "Taux d\u2019autonomie"
333
+ ] }),
334
+ /* @__PURE__ */ jsx("p", { className: "text-4xl font-semibold leading-tight tabular-nums text-foreground", children: formatRate(rate) }),
335
+ points !== null && // Direction is in the sign as well as the colour — `KpiCard`'s own
336
+ // rule, restated here because this card does not go through it.
337
+ /* @__PURE__ */ jsxs(
338
+ "p",
339
+ {
340
+ className: `text-xs font-semibold tabular-nums ${points < 0 ? "text-status-blocked" : "text-status-success"}`,
341
+ children: [
342
+ POINTS_FORMAT.format(points),
343
+ " pts",
344
+ /* @__PURE__ */ jsxs("span", { className: "ml-1 font-normal text-muted-foreground", children: [
345
+ "vs ",
346
+ formatRate(compareRate)
347
+ ] })
348
+ ]
349
+ }
350
+ ),
351
+ /* @__PURE__ */ jsx("p", { className: "pt-1 text-xs text-muted-foreground", children: caption })
352
+ ] }) });
192
353
  }
193
- function TriageHealthTone({ enabled }) {
194
- return /* @__PURE__ */ jsx(Badge, { variant: enabled ? "success" : "danger", children: enabled ? "Actif" : "Coup\xE9" });
354
+ var DASHBOARD_PRESETS = [
355
+ { key: "last7", label: "7 derniers jours" },
356
+ { key: "last30", label: "30 derniers jours" }
357
+ ];
358
+ var WEEKLY_BUCKET_FROM_DAYS = 46;
359
+ var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
360
+ var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
361
+ function startOfDayIso(day) {
362
+ return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
363
+ }
364
+ function endOfDayIso(day) {
365
+ return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : (/* @__PURE__ */ new Date()).toISOString();
366
+ }
367
+ function dayCount(bounds) {
368
+ const from = Date.parse(bounds.fromIso);
369
+ const to = Date.parse(bounds.toIso);
370
+ if (Number.isNaN(from) || Number.isNaN(to)) return 0;
371
+ return Math.max(1, Math.round((to - from) / 864e5));
372
+ }
373
+ function periodBoundsOf(value) {
374
+ const current = {
375
+ fromIso: startOfDayIso(value.range.from),
376
+ toIso: endOfDayIso(value.range.to)
377
+ };
378
+ const compare = value.compare === "none" ? void 0 : value.compareRange ?? comparisonRange(value.preset, value.range, value.compare);
379
+ const days = dayCount(current);
380
+ return {
381
+ current,
382
+ previous: compare === void 0 ? null : { fromIso: startOfDayIso(compare.from), toIso: endOfDayIso(compare.to) },
383
+ days,
384
+ interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
385
+ };
386
+ }
387
+ function defaultPeriod(today = /* @__PURE__ */ new Date()) {
388
+ const to = today.toISOString().slice(0, 10);
389
+ const start = new Date(today);
390
+ start.setUTCDate(start.getUTCDate() - 29);
391
+ const range = { from: start.toISOString().slice(0, 10), to };
392
+ const compareRange = comparisonRange("last30", range, "previous_period");
393
+ return {
394
+ preset: "last30",
395
+ range,
396
+ compare: "previous_period",
397
+ ...compareRange === void 0 ? {} : { compareRange }
398
+ };
399
+ }
400
+ function sharePercent(value, total) {
401
+ return total > 0 ? `${Math.round(value / total * 100)} %` : null;
402
+ }
403
+ function StackedRow({
404
+ label,
405
+ segments,
406
+ total,
407
+ scale,
408
+ formatCount: formatCount2
409
+ }) {
410
+ const width = scale > 0 ? total / scale * 100 : 0;
411
+ return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[minmax(6rem,9rem)_1fr_auto] items-center gap-3 text-xs", children: [
412
+ /* @__PURE__ */ jsx("span", { className: "truncate text-muted-foreground", title: label, children: label }),
413
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-full", children: /* @__PURE__ */ jsx("div", { className: "flex h-full overflow-hidden rounded-sm", style: { width: `${width}%` }, children: segments.filter((segment) => segment.value > 0).map((segment) => /* @__PURE__ */ jsx(
414
+ "div",
415
+ {
416
+ role: "presentation",
417
+ title: `${segment.label} : ${formatCount2(segment.value)}${sharePercent(segment.value, total) === null ? "" : ` (${sharePercent(segment.value, total)})`}`,
418
+ style: {
419
+ width: `${segment.value / total * 100}%`,
420
+ backgroundColor: segment.color
421
+ }
422
+ },
423
+ segment.key
424
+ )) }) }),
425
+ /* @__PURE__ */ jsx("span", { className: "tabular-nums text-muted-foreground", children: formatCount2(total) })
426
+ ] });
427
+ }
428
+ function StackedLegend({ segments }) {
429
+ return /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", children: segments.map((segment) => /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
430
+ /* @__PURE__ */ jsx(
431
+ "span",
432
+ {
433
+ "aria-hidden": true,
434
+ className: "inline-block size-2 rounded-[2px]",
435
+ style: { backgroundColor: segment.color }
436
+ }
437
+ ),
438
+ segment.label
439
+ ] }, segment.key)) });
440
+ }
441
+ var OUTCOME_METRICS = [{ op: "count", as: "count" }];
442
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision"];
443
+ var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision"];
444
+ var CATEGORY_COLORS = {
445
+ auto: "var(--chart-1)",
446
+ human: "var(--chart-2)",
447
+ noReply: "var(--chart-4)",
448
+ undrafted: "var(--muted)"
449
+ };
450
+ var CATEGORY_LEGEND = [
451
+ { key: "auto", label: "R\xE9ponse automatis\xE9e par l\u2019agent", color: CATEGORY_COLORS.auto },
452
+ { key: "human", label: "Repris par un humain", color: CATEGORY_COLORS.human },
453
+ { key: "noReply", label: "Sans r\xE9ponse n\xE9cessaire", color: CATEGORY_COLORS.noReply },
454
+ { key: "undrafted", label: "Sans brouillon", color: CATEGORY_COLORS.undrafted }
455
+ ];
456
+ function formatCount(value) {
457
+ return Number.isNaN(value) ? "\u2026" : value.toLocaleString("fr-FR");
458
+ }
459
+ function dayLabel(day) {
460
+ const parsed = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
461
+ return Number.isNaN(parsed.getTime()) ? day : parsed.toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", timeZone: "UTC" });
195
462
  }
196
463
  function DashboardPage() {
197
464
  const { appSlug } = useAppContext();
198
- const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS[0]);
199
- const { settings, error: settingsError } = useAppSettings();
465
+ const [period, setPeriod] = useState(() => defaultPeriod());
466
+ const { settings } = useAppSettings();
200
467
  const timezone = settings?.statsTimezone ?? "UTC";
201
- const cutoffIso = useMemo(() => windowCutoffIso(windowDays), [windowDays]);
202
- const { rows: statusCounts, isLoading: statusLoading, error: statusError } = useAggregate("generated-response", {
203
- filter: { generatedAt: { gte: cutoffIso } },
204
- groupBy: ["status"],
205
- metrics: [{ op: "count", as: "count" }]
206
- });
207
- const { rows: autoSendCounts, isLoading: autoSendLoading } = useAggregate("generated-response", {
208
- filter: { generatedAt: { gte: cutoffIso } },
209
- groupBy: ["autoSendDecision"],
210
- metrics: [{ op: "count", as: "count" }]
468
+ const periodKey = JSON.stringify(period);
469
+ const bounds = useMemo(() => periodBoundsOf(JSON.parse(periodKey)), [periodKey]);
470
+ const currentFilter = { generatedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } };
471
+ const previousBounds = bounds.previous ?? bounds.current;
472
+ const {
473
+ rows: dailyRows,
474
+ isLoading: dailyLoading,
475
+ error: dailyError
476
+ } = useAggregate("generated-response", {
477
+ filter: currentFilter,
478
+ groupBy: OUTCOME_GROUP_BY,
479
+ bucket: { field: "generatedAt", interval: bounds.interval, tz: timezone },
480
+ metrics: OUTCOME_METRICS
211
481
  });
212
- const { rows: escalatedRows, isLoading: escalatedLoading, error: escalatedError } = useAggregate("triage-decision", {
213
- filter: { escalated: { eq: true } },
214
- metrics: [{ op: "count", as: "count" }]
482
+ const { rows: previousRows, isLoading: previousLoading } = useAggregate("generated-response", {
483
+ filter: { generatedAt: { gte: previousBounds.fromIso, lte: previousBounds.toIso } },
484
+ groupBy: OUTCOME_GROUP_BY,
485
+ metrics: OUTCOME_METRICS
215
486
  });
216
- const { rows: categoryCounts, isLoading: categoryLoading, error: categoryError } = useAggregate("triage-decision", {
217
- filter: { decidedAt: { gte: cutoffIso } },
487
+ const {
488
+ rows: categoryCounts,
489
+ isLoading: categoryLoading,
490
+ error: categoryError
491
+ } = useAggregate("triage-decision", {
492
+ filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
218
493
  groupBy: ["categoryId"],
219
- metrics: [{ op: "count", as: "count" }]
494
+ metrics: OUTCOME_METRICS
220
495
  });
221
- const { rows: dailySent, error: dailySentError } = useAggregate("generated-response", {
222
- filter: { generatedAt: { gte: cutoffIso }, status: { eq: "sent" } },
223
- bucket: { field: "generatedAt", interval: "day", tz: timezone },
224
- metrics: [{ op: "count", as: "count" }]
496
+ const { rows: categoryOutcomes } = useAggregate("generated-response", {
497
+ filter: currentFilter,
498
+ groupBy: CATEGORY_OUTCOME_GROUP_BY,
499
+ metrics: OUTCOME_METRICS
225
500
  });
226
- const { rows: dailyHeld, error: dailyHeldError } = useAggregate("generated-response", {
227
- filter: { generatedAt: { gte: cutoffIso }, autoSendDecision: { eq: "hold" } },
228
- bucket: { field: "generatedAt", interval: "day", tz: timezone },
229
- metrics: [{ op: "count", as: "count" }]
230
- });
231
- const dailySeriesError = dailySentError !== void 0 || dailyHeldError !== void 0;
232
501
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
233
502
  const categoryNames = useMemo(() => toNameMap(categories), [categories]);
234
- const {
235
- rows: recentActivity,
236
- isLoading: activityLoading,
237
- error: activityError
238
- } = useRecordList(
239
- "triage-decision",
240
- { sort: [{ field: "decidedAt", direction: "desc" }], limit: RECENT_ACTIVITY_LIMIT },
241
- toTriageDecision
503
+ const totals = useMemo(() => foldOutcomes(dailyRows), [dailyRows]);
504
+ const compareTotals = useMemo(
505
+ () => bounds.previous === null ? null : foldOutcomes(previousRows),
506
+ [bounds.previous, previousRows]
242
507
  );
243
- const totalGenerated = sumCounts(statusCounts);
244
- const sentCount = countFor(statusCounts, "status", "sent");
245
- const heldCount = countFor(autoSendCounts, "autoSendDecision", "hold");
246
- const escalatedTotal = escalatedRows[0] ? Number(escalatedRows[0]["count"]) || 0 : 0;
247
- const categoryBars = foldCategoryBreakdown(categoryCounts, categoryNames);
248
- const dailySeries = mergeDailySeries(dailySent, dailyHeld);
249
- const alarming = settingsError !== void 0 || settings !== void 0 && settings.triageEnabled === false;
250
- const healthBand = /* @__PURE__ */ jsxs("section", { "data-testid": "dashboard-health", children: [
251
- /* @__PURE__ */ jsx("h2", { className: "mb-2 text-xs font-semibold uppercase tracking-wider text-muted-foreground", children: "Sant\xE9" }),
252
- /* @__PURE__ */ jsx("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-3", children: settingsError !== void 0 ? /* @__PURE__ */ jsx(Card, { className: "sm:col-span-3", children: /* @__PURE__ */ jsx(CardContent, { className: "p-4 text-sm text-destructive", children: "\xC9tat du triage indisponible." }) }) : settings === void 0 ? /* @__PURE__ */ jsx(Card, { className: "sm:col-span-3", children: /* @__PURE__ */ jsx(CardContent, { className: "p-4 text-sm text-muted-foreground", children: "Chargement de l'\xE9tat du triage\u2026" }) }) : /* @__PURE__ */ jsxs(Fragment, { children: [
253
- /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-1 p-4", children: [
254
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Triage" }),
255
- /* @__PURE__ */ jsx(TriageHealthTone, { enabled: settings.triageEnabled === true })
256
- ] }) }),
257
- /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-1 p-4", children: [
258
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Cadence" }),
259
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: settings.triageIntervalMinutes ? `Toutes les ${settings.triageIntervalMinutes} minutes` : "\u2014" })
260
- ] }) }),
261
- /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-1 p-4", children: [
262
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Escalades" }),
263
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: escalatedLoading ? "\u2026" : escalatedError ? "Indisponible" : `${escalatedTotal} au total` })
264
- ] }) })
265
- ] }) })
266
- ] });
267
- const columns = [
268
- { key: "ticketId", header: "Ticket", cell: (row) => row.ticketId },
269
- { key: "category", header: "Cat\xE9gorie", cell: (row) => row.categoryId && categoryNames.get(row.categoryId) || "\u2014" },
270
- {
271
- key: "escalated",
272
- header: "Escalade",
273
- cell: (row) => row.escalated ? /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Escalad\xE9" }) : /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: "Non escalad\xE9" })
274
- },
275
- { key: "decidedAt", header: "Date", cell: (row) => formatDate(row.decidedAt) }
276
- ];
508
+ const daily = useMemo(() => {
509
+ const folded = foldDailyOutcomes(dailyRows);
510
+ return bounds.interval === "day" ? fillMissingDays(folded, bounds.current.fromIso, bounds.current.toIso) : folded;
511
+ }, [dailyRows, bounds]);
512
+ const rate = autonomyRate(totals);
513
+ const compareRate = compareTotals === null ? Number.NaN : autonomyRate(compareTotals);
514
+ const settled = settledCount(totals);
515
+ const signals = useMemo(() => dashboardSignals(totals, compareTotals), [totals, compareTotals]);
516
+ const reasons = useMemo(() => foldHumanReasons(dailyRows), [dailyRows]);
517
+ const categoryBars = useMemo(
518
+ () => foldCategoryOutcomes(categoryCounts, categoryOutcomes, categoryNames),
519
+ [categoryCounts, categoryOutcomes, categoryNames]
520
+ );
521
+ const categoryScale = categoryBars.reduce((max, bar) => Math.max(max, bar.total), 0);
522
+ const loading = dailyLoading || previousLoading;
523
+ const chartData = daily.map((point) => ({ ...point, jour: dayLabel(point.day) }));
524
+ const bucketWord = bounds.interval === "day" ? "jour" : "semaine";
277
525
  return /* @__PURE__ */ jsxs(PageShell, { children: [
278
526
  /* @__PURE__ */ jsx(
279
527
  PageHeader,
280
528
  {
281
529
  title: "Tableau de bord",
282
- description: "Les chiffres cl\xE9s et les graphiques couvrent la fen\xEAtre choisie ; la sant\xE9 annonce la sienne.",
283
- actions: /* @__PURE__ */ jsx(Fragment, { children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
284
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
285
- /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Fen\xEAtre :" }),
286
- WINDOW_OPTIONS.map((days) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
287
- days,
288
- " j"
289
- ] }, days))
290
- ] }),
530
+ description: "Ce que l\u2019IA a r\xE9gl\xE9 seule sur la p\xE9riode, et ce qui est retomb\xE9 sur un humain.",
531
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [
532
+ /* @__PURE__ */ jsx(
533
+ DateRangeCompare,
534
+ {
535
+ value: period,
536
+ onChange: setPeriod,
537
+ comparable: true,
538
+ presets: DASHBOARD_PRESETS,
539
+ align: "end"
540
+ }
541
+ ),
291
542
  /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/pipeline`, children: "Voir le pipeline complet" })
292
- ] }) })
543
+ ] })
293
544
  }
294
545
  ),
295
- alarming && healthBand,
296
- /* @__PURE__ */ jsxs("div", { "data-testid": "dashboard-kpis", className: "grid grid-cols-1 gap-4 sm:grid-cols-3", children: [
297
- /* @__PURE__ */ jsxs("div", { children: [
298
- /* @__PURE__ */ jsx(KpiCard, { label: "G\xE9n\xE9r\xE9", value: statusLoading ? Number.NaN : totalGenerated, formatValue: (v) => Number.isNaN(v) ? "\u2026" : String(v) }),
299
- /* @__PURE__ */ 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)." })
546
+ /* @__PURE__ */ jsxs(
547
+ "div",
548
+ {
549
+ "data-testid": "dashboard-kpis",
550
+ className: "grid grid-cols-1 gap-4 sm:grid-cols-[1.3fr_1fr_1fr]",
551
+ children: [
552
+ /* @__PURE__ */ jsx(
553
+ AutonomyHero,
554
+ {
555
+ rate: loading ? Number.NaN : rate,
556
+ compareRate,
557
+ caption: loading ? "Calcul en cours\u2026" : `${formatCount(totals.auto)} r\xE9gl\xE9es par l\u2019IA sur ${formatCount(settled)} demandes r\xE9gl\xE9es.`
558
+ }
559
+ ),
560
+ /* @__PURE__ */ jsx(
561
+ KpiCard,
562
+ {
563
+ label: "R\xE9ponse automatis\xE9e par l\u2019agent",
564
+ value: loading ? Number.NaN : totals.auto,
565
+ ...compareTotals === null ? {} : { compareValue: compareTotals.auto },
566
+ formatValue: formatCount
567
+ }
568
+ ),
569
+ /* @__PURE__ */ jsx(
570
+ KpiCard,
571
+ {
572
+ label: "Repris par un humain",
573
+ value: loading ? Number.NaN : totals.human,
574
+ ...compareTotals === null ? {} : { compareValue: compareTotals.human },
575
+ formatValue: formatCount,
576
+ lowerIsBetter: true
577
+ }
578
+ )
579
+ ]
580
+ }
581
+ ),
582
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-2", children: [
583
+ /* @__PURE__ */ jsx(
584
+ KpiCard,
585
+ {
586
+ label: "Encore en cours",
587
+ value: loading ? Number.NaN : totals.inProgress,
588
+ formatValue: formatCount
589
+ }
590
+ ),
591
+ /* @__PURE__ */ jsx(
592
+ KpiCard,
593
+ {
594
+ label: "Sans r\xE9ponse n\xE9cessaire",
595
+ value: loading ? Number.NaN : totals.noReplyNeeded,
596
+ formatValue: formatCount
597
+ }
598
+ )
599
+ ] }),
600
+ /* @__PURE__ */ jsxs("details", { className: "text-xs leading-relaxed text-muted-foreground", children: [
601
+ /* @__PURE__ */ jsx("summary", { className: "cursor-pointer select-none font-medium", children: "Comment le taux d\u2019autonomie est calcul\xE9" }),
602
+ /* @__PURE__ */ jsx("p", { className: "mt-2", 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." })
603
+ ] }),
604
+ dailyError !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
605
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [
606
+ /* @__PURE__ */ jsxs(Card, { children: [
607
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs(CardTitle, { className: "text-sm", children: [
608
+ "Automatique ou humain, ",
609
+ bucketWord,
610
+ " par ",
611
+ bucketWord
612
+ ] }) }),
613
+ /* @__PURE__ */ jsx(CardContent, { children: dailyError !== void 0 ? /* @__PURE__ */ jsxs("p", { className: "text-sm text-destructive", children: [
614
+ "Impossible de calculer l\u2019\xE9volution par ",
615
+ bucketWord,
616
+ "."
617
+ ] }) : chartData.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune journ\xE9e mesur\xE9e sur cette p\xE9riode." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
618
+ /* @__PURE__ */ jsx("p", { className: "mb-1 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: "Part r\xE9gl\xE9e par l\u2019IA" }),
619
+ /* @__PURE__ */ jsx(
620
+ AreaChart,
621
+ {
622
+ data: chartData,
623
+ x: "jour",
624
+ series: [{ key: "rate", label: "Taux d\u2019autonomie" }],
625
+ formatValue: formatRate,
626
+ height: 150,
627
+ hideLegend: true
628
+ }
629
+ ),
630
+ /* @__PURE__ */ jsx("p", { className: "mb-1 mt-4 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: "Demandes r\xE9gl\xE9es, en volume" }),
631
+ /* @__PURE__ */ jsx(
632
+ StackedBarChart,
633
+ {
634
+ data: chartData,
635
+ x: "jour",
636
+ label: `Demandes r\xE9gl\xE9es par ${bucketWord}`,
637
+ series: [
638
+ { key: "auto", label: "R\xE9gl\xE9 par l\u2019IA", colorIndex: 0 },
639
+ { key: "human", label: "Repris par un humain", colorIndex: 1 }
640
+ ],
641
+ formatValue: formatCount,
642
+ height: 150
643
+ }
644
+ ),
645
+ /* @__PURE__ */ jsxs("p", { className: "mt-3 text-xs leading-relaxed text-muted-foreground", children: [
646
+ "La courbe est la ",
647
+ /* @__PURE__ */ jsx("strong", { children: "part" }),
648
+ " r\xE9gl\xE9e sans personne ; les barres sont le",
649
+ " ",
650
+ /* @__PURE__ */ jsx("strong", { children: "volume" }),
651
+ " qu\u2019elle recouvre. Un ",
652
+ bucketWord,
653
+ " \xE0 100 % sur deux demandes n\u2019est pas la m\xEAme nouvelle qu\u2019un ",
654
+ bucketWord,
655
+ " \xE0 80 % sur deux cents."
656
+ ] }),
657
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs leading-relaxed text-muted-foreground", children: [
658
+ "Un trou dans la courbe veut dire \xAB rien de r\xE9gl\xE9 ce ",
659
+ bucketWord,
660
+ "-l\xE0 \xBB, jamais \xAB 0 % \xBB : sans d\xE9nominateur, il n\u2019y a pas de taux \xE0 tracer."
661
+ ] })
662
+ ] }) })
300
663
  ] }),
301
- /* @__PURE__ */ jsxs("div", { children: [
664
+ /* @__PURE__ */ jsxs(Card, { children: [
665
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "R\xE9partition par cat\xE9gorie" }) }),
666
+ /* @__PURE__ */ jsx(CardContent, { className: "space-y-3", children: categoryLoading ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : categoryError !== void 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer la r\xE9partition par cat\xE9gorie." }) : categoryBars.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun volume calcul\xE9 pour l'instant sur cette p\xE9riode." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
667
+ /* @__PURE__ */ jsx(StackedLegend, { segments: CATEGORY_LEGEND }),
668
+ /* @__PURE__ */ jsx("div", { className: "space-y-1.5", children: categoryBars.map((bar) => /* @__PURE__ */ jsx(
669
+ StackedRow,
670
+ {
671
+ label: bar.label,
672
+ total: bar.total,
673
+ scale: categoryScale,
674
+ formatCount,
675
+ segments: [
676
+ {
677
+ key: "auto",
678
+ label: "R\xE9ponse automatis\xE9e par l\u2019agent",
679
+ value: bar.auto,
680
+ color: CATEGORY_COLORS.auto
681
+ },
682
+ {
683
+ key: "human",
684
+ label: "Repris par un humain",
685
+ value: bar.human,
686
+ color: CATEGORY_COLORS.human
687
+ },
688
+ {
689
+ key: "noReply",
690
+ label: "Sans r\xE9ponse n\xE9cessaire",
691
+ value: bar.noReply,
692
+ color: CATEGORY_COLORS.noReply
693
+ },
694
+ {
695
+ key: "undrafted",
696
+ label: "Sans brouillon",
697
+ value: bar.undrafted,
698
+ color: CATEGORY_COLORS.undrafted
699
+ }
700
+ ]
701
+ },
702
+ bar.label
703
+ )) }),
704
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-relaxed text-muted-foreground", children: "Ce qui arrive, par cat\xE9gorie \u2014 et qui l\u2019a trait\xE9. La longueur d\u2019une barre est le volume tri\xE9 sur la p\xE9riode ; les couleurs sont ce que ce volume est devenu. \xAB\xA0Sans brouillon\xA0\xBB couvre ce que le triage a vu sans qu\u2019une r\xE9ponse soit g\xE9n\xE9r\xE9e : escalade imm\xE9diate, conversation d\xE9j\xE0 close, ou traitement encore en cours." })
705
+ ] }) })
706
+ ] })
707
+ ] }),
708
+ /* @__PURE__ */ jsxs(Card, { children: [
709
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "Pourquoi un humain a repris" }) }),
710
+ /* @__PURE__ */ jsx(CardContent, { className: "space-y-3", children: loading ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : totals.human === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune reprise humaine sur cette p\xE9riode." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
302
711
  /* @__PURE__ */ jsx(
303
- KpiCard,
712
+ StackedRow,
304
713
  {
305
- label: "Taux d'envoi auto",
306
- value: statusLoading || autoSendLoading ? Number.NaN : rateOrNaN(sentCount, totalGenerated),
307
- formatValue: formatRate
714
+ label: "Motifs",
715
+ total: totals.human,
716
+ scale: totals.human,
717
+ formatCount,
718
+ segments: [
719
+ {
720
+ key: "blocked",
721
+ label: "Bloqu\xE9 avant envoi",
722
+ value: reasons.blocked,
723
+ color: "var(--chart-2)"
724
+ },
725
+ {
726
+ key: "invalidated",
727
+ label: "Un agent avait d\xE9j\xE0 r\xE9pondu",
728
+ value: reasons.invalidated,
729
+ color: "var(--chart-3)"
730
+ },
731
+ {
732
+ key: "expired",
733
+ label: "Brouillon expir\xE9",
734
+ value: reasons.expired,
735
+ color: "var(--chart-5)"
736
+ }
737
+ ]
308
738
  }
309
739
  ),
310
- /* @__PURE__ */ 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." })
311
- ] }),
312
- /* @__PURE__ */ jsxs("div", { children: [
313
740
  /* @__PURE__ */ jsx(
314
- KpiCard,
741
+ StackedLegend,
315
742
  {
316
- label: "Taux de blocage",
317
- value: statusLoading || autoSendLoading ? Number.NaN : rateOrNaN(heldCount, totalGenerated),
318
- formatValue: formatRate,
319
- lowerIsBetter: true
320
- }
321
- ),
322
- /* @__PURE__ */ 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)." })
323
- ] })
324
- ] }),
325
- statusError !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
326
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [
327
- /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "p-4", children: [
328
- /* @__PURE__ */ jsx("p", { className: "mb-3 text-sm font-medium", children: "R\xE9partition par cat\xE9gorie" }),
329
- categoryLoading ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : categoryError !== void 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer la r\xE9partition par cat\xE9gorie." }) : categoryBars.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun volume calcul\xE9 pour l'instant sur cette fen\xEAtre." }) : /* @__PURE__ */ jsx(BarChart, { data: categoryBars, x: "label", series: [{ key: "value", label: "Volume", colorIndex: 0 }] })
330
- ] }) }),
331
- /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "p-4", children: [
332
- /* @__PURE__ */ jsx("p", { className: "mb-3 text-sm font-medium", children: "\xC9volution par jour" }),
333
- dailySeriesError ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer l'\xE9volution par jour." }) : dailySeries.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune journ\xE9e mesur\xE9e sur cette fen\xEAtre." }) : /* @__PURE__ */ jsx(
334
- StackedBarChart,
335
- {
336
- data: dailySeries,
337
- x: "day",
338
- label: "\xC9volution par jour",
339
- series: [
340
- { key: "sent", label: "Envoy\xE9es", colorIndex: 0 },
341
- { key: "held", label: "Bloqu\xE9es", colorIndex: 1 }
743
+ segments: [
744
+ {
745
+ key: "blocked",
746
+ label: `Bloqu\xE9 avant envoi (${formatCount(reasons.blocked)})`,
747
+ color: "var(--chart-2)"
748
+ },
749
+ {
750
+ key: "invalidated",
751
+ label: `Un agent avait d\xE9j\xE0 r\xE9pondu (${formatCount(reasons.invalidated)})`,
752
+ color: "var(--chart-3)"
753
+ },
754
+ {
755
+ key: "expired",
756
+ label: `Brouillon expir\xE9 (${formatCount(reasons.expired)})`,
757
+ color: "var(--chart-5)"
758
+ }
342
759
  ]
343
760
  }
344
- )
761
+ ),
762
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-relaxed text-muted-foreground", children: "Les escalades sont dans \xAB\xA0bloqu\xE9\xA0\xBB : un ticket escalad\xE9 voit son brouillon retenu par le garde-fou, c\u2019est un motif de blocage et non un camp de plus. Le d\xE9tail ticket par ticket est sur la page Escalades." })
345
763
  ] }) })
346
764
  ] }),
347
- !alarming && healthBand,
348
- /* @__PURE__ */ jsxs("section", { children: [
349
- /* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-baseline justify-between gap-4", children: [
350
- /* @__PURE__ */ jsx("h2", { className: "text-xs font-semibold uppercase tracking-wider text-muted-foreground", children: "Activit\xE9 r\xE9cente" }),
351
- /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/tickets`, children: "Ouvrir le suivi des demandes" })
352
- ] }),
353
- /* @__PURE__ */ jsx(
354
- DataTable,
355
- {
356
- columns,
357
- rows: recentActivity,
358
- rowId: (row) => row.id,
359
- manual: true,
360
- loading: activityLoading,
361
- error: activityError ? "Erreur lors du chargement de l\u2019activit\xE9 r\xE9cente." : void 0,
362
- empty: "Aucune d\xE9cision de triage enregistr\xE9e pour l\u2019instant."
363
- }
364
- )
765
+ /* @__PURE__ */ jsxs(Card, { children: [
766
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "Signaux \xE0 surveiller" }) }),
767
+ /* @__PURE__ */ jsx(CardContent, { children: signals.length === 0 ? /* @__PURE__ */ 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__ */ jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
768
+ /* @__PURE__ */ jsx(Badge, { variant: signal.level === "creuser" ? "warning" : "neutral", children: signal.level === "creuser" ? "\xC0 creuser" : "Info" }),
769
+ /* @__PURE__ */ jsx("span", { className: "text-sm leading-relaxed", children: signal.text })
770
+ ] }, signal.text)) }) })
365
771
  ] })
366
772
  ] });
367
773
  }
@@ -1039,7 +1445,7 @@ function computePipelineStats(rows, timezone = "UTC") {
1039
1445
  }
1040
1446
  var STATS_PAGE_SIZE = 200;
1041
1447
  var TABLE_PAGE_SIZE = 200;
1042
- var WINDOW_OPTIONS2 = [7, 14, 30];
1448
+ var WINDOW_OPTIONS = [7, 14, 30];
1043
1449
  var DECISION_OPTIONS = [
1044
1450
  { value: "", label: "Tous" },
1045
1451
  { value: "sent", label: "Envoy\xE9s auto" },
@@ -1067,7 +1473,7 @@ function buildTableFilter(decision, status) {
1067
1473
  function countOrEllipsis(value) {
1068
1474
  return Number.isNaN(value) ? "\u2026" : String(value);
1069
1475
  }
1070
- function windowCutoffIso2(days) {
1476
+ function windowCutoffIso(days) {
1071
1477
  return new Date(Date.now() - days * 24 * 60 * 60 * 1e3).toISOString();
1072
1478
  }
1073
1479
  function ConfidenceCell({ confidence }) {
@@ -1155,7 +1561,7 @@ function PipelinePage() {
1155
1561
  const toast = useToast();
1156
1562
  const [isTriaging, setIsTriaging] = useState(false);
1157
1563
  const isTriagingRef = useRef(false);
1158
- const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS2[0]);
1564
+ const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS[0]);
1159
1565
  const [decisionFilter, setDecisionFilter] = useState("");
1160
1566
  const [statusFilter, setStatusFilter] = useState("");
1161
1567
  const [verdictFilter, setVerdictFilter] = useState("");
@@ -1190,7 +1596,7 @@ function PipelinePage() {
1190
1596
  const categoryNames = useMemo(() => toNameMap(categories), [categories]);
1191
1597
  const agentNames = useMemo(() => toNameMap(agents), [agents]);
1192
1598
  const windowedStatsRows = useMemo(() => {
1193
- const cutoff = windowCutoffIso2(windowDays);
1599
+ const cutoff = windowCutoffIso(windowDays);
1194
1600
  return statsRows.filter((row) => row.generatedAt !== null && row.generatedAt >= cutoff);
1195
1601
  }, [statsRows, windowDays]);
1196
1602
  const stats = useMemo(
@@ -1285,7 +1691,7 @@ function PipelinePage() {
1285
1691
  ),
1286
1692
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1287
1693
  /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "Fen\xEAtre :" }),
1288
- WINDOW_OPTIONS2.map((days) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
1694
+ WINDOW_OPTIONS.map((days) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
1289
1695
  days,
1290
1696
  " j"
1291
1697
  ] }, days))
@@ -4794,7 +5200,7 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
4794
5200
  globalNotes: promptWarningNodes.length > 0 ? [{ ...PROMPT_403_NOTE, nodes: promptWarningNodes }] : []
4795
5201
  };
4796
5202
  }
4797
- function windowCutoffIso3(days, now = Date.now()) {
5203
+ function windowCutoffIso2(days, now = Date.now()) {
4798
5204
  return new Date(now - days * 24 * 60 * 60 * 1e3).toISOString();
4799
5205
  }
4800
5206
  function totalOf(rows) {
@@ -4808,7 +5214,7 @@ function totalOf(rows) {
4808
5214
  return total;
4809
5215
  }
4810
5216
  function useGraphTraffic(windowDays) {
4811
- const cutoffIso = useMemo(() => windowCutoffIso3(windowDays), [windowDays]);
5217
+ const cutoffIso = useMemo(() => windowCutoffIso2(windowDays), [windowDays]);
4812
5218
  const triaged = useAggregate("triage-decision", {
4813
5219
  filter: { decidedAt: { gte: cutoffIso } },
4814
5220
  metrics: [{ op: "count", as: "count" }]