@dxv-systems/mail-graph 0.5.0 → 0.5.2
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/docs/app-integration.md +321 -7
- package/package.json +1 -1
package/docs/app-integration.md
CHANGED
|
@@ -17,13 +17,15 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
|
|
|
17
17
|
## 1. Install
|
|
18
18
|
|
|
19
19
|
```bash
|
|
20
|
-
npm install --save-exact @dxv-systems/mail-graph@0.5.
|
|
20
|
+
npm install --save-exact @dxv-systems/mail-graph@0.5.2 @dxv-systems/helpdesk@0.14.0 @vercel/oidc@4.0.1
|
|
21
21
|
```
|
|
22
22
|
|
|
23
23
|
Use the published versions (exact, never a range; upgrading is a deliberate change). **Vendored variant** (before publication, e.g. the rehearsal): `npm pack` each package into `vendor/` and install `file:vendor/dxv-systems-mail-graph-<version>.tgz file:vendor/dxv-systems-helpdesk-<version>.tgz` instead; commit the tarballs with `package.json` and the lockfile.
|
|
24
24
|
|
|
25
25
|
`@vercel/oidc` is already in the lockfile through `@dxv-systems/ai`; pin the same version so it is not duplicated.
|
|
26
26
|
|
|
27
|
+
The FAQ distiller in `deps.ts` starts runs by gateway feature, which needs `@dxv-systems/ai` 0.3 or later. The company app template still ships `^0.2`, so raise it: `npm install @dxv-systems/ai@^0.3.2`. Its 0.3.0 dropped the agent UUID from `createRuns().fireRun`; an app that calls it elsewhere passes the feature to `createRuns` instead.
|
|
28
|
+
|
|
27
29
|
## 2. Environment
|
|
28
30
|
|
|
29
31
|
DXV switches the helpdesk on for an app in the Portal (the app's services, "Microsoft 365 helpdesk", DXV staff only). DXV's infrastructure then creates the app's Entra app and sets the variables below, and the Portal files the request that applies this recipe. The app's code changes nothing in infrastructure, and adds no variables to it.
|
|
@@ -76,6 +78,7 @@ Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryK
|
|
|
76
78
|
```ts
|
|
77
79
|
import type { M365Connection } from "@dxv-systems/mail-graph/setup";
|
|
78
80
|
import type {
|
|
81
|
+
DistillState,
|
|
79
82
|
DraftRunStatus,
|
|
80
83
|
HistoryState,
|
|
81
84
|
MessageDirection,
|
|
@@ -114,6 +117,8 @@ export const helpdeskSettings = pgTable(
|
|
|
114
117
|
syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
|
|
115
118
|
/** Lease of the history cron, apart from the sync's, so neither waits for the other. */
|
|
116
119
|
historyLeaseUntil: timestamp("history_lease_until", { withTimezone: true }),
|
|
120
|
+
/** Lease of the FAQ distill cron, apart from the others. */
|
|
121
|
+
distillLeaseUntil: timestamp("distill_lease_until", { withTimezone: true }),
|
|
117
122
|
updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }),
|
|
118
123
|
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
|
119
124
|
},
|
|
@@ -142,6 +147,13 @@ export const helpdeskHistoryStates = pgTable("helpdesk_history_states", {
|
|
|
142
147
|
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
|
143
148
|
});
|
|
144
149
|
|
|
150
|
+
/** FAQ distillation per mailbox (`DistillState`): Sent Items cursors, pending pairs and the open run, in one value. */
|
|
151
|
+
export const helpdeskDistillStates = pgTable("helpdesk_distill_states", {
|
|
152
|
+
mailbox: varchar("mailbox", { length: 320 }).primaryKey(),
|
|
153
|
+
state: jsonb("state").$type<DistillState>().notNull(),
|
|
154
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
|
155
|
+
});
|
|
156
|
+
|
|
145
157
|
/** Tickets (`Thread`), plus the inbox's assignment (app data). */
|
|
146
158
|
export const helpdeskThreads = pgTable(
|
|
147
159
|
"helpdesk_threads",
|
|
@@ -286,7 +298,7 @@ export const helpdeskReplyAttachments = pgTable(
|
|
|
286
298
|
);
|
|
287
299
|
```
|
|
288
300
|
|
|
289
|
-
Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (
|
|
301
|
+
Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (ten `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5). An app on helpdesk 0.11 upgrades with one generated migration: the table `helpdesk_history_states` and `history_lease_until` on `helpdesk_settings`, nothing dropped (see the helpdesk README, Upgrading from 0.11). An app on helpdesk 0.13 upgrades with one generated migration: the table `helpdesk_distill_states` and `distill_lease_until` on `helpdesk_settings`, nothing dropped; then add the store methods, `claimDistillLease`, the distiller in `deps.ts`, the distill cron and the settings card below (see the helpdesk README, Upgrading from 0.13.0).
|
|
290
302
|
|
|
291
303
|
## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
|
|
292
304
|
|
|
@@ -449,6 +461,7 @@ export function isCronRequest(request: Request): boolean {
|
|
|
449
461
|
import "server-only";
|
|
450
462
|
import { and, asc, desc, eq, gte, inArray, lt } from "drizzle-orm";
|
|
451
463
|
import type {
|
|
464
|
+
DistillState,
|
|
452
465
|
DraftRun,
|
|
453
466
|
HelpdeskStore,
|
|
454
467
|
HistoryState,
|
|
@@ -460,6 +473,7 @@ import type {
|
|
|
460
473
|
} from "@dxv-systems/helpdesk";
|
|
461
474
|
import { db, type DbClient } from "@/lib/db";
|
|
462
475
|
import {
|
|
476
|
+
helpdeskDistillStates,
|
|
463
477
|
helpdeskDraftRuns,
|
|
464
478
|
helpdeskHistoryStates,
|
|
465
479
|
helpdeskMessages,
|
|
@@ -637,6 +651,22 @@ export const helpdeskStore: HelpdeskStore = {
|
|
|
637
651
|
.onConflictDoUpdate({ target: helpdeskHistoryStates.mailbox, set: { state, updatedAt: new Date() } });
|
|
638
652
|
},
|
|
639
653
|
|
|
654
|
+
async getDistillState(mailbox): Promise<DistillState | null> {
|
|
655
|
+
const [row] = await db
|
|
656
|
+
.select({ state: helpdeskDistillStates.state })
|
|
657
|
+
.from(helpdeskDistillStates)
|
|
658
|
+
.where(eq(helpdeskDistillStates.mailbox, mailbox))
|
|
659
|
+
.limit(1);
|
|
660
|
+
return row?.state ?? null;
|
|
661
|
+
},
|
|
662
|
+
|
|
663
|
+
async saveDistillState(mailbox, state) {
|
|
664
|
+
await db
|
|
665
|
+
.insert(helpdeskDistillStates)
|
|
666
|
+
.values({ mailbox, state })
|
|
667
|
+
.onConflictDoUpdate({ target: helpdeskDistillStates.mailbox, set: { state, updatedAt: new Date() } });
|
|
668
|
+
},
|
|
669
|
+
|
|
640
670
|
async getMessage(mailbox, id) {
|
|
641
671
|
const [row] = await db
|
|
642
672
|
.select()
|
|
@@ -1148,17 +1178,41 @@ export async function claimHistoryLease(ms: number): Promise<boolean> {
|
|
|
1148
1178
|
export async function releaseHistoryLease(): Promise<void> {
|
|
1149
1179
|
await db.update(helpdeskSettings).set({ historyLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
|
|
1150
1180
|
}
|
|
1181
|
+
|
|
1182
|
+
/** Claims the FAQ distill cron's lease, the same way. */
|
|
1183
|
+
export async function claimDistillLease(ms: number): Promise<boolean> {
|
|
1184
|
+
await db.insert(helpdeskSettings).values({ id: 1 }).onConflictDoNothing();
|
|
1185
|
+
const now = new Date();
|
|
1186
|
+
const claimed = await db
|
|
1187
|
+
.update(helpdeskSettings)
|
|
1188
|
+
.set({ distillLeaseUntil: new Date(now.getTime() + ms) })
|
|
1189
|
+
.where(
|
|
1190
|
+
and(
|
|
1191
|
+
eq(helpdeskSettings.id, 1),
|
|
1192
|
+
or(isNull(helpdeskSettings.distillLeaseUntil), lt(helpdeskSettings.distillLeaseUntil, now)),
|
|
1193
|
+
),
|
|
1194
|
+
)
|
|
1195
|
+
.returning({ id: helpdeskSettings.id });
|
|
1196
|
+
return claimed.length > 0;
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
export async function releaseDistillLease(): Promise<void> {
|
|
1200
|
+
await db.update(helpdeskSettings).set({ distillLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
|
|
1201
|
+
}
|
|
1151
1202
|
```
|
|
1152
1203
|
|
|
1153
1204
|
**No drafter yet.** `HelpdeskDeps.drafter` is optional and left out: every new customer mail opens its ticket in review (`reviewReason: "no_draft"`, label "Zelf antwoorden") with an empty "Jouw antwoord" box. Staff write the reply; saving it creates a staff run (an ordinary draft run with `text: null`, `reason: "staff"`), and "Goedkeuren en versturen" saves and sends it. A blank reply is refused (422 `empty_reply`). When the DXV AI gateway drafter is published, add it as `drafter` in `deps.ts` (its `start` calls the published agent with the idempotency key) and call `completeDraft` when it reports; nothing else changes.
|
|
1154
1205
|
|
|
1155
1206
|
`src/lib/helpdesk/deps.ts`: one `HelpdeskDeps` per call, built from the stored connection. The notifier sends in-app notifications (template `notifyUsers`) to everyone with `helpdesk:use`, linking to the ticket. That matches this recipe's `getStaff`, where every helpdesk user has access to every connected mailbox; an app with access per person sends each event only to the people with access to `event.mailbox` (helpdesk README, Access per mailbox). `assigned` goes to the assignee only, with the internal note.
|
|
1156
1207
|
|
|
1208
|
+
The distiller starts and reads runs of the gateway feature `helpdesk.faq-distill` (`createRuns` from the template's `@/lib/ai`). DXV registers that feature for the app in the Portal, pointing to the platform agent `klantenservice-faq`. Until then a run start fails, the card shows the error and the pairs wait; nothing else is affected.
|
|
1209
|
+
|
|
1157
1210
|
```ts
|
|
1158
1211
|
import "server-only";
|
|
1159
1212
|
import { inArray } from "drizzle-orm";
|
|
1160
|
-
import type { HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
|
|
1213
|
+
import type { Distiller, HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
|
|
1161
1214
|
import { activeScope } from "@dxv-systems/mail-graph/setup";
|
|
1215
|
+
import { createRuns } from "@/lib/ai";
|
|
1162
1216
|
import { rolesWithPermission } from "@/lib/auth/permissions";
|
|
1163
1217
|
import { db } from "@/lib/db";
|
|
1164
1218
|
import { users } from "@/lib/db/schema";
|
|
@@ -1221,6 +1275,18 @@ const notifier: Notifier = {
|
|
|
1221
1275
|
},
|
|
1222
1276
|
};
|
|
1223
1277
|
|
|
1278
|
+
/** FAQ distillation runs (agent `klantenservice-faq`). Created per call, so a missing AI setup fails only the run start. */
|
|
1279
|
+
const distiller: Distiller = {
|
|
1280
|
+
async fire(input, { eventKey }) {
|
|
1281
|
+
const { id } = await createRuns({ feature: "helpdesk.faq-distill" }).fireRun(input, { eventKey });
|
|
1282
|
+
return { runId: String(id) };
|
|
1283
|
+
},
|
|
1284
|
+
async read(runId) {
|
|
1285
|
+
const run = await createRuns({ feature: "helpdesk.faq-distill" }).getRun(runId);
|
|
1286
|
+
return { status: run.status, ...(run.error ? { error: run.error } : {}) };
|
|
1287
|
+
},
|
|
1288
|
+
};
|
|
1289
|
+
|
|
1224
1290
|
/** The app's own sender (EMAIL_FROM): its mail is never a ticket. */
|
|
1225
1291
|
function ownAddresses(): string[] {
|
|
1226
1292
|
const from = process.env.EMAIL_FROM?.trim();
|
|
@@ -1244,6 +1310,7 @@ export async function getHelpdeskDeps(): Promise<HelpdeskDeps | null> {
|
|
|
1244
1310
|
controls: loadHelpdeskControls,
|
|
1245
1311
|
notifier,
|
|
1246
1312
|
attachments: helpdeskReplyFiles,
|
|
1313
|
+
distiller,
|
|
1247
1314
|
};
|
|
1248
1315
|
}
|
|
1249
1316
|
```
|
|
@@ -1333,6 +1400,7 @@ import {
|
|
|
1333
1400
|
isPaused,
|
|
1334
1401
|
isSyncFailing,
|
|
1335
1402
|
reconcileUnknownSends,
|
|
1403
|
+
runDistill,
|
|
1336
1404
|
runHistory,
|
|
1337
1405
|
sweepStuckDrafts,
|
|
1338
1406
|
syncMailbox,
|
|
@@ -1342,7 +1410,14 @@ import { db } from "@/lib/db";
|
|
|
1342
1410
|
import { helpdeskHistoryStates, helpdeskSyncStates } from "@/lib/db/schema";
|
|
1343
1411
|
import { notifyUsers } from "@/lib/notifications/service";
|
|
1344
1412
|
import { getHelpdeskDeps } from "./deps";
|
|
1345
|
-
import {
|
|
1413
|
+
import {
|
|
1414
|
+
claimDistillLease,
|
|
1415
|
+
claimHistoryLease,
|
|
1416
|
+
claimSyncLease,
|
|
1417
|
+
releaseDistillLease,
|
|
1418
|
+
releaseHistoryLease,
|
|
1419
|
+
releaseSyncLease,
|
|
1420
|
+
} from "./settings";
|
|
1346
1421
|
|
|
1347
1422
|
/** Longer than the cron route's maxDuration, so a dead run's lease expires on its own. */
|
|
1348
1423
|
const SYNC_LEASE_MS = 6 * 60_000;
|
|
@@ -1354,7 +1429,7 @@ export async function onHelpdeskConnected(connection: M365Connection): Promise<v
|
|
|
1354
1429
|
for (const mailbox of connection.mailboxes) await connectMailbox(deps, mailbox);
|
|
1355
1430
|
}
|
|
1356
1431
|
|
|
1357
|
-
/** Setup `onReset`: forget delta and history positions; tickets stay. Tells the admin who reset. */
|
|
1432
|
+
/** Setup `onReset`: forget delta and history positions; tickets and distill states stay. Tells the admin who reset. */
|
|
1358
1433
|
export async function onHelpdeskReset(adminId: number | null): Promise<void> {
|
|
1359
1434
|
await db.delete(helpdeskSyncStates);
|
|
1360
1435
|
await db.delete(helpdeskHistoryStates);
|
|
@@ -1419,6 +1494,28 @@ export async function runHelpdeskHistory(): Promise<HelpdeskSyncOutcome> {
|
|
|
1419
1494
|
await releaseHistoryLease();
|
|
1420
1495
|
}
|
|
1421
1496
|
}
|
|
1497
|
+
|
|
1498
|
+
/** Cron: FAQ distillation into the kennisbank (off until started per mailbox), one run at a time, apart from the others. */
|
|
1499
|
+
export async function runHelpdeskDistill(): Promise<HelpdeskSyncOutcome> {
|
|
1500
|
+
const deps = await getHelpdeskDeps();
|
|
1501
|
+
if (!deps) return "not_connected";
|
|
1502
|
+
if (!(await claimDistillLease(SYNC_LEASE_MS))) return "busy";
|
|
1503
|
+
try {
|
|
1504
|
+
for (const mailbox of deps.config.connectedMailboxes) {
|
|
1505
|
+
const result = await runDistill(deps, mailbox);
|
|
1506
|
+
if (isPaused(result)) return "paused";
|
|
1507
|
+
if (result.status === "throttled") {
|
|
1508
|
+
console.warn("helpdesk distill: Microsoft asked to wait", { mailbox, retryAfter: result.retryAfter, error: result.error });
|
|
1509
|
+
}
|
|
1510
|
+
if (result.status === "ran" && result.round.error) {
|
|
1511
|
+
console.warn("helpdesk distill: run problem", { mailbox, error: result.round.error });
|
|
1512
|
+
}
|
|
1513
|
+
}
|
|
1514
|
+
return "done";
|
|
1515
|
+
} finally {
|
|
1516
|
+
await releaseDistillLease();
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1422
1519
|
```
|
|
1423
1520
|
|
|
1424
1521
|
`src/lib/helpdesk/queries.ts` (guarded reads for the pages)
|
|
@@ -1434,7 +1531,7 @@ export async function getHelpdeskSettingsForAdmin(): Promise<HelpdeskSettingsVie
|
|
|
1434
1531
|
return readHelpdeskSettings();
|
|
1435
1532
|
}
|
|
1436
1533
|
|
|
1437
|
-
/** The mailboxes whose history import the settings page shows: the connected ones the routes serve. */
|
|
1534
|
+
/** The mailboxes whose history import and FAQ distillation the settings page shows: the connected ones the routes serve. */
|
|
1438
1535
|
export async function getHistoryMailboxesForAdmin(): Promise<string[]> {
|
|
1439
1536
|
await requirePermission("m365:manage");
|
|
1440
1537
|
return (await getHelpdeskDeps())?.config.connectedMailboxes ?? [];
|
|
@@ -1589,6 +1686,21 @@ export async function GET(request: Request): Promise<Response> {
|
|
|
1589
1686
|
}
|
|
1590
1687
|
```
|
|
1591
1688
|
|
|
1689
|
+
`src/app/api/cron/helpdesk-distill/route.ts`
|
|
1690
|
+
|
|
1691
|
+
```ts
|
|
1692
|
+
import { runHelpdeskDistill } from "@/lib/helpdesk/service";
|
|
1693
|
+
import { isCronRequest } from "@/lib/m365/cron";
|
|
1694
|
+
|
|
1695
|
+
export const maxDuration = 300;
|
|
1696
|
+
|
|
1697
|
+
/** FAQ distillation of the mailboxes where it was started; idle otherwise. */
|
|
1698
|
+
export async function GET(request: Request): Promise<Response> {
|
|
1699
|
+
if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
|
|
1700
|
+
return Response.json({ outcome: await runHelpdeskDistill() });
|
|
1701
|
+
}
|
|
1702
|
+
```
|
|
1703
|
+
|
|
1592
1704
|
`vercel.json`:
|
|
1593
1705
|
|
|
1594
1706
|
```json
|
|
@@ -1597,6 +1709,7 @@ export async function GET(request: Request): Promise<Response> {
|
|
|
1597
1709
|
"crons": [
|
|
1598
1710
|
{ "path": "/api/cron/helpdesk-sync", "schedule": "*/5 * * * *" },
|
|
1599
1711
|
{ "path": "/api/cron/helpdesk-history", "schedule": "2-59/5 * * * *" },
|
|
1712
|
+
{ "path": "/api/cron/helpdesk-distill", "schedule": "41 * * * *" },
|
|
1600
1713
|
{ "path": "/api/cron/m365-access", "schedule": "*/10 * * * *" }
|
|
1601
1714
|
]
|
|
1602
1715
|
}
|
|
@@ -1885,7 +1998,182 @@ export function MailHistorySettings({ mailboxes }: { mailboxes: string[] }) {
|
|
|
1885
1998
|
}
|
|
1886
1999
|
```
|
|
1887
2000
|
|
|
1888
|
-
|
|
2001
|
+
`src/components/helpdesk/mail-distill-settings.tsx` (the FAQ distillation per mailbox: it reads Sent Items and has the platform agent turn question and answer pairs into general answers in the kennisbank; the package works out the stage and the counts, the cron does the work, and nothing starts until an admin presses Starten):
|
|
2002
|
+
|
|
2003
|
+
```tsx
|
|
2004
|
+
"use client";
|
|
2005
|
+
|
|
2006
|
+
import { useEffect, useState } from "react";
|
|
2007
|
+
import { toast } from "sonner";
|
|
2008
|
+
import { createHelpdeskClient, HelpdeskClientError } from "@dxv-systems/helpdesk/client";
|
|
2009
|
+
import type { InboxDistill } from "@dxv-systems/helpdesk/server";
|
|
2010
|
+
import { Button } from "@/components/ui/button";
|
|
2011
|
+
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
2012
|
+
import { Input } from "@/components/ui/input";
|
|
2013
|
+
import { Label } from "@/components/ui/label";
|
|
2014
|
+
|
|
2015
|
+
const helpdesk = createHelpdeskClient();
|
|
2016
|
+
|
|
2017
|
+
const STAGE_LABELS: Record<InboxDistill["stage"], string> = {
|
|
2018
|
+
not_started: "Niet gestart",
|
|
2019
|
+
running: "Bezig met lezen",
|
|
2020
|
+
waiting: "Wacht op Microsoft",
|
|
2021
|
+
paused: "Gepauzeerd",
|
|
2022
|
+
done_backfill: "Historie gelezen. Nieuwe antwoorden komen er vanzelf bij.",
|
|
2023
|
+
};
|
|
2024
|
+
|
|
2025
|
+
const date = (iso: string) => new Date(iso).toLocaleDateString("nl-NL", { day: "numeric", month: "long", year: "numeric" });
|
|
2026
|
+
const time = (iso: string) => new Date(iso).toLocaleTimeString("nl-NL", { hour: "2-digit", minute: "2-digit" });
|
|
2027
|
+
const count = (n: number) => n.toLocaleString("nl-NL");
|
|
2028
|
+
|
|
2029
|
+
/** yyyy-mm-dd, 3 years back: the package's default start. */
|
|
2030
|
+
function defaultSince(): string {
|
|
2031
|
+
const d = new Date();
|
|
2032
|
+
d.setFullYear(d.getFullYear() - 3);
|
|
2033
|
+
return d.toISOString().slice(0, 10);
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
function errorText(error: unknown): string {
|
|
2037
|
+
if (error instanceof HelpdeskClientError && error.status === 403) {
|
|
2038
|
+
return "Je hebt zelf geen toegang tot deze mailbox. Geef jezelf toegang om dit te zien en te starten.";
|
|
2039
|
+
}
|
|
2040
|
+
if (error instanceof HelpdeskClientError && error.status === 400) return "Kies een startdatum in het verleden.";
|
|
2041
|
+
return error instanceof HelpdeskClientError ? error.message : "De stand kon niet worden geladen. Probeer het opnieuw.";
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
function MailboxDistill({ mailbox }: { mailbox: string }) {
|
|
2045
|
+
const [distill, setDistill] = useState<InboxDistill | null>(null);
|
|
2046
|
+
const [since, setSince] = useState("");
|
|
2047
|
+
const [error, setError] = useState<string | null>(null);
|
|
2048
|
+
const [busy, setBusy] = useState(false);
|
|
2049
|
+
|
|
2050
|
+
useEffect(() => {
|
|
2051
|
+
let live = true;
|
|
2052
|
+
const load = () =>
|
|
2053
|
+
helpdesk.distill(mailbox).then(
|
|
2054
|
+
(d) => {
|
|
2055
|
+
if (!live) return;
|
|
2056
|
+
setDistill(d);
|
|
2057
|
+
setSince((current) => current || defaultSince());
|
|
2058
|
+
setError(null);
|
|
2059
|
+
},
|
|
2060
|
+
(e: unknown) => {
|
|
2061
|
+
if (live) setError(errorText(e));
|
|
2062
|
+
},
|
|
2063
|
+
);
|
|
2064
|
+
void load();
|
|
2065
|
+
// The cron works once an hour: refresh the counts while the page is open.
|
|
2066
|
+
const timer = window.setInterval(() => void load(), 60_000);
|
|
2067
|
+
return () => {
|
|
2068
|
+
live = false;
|
|
2069
|
+
window.clearInterval(timer);
|
|
2070
|
+
};
|
|
2071
|
+
}, [mailbox]);
|
|
2072
|
+
|
|
2073
|
+
async function run(action: "start" | "pause") {
|
|
2074
|
+
setBusy(true);
|
|
2075
|
+
try {
|
|
2076
|
+
const first = distill?.stage === "not_started";
|
|
2077
|
+
setDistill(
|
|
2078
|
+
action === "start"
|
|
2079
|
+
? await helpdesk.startDistill(mailbox, first ? { since } : {})
|
|
2080
|
+
: await helpdesk.pauseDistill(mailbox),
|
|
2081
|
+
);
|
|
2082
|
+
toast.success(action === "start" ? "Het lezen loopt. De eerste antwoorden gaan binnen een uur naar de kennisbank." : "Gepauzeerd.");
|
|
2083
|
+
} catch (e) {
|
|
2084
|
+
toast.error(errorText(e));
|
|
2085
|
+
} finally {
|
|
2086
|
+
setBusy(false);
|
|
2087
|
+
}
|
|
2088
|
+
}
|
|
2089
|
+
|
|
2090
|
+
const inputId = `distill-since-${mailbox}`;
|
|
2091
|
+
return (
|
|
2092
|
+
<Card>
|
|
2093
|
+
<CardHeader>
|
|
2094
|
+
<CardTitle className="break-all">{mailbox}</CardTitle>
|
|
2095
|
+
<CardDescription>
|
|
2096
|
+
Leest de antwoorden die vanuit deze mailbox zijn verstuurd, met de vraag van de klant ervoor, ook uit Archief en
|
|
2097
|
+
eigen mappen. Een agent maakt daar algemene antwoorden van in de kennisbank (klantenservice/faq), zonder namen of
|
|
2098
|
+
persoonsgegevens. Alleen lezen: in Outlook verandert niets.
|
|
2099
|
+
</CardDescription>
|
|
2100
|
+
</CardHeader>
|
|
2101
|
+
<CardContent className="space-y-4 text-sm">
|
|
2102
|
+
{error && <p className="text-muted-foreground">{error}</p>}
|
|
2103
|
+
{!error && !distill && <p className="text-muted-foreground">Laden…</p>}
|
|
2104
|
+
{!error && distill && !distill.supported && (
|
|
2105
|
+
<p className="text-muted-foreground">De kennisbank vullen uit mailhistorie is voor deze mailbox niet beschikbaar.</p>
|
|
2106
|
+
)}
|
|
2107
|
+
{!error && distill?.supported && (
|
|
2108
|
+
<>
|
|
2109
|
+
<div className="space-y-1">
|
|
2110
|
+
<p className="font-medium">{STAGE_LABELS[distill.stage]}</p>
|
|
2111
|
+
{distill.retryAfter && (
|
|
2112
|
+
<p className="text-muted-foreground">
|
|
2113
|
+
Microsoft vraagt even te wachten. Het lezen gaat vanzelf verder na {time(distill.retryAfter)}.
|
|
2114
|
+
</p>
|
|
2115
|
+
)}
|
|
2116
|
+
{distill.since && <p className="text-muted-foreground">Vanaf {date(distill.since)}</p>}
|
|
2117
|
+
{distill.reachedBack && <p className="text-muted-foreground">Gelezen tot en met {date(distill.reachedBack)}</p>}
|
|
2118
|
+
{distill.runOpen && <p className="text-muted-foreground">De agent verwerkt nu een ronde.</p>}
|
|
2119
|
+
{distill.lastError && <p className="text-destructive">Laatste fout: {distill.lastError}</p>}
|
|
2120
|
+
</div>
|
|
2121
|
+
{distill.stage !== "not_started" && (
|
|
2122
|
+
<table className="w-full max-w-sm">
|
|
2123
|
+
<tbody>
|
|
2124
|
+
<tr className="border-t">
|
|
2125
|
+
<td className="py-1 pr-3">Vragen met antwoord in de kennisbank</td>
|
|
2126
|
+
<td className="py-1 text-right tabular-nums">{count(distill.pairsSent)}</td>
|
|
2127
|
+
</tr>
|
|
2128
|
+
<tr className="border-t">
|
|
2129
|
+
<td className="py-1 pr-3">Verwerkte rondes</td>
|
|
2130
|
+
<td className="py-1 text-right tabular-nums">{count(distill.runsSent)}</td>
|
|
2131
|
+
</tr>
|
|
2132
|
+
<tr className="border-t">
|
|
2133
|
+
<td className="py-1 pr-3">Klaar voor de volgende ronde</td>
|
|
2134
|
+
<td className="py-1 text-right tabular-nums">{count(distill.pendingPairs)}</td>
|
|
2135
|
+
</tr>
|
|
2136
|
+
</tbody>
|
|
2137
|
+
</table>
|
|
2138
|
+
)}
|
|
2139
|
+
{distill.stage === "not_started" && (
|
|
2140
|
+
<div className="max-w-xs space-y-2">
|
|
2141
|
+
<Label htmlFor={inputId}>Startdatum</Label>
|
|
2142
|
+
<Input id={inputId} type="date" value={since} onChange={(e) => setSince(e.target.value)} />
|
|
2143
|
+
</div>
|
|
2144
|
+
)}
|
|
2145
|
+
{(distill.stage === "not_started" || distill.stage === "paused") && (
|
|
2146
|
+
<Button size="sm" disabled={busy || (distill.stage === "not_started" && !since)} onClick={() => void run("start")}>
|
|
2147
|
+
{distill.stage === "paused" ? "Hervatten" : "Starten"}
|
|
2148
|
+
</Button>
|
|
2149
|
+
)}
|
|
2150
|
+
{(distill.stage === "running" || distill.stage === "waiting" || distill.stage === "done_backfill") && (
|
|
2151
|
+
<Button size="sm" variant="outline" disabled={busy} onClick={() => void run("pause")}>
|
|
2152
|
+
Pauzeren
|
|
2153
|
+
</Button>
|
|
2154
|
+
)}
|
|
2155
|
+
</>
|
|
2156
|
+
)}
|
|
2157
|
+
</CardContent>
|
|
2158
|
+
</Card>
|
|
2159
|
+
);
|
|
2160
|
+
}
|
|
2161
|
+
|
|
2162
|
+
/** One card per connected mailbox; nothing when there is none. */
|
|
2163
|
+
export function MailDistillSettings({ mailboxes }: { mailboxes: string[] }) {
|
|
2164
|
+
if (mailboxes.length === 0) return null;
|
|
2165
|
+
return (
|
|
2166
|
+
<section className="space-y-4">
|
|
2167
|
+
<h2 className="text-lg font-semibold">Kennisbank vullen uit mailhistorie</h2>
|
|
2168
|
+
{mailboxes.map((mailbox) => (
|
|
2169
|
+
<MailboxDistill key={mailbox} mailbox={mailbox} />
|
|
2170
|
+
))}
|
|
2171
|
+
</section>
|
|
2172
|
+
);
|
|
2173
|
+
}
|
|
2174
|
+
```
|
|
2175
|
+
|
|
2176
|
+
Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode, the history import and the FAQ distillation; admins only, linked from the inbox and the setup page):
|
|
1889
2177
|
|
|
1890
2178
|
```tsx
|
|
1891
2179
|
import type { Metadata } from "next";
|
|
@@ -1894,6 +2182,7 @@ import { requirePermission } from "@/lib/auth/dal";
|
|
|
1894
2182
|
import { getHelpdeskSettingsForAdmin, getHistoryMailboxesForAdmin } from "@/lib/helpdesk/queries";
|
|
1895
2183
|
import { PageHeader } from "@/components/app/page-header";
|
|
1896
2184
|
import { HelpdeskSettingsForm } from "@/components/helpdesk/helpdesk-settings-form";
|
|
2185
|
+
import { MailDistillSettings } from "@/components/helpdesk/mail-distill-settings";
|
|
1897
2186
|
import { MailHistorySettings } from "@/components/helpdesk/mail-history-settings";
|
|
1898
2187
|
|
|
1899
2188
|
export const metadata: Metadata = { title: "Helpdesk-instellingen" };
|
|
@@ -1906,6 +2195,7 @@ export default async function HelpdeskSettingsPage() {
|
|
|
1906
2195
|
<PageHeader title="Helpdesk-instellingen" />
|
|
1907
2196
|
<HelpdeskSettingsForm paused={settings.paused} />
|
|
1908
2197
|
<MailHistorySettings mailboxes={historyMailboxes} />
|
|
2198
|
+
<MailDistillSettings mailboxes={historyMailboxes} />
|
|
1909
2199
|
</div>
|
|
1910
2200
|
);
|
|
1911
2201
|
}
|
|
@@ -2226,6 +2516,30 @@ describe("helpdesk store on Postgres", () => {
|
|
|
2226
2516
|
expect(await helpdeskStore.getSyncState(MAILBOX)).toEqual(sync);
|
|
2227
2517
|
});
|
|
2228
2518
|
|
|
2519
|
+
it("keeps the distill state as one value per mailbox", async () => {
|
|
2520
|
+
const at = "2026-11-01T00:00:00.000Z";
|
|
2521
|
+
const distill = {
|
|
2522
|
+
since: "2023-11-01T00:00:00.000Z",
|
|
2523
|
+
startedAt: at,
|
|
2524
|
+
pausedAt: null,
|
|
2525
|
+
retryAfter: null,
|
|
2526
|
+
lastError: null,
|
|
2527
|
+
lastRunAt: null,
|
|
2528
|
+
backfill: { link: null, oldest: null, doneAt: null },
|
|
2529
|
+
forward: { after: { at, ids: [] }, link: null, reached: null, top: null },
|
|
2530
|
+
pending: [{ kind: "reply" as const, channel: "email" as const, question: "Vraag", answer: "Antwoord", answeredAt: "2026-10-01" }],
|
|
2531
|
+
unfiredBatch: null,
|
|
2532
|
+
openRun: null,
|
|
2533
|
+
lastFiredAt: null,
|
|
2534
|
+
firedToday: { day: "2026-11-01", runs: 0 },
|
|
2535
|
+
totals: { runs: 0, pairs: 0 },
|
|
2536
|
+
};
|
|
2537
|
+
expect(await helpdeskStore.getDistillState!(MAILBOX)).toBeNull();
|
|
2538
|
+
await helpdeskStore.saveDistillState!(MAILBOX, distill);
|
|
2539
|
+
await helpdeskStore.saveDistillState!(MAILBOX, { ...distill, pausedAt: at });
|
|
2540
|
+
expect(await helpdeskStore.getDistillState!(MAILBOX)).toEqual({ ...distill, pausedAt: at });
|
|
2541
|
+
});
|
|
2542
|
+
|
|
2229
2543
|
it("lists conversations by folder with unread, preview and search, and counts unread", async () => {
|
|
2230
2544
|
mailbox.deliver({ id: "m9", from: "trap@example.test", fromName: "Trap & Co", subject: "Leuning 50%", conversationId: "c9", receivedDateTime: soon(9_000), bodyText: "Graag een offerte" });
|
|
2231
2545
|
await syncMailbox(deps, MAILBOX);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxv-systems/mail-graph",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.2",
|
|
4
4
|
"description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dxv",
|