@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.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, Card, CardContent, Badge, KpiCard, CardHeader, CardTitle, AreaChart, StackedBarChart, BarChart, 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,33 +143,110 @@ 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
+ });
171
236
  }
172
- return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, counts]) => ({ day, ...counts }));
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
+ });
248
+ }
249
+ return signals;
173
250
  }
174
251
  var DEFAULT_TOP_N = 6;
175
252
  function foldCategoryBreakdown(rows, categoryNames, topN = DEFAULT_TOP_N) {
@@ -182,186 +259,335 @@ function foldCategoryBreakdown(rows, categoryNames, topN = DEFAULT_TOP_N) {
182
259
  const tail = measured.slice(topN).reduce((sum, bar) => sum + bar.value, 0);
183
260
  return [...measured.slice(0, topN), { label: "Autres", value: tail }];
184
261
  }
185
- var WINDOW_OPTIONS = [7, 14, 30];
186
- var RECENT_ACTIVITY_LIMIT = 8;
262
+ var POINTS_FORMAT = new Intl.NumberFormat("fr-FR", {
263
+ maximumFractionDigits: 1,
264
+ signDisplay: "exceptZero"
265
+ });
187
266
  function formatRate(value) {
188
- return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)}%`;
267
+ return Number.isNaN(value) ? "\u2014" : `${Math.round(value * 100)} %`;
189
268
  }
190
- function rateOrNaN(numerator, denominator) {
191
- return denominator > 0 ? numerator / denominator : Number.NaN;
269
+ function AutonomyHero({
270
+ rate,
271
+ compareRate,
272
+ caption
273
+ }) {
274
+ const points = ratePoints(rate, compareRate);
275
+ 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: [
276
+ /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.06em] text-muted-foreground", children: [
277
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "inline-block size-2 rounded-full bg-primary" }),
278
+ "Taux d\u2019autonomie"
279
+ ] }),
280
+ /* @__PURE__ */ jsx("p", { className: "text-4xl font-semibold leading-tight tabular-nums text-foreground", children: formatRate(rate) }),
281
+ points !== null && // Direction is in the sign as well as the colour — `KpiCard`'s own
282
+ // rule, restated here because this card does not go through it.
283
+ /* @__PURE__ */ jsxs(
284
+ "p",
285
+ {
286
+ className: `text-xs font-semibold tabular-nums ${points < 0 ? "text-status-blocked" : "text-status-success"}`,
287
+ children: [
288
+ POINTS_FORMAT.format(points),
289
+ " pts",
290
+ /* @__PURE__ */ jsxs("span", { className: "ml-1 font-normal text-muted-foreground", children: [
291
+ "vs ",
292
+ formatRate(compareRate)
293
+ ] })
294
+ ]
295
+ }
296
+ ),
297
+ /* @__PURE__ */ jsx("p", { className: "pt-1 text-xs text-muted-foreground", children: caption })
298
+ ] }) });
192
299
  }
193
- function TriageHealthTone({ enabled }) {
194
- return /* @__PURE__ */ jsx(Badge, { variant: enabled ? "success" : "danger", children: enabled ? "Actif" : "Coup\xE9" });
300
+ var DASHBOARD_PRESETS = [
301
+ { key: "last7", label: "7 derniers jours" },
302
+ { key: "last30", label: "30 derniers jours" }
303
+ ];
304
+ var WEEKLY_BUCKET_FROM_DAYS = 46;
305
+ var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
306
+ var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
307
+ function startOfDayIso(day) {
308
+ return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
309
+ }
310
+ function endOfDayIso(day) {
311
+ return DAY_PATTERN.test(day) ? `${day}T23:59:59.999Z` : (/* @__PURE__ */ new Date()).toISOString();
312
+ }
313
+ function dayCount(bounds) {
314
+ const from = Date.parse(bounds.fromIso);
315
+ const to = Date.parse(bounds.toIso);
316
+ if (Number.isNaN(from) || Number.isNaN(to)) return 0;
317
+ return Math.max(1, Math.round((to - from) / 864e5));
318
+ }
319
+ function periodBoundsOf(value) {
320
+ const current = {
321
+ fromIso: startOfDayIso(value.range.from),
322
+ toIso: endOfDayIso(value.range.to)
323
+ };
324
+ const compare = value.compare === "none" ? void 0 : value.compareRange ?? comparisonRange(value.preset, value.range, value.compare);
325
+ const days = dayCount(current);
326
+ return {
327
+ current,
328
+ previous: compare === void 0 ? null : { fromIso: startOfDayIso(compare.from), toIso: endOfDayIso(compare.to) },
329
+ days,
330
+ interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
331
+ };
332
+ }
333
+ function defaultPeriod(today = /* @__PURE__ */ new Date()) {
334
+ const to = today.toISOString().slice(0, 10);
335
+ const start = new Date(today);
336
+ start.setUTCDate(start.getUTCDate() - 29);
337
+ const range = { from: start.toISOString().slice(0, 10), to };
338
+ const compareRange = comparisonRange("last30", range, "previous_period");
339
+ return {
340
+ preset: "last30",
341
+ range,
342
+ compare: "previous_period",
343
+ ...compareRange === void 0 ? {} : { compareRange }
344
+ };
345
+ }
346
+ var OUTCOME_METRICS = [{ op: "count", as: "count" }];
347
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision"];
348
+ function formatCount(value) {
349
+ return Number.isNaN(value) ? "\u2026" : value.toLocaleString("fr-FR");
350
+ }
351
+ function dayLabel(day) {
352
+ const parsed = /* @__PURE__ */ new Date(`${day}T00:00:00.000Z`);
353
+ return Number.isNaN(parsed.getTime()) ? day : parsed.toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", timeZone: "UTC" });
195
354
  }
196
355
  function DashboardPage() {
197
356
  const { appSlug } = useAppContext();
198
- const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS[0]);
199
- const { settings, error: settingsError } = useAppSettings();
357
+ const [period, setPeriod] = useState(() => defaultPeriod());
358
+ const { settings } = useAppSettings();
200
359
  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" }]
360
+ const periodKey = JSON.stringify(period);
361
+ const bounds = useMemo(() => periodBoundsOf(JSON.parse(periodKey)), [periodKey]);
362
+ const currentFilter = { generatedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } };
363
+ const previousBounds = bounds.previous ?? bounds.current;
364
+ const {
365
+ rows: dailyRows,
366
+ isLoading: dailyLoading,
367
+ error: dailyError
368
+ } = useAggregate("generated-response", {
369
+ filter: currentFilter,
370
+ groupBy: OUTCOME_GROUP_BY,
371
+ bucket: { field: "generatedAt", interval: bounds.interval, tz: timezone },
372
+ metrics: OUTCOME_METRICS
206
373
  });
207
- const { rows: autoSendCounts, isLoading: autoSendLoading } = useAggregate("generated-response", {
208
- filter: { generatedAt: { gte: cutoffIso } },
209
- groupBy: ["autoSendDecision"],
210
- metrics: [{ op: "count", as: "count" }]
374
+ const { rows: previousRows, isLoading: previousLoading } = useAggregate("generated-response", {
375
+ filter: { generatedAt: { gte: previousBounds.fromIso, lte: previousBounds.toIso } },
376
+ groupBy: OUTCOME_GROUP_BY,
377
+ metrics: OUTCOME_METRICS
211
378
  });
212
- const { rows: escalatedRows, isLoading: escalatedLoading, error: escalatedError } = useAggregate("triage-decision", {
213
- filter: { escalated: { eq: true } },
214
- metrics: [{ op: "count", as: "count" }]
215
- });
216
- const { rows: categoryCounts, isLoading: categoryLoading, error: categoryError } = useAggregate("triage-decision", {
217
- filter: { decidedAt: { gte: cutoffIso } },
379
+ const {
380
+ rows: categoryCounts,
381
+ isLoading: categoryLoading,
382
+ error: categoryError
383
+ } = useAggregate("triage-decision", {
384
+ filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
218
385
  groupBy: ["categoryId"],
219
- metrics: [{ op: "count", as: "count" }]
220
- });
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" }]
386
+ metrics: OUTCOME_METRICS
225
387
  });
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
388
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
233
389
  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
390
+ const totals = useMemo(() => foldOutcomes(dailyRows), [dailyRows]);
391
+ const compareTotals = useMemo(
392
+ () => bounds.previous === null ? null : foldOutcomes(previousRows),
393
+ [bounds.previous, previousRows]
242
394
  );
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;
395
+ const daily = useMemo(() => {
396
+ const folded = foldDailyOutcomes(dailyRows);
397
+ return bounds.interval === "day" ? fillMissingDays(folded, bounds.current.fromIso, bounds.current.toIso) : folded;
398
+ }, [dailyRows, bounds]);
399
+ const rate = autonomyRate(totals);
400
+ const compareRate = compareTotals === null ? Number.NaN : autonomyRate(compareTotals);
401
+ const settled = settledCount(totals);
402
+ const signals = useMemo(() => dashboardSignals(totals, compareTotals), [totals, compareTotals]);
247
403
  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
- ];
404
+ const loading = dailyLoading || previousLoading;
405
+ const chartData = daily.map((point) => ({ ...point, jour: dayLabel(point.day) }));
406
+ const bucketWord = bounds.interval === "day" ? "jour" : "semaine";
407
+ const aCreuser = signals.find((signal) => signal.level === "creuser");
408
+ const lead = loading ? null : settled === 0 ? {
409
+ alert: false,
410
+ title: "Aucune demande r\xE9gl\xE9e sur cette p\xE9riode",
411
+ detail: "Choisis une autre p\xE9riode, ou v\xE9rifie que le triage tourne (Param\xE8tres \u203A Triage)."
412
+ } : aCreuser !== void 0 ? { alert: true, title: "Un point m\xE9rite ton attention", detail: aCreuser.text } : {
413
+ alert: false,
414
+ title: `${formatRate(rate)} des demandes r\xE9gl\xE9es sans personne`,
415
+ 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.`
416
+ };
277
417
  return /* @__PURE__ */ jsxs(PageShell, { children: [
278
418
  /* @__PURE__ */ jsx(
279
419
  PageHeader,
280
420
  {
281
421
  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
- ] }),
422
+ description: "Ce que l\u2019IA a r\xE9gl\xE9 seule sur la p\xE9riode, et ce qui est retomb\xE9 sur un humain.",
423
+ actions: /* @__PURE__ */ jsxs(Fragment, { children: [
424
+ /* @__PURE__ */ jsx(
425
+ DateRangeCompare,
426
+ {
427
+ value: period,
428
+ onChange: setPeriod,
429
+ comparable: true,
430
+ presets: DASHBOARD_PRESETS,
431
+ align: "end"
432
+ }
433
+ ),
291
434
  /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/pipeline`, children: "Voir le pipeline complet" })
292
- ] }) })
435
+ ] })
293
436
  }
294
437
  ),
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)." })
300
- ] }),
301
- /* @__PURE__ */ jsxs("div", { children: [
302
- /* @__PURE__ */ jsx(
303
- KpiCard,
304
- {
305
- label: "Taux d'envoi auto",
306
- value: statusLoading || autoSendLoading ? Number.NaN : rateOrNaN(sentCount, totalGenerated),
307
- formatValue: formatRate
308
- }
309
- ),
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
- ] }),
438
+ lead !== null && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "flex items-start gap-3 p-4", children: [
439
+ /* @__PURE__ */ jsx(Badge, { variant: lead.alert ? "warning" : "brand", children: lead.alert ? "\xC0 creuser" : "Cap" }),
312
440
  /* @__PURE__ */ jsxs("div", { children: [
313
- /* @__PURE__ */ jsx(
314
- KpiCard,
315
- {
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)." })
441
+ /* @__PURE__ */ jsx("p", { className: "text-base font-semibold leading-snug", children: lead.title }),
442
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm leading-relaxed text-muted-foreground", children: lead.detail })
323
443
  ] })
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 }
342
- ]
343
- }
344
- )
345
- ] }) })
346
- ] }),
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
- ] }),
444
+ ] }) }),
445
+ /* @__PURE__ */ jsxs(
446
+ "div",
447
+ {
448
+ "data-testid": "dashboard-kpis",
449
+ className: "grid grid-cols-1 gap-4 sm:grid-cols-[1.3fr_1fr_1fr]",
450
+ children: [
451
+ /* @__PURE__ */ jsx(
452
+ AutonomyHero,
453
+ {
454
+ rate: loading ? Number.NaN : rate,
455
+ compareRate,
456
+ caption: loading ? "Calcul en cours\u2026" : `${formatCount(totals.auto)} r\xE9gl\xE9es par l\u2019IA sur ${formatCount(settled)} demandes r\xE9gl\xE9es.`
457
+ }
458
+ ),
459
+ /* @__PURE__ */ jsx(
460
+ KpiCard,
461
+ {
462
+ label: "R\xE9gl\xE9 par l\u2019IA",
463
+ value: loading ? Number.NaN : totals.auto,
464
+ ...compareTotals === null ? {} : { compareValue: compareTotals.auto },
465
+ formatValue: formatCount
466
+ }
467
+ ),
468
+ /* @__PURE__ */ jsx(
469
+ KpiCard,
470
+ {
471
+ label: "Repris par un humain",
472
+ value: loading ? Number.NaN : totals.human,
473
+ ...compareTotals === null ? {} : { compareValue: compareTotals.human },
474
+ formatValue: formatCount,
475
+ lowerIsBetter: true
476
+ }
477
+ )
478
+ ]
479
+ }
480
+ ),
481
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 sm:grid-cols-3", children: [
353
482
  /* @__PURE__ */ jsx(
354
- DataTable,
483
+ KpiCard,
355
484
  {
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."
485
+ label: "Encore en cours",
486
+ value: loading ? Number.NaN : totals.inProgress,
487
+ formatValue: formatCount
488
+ }
489
+ ),
490
+ /* @__PURE__ */ jsx(
491
+ KpiCard,
492
+ {
493
+ label: "Sans r\xE9ponse n\xE9cessaire",
494
+ value: loading ? Number.NaN : totals.noReplyNeeded,
495
+ formatValue: formatCount
496
+ }
497
+ ),
498
+ /* @__PURE__ */ jsx(
499
+ KpiCard,
500
+ {
501
+ label: "\xC9checs techniques",
502
+ value: loading ? Number.NaN : totals.failed,
503
+ ...compareTotals === null ? {} : { compareValue: compareTotals.failed },
504
+ formatValue: formatCount,
505
+ lowerIsBetter: true
363
506
  }
364
507
  )
508
+ ] }),
509
+ /* @__PURE__ */ 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." }),
510
+ dailyError !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
511
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4 lg:grid-cols-2", children: [
512
+ /* @__PURE__ */ jsxs(Card, { children: [
513
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs(CardTitle, { className: "text-sm", children: [
514
+ "Automatique ou humain, ",
515
+ bucketWord,
516
+ " par ",
517
+ bucketWord
518
+ ] }) }),
519
+ /* @__PURE__ */ jsx(CardContent, { children: dailyError !== void 0 ? /* @__PURE__ */ jsxs("p", { className: "text-sm text-destructive", children: [
520
+ "Impossible de calculer l\u2019\xE9volution par ",
521
+ bucketWord,
522
+ "."
523
+ ] }) : 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: [
524
+ /* @__PURE__ */ jsx("p", { className: "mb-1 text-xs font-medium uppercase tracking-widest text-muted-foreground", children: "Part r\xE9gl\xE9e par l\u2019IA" }),
525
+ /* @__PURE__ */ jsx(
526
+ AreaChart,
527
+ {
528
+ data: chartData,
529
+ x: "jour",
530
+ series: [{ key: "rate", label: "Taux d\u2019autonomie" }],
531
+ formatValue: formatRate,
532
+ height: 150,
533
+ hideLegend: true
534
+ }
535
+ ),
536
+ /* @__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" }),
537
+ /* @__PURE__ */ jsx(
538
+ StackedBarChart,
539
+ {
540
+ data: chartData,
541
+ x: "jour",
542
+ label: `Demandes r\xE9gl\xE9es par ${bucketWord}`,
543
+ series: [
544
+ { key: "auto", label: "R\xE9gl\xE9 par l\u2019IA", colorIndex: 0 },
545
+ { key: "human", label: "Repris par un humain", colorIndex: 1 }
546
+ ],
547
+ formatValue: formatCount,
548
+ height: 150
549
+ }
550
+ ),
551
+ /* @__PURE__ */ jsxs("p", { className: "mt-3 text-xs leading-relaxed text-muted-foreground", children: [
552
+ "La courbe est la ",
553
+ /* @__PURE__ */ jsx("strong", { children: "part" }),
554
+ " r\xE9gl\xE9e sans personne ; les barres sont le",
555
+ " ",
556
+ /* @__PURE__ */ jsx("strong", { children: "volume" }),
557
+ " qu\u2019elle recouvre. Un ",
558
+ bucketWord,
559
+ " \xE0 100 % sur deux demandes n\u2019est pas la m\xEAme nouvelle qu\u2019un ",
560
+ bucketWord,
561
+ " \xE0 80 % sur deux cents."
562
+ ] }),
563
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs leading-relaxed text-muted-foreground", children: [
564
+ "Un trou dans la courbe veut dire \xAB rien de r\xE9gl\xE9 ce ",
565
+ bucketWord,
566
+ "-l\xE0 \xBB, jamais \xAB 0 % \xBB : sans d\xE9nominateur, il n\u2019y a pas de taux \xE0 tracer."
567
+ ] })
568
+ ] }) })
569
+ ] }),
570
+ /* @__PURE__ */ jsxs(Card, { children: [
571
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "R\xE9partition par cat\xE9gorie" }) }),
572
+ /* @__PURE__ */ jsx(CardContent, { 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: [
573
+ /* @__PURE__ */ jsx(
574
+ BarChart,
575
+ {
576
+ data: categoryBars,
577
+ x: "label",
578
+ series: [{ key: "value", label: "Volume", colorIndex: 0 }]
579
+ }
580
+ ),
581
+ /* @__PURE__ */ 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." })
582
+ ] }) })
583
+ ] })
584
+ ] }),
585
+ /* @__PURE__ */ jsxs(Card, { children: [
586
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "Signaux \xE0 surveiller" }) }),
587
+ /* @__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: [
588
+ /* @__PURE__ */ jsx(Badge, { variant: signal.level === "creuser" ? "warning" : "neutral", children: signal.level === "creuser" ? "\xC0 creuser" : "Info" }),
589
+ /* @__PURE__ */ jsx("span", { className: "text-sm leading-relaxed", children: signal.text })
590
+ ] }, signal.text)) }) })
365
591
  ] })
366
592
  ] });
367
593
  }
@@ -1039,7 +1265,7 @@ function computePipelineStats(rows, timezone = "UTC") {
1039
1265
  }
1040
1266
  var STATS_PAGE_SIZE = 200;
1041
1267
  var TABLE_PAGE_SIZE = 200;
1042
- var WINDOW_OPTIONS2 = [7, 14, 30];
1268
+ var WINDOW_OPTIONS = [7, 14, 30];
1043
1269
  var DECISION_OPTIONS = [
1044
1270
  { value: "", label: "Tous" },
1045
1271
  { value: "sent", label: "Envoy\xE9s auto" },
@@ -1067,7 +1293,7 @@ function buildTableFilter(decision, status) {
1067
1293
  function countOrEllipsis(value) {
1068
1294
  return Number.isNaN(value) ? "\u2026" : String(value);
1069
1295
  }
1070
- function windowCutoffIso2(days) {
1296
+ function windowCutoffIso(days) {
1071
1297
  return new Date(Date.now() - days * 24 * 60 * 60 * 1e3).toISOString();
1072
1298
  }
1073
1299
  function ConfidenceCell({ confidence }) {
@@ -1155,7 +1381,7 @@ function PipelinePage() {
1155
1381
  const toast = useToast();
1156
1382
  const [isTriaging, setIsTriaging] = useState(false);
1157
1383
  const isTriagingRef = useRef(false);
1158
- const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS2[0]);
1384
+ const [windowDays, setWindowDays] = useState(WINDOW_OPTIONS[0]);
1159
1385
  const [decisionFilter, setDecisionFilter] = useState("");
1160
1386
  const [statusFilter, setStatusFilter] = useState("");
1161
1387
  const [verdictFilter, setVerdictFilter] = useState("");
@@ -1190,7 +1416,7 @@ function PipelinePage() {
1190
1416
  const categoryNames = useMemo(() => toNameMap(categories), [categories]);
1191
1417
  const agentNames = useMemo(() => toNameMap(agents), [agents]);
1192
1418
  const windowedStatsRows = useMemo(() => {
1193
- const cutoff = windowCutoffIso2(windowDays);
1419
+ const cutoff = windowCutoffIso(windowDays);
1194
1420
  return statsRows.filter((row) => row.generatedAt !== null && row.generatedAt >= cutoff);
1195
1421
  }, [statsRows, windowDays]);
1196
1422
  const stats = useMemo(
@@ -1285,7 +1511,7 @@ function PipelinePage() {
1285
1511
  ),
1286
1512
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1287
1513
  /* @__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: [
1514
+ WINDOW_OPTIONS.map((days) => /* @__PURE__ */ jsxs(Button, { size: "sm", variant: windowDays === days ? "default" : "outline", onClick: () => setWindowDays(days), children: [
1289
1515
  days,
1290
1516
  " j"
1291
1517
  ] }, days))
@@ -4794,7 +5020,7 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
4794
5020
  globalNotes: promptWarningNodes.length > 0 ? [{ ...PROMPT_403_NOTE, nodes: promptWarningNodes }] : []
4795
5021
  };
4796
5022
  }
4797
- function windowCutoffIso3(days, now = Date.now()) {
5023
+ function windowCutoffIso2(days, now = Date.now()) {
4798
5024
  return new Date(now - days * 24 * 60 * 60 * 1e3).toISOString();
4799
5025
  }
4800
5026
  function totalOf(rows) {
@@ -4808,7 +5034,7 @@ function totalOf(rows) {
4808
5034
  return total;
4809
5035
  }
4810
5036
  function useGraphTraffic(windowDays) {
4811
- const cutoffIso = useMemo(() => windowCutoffIso3(windowDays), [windowDays]);
5037
+ const cutoffIso = useMemo(() => windowCutoffIso2(windowDays), [windowDays]);
4812
5038
  const triaged = useAggregate("triage-decision", {
4813
5039
  filter: { decidedAt: { gte: cutoffIso } },
4814
5040
  metrics: [{ op: "count", as: "count" }]