@dxv-systems/mail-graph 0.1.1 → 0.1.3
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/README.md +1 -1
- package/dist/setup/handlers.js +10 -6
- package/dist/setup/messages.d.ts +2 -1
- package/dist/setup/messages.js +5 -1
- package/dist/setup/react.js +27 -2
- package/dist/setup/types.d.ts +1 -0
- package/docs/app-integration.md +1814 -0
- package/package.json +3 -2
|
@@ -0,0 +1,1814 @@
|
|
|
1
|
+
# Microsoft 365 helpdesk: app integration recipe
|
|
2
|
+
|
|
3
|
+
For a coding agent adding the Microsoft 365 helpdesk to an app built on `company-app-template`. Apply it exactly. All logic lives in `@dxv-systems/mail-graph` (Graph client, guided setup) and `@dxv-systems/helpdesk` (tickets, drafting, sending, staff inbox); the app adds a thin, fixed layer: tables, adapters, two catch-all routes, three pages, two crons. Read the package READMEs ("Guided Microsoft 365 setup", "Pilot controls", "Inbox UI") once; this recipe does not repeat them.
|
|
4
|
+
|
|
5
|
+
This recipe ships inside the package: after step 1 it is at `node_modules/@dxv-systems/mail-graph/docs/app-integration.md` (from 0.1.2 on), so an agent working in the app's repository can read it without access to dxv-packages.
|
|
6
|
+
|
|
7
|
+
The code below was compiled, linted, knip-checked, built and tested against a fresh `company-app-template` app. If a step does not fit the app (a template file has drifted), adapt that step minimally and say so in the PR; do not change the packages.
|
|
8
|
+
|
|
9
|
+
## Rules
|
|
10
|
+
|
|
11
|
+
- **Production only.** Microsoft 365 is off unless `VERCEL_ENV=production` and `M365_CLIENT_ID` and `APP_URL` are set (`readM365Env()`). While off, every page renders a "not enabled" card and the routes answer `503 not_configured`; nothing crashes and no Graph call is made. Previews and staging never reach a client tenant.
|
|
12
|
+
- **Admin only for setup:** permission `m365:manage` (admins). **Staff only for the inbox:** permission `helpdesk:use` (managers and admins). Code checks permissions, never roles.
|
|
13
|
+
- **The helpdesk runs only while the connection is `connected`** (`getHelpdeskDeps()` returns null otherwise). The scope is exactly the connected mailboxes.
|
|
14
|
+
- **One way of working:** a person approves each reply in the helpdesk, and the helpdesk then sends it from the mailbox (`writeMode: "approve_and_send"`). Nothing reaches Outlook before that approval. The only switch is `paused` (kill switch, default off) in `helpdesk_settings`, edited on the admin page; it applies on the next call, no redeploy.
|
|
15
|
+
- Never call Graph or the helpdesk functions anywhere else than the files below. UI never imports `@/lib/db` (ESLint).
|
|
16
|
+
|
|
17
|
+
## 1. Install
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
npm install --save-exact @dxv-systems/mail-graph@0.1.3 @dxv-systems/helpdesk@0.3.0 @vercel/oidc@4.0.1
|
|
21
|
+
```
|
|
22
|
+
|
|
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
|
+
|
|
25
|
+
`@vercel/oidc` is already in the lockfile through `@dxv-systems/ai`; pin the same version so it is not duplicated.
|
|
26
|
+
|
|
27
|
+
## 2. Environment
|
|
28
|
+
|
|
29
|
+
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.
|
|
30
|
+
|
|
31
|
+
| Variable | Value | Provided by |
|
|
32
|
+
|---|---|---|
|
|
33
|
+
| `M365_CLIENT_ID` | The app's Entra app client id. | DXV's infrastructure, once the helpdesk is switched on (production only; setting it also rebuilds production). Never set by hand. |
|
|
34
|
+
| `M365_SETUP_READY` | `"true"` once DXV has publisher verified the app's Entra app, else `"false"`. Until then the setup page says DXV is preparing it and offers no sign-in, so the client's admin never sees "unverified" on Microsoft's consent screen. Sync, checks and a made connection ignore it. | DXV's infrastructure, at the same time (production only). Never set by hand. |
|
|
35
|
+
| `CRON_SECRET` | Authenticates the cron routes (Vercel Cron sends `Authorization: Bearer <CRON_SECRET>`). | DXV's infrastructure (generated, production). Switching the helpdesk on in the Portal includes it. Without it the crons answer 401 and nothing syncs. |
|
|
36
|
+
| `SESSION_SECRET` | Existing. The setup's signing key (consent `state`, IT links) is derived from it with HKDF-SHA256 (`dxv-m365-setup/v1`), so there is no setup secret to provision. Rotating it voids open IT links and pending consents (and signs everyone out, as before). | DXV's infrastructure (every template app has it). |
|
|
37
|
+
| `APP_URL` | Production origin; the consent redirect URI is built on it. DXV's infrastructure registers the redirect URI from the same value, so the two cannot differ; a custom domain is one change, to that `APP_URL`. | DXV's infrastructure (already set for template apps). |
|
|
38
|
+
| `EMAIL_FROM` | Optional; its address is treated as the app's own (never a ticket). | Already set for template apps. |
|
|
39
|
+
|
|
40
|
+
The only new variables are `M365_CLIENT_ID` and `M365_SETUP_READY`. The Graph sign-in uses the Vercel OIDC token of the production deployment as client assertion: the federated credential DXV's infrastructure creates accepts the default Vercel audience `https://vercel.com/<team-slug>`, which is what `getVercelOidcToken()` returns. Nothing else to configure.
|
|
41
|
+
|
|
42
|
+
Append to `.env.example`:
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
46
|
+
# Microsoft 365 helpdesk (@dxv-systems/mail-graph, @dxv-systems/helpdesk)
|
|
47
|
+
# ─────────────────────────────────────────────────────────────────────────────
|
|
48
|
+
# Production only; everything stays off (pages say so) until this is set.
|
|
49
|
+
# The app's Entra app, set by DXV's infrastructure. Never by hand. The setup's
|
|
50
|
+
# signing key is derived from SESSION_SECRET (src/lib/m365/config.ts).
|
|
51
|
+
# M365_CLIENT_ID=""
|
|
52
|
+
# "true" once DXV has verified that Entra app; the setup page waits for it.
|
|
53
|
+
# M365_SETUP_READY=""
|
|
54
|
+
# Authenticates the cron routes (Vercel sends it as a Bearer token);
|
|
55
|
+
# DXV's infrastructure generates it.
|
|
56
|
+
# CRON_SECRET=""
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## 3. Permissions — `src/lib/auth/permissions.ts`
|
|
60
|
+
|
|
61
|
+
Add to `PERMISSIONS` (after `"diagnostics:run"`):
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
/** Connect Microsoft 365 (guided setup) and pause the helpdesk. */
|
|
65
|
+
"m365:manage",
|
|
66
|
+
/** Work in the helpdesk inbox: read, edit, send and close tickets. */
|
|
67
|
+
"helpdesk:use",
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Grant `"helpdesk:use"` in `MANAGER_PERMISSIONS` (first entry after the spread) and `"m365:manage"` at the end of `ADMIN_PERMISSIONS`. Do not grant either to employees: the template's `permissions.test.ts` asserts employees hold no permission.
|
|
71
|
+
|
|
72
|
+
## 4. Schema and migration — `src/lib/db/schema.ts`
|
|
73
|
+
|
|
74
|
+
Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryKey, uniqueIndex`, and add these type imports below it:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import type { M365Connection } from "@dxv-systems/mail-graph/setup";
|
|
78
|
+
import type {
|
|
79
|
+
DraftRunStatus,
|
|
80
|
+
MessageDirection,
|
|
81
|
+
NoiseReason,
|
|
82
|
+
ReviewReason,
|
|
83
|
+
SendStatus,
|
|
84
|
+
TicketState,
|
|
85
|
+
} from "@dxv-systems/helpdesk";
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
Append at the end of the file:
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
// ─── Microsoft 365 and helpdesk (value lists owned by the packages: typed text, no enums) ───
|
|
92
|
+
|
|
93
|
+
/** The single Microsoft 365 connection (id = 1), the setup's `M365Connection`. */
|
|
94
|
+
export const m365Connection = pgTable(
|
|
95
|
+
"m365_connection",
|
|
96
|
+
{
|
|
97
|
+
id: integer("id").primaryKey().default(1),
|
|
98
|
+
data: jsonb("data").$type<M365Connection>().notNull(),
|
|
99
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
|
100
|
+
},
|
|
101
|
+
(table) => [check("m365_connection_singleton", sql`${table.id} = 1`)],
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
/** Helpdesk switches (id = 1), read on every helpdesk call. No row = defaults. */
|
|
105
|
+
export const helpdeskSettings = pgTable(
|
|
106
|
+
"helpdesk_settings",
|
|
107
|
+
{
|
|
108
|
+
id: integer("id").primaryKey().default(1),
|
|
109
|
+
/** Kill switch: no sync, drafting, sending or Graph call at all. */
|
|
110
|
+
paused: boolean("paused").notNull().default(false),
|
|
111
|
+
/** Lease of the sync cron: a run starts only when this is null or past. */
|
|
112
|
+
syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
|
|
113
|
+
updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }),
|
|
114
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
|
|
115
|
+
},
|
|
116
|
+
(table) => [check("helpdesk_settings_singleton", sql`${table.id} = 1`)],
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
/** Delta sync position per connected mailbox (`SyncState`). */
|
|
120
|
+
export const helpdeskSyncStates = pgTable("helpdesk_sync_states", {
|
|
121
|
+
mailbox: varchar("mailbox", { length: 320 }).primaryKey(),
|
|
122
|
+
link: text("link"),
|
|
123
|
+
connectedAt: timestamp("connected_at", { withTimezone: true }).notNull(),
|
|
124
|
+
lastReceivedAt: timestamp("last_received_at", { withTimezone: true }),
|
|
125
|
+
/** Sent Items delta position, next to the Inbox's. */
|
|
126
|
+
sentLink: text("sent_link"),
|
|
127
|
+
sentLastReceivedAt: timestamp("sent_last_received_at", { withTimezone: true }),
|
|
128
|
+
/** Microsoft unreachable since (first failed sync of a run of failures); null when syncing works. */
|
|
129
|
+
failingSince: timestamp("failing_since", { withTimezone: true }),
|
|
130
|
+
failures: integer("failures").notNull().default(0),
|
|
131
|
+
lastError: text("last_error"),
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
/** Tickets (`Thread`), plus the inbox's assignment (app data). */
|
|
135
|
+
export const helpdeskThreads = pgTable(
|
|
136
|
+
"helpdesk_threads",
|
|
137
|
+
{
|
|
138
|
+
id: text("id").primaryKey(),
|
|
139
|
+
mailbox: varchar("mailbox", { length: 320 }).notNull(),
|
|
140
|
+
state: text("state").$type<TicketState>().notNull(),
|
|
141
|
+
subjectKey: text("subject_key").notNull(),
|
|
142
|
+
subject: text("subject").notNull(),
|
|
143
|
+
customerAddress: varchar("customer_address", { length: 320 }).notNull(),
|
|
144
|
+
participants: text("participants").array().notNull(),
|
|
145
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
146
|
+
lastActivityAt: timestamp("last_activity_at", { withTimezone: true }).notNull(),
|
|
147
|
+
latestInboundId: text("latest_inbound_id"),
|
|
148
|
+
reviewReason: text("review_reason").$type<ReviewReason>(),
|
|
149
|
+
autoReplyCount: integer("auto_reply_count").notNull().default(0),
|
|
150
|
+
relatedThreadId: text("related_thread_id").references((): AnyPgColumn => helpdeskThreads.id, {
|
|
151
|
+
onDelete: "set null",
|
|
152
|
+
}),
|
|
153
|
+
/** Staff id that marked "Geen antwoord nodig"; null when the noise filter ignored it. */
|
|
154
|
+
dismissedBy: text("dismissed_by"),
|
|
155
|
+
assigneeId: integer("assignee_id").references(() => users.id, { onDelete: "set null" }),
|
|
156
|
+
},
|
|
157
|
+
(table) => [
|
|
158
|
+
index("helpdesk_threads_activity_idx").on(table.lastActivityAt, table.id),
|
|
159
|
+
index("helpdesk_threads_subject_idx").on(table.mailbox, table.subjectKey, table.lastActivityAt),
|
|
160
|
+
],
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
/** Ingested mail (`StoredMessage`): metadata only, bodies stay in the mailbox. */
|
|
164
|
+
export const helpdeskMessages = pgTable(
|
|
165
|
+
"helpdesk_messages",
|
|
166
|
+
{
|
|
167
|
+
mailbox: varchar("mailbox", { length: 320 }).notNull(),
|
|
168
|
+
/** Immutable Graph id. */
|
|
169
|
+
id: text("id").notNull(),
|
|
170
|
+
threadId: text("thread_id")
|
|
171
|
+
.notNull()
|
|
172
|
+
.references(() => helpdeskThreads.id, { onDelete: "cascade" }),
|
|
173
|
+
internetMessageId: text("internet_message_id"),
|
|
174
|
+
conversationId: text("conversation_id"),
|
|
175
|
+
subject: text("subject").notNull(),
|
|
176
|
+
fromAddress: varchar("from_address", { length: 320 }).notNull(),
|
|
177
|
+
receivedAt: timestamp("received_at", { withTimezone: true }).notNull(),
|
|
178
|
+
noiseAction: text("noise_action").$type<"ignore" | "process">().notNull(),
|
|
179
|
+
noiseReason: text("noise_reason").$type<NoiseReason>().notNull(),
|
|
180
|
+
suppressAutoResponse: boolean("suppress_auto_response").notNull().default(false),
|
|
181
|
+
removedAt: timestamp("removed_at", { withTimezone: true }),
|
|
182
|
+
/** `outbound`: a reply synced from Sent Items (display only). */
|
|
183
|
+
direction: text("direction").$type<MessageDirection>().notNull().default("inbound"),
|
|
184
|
+
},
|
|
185
|
+
(table) => [
|
|
186
|
+
primaryKey({ columns: [table.mailbox, table.id] }),
|
|
187
|
+
index("helpdesk_messages_thread_idx").on(table.threadId, table.receivedAt),
|
|
188
|
+
index("helpdesk_messages_conversation_idx").on(table.mailbox, table.conversationId),
|
|
189
|
+
index("helpdesk_messages_internet_id_idx").on(table.mailbox, table.internetMessageId),
|
|
190
|
+
],
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
/** Draft runs (`DraftRun`), one per inbound message and generation. */
|
|
194
|
+
export const helpdeskDraftRuns = pgTable(
|
|
195
|
+
"helpdesk_draft_runs",
|
|
196
|
+
{
|
|
197
|
+
idempotencyKey: text("idempotency_key").primaryKey(),
|
|
198
|
+
/** Creation order: the latest run of a thread is the highest seq. */
|
|
199
|
+
seq: serial("seq").notNull(),
|
|
200
|
+
mailbox: varchar("mailbox", { length: 320 }).notNull(),
|
|
201
|
+
threadId: text("thread_id")
|
|
202
|
+
.notNull()
|
|
203
|
+
.references(() => helpdeskThreads.id, { onDelete: "cascade" }),
|
|
204
|
+
inboundMessageId: text("inbound_message_id").notNull(),
|
|
205
|
+
generation: integer("generation").notNull(),
|
|
206
|
+
status: text("status").$type<DraftRunStatus>().notNull(),
|
|
207
|
+
externalRunId: text("external_run_id"),
|
|
208
|
+
requestedAt: timestamp("requested_at", { withTimezone: true }).notNull(),
|
|
209
|
+
error: text("error"),
|
|
210
|
+
text: text("text"),
|
|
211
|
+
confidence: doublePrecision("confidence"),
|
|
212
|
+
reason: text("reason"),
|
|
213
|
+
category: text("category"),
|
|
214
|
+
placedDraftId: text("placed_draft_id"),
|
|
215
|
+
placedBodyHtml: text("placed_body_html"),
|
|
216
|
+
commentText: text("comment_text"),
|
|
217
|
+
},
|
|
218
|
+
(table) => [
|
|
219
|
+
uniqueIndex("helpdesk_draft_runs_generation_key").on(
|
|
220
|
+
table.mailbox,
|
|
221
|
+
table.inboundMessageId,
|
|
222
|
+
table.generation,
|
|
223
|
+
),
|
|
224
|
+
index("helpdesk_draft_runs_thread_idx").on(table.threadId, table.seq),
|
|
225
|
+
index("helpdesk_draft_runs_in_flight_idx").on(table.mailbox, table.status, table.requestedAt),
|
|
226
|
+
],
|
|
227
|
+
);
|
|
228
|
+
|
|
229
|
+
/** Send intents (`SendIntent`): stored before every send, compare-and-set after. */
|
|
230
|
+
export const helpdeskSendIntents = pgTable("helpdesk_send_intents", {
|
|
231
|
+
id: text("id").primaryKey(),
|
|
232
|
+
mailbox: varchar("mailbox", { length: 320 }).notNull(),
|
|
233
|
+
threadId: text("thread_id")
|
|
234
|
+
.notNull()
|
|
235
|
+
.references(() => helpdeskThreads.id, { onDelete: "cascade" }),
|
|
236
|
+
draftId: text("draft_id"),
|
|
237
|
+
/** Staff user id (as text) of the approver. */
|
|
238
|
+
approvedBy: text("approved_by").notNull(),
|
|
239
|
+
status: text("status").$type<SendStatus>().notNull(),
|
|
240
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
241
|
+
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
|
|
242
|
+
error: text("error"),
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
/** Files staff add to a reply (`ReplyAttachment`). The bytes live in the `files` module. */
|
|
246
|
+
export const helpdeskReplyAttachments = pgTable(
|
|
247
|
+
"helpdesk_reply_attachments",
|
|
248
|
+
{
|
|
249
|
+
id: text("id").primaryKey(),
|
|
250
|
+
threadId: text("thread_id")
|
|
251
|
+
.notNull()
|
|
252
|
+
.references(() => helpdeskThreads.id, { onDelete: "cascade" }),
|
|
253
|
+
mailbox: varchar("mailbox", { length: 320 }).notNull(),
|
|
254
|
+
/** `files.id` (as text) of the uploaded file. */
|
|
255
|
+
fileId: text("file_id").notNull(),
|
|
256
|
+
name: text("name").notNull(),
|
|
257
|
+
contentType: text("content_type").notNull(),
|
|
258
|
+
size: integer("size").notNull(),
|
|
259
|
+
/** Staff user id (as text) that added it. */
|
|
260
|
+
addedBy: text("added_by").notNull(),
|
|
261
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
262
|
+
placedDraftId: text("placed_draft_id"),
|
|
263
|
+
sentIntentId: text("sent_intent_id"),
|
|
264
|
+
},
|
|
265
|
+
(table) => [index("helpdesk_reply_attachments_thread_idx").on(table.threadId, table.createdAt)],
|
|
266
|
+
);
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id` is the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (eight `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).
|
|
270
|
+
|
|
271
|
+
## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
|
|
272
|
+
|
|
273
|
+
`src/lib/m365/config.ts`
|
|
274
|
+
|
|
275
|
+
```ts
|
|
276
|
+
import "server-only";
|
|
277
|
+
import { hkdfSync } from "node:crypto";
|
|
278
|
+
import { getSessionSecret } from "@/lib/auth/session";
|
|
279
|
+
|
|
280
|
+
export interface M365Env {
|
|
281
|
+
clientId: string;
|
|
282
|
+
secret: string;
|
|
283
|
+
appOrigin: string;
|
|
284
|
+
/** DXV has publisher verified the Entra app: the setup page may offer the sign-in. */
|
|
285
|
+
setupReady: boolean;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// Signs consent state and IT links: a domain-separated key from SESSION_SECRET, no new secret.
|
|
289
|
+
const SETUP_KEY_INFO = "dxv-m365-setup/v1";
|
|
290
|
+
|
|
291
|
+
/** Null while Microsoft 365 is off: not production, or no `M365_CLIENT_ID` / `APP_URL`. Read lazily. */
|
|
292
|
+
export function readM365Env(): M365Env | null {
|
|
293
|
+
if (process.env.VERCEL_ENV !== "production") return null;
|
|
294
|
+
const clientId = process.env.M365_CLIENT_ID?.trim();
|
|
295
|
+
const appOrigin = process.env.APP_URL?.trim();
|
|
296
|
+
if (!clientId || !appOrigin) return null;
|
|
297
|
+
const key = Buffer.from(hkdfSync("sha256", getSessionSecret(), "", SETUP_KEY_INFO, 32));
|
|
298
|
+
const setupReady = process.env.M365_SETUP_READY?.trim() === "true";
|
|
299
|
+
return { clientId, secret: key.toString("base64url"), appOrigin, setupReady };
|
|
300
|
+
}
|
|
301
|
+
```
|
|
302
|
+
|
|
303
|
+
`src/lib/m365/graph.ts`
|
|
304
|
+
|
|
305
|
+
```ts
|
|
306
|
+
import "server-only";
|
|
307
|
+
import { createGraphClient, type GraphClient } from "@dxv-systems/mail-graph";
|
|
308
|
+
import { getVercelOidcToken } from "@vercel/oidc";
|
|
309
|
+
|
|
310
|
+
// One client per tenant per instance, so the token cache and per-mailbox limiter are shared.
|
|
311
|
+
const clients = new Map<string, GraphClient>();
|
|
312
|
+
|
|
313
|
+
/** Graph as this app's Entra app; the Vercel OIDC token is the client assertion (production only). */
|
|
314
|
+
export function graphClientFor(clientId: string, tenantId: string): GraphClient {
|
|
315
|
+
const key = `${clientId}:${tenantId}`;
|
|
316
|
+
let client = clients.get(key);
|
|
317
|
+
if (!client) {
|
|
318
|
+
client = createGraphClient({ tenantId, clientId, getClientAssertion: () => getVercelOidcToken() });
|
|
319
|
+
clients.set(key, client);
|
|
320
|
+
}
|
|
321
|
+
return client;
|
|
322
|
+
}
|
|
323
|
+
```
|
|
324
|
+
|
|
325
|
+
`src/lib/m365/connection.ts` (the setup's `ConnectionStore`: one row, JSON column)
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
import "server-only";
|
|
329
|
+
import { eq } from "drizzle-orm";
|
|
330
|
+
import type { ConnectionStore, M365Connection } from "@dxv-systems/mail-graph/setup";
|
|
331
|
+
import { db } from "@/lib/db";
|
|
332
|
+
import { m365Connection } from "@/lib/db/schema";
|
|
333
|
+
|
|
334
|
+
/** The stored connection, or null before the setup was first saved. Not user-scoped. */
|
|
335
|
+
export async function loadM365Connection(): Promise<M365Connection | null> {
|
|
336
|
+
const [row] = await db
|
|
337
|
+
.select({ data: m365Connection.data })
|
|
338
|
+
.from(m365Connection)
|
|
339
|
+
.where(eq(m365Connection.id, 1))
|
|
340
|
+
.limit(1);
|
|
341
|
+
return row?.data ?? null;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export const connectionStore: ConnectionStore = {
|
|
345
|
+
load: loadM365Connection,
|
|
346
|
+
async save(connection) {
|
|
347
|
+
const updatedAt = new Date();
|
|
348
|
+
await db
|
|
349
|
+
.insert(m365Connection)
|
|
350
|
+
.values({ id: 1, data: connection, updatedAt })
|
|
351
|
+
.onConflictDoUpdate({ target: m365Connection.id, set: { data: connection, updatedAt } });
|
|
352
|
+
},
|
|
353
|
+
};
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
`src/lib/m365/setup.ts`. Set `ENTRA_APP_NAME` to the Entra app's display name: `DXV Helpdesk - ` + the client name: `m365_helpdesk.client_name` in the app's workloads YAML, else its production `NEXT_PUBLIC_SITE_NAME` (the FR states it); the page shows it to the tenant admin.
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
import "server-only";
|
|
360
|
+
import { createM365SetupHandlers, type M365SetupHandlers } from "@dxv-systems/mail-graph/setup";
|
|
361
|
+
import { getVerifiedUser } from "@/lib/auth/dal";
|
|
362
|
+
import { hasPermission } from "@/lib/auth/permissions";
|
|
363
|
+
import { branding } from "@/lib/config/branding";
|
|
364
|
+
import { onHelpdeskConnected, onHelpdeskReset } from "@/lib/helpdesk/service";
|
|
365
|
+
import { getVercelOidcToken } from "@vercel/oidc";
|
|
366
|
+
import { readM365Env } from "./config";
|
|
367
|
+
import { connectionStore } from "./connection";
|
|
368
|
+
import { graphClientFor } from "./graph";
|
|
369
|
+
|
|
370
|
+
/** Must equal the Entra app's display name, `DXV Helpdesk - <client name>`, which DXV's infrastructure sets. */
|
|
371
|
+
const ENTRA_APP_NAME = "DXV Helpdesk - <client_name>";
|
|
372
|
+
|
|
373
|
+
let handlers: M365SetupHandlers | null = null;
|
|
374
|
+
|
|
375
|
+
/** The setup route handlers, or null while Microsoft 365 is off (see readM365Env). */
|
|
376
|
+
export function getM365Setup(): M365SetupHandlers | null {
|
|
377
|
+
const env = readM365Env();
|
|
378
|
+
if (!env) return null;
|
|
379
|
+
handlers ??= createM365SetupHandlers({
|
|
380
|
+
isProduction: true,
|
|
381
|
+
clientId: env.clientId,
|
|
382
|
+
setupReady: env.setupReady,
|
|
383
|
+
appOrigin: env.appOrigin,
|
|
384
|
+
secret: env.secret,
|
|
385
|
+
store: connectionStore,
|
|
386
|
+
async getAdmin() {
|
|
387
|
+
const user = await getVerifiedUser();
|
|
388
|
+
return user && hasPermission(user.role, "m365:manage") ? { id: String(user.id), email: user.email } : null;
|
|
389
|
+
},
|
|
390
|
+
createGraphClient: (tenantId) => graphClientFor(env.clientId, tenantId),
|
|
391
|
+
// Lets the app set up its own Exchange access on the admin's sign-in, so no script is needed.
|
|
392
|
+
getClientAssertion: () => getVercelOidcToken(),
|
|
393
|
+
companyName: branding.companyName,
|
|
394
|
+
entraAppName: ENTRA_APP_NAME,
|
|
395
|
+
pagePath: "/dashboard/microsoft-365",
|
|
396
|
+
itLinkPagePath: "/microsoft-365/koppelen",
|
|
397
|
+
onConnected: onHelpdeskConnected,
|
|
398
|
+
async onReset() {
|
|
399
|
+
const user = await getVerifiedUser();
|
|
400
|
+
await onHelpdeskReset(user?.id ?? null);
|
|
401
|
+
},
|
|
402
|
+
});
|
|
403
|
+
return handlers;
|
|
404
|
+
}
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
`onConnected` runs once when the access check first finds the connection complete: it creates a sync state per mailbox (DB only; the next cron run syncs). `onReset` forgets the delta positions (tickets stay) and notifies the admin who reset.
|
|
408
|
+
|
|
409
|
+
`src/lib/m365/cron.ts`
|
|
410
|
+
|
|
411
|
+
```ts
|
|
412
|
+
import "server-only";
|
|
413
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
414
|
+
|
|
415
|
+
/** Vercel Cron sends `Authorization: Bearer $CRON_SECRET`; no secret means no cron. */
|
|
416
|
+
export function isCronRequest(request: Request): boolean {
|
|
417
|
+
const secret = process.env.CRON_SECRET;
|
|
418
|
+
if (!secret) return false;
|
|
419
|
+
const digest = (value: string) => createHash("sha256").update(value).digest();
|
|
420
|
+
return timingSafeEqual(digest(request.headers.get("authorization") ?? ""), digest(`Bearer ${secret}`));
|
|
421
|
+
}
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
## 6. `src/lib/helpdesk/` (adapters, switches, cron)
|
|
425
|
+
|
|
426
|
+
`src/lib/helpdesk/store.ts`: the package's `HelpdeskStore`. `createThread` and `appendMessage` are single transactions; `updateThread`, `transitionSendIntent` are compare-and-set; an empty patch is a read (the package calls `updateDraftRun(key, {})`).
|
|
427
|
+
|
|
428
|
+
```ts
|
|
429
|
+
import "server-only";
|
|
430
|
+
import { and, asc, desc, eq, gte, inArray, lt } from "drizzle-orm";
|
|
431
|
+
import type {
|
|
432
|
+
DraftRun,
|
|
433
|
+
HelpdeskStore,
|
|
434
|
+
SendIntent,
|
|
435
|
+
StoredMessage,
|
|
436
|
+
SyncState,
|
|
437
|
+
Thread,
|
|
438
|
+
ThreadPatch,
|
|
439
|
+
} from "@dxv-systems/helpdesk";
|
|
440
|
+
import { db, type DbClient } from "@/lib/db";
|
|
441
|
+
import {
|
|
442
|
+
helpdeskDraftRuns,
|
|
443
|
+
helpdeskMessages,
|
|
444
|
+
helpdeskSendIntents,
|
|
445
|
+
helpdeskSyncStates,
|
|
446
|
+
helpdeskThreads,
|
|
447
|
+
} from "@/lib/db/schema";
|
|
448
|
+
|
|
449
|
+
// The package's HelpdeskStore over Drizzle. Not user-scoped: callers are the
|
|
450
|
+
// cron (CRON_SECRET) and the inbox route (getStaff). Never import it from UI.
|
|
451
|
+
|
|
452
|
+
type ThreadRow = typeof helpdeskThreads.$inferSelect;
|
|
453
|
+
type MessageRow = typeof helpdeskMessages.$inferSelect;
|
|
454
|
+
type RunRow = typeof helpdeskDraftRuns.$inferSelect;
|
|
455
|
+
type IntentRow = typeof helpdeskSendIntents.$inferSelect;
|
|
456
|
+
|
|
457
|
+
const iso = (d: Date) => d.toISOString();
|
|
458
|
+
const isoOrNull = (d: Date | null) => (d ? d.toISOString() : null);
|
|
459
|
+
const date = (s: string) => new Date(s);
|
|
460
|
+
const dateOrNull = (s: string | null) => (s === null ? null : new Date(s));
|
|
461
|
+
|
|
462
|
+
/** Rolls a transaction back without treating it as a failure. */
|
|
463
|
+
class Rollback extends Error {
|
|
464
|
+
constructor(readonly outcome: "duplicate" | "stale") {
|
|
465
|
+
super(outcome);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
export function toThread(row: ThreadRow): Thread {
|
|
470
|
+
return {
|
|
471
|
+
id: row.id,
|
|
472
|
+
mailbox: row.mailbox,
|
|
473
|
+
state: row.state,
|
|
474
|
+
subjectKey: row.subjectKey,
|
|
475
|
+
subject: row.subject,
|
|
476
|
+
customerAddress: row.customerAddress,
|
|
477
|
+
participants: row.participants,
|
|
478
|
+
createdAt: iso(row.createdAt),
|
|
479
|
+
lastActivityAt: iso(row.lastActivityAt),
|
|
480
|
+
latestInboundId: row.latestInboundId,
|
|
481
|
+
reviewReason: row.reviewReason,
|
|
482
|
+
autoReplyCount: row.autoReplyCount,
|
|
483
|
+
relatedThreadId: row.relatedThreadId,
|
|
484
|
+
dismissedBy: row.dismissedBy,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export function toMessage(row: MessageRow): StoredMessage {
|
|
489
|
+
return {
|
|
490
|
+
id: row.id,
|
|
491
|
+
mailbox: row.mailbox,
|
|
492
|
+
threadId: row.threadId,
|
|
493
|
+
internetMessageId: row.internetMessageId,
|
|
494
|
+
conversationId: row.conversationId,
|
|
495
|
+
subject: row.subject,
|
|
496
|
+
fromAddress: row.fromAddress,
|
|
497
|
+
receivedAt: iso(row.receivedAt),
|
|
498
|
+
noise: { action: row.noiseAction, reason: row.noiseReason },
|
|
499
|
+
suppressAutoResponse: row.suppressAutoResponse,
|
|
500
|
+
removedAt: isoOrNull(row.removedAt),
|
|
501
|
+
direction: row.direction,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function toRun(row: RunRow): DraftRun {
|
|
506
|
+
const { seq: _seq, requestedAt, ...rest } = row;
|
|
507
|
+
return { ...rest, requestedAt: iso(requestedAt) };
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function toIntent(row: IntentRow): SendIntent {
|
|
511
|
+
return { ...row, createdAt: iso(row.createdAt), updatedAt: iso(row.updatedAt) };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function threadValues(thread: Thread): typeof helpdeskThreads.$inferInsert {
|
|
515
|
+
return {
|
|
516
|
+
...thread,
|
|
517
|
+
createdAt: date(thread.createdAt),
|
|
518
|
+
lastActivityAt: date(thread.lastActivityAt),
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function messageValues(message: StoredMessage): typeof helpdeskMessages.$inferInsert {
|
|
523
|
+
const { noise, receivedAt, removedAt, ...rest } = message;
|
|
524
|
+
return {
|
|
525
|
+
...rest,
|
|
526
|
+
noiseAction: noise.action,
|
|
527
|
+
noiseReason: noise.reason,
|
|
528
|
+
receivedAt: date(receivedAt),
|
|
529
|
+
removedAt: dateOrNull(removedAt),
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function threadPatch(patch: ThreadPatch): Partial<typeof helpdeskThreads.$inferInsert> {
|
|
534
|
+
const { lastActivityAt, ...rest } = patch;
|
|
535
|
+
return lastActivityAt === undefined ? rest : { ...rest, lastActivityAt: date(lastActivityAt) };
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
async function casThread(dbc: DbClient, threadId: string, expected: Thread["state"], patch: ThreadPatch) {
|
|
539
|
+
const set = threadPatch(patch);
|
|
540
|
+
const where = and(eq(helpdeskThreads.id, threadId), eq(helpdeskThreads.state, expected));
|
|
541
|
+
// An empty patch is still a compare: it answers whether the state is unchanged.
|
|
542
|
+
const rows =
|
|
543
|
+
Object.keys(set).length === 0
|
|
544
|
+
? await dbc.select({ id: helpdeskThreads.id }).from(helpdeskThreads).where(where)
|
|
545
|
+
: await dbc.update(helpdeskThreads).set(set).where(where).returning({ id: helpdeskThreads.id });
|
|
546
|
+
return rows.length > 0;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
async function threadsByIds(ids: string[]): Promise<Thread[]> {
|
|
550
|
+
if (ids.length === 0) return [];
|
|
551
|
+
const rows = await db
|
|
552
|
+
.select()
|
|
553
|
+
.from(helpdeskThreads)
|
|
554
|
+
.where(inArray(helpdeskThreads.id, ids))
|
|
555
|
+
.orderBy(desc(helpdeskThreads.lastActivityAt));
|
|
556
|
+
return rows.map(toThread);
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
export const helpdeskStore: HelpdeskStore = {
|
|
560
|
+
async getSyncState(mailbox): Promise<SyncState | null> {
|
|
561
|
+
const [row] = await db
|
|
562
|
+
.select()
|
|
563
|
+
.from(helpdeskSyncStates)
|
|
564
|
+
.where(eq(helpdeskSyncStates.mailbox, mailbox))
|
|
565
|
+
.limit(1);
|
|
566
|
+
return row
|
|
567
|
+
? {
|
|
568
|
+
link: row.link,
|
|
569
|
+
connectedAt: iso(row.connectedAt),
|
|
570
|
+
lastReceivedAt: isoOrNull(row.lastReceivedAt),
|
|
571
|
+
sentLink: row.sentLink,
|
|
572
|
+
sentLastReceivedAt: isoOrNull(row.sentLastReceivedAt),
|
|
573
|
+
failingSince: isoOrNull(row.failingSince),
|
|
574
|
+
failures: row.failures,
|
|
575
|
+
lastError: row.lastError,
|
|
576
|
+
}
|
|
577
|
+
: null;
|
|
578
|
+
},
|
|
579
|
+
|
|
580
|
+
async saveSyncState(mailbox, state) {
|
|
581
|
+
const values = {
|
|
582
|
+
link: state.link,
|
|
583
|
+
connectedAt: date(state.connectedAt),
|
|
584
|
+
lastReceivedAt: dateOrNull(state.lastReceivedAt),
|
|
585
|
+
sentLink: state.sentLink ?? null,
|
|
586
|
+
sentLastReceivedAt: dateOrNull(state.sentLastReceivedAt ?? null),
|
|
587
|
+
failingSince: dateOrNull(state.failingSince ?? null),
|
|
588
|
+
failures: state.failures ?? 0,
|
|
589
|
+
lastError: state.lastError ?? null,
|
|
590
|
+
};
|
|
591
|
+
await db
|
|
592
|
+
.insert(helpdeskSyncStates)
|
|
593
|
+
.values({ mailbox, ...values })
|
|
594
|
+
.onConflictDoUpdate({ target: helpdeskSyncStates.mailbox, set: values });
|
|
595
|
+
},
|
|
596
|
+
|
|
597
|
+
async getMessage(mailbox, id) {
|
|
598
|
+
const [row] = await db
|
|
599
|
+
.select()
|
|
600
|
+
.from(helpdeskMessages)
|
|
601
|
+
.where(and(eq(helpdeskMessages.mailbox, mailbox), eq(helpdeskMessages.id, id)))
|
|
602
|
+
.limit(1);
|
|
603
|
+
return row ? toMessage(row) : null;
|
|
604
|
+
},
|
|
605
|
+
|
|
606
|
+
async markMessageRemoved(mailbox, id, at) {
|
|
607
|
+
await db
|
|
608
|
+
.update(helpdeskMessages)
|
|
609
|
+
.set({ removedAt: date(at) })
|
|
610
|
+
.where(and(eq(helpdeskMessages.mailbox, mailbox), eq(helpdeskMessages.id, id)));
|
|
611
|
+
},
|
|
612
|
+
|
|
613
|
+
async getThread(id) {
|
|
614
|
+
const [row] = await db.select().from(helpdeskThreads).where(eq(helpdeskThreads.id, id)).limit(1);
|
|
615
|
+
return row ? toThread(row) : null;
|
|
616
|
+
},
|
|
617
|
+
|
|
618
|
+
async getLatestMessageForThread(threadId) {
|
|
619
|
+
// Inbound only: our own sent mail is never the message to answer.
|
|
620
|
+
const [row] = await db
|
|
621
|
+
.select()
|
|
622
|
+
.from(helpdeskMessages)
|
|
623
|
+
.where(and(eq(helpdeskMessages.threadId, threadId), eq(helpdeskMessages.direction, "inbound")))
|
|
624
|
+
.orderBy(desc(helpdeskMessages.receivedAt))
|
|
625
|
+
.limit(1);
|
|
626
|
+
return row ? toMessage(row) : null;
|
|
627
|
+
},
|
|
628
|
+
|
|
629
|
+
async findThreadsByConversationId(mailbox, conversationId) {
|
|
630
|
+
const rows = await db
|
|
631
|
+
.selectDistinct({ threadId: helpdeskMessages.threadId })
|
|
632
|
+
.from(helpdeskMessages)
|
|
633
|
+
.where(and(eq(helpdeskMessages.mailbox, mailbox), eq(helpdeskMessages.conversationId, conversationId)));
|
|
634
|
+
return threadsByIds(rows.map((r) => r.threadId));
|
|
635
|
+
},
|
|
636
|
+
|
|
637
|
+
async findMessageThreads(mailbox, internetMessageIds) {
|
|
638
|
+
if (internetMessageIds.length === 0) return [];
|
|
639
|
+
const rows = await db
|
|
640
|
+
.select({ threadId: helpdeskMessages.threadId, internetMessageId: helpdeskMessages.internetMessageId })
|
|
641
|
+
.from(helpdeskMessages)
|
|
642
|
+
.where(
|
|
643
|
+
and(
|
|
644
|
+
eq(helpdeskMessages.mailbox, mailbox),
|
|
645
|
+
inArray(helpdeskMessages.internetMessageId, internetMessageIds),
|
|
646
|
+
),
|
|
647
|
+
);
|
|
648
|
+
return rows.flatMap((r) => (r.internetMessageId ? [{ threadId: r.threadId, internetMessageId: r.internetMessageId }] : []));
|
|
649
|
+
},
|
|
650
|
+
|
|
651
|
+
async findThreadsBySubjectKey(mailbox, subjectKey, activeSince) {
|
|
652
|
+
const rows = await db
|
|
653
|
+
.select()
|
|
654
|
+
.from(helpdeskThreads)
|
|
655
|
+
.where(
|
|
656
|
+
and(
|
|
657
|
+
eq(helpdeskThreads.mailbox, mailbox),
|
|
658
|
+
eq(helpdeskThreads.subjectKey, subjectKey),
|
|
659
|
+
gte(helpdeskThreads.lastActivityAt, date(activeSince)),
|
|
660
|
+
),
|
|
661
|
+
)
|
|
662
|
+
.orderBy(desc(helpdeskThreads.lastActivityAt));
|
|
663
|
+
return rows.map(toThread);
|
|
664
|
+
},
|
|
665
|
+
|
|
666
|
+
async createThread(thread, firstMessage) {
|
|
667
|
+
try {
|
|
668
|
+
await db.transaction(async (tx) => {
|
|
669
|
+
await tx.insert(helpdeskThreads).values(threadValues(thread));
|
|
670
|
+
const inserted = await tx
|
|
671
|
+
.insert(helpdeskMessages)
|
|
672
|
+
.values(messageValues(firstMessage))
|
|
673
|
+
.onConflictDoNothing()
|
|
674
|
+
.returning({ id: helpdeskMessages.id });
|
|
675
|
+
if (inserted.length === 0) throw new Rollback("duplicate");
|
|
676
|
+
});
|
|
677
|
+
return "created";
|
|
678
|
+
} catch (err) {
|
|
679
|
+
if (err instanceof Rollback) return "duplicate";
|
|
680
|
+
throw err;
|
|
681
|
+
}
|
|
682
|
+
},
|
|
683
|
+
|
|
684
|
+
async appendMessage(message, update) {
|
|
685
|
+
try {
|
|
686
|
+
await db.transaction(async (tx) => {
|
|
687
|
+
const inserted = await tx
|
|
688
|
+
.insert(helpdeskMessages)
|
|
689
|
+
.values(messageValues(message))
|
|
690
|
+
.onConflictDoNothing()
|
|
691
|
+
.returning({ id: helpdeskMessages.id });
|
|
692
|
+
if (inserted.length === 0) throw new Rollback("duplicate");
|
|
693
|
+
if (!(await casThread(tx, update.threadId, update.expectedState, update.patch))) {
|
|
694
|
+
throw new Rollback("stale");
|
|
695
|
+
}
|
|
696
|
+
});
|
|
697
|
+
return "appended";
|
|
698
|
+
} catch (err) {
|
|
699
|
+
if (err instanceof Rollback) return err.outcome;
|
|
700
|
+
throw err;
|
|
701
|
+
}
|
|
702
|
+
},
|
|
703
|
+
|
|
704
|
+
updateThread(update) {
|
|
705
|
+
return casThread(db, update.threadId, update.expectedState, update.patch);
|
|
706
|
+
},
|
|
707
|
+
|
|
708
|
+
async createDraftRunIfAbsent(run) {
|
|
709
|
+
const inserted = await db
|
|
710
|
+
.insert(helpdeskDraftRuns)
|
|
711
|
+
.values({ ...run, requestedAt: date(run.requestedAt) })
|
|
712
|
+
.onConflictDoNothing()
|
|
713
|
+
.returning();
|
|
714
|
+
if (inserted[0]) return { created: true, run: toRun(inserted[0]) };
|
|
715
|
+
const [existing] = await db
|
|
716
|
+
.select()
|
|
717
|
+
.from(helpdeskDraftRuns)
|
|
718
|
+
.where(
|
|
719
|
+
and(
|
|
720
|
+
eq(helpdeskDraftRuns.mailbox, run.mailbox),
|
|
721
|
+
eq(helpdeskDraftRuns.inboundMessageId, run.inboundMessageId),
|
|
722
|
+
eq(helpdeskDraftRuns.generation, run.generation),
|
|
723
|
+
),
|
|
724
|
+
)
|
|
725
|
+
.limit(1);
|
|
726
|
+
if (!existing) throw new Error(`draft run ${run.idempotencyKey} conflicted but was not found`);
|
|
727
|
+
return { created: false, run: toRun(existing) };
|
|
728
|
+
},
|
|
729
|
+
|
|
730
|
+
async getLatestDraftRun(mailbox, inboundMessageId) {
|
|
731
|
+
const [row] = await db
|
|
732
|
+
.select()
|
|
733
|
+
.from(helpdeskDraftRuns)
|
|
734
|
+
.where(and(eq(helpdeskDraftRuns.mailbox, mailbox), eq(helpdeskDraftRuns.inboundMessageId, inboundMessageId)))
|
|
735
|
+
.orderBy(desc(helpdeskDraftRuns.generation))
|
|
736
|
+
.limit(1);
|
|
737
|
+
return row ? toRun(row) : null;
|
|
738
|
+
},
|
|
739
|
+
|
|
740
|
+
async getLatestDraftRunForThread(threadId) {
|
|
741
|
+
const [row] = await db
|
|
742
|
+
.select()
|
|
743
|
+
.from(helpdeskDraftRuns)
|
|
744
|
+
.where(eq(helpdeskDraftRuns.threadId, threadId))
|
|
745
|
+
.orderBy(desc(helpdeskDraftRuns.seq))
|
|
746
|
+
.limit(1);
|
|
747
|
+
return row ? toRun(row) : null;
|
|
748
|
+
},
|
|
749
|
+
|
|
750
|
+
async listInFlightDraftRuns(mailbox, olderThan) {
|
|
751
|
+
const rows = await db
|
|
752
|
+
.select()
|
|
753
|
+
.from(helpdeskDraftRuns)
|
|
754
|
+
.where(
|
|
755
|
+
and(
|
|
756
|
+
eq(helpdeskDraftRuns.mailbox, mailbox),
|
|
757
|
+
inArray(helpdeskDraftRuns.status, ["requested", "started"]),
|
|
758
|
+
lt(helpdeskDraftRuns.requestedAt, date(olderThan)),
|
|
759
|
+
),
|
|
760
|
+
)
|
|
761
|
+
.orderBy(asc(helpdeskDraftRuns.seq));
|
|
762
|
+
return rows.map(toRun);
|
|
763
|
+
},
|
|
764
|
+
|
|
765
|
+
async updateDraftRun(key, patch) {
|
|
766
|
+
const { requestedAt, ...rest } = patch;
|
|
767
|
+
const set = requestedAt === undefined ? rest : { ...rest, requestedAt: date(requestedAt) };
|
|
768
|
+
// The package calls this with an empty patch to re-read a run.
|
|
769
|
+
const [row] =
|
|
770
|
+
Object.keys(set).length === 0
|
|
771
|
+
? await db.select().from(helpdeskDraftRuns).where(eq(helpdeskDraftRuns.idempotencyKey, key)).limit(1)
|
|
772
|
+
: await db.update(helpdeskDraftRuns).set(set).where(eq(helpdeskDraftRuns.idempotencyKey, key)).returning();
|
|
773
|
+
if (!row) throw new Error(`no draft run ${key}`);
|
|
774
|
+
return toRun(row);
|
|
775
|
+
},
|
|
776
|
+
|
|
777
|
+
async createSendIntentIfAbsent(intent) {
|
|
778
|
+
const inserted = await db
|
|
779
|
+
.insert(helpdeskSendIntents)
|
|
780
|
+
.values({ ...intent, createdAt: date(intent.createdAt), updatedAt: date(intent.updatedAt) })
|
|
781
|
+
.onConflictDoNothing()
|
|
782
|
+
.returning();
|
|
783
|
+
if (inserted[0]) return { created: true, intent: toIntent(inserted[0]) };
|
|
784
|
+
const existing = await helpdeskStore.getSendIntent(intent.id);
|
|
785
|
+
if (!existing) throw new Error(`send intent ${intent.id} conflicted but was not found`);
|
|
786
|
+
return { created: false, intent: existing };
|
|
787
|
+
},
|
|
788
|
+
|
|
789
|
+
async listSendIntentsByStatus(mailbox, status) {
|
|
790
|
+
const rows = await db
|
|
791
|
+
.select()
|
|
792
|
+
.from(helpdeskSendIntents)
|
|
793
|
+
.where(and(eq(helpdeskSendIntents.mailbox, mailbox), eq(helpdeskSendIntents.status, status)))
|
|
794
|
+
.orderBy(asc(helpdeskSendIntents.createdAt));
|
|
795
|
+
return rows.map(toIntent);
|
|
796
|
+
},
|
|
797
|
+
|
|
798
|
+
async getSendIntent(id) {
|
|
799
|
+
const [row] = await db.select().from(helpdeskSendIntents).where(eq(helpdeskSendIntents.id, id)).limit(1);
|
|
800
|
+
return row ? toIntent(row) : null;
|
|
801
|
+
},
|
|
802
|
+
|
|
803
|
+
async transitionSendIntent(id, from, patch) {
|
|
804
|
+
if (from.length === 0) return null;
|
|
805
|
+
const { updatedAt, ...rest } = patch;
|
|
806
|
+
const set = updatedAt === undefined ? rest : { ...rest, updatedAt: date(updatedAt) };
|
|
807
|
+
const where = and(eq(helpdeskSendIntents.id, id), inArray(helpdeskSendIntents.status, from));
|
|
808
|
+
const [row] =
|
|
809
|
+
Object.keys(set).length === 0
|
|
810
|
+
? await db.select().from(helpdeskSendIntents).where(where).limit(1)
|
|
811
|
+
: await db.update(helpdeskSendIntents).set(set).where(where).returning();
|
|
812
|
+
return row ? toIntent(row) : null;
|
|
813
|
+
},
|
|
814
|
+
};
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
`src/lib/helpdesk/inbox.ts`: `HelpdeskInboxQueries` (newest activity first, keyset cursor, assignment = `helpdesk_threads.assignee_id`).
|
|
818
|
+
|
|
819
|
+
```ts
|
|
820
|
+
import "server-only";
|
|
821
|
+
import { and, asc, desc, eq, inArray, isNull, sql, type SQL } from "drizzle-orm";
|
|
822
|
+
import type { HelpdeskInboxQueries } from "@dxv-systems/helpdesk/server";
|
|
823
|
+
import { db } from "@/lib/db";
|
|
824
|
+
import { helpdeskMessages, helpdeskThreads, users } from "@/lib/db/schema";
|
|
825
|
+
import { toMessage, toThread } from "./store";
|
|
826
|
+
|
|
827
|
+
// Reads and assignment for the staff inbox. Not user-scoped: the inbox route
|
|
828
|
+
// guards every call with getStaff.
|
|
829
|
+
|
|
830
|
+
function encodeCursor(at: Date, id: string): string {
|
|
831
|
+
return Buffer.from(JSON.stringify([at.toISOString(), id])).toString("base64url");
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function decodeCursor(cursor: string): [Date, string] | null {
|
|
835
|
+
try {
|
|
836
|
+
const [at, id] = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8")) as [unknown, unknown];
|
|
837
|
+
const date = typeof at === "string" ? new Date(at) : null;
|
|
838
|
+
return date && !Number.isNaN(date.getTime()) && typeof id === "string" ? [date, id] : null;
|
|
839
|
+
} catch {
|
|
840
|
+
return null;
|
|
841
|
+
}
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
export const helpdeskInbox: HelpdeskInboxQueries = {
|
|
845
|
+
async listThreads(query) {
|
|
846
|
+
const where: SQL[] = [];
|
|
847
|
+
if (query.states) where.push(inArray(helpdeskThreads.state, query.states));
|
|
848
|
+
if (query.mailbox) where.push(eq(helpdeskThreads.mailbox, query.mailbox));
|
|
849
|
+
if (query.assigneeId === null) where.push(isNull(helpdeskThreads.assigneeId));
|
|
850
|
+
else if (query.assigneeId !== undefined) {
|
|
851
|
+
const assignee = Number(query.assigneeId);
|
|
852
|
+
if (!Number.isInteger(assignee)) return { rows: [], nextCursor: null };
|
|
853
|
+
where.push(eq(helpdeskThreads.assigneeId, assignee));
|
|
854
|
+
}
|
|
855
|
+
if (query.cursor) {
|
|
856
|
+
const cursor = decodeCursor(query.cursor);
|
|
857
|
+
if (!cursor) return { rows: [], nextCursor: null };
|
|
858
|
+
where.push(sql`(${helpdeskThreads.lastActivityAt}, ${helpdeskThreads.id}) < (${cursor[0]}, ${cursor[1]})`);
|
|
859
|
+
}
|
|
860
|
+
const rows = await db
|
|
861
|
+
.select({ thread: helpdeskThreads, assigneeName: users.name })
|
|
862
|
+
.from(helpdeskThreads)
|
|
863
|
+
.leftJoin(users, eq(users.id, helpdeskThreads.assigneeId))
|
|
864
|
+
.where(where.length ? and(...where) : undefined)
|
|
865
|
+
.orderBy(desc(helpdeskThreads.lastActivityAt), desc(helpdeskThreads.id))
|
|
866
|
+
.limit(query.limit + 1);
|
|
867
|
+
const page = rows.slice(0, query.limit);
|
|
868
|
+
const last = page.at(-1);
|
|
869
|
+
return {
|
|
870
|
+
rows: page.map((r) => ({
|
|
871
|
+
thread: toThread(r.thread),
|
|
872
|
+
assignee:
|
|
873
|
+
r.thread.assigneeId !== null && r.assigneeName !== null
|
|
874
|
+
? { id: String(r.thread.assigneeId), name: r.assigneeName }
|
|
875
|
+
: null,
|
|
876
|
+
})),
|
|
877
|
+
nextCursor: rows.length > query.limit && last ? encodeCursor(last.thread.lastActivityAt, last.thread.id) : null,
|
|
878
|
+
};
|
|
879
|
+
},
|
|
880
|
+
|
|
881
|
+
async listMessages(threadId) {
|
|
882
|
+
const rows = await db
|
|
883
|
+
.select()
|
|
884
|
+
.from(helpdeskMessages)
|
|
885
|
+
.where(eq(helpdeskMessages.threadId, threadId))
|
|
886
|
+
.orderBy(asc(helpdeskMessages.receivedAt));
|
|
887
|
+
return rows.map(toMessage);
|
|
888
|
+
},
|
|
889
|
+
|
|
890
|
+
async getAssignee(threadId) {
|
|
891
|
+
const [row] = await db
|
|
892
|
+
.select({ id: users.id, name: users.name })
|
|
893
|
+
.from(helpdeskThreads)
|
|
894
|
+
.innerJoin(users, eq(users.id, helpdeskThreads.assigneeId))
|
|
895
|
+
.where(eq(helpdeskThreads.id, threadId))
|
|
896
|
+
.limit(1);
|
|
897
|
+
return row ? { id: String(row.id), name: row.name } : null;
|
|
898
|
+
},
|
|
899
|
+
|
|
900
|
+
async setAssignee(threadId, assignee) {
|
|
901
|
+
await db
|
|
902
|
+
.update(helpdeskThreads)
|
|
903
|
+
.set({ assigneeId: assignee ? Number(assignee.id) : null })
|
|
904
|
+
.where(eq(helpdeskThreads.id, threadId));
|
|
905
|
+
},
|
|
906
|
+
};
|
|
907
|
+
```
|
|
908
|
+
|
|
909
|
+
`src/lib/helpdesk/settings.ts`: the pause switch (`deps.controls`) and the sync lease. A lease row instead of `pg_advisory_lock`, because the runtime connects through a transaction-mode pooler.
|
|
910
|
+
|
|
911
|
+
```ts
|
|
912
|
+
import "server-only";
|
|
913
|
+
import { and, eq, isNull, lt, or } from "drizzle-orm";
|
|
914
|
+
import type { HelpdeskControls } from "@dxv-systems/helpdesk";
|
|
915
|
+
import { db } from "@/lib/db";
|
|
916
|
+
import { helpdeskSettings } from "@/lib/db/schema";
|
|
917
|
+
|
|
918
|
+
export interface HelpdeskSettingsView {
|
|
919
|
+
paused: boolean;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
const DEFAULTS: HelpdeskSettingsView = { paused: false };
|
|
923
|
+
|
|
924
|
+
/** The switches as stored (no row: the defaults). Not user-scoped. */
|
|
925
|
+
export async function readHelpdeskSettings(): Promise<HelpdeskSettingsView> {
|
|
926
|
+
const [row] = await db
|
|
927
|
+
.select({ paused: helpdeskSettings.paused })
|
|
928
|
+
.from(helpdeskSettings)
|
|
929
|
+
.where(eq(helpdeskSettings.id, 1))
|
|
930
|
+
.limit(1);
|
|
931
|
+
return row ?? DEFAULTS;
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
/**
|
|
935
|
+
* `HelpdeskDeps.controls`: called at the start of every helpdesk call. One way of working: a
|
|
936
|
+
* person approves each reply in the helpdesk, which then sends it. Pause is the only switch.
|
|
937
|
+
*/
|
|
938
|
+
export async function loadHelpdeskControls(): Promise<HelpdeskControls> {
|
|
939
|
+
const { paused } = await readHelpdeskSettings();
|
|
940
|
+
return { paused, writeMode: "approve_and_send" };
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
export async function saveHelpdeskSettings(settings: HelpdeskSettingsView, userId: number): Promise<void> {
|
|
944
|
+
const values = { ...settings, updatedBy: userId, updatedAt: new Date() };
|
|
945
|
+
await db
|
|
946
|
+
.insert(helpdeskSettings)
|
|
947
|
+
.values({ id: 1, ...values })
|
|
948
|
+
.onConflictDoUpdate({ target: helpdeskSettings.id, set: values });
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/** Claims the sync lease; false while another run holds it. Pooler-safe (no session lock). */
|
|
952
|
+
export async function claimSyncLease(ms: number): Promise<boolean> {
|
|
953
|
+
await db.insert(helpdeskSettings).values({ id: 1 }).onConflictDoNothing();
|
|
954
|
+
const now = new Date();
|
|
955
|
+
const claimed = await db
|
|
956
|
+
.update(helpdeskSettings)
|
|
957
|
+
.set({ syncLeaseUntil: new Date(now.getTime() + ms) })
|
|
958
|
+
.where(
|
|
959
|
+
and(
|
|
960
|
+
eq(helpdeskSettings.id, 1),
|
|
961
|
+
or(isNull(helpdeskSettings.syncLeaseUntil), lt(helpdeskSettings.syncLeaseUntil, now)),
|
|
962
|
+
),
|
|
963
|
+
)
|
|
964
|
+
.returning({ id: helpdeskSettings.id });
|
|
965
|
+
return claimed.length > 0;
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
export async function releaseSyncLease(): Promise<void> {
|
|
969
|
+
await db.update(helpdeskSettings).set({ syncLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
|
|
970
|
+
}
|
|
971
|
+
```
|
|
972
|
+
|
|
973
|
+
**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.
|
|
974
|
+
|
|
975
|
+
`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.
|
|
976
|
+
|
|
977
|
+
```ts
|
|
978
|
+
import "server-only";
|
|
979
|
+
import { inArray } from "drizzle-orm";
|
|
980
|
+
import type { HelpdeskDeps, Notifier } from "@dxv-systems/helpdesk";
|
|
981
|
+
import { rolesWithPermission } from "@/lib/auth/permissions";
|
|
982
|
+
import { db } from "@/lib/db";
|
|
983
|
+
import { users } from "@/lib/db/schema";
|
|
984
|
+
import { readM365Env } from "@/lib/m365/config";
|
|
985
|
+
import { loadM365Connection } from "@/lib/m365/connection";
|
|
986
|
+
import { graphClientFor } from "@/lib/m365/graph";
|
|
987
|
+
import { notifyUsers } from "@/lib/notifications/service";
|
|
988
|
+
import { helpdeskReplyFiles } from "./reply-files";
|
|
989
|
+
import { loadHelpdeskControls } from "./settings";
|
|
990
|
+
import { helpdeskStore } from "./store";
|
|
991
|
+
|
|
992
|
+
const notifier: Notifier = {
|
|
993
|
+
async notify(event) {
|
|
994
|
+
const staff = await db
|
|
995
|
+
.select({ id: users.id })
|
|
996
|
+
.from(users)
|
|
997
|
+
.where(inArray(users.role, rolesWithPermission("helpdesk:use")));
|
|
998
|
+
if (event.type === "sync_failing" || event.type === "sync_recovered") {
|
|
999
|
+
const failing = event.type === "sync_failing";
|
|
1000
|
+
await notifyUsers(
|
|
1001
|
+
staff.map((s) => s.id),
|
|
1002
|
+
{
|
|
1003
|
+
type: failing ? "helpdesk.sync_failing" : "helpdesk.sync_recovered",
|
|
1004
|
+
title: failing ? "Microsoft 365 is niet bereikbaar" : "Microsoft 365 werkt weer",
|
|
1005
|
+
body: failing
|
|
1006
|
+
? `${event.mailbox}: nieuwe mail komt binnen zodra het weer werkt.`
|
|
1007
|
+
: `${event.mailbox}: de helpdesk haalt de mail van de afgelopen tijd op.`,
|
|
1008
|
+
href: "/dashboard/helpdesk",
|
|
1009
|
+
severity: failing ? "warning" : "info",
|
|
1010
|
+
},
|
|
1011
|
+
);
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
const unknown = event.type === "send_outcome_unknown";
|
|
1015
|
+
const bounced = event.type === "review_needed" && event.reason === "delivery_failed";
|
|
1016
|
+
await notifyUsers(
|
|
1017
|
+
staff.map((s) => s.id),
|
|
1018
|
+
{
|
|
1019
|
+
type: unknown ? "helpdesk.send_outcome_unknown" : "helpdesk.review_needed",
|
|
1020
|
+
title: unknown
|
|
1021
|
+
? "Controleer of een antwoord is verstuurd"
|
|
1022
|
+
: bounced
|
|
1023
|
+
? "Antwoord niet afgeleverd"
|
|
1024
|
+
: "Nieuwe mail in de helpdesk",
|
|
1025
|
+
body: `${event.subject || "(geen onderwerp)"} · ${event.mailbox}`,
|
|
1026
|
+
href: `/dashboard/helpdesk?ticket=${encodeURIComponent(event.threadId)}`,
|
|
1027
|
+
severity: unknown || bounced ? "warning" : "info",
|
|
1028
|
+
},
|
|
1029
|
+
);
|
|
1030
|
+
},
|
|
1031
|
+
};
|
|
1032
|
+
|
|
1033
|
+
/** The app's own sender (EMAIL_FROM): its mail is never a ticket. */
|
|
1034
|
+
function ownAddresses(): string[] {
|
|
1035
|
+
const from = process.env.EMAIL_FROM?.trim();
|
|
1036
|
+
if (!from) return [];
|
|
1037
|
+
return [(/<([^>]+)>/.exec(from)?.[1] ?? from).toLowerCase()];
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/** Null unless Microsoft 365 is on and the connection is `connected`; scope = its mailboxes. */
|
|
1041
|
+
export async function getHelpdeskDeps(): Promise<HelpdeskDeps | null> {
|
|
1042
|
+
const env = readM365Env();
|
|
1043
|
+
if (!env) return null;
|
|
1044
|
+
const connection = await loadM365Connection();
|
|
1045
|
+
if (connection?.step !== "connected" || !connection.tenantId) return null;
|
|
1046
|
+
const graph = graphClientFor(env.clientId, connection.tenantId);
|
|
1047
|
+
return {
|
|
1048
|
+
store: helpdeskStore,
|
|
1049
|
+
gatewayFor: (mailbox) => graph.mailbox(mailbox),
|
|
1050
|
+
clock: { now: () => new Date() },
|
|
1051
|
+
config: { ownAddresses: ownAddresses(), connectedMailboxes: connection.mailboxes },
|
|
1052
|
+
controls: loadHelpdeskControls,
|
|
1053
|
+
notifier,
|
|
1054
|
+
attachments: helpdeskReplyFiles,
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
```
|
|
1058
|
+
|
|
1059
|
+
`src/lib/helpdesk/reply-files.ts`: files on replies. The package keeps one row per file in `helpdesk_reply_attachments`; the bytes go through the template's own `files` module, with its direct browser upload (the presigned PUT the template already uses, so no file passes the 4.5 MB request limit of a Vercel function) and its access rules. The package passes the id of the staff member who added the file, because the `files` module checks the user on every read.
|
|
1060
|
+
|
|
1061
|
+
```ts
|
|
1062
|
+
import "server-only";
|
|
1063
|
+
import { and, asc, eq, isNull } from "drizzle-orm";
|
|
1064
|
+
import type { ReplyAttachment, ReplyAttachmentsDeps } from "@dxv-systems/helpdesk";
|
|
1065
|
+
import { db } from "@/lib/db";
|
|
1066
|
+
import { helpdeskReplyAttachments, users, type SessionUser } from "@/lib/db/schema";
|
|
1067
|
+
import { completeUpload, createUploadTarget, deleteFile, openFile } from "@/lib/files/service";
|
|
1068
|
+
|
|
1069
|
+
type Row = typeof helpdeskReplyAttachments.$inferSelect;
|
|
1070
|
+
|
|
1071
|
+
const toAttachment = (r: Row): ReplyAttachment => ({ ...r, createdAt: r.createdAt.toISOString() });
|
|
1072
|
+
|
|
1073
|
+
// The files module authorises by user: the file belongs to the staff member who added it.
|
|
1074
|
+
async function staffUser(staffId: string): Promise<SessionUser> {
|
|
1075
|
+
const [row] = await db
|
|
1076
|
+
.select({ id: users.id, username: users.username, name: users.name, email: users.email, role: users.role })
|
|
1077
|
+
.from(users)
|
|
1078
|
+
.where(eq(users.id, Number(staffId)))
|
|
1079
|
+
.limit(1);
|
|
1080
|
+
if (!row) throw new Error("Unknown staff member for a reply attachment.");
|
|
1081
|
+
return { ...row, mfaEnabled: false };
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
async function readAll(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
|
|
1085
|
+
return new Uint8Array(await new Response(stream).arrayBuffer());
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
export const helpdeskReplyFiles: ReplyAttachmentsDeps = {
|
|
1089
|
+
store: {
|
|
1090
|
+
async add(a) {
|
|
1091
|
+
await db.insert(helpdeskReplyAttachments).values({ ...a, createdAt: new Date(a.createdAt) });
|
|
1092
|
+
},
|
|
1093
|
+
async listForThread(threadId) {
|
|
1094
|
+
const rows = await db
|
|
1095
|
+
.select()
|
|
1096
|
+
.from(helpdeskReplyAttachments)
|
|
1097
|
+
.where(eq(helpdeskReplyAttachments.threadId, threadId))
|
|
1098
|
+
.orderBy(asc(helpdeskReplyAttachments.createdAt), asc(helpdeskReplyAttachments.id));
|
|
1099
|
+
return rows.map(toAttachment);
|
|
1100
|
+
},
|
|
1101
|
+
async update(id, patch) {
|
|
1102
|
+
if (Object.keys(patch).length === 0) return;
|
|
1103
|
+
await db.update(helpdeskReplyAttachments).set(patch).where(eq(helpdeskReplyAttachments.id, id));
|
|
1104
|
+
},
|
|
1105
|
+
async removeUnsent(id) {
|
|
1106
|
+
const [row] = await db
|
|
1107
|
+
.delete(helpdeskReplyAttachments)
|
|
1108
|
+
.where(and(eq(helpdeskReplyAttachments.id, id), isNull(helpdeskReplyAttachments.sentIntentId)))
|
|
1109
|
+
.returning();
|
|
1110
|
+
return row ? toAttachment(row) : null;
|
|
1111
|
+
},
|
|
1112
|
+
},
|
|
1113
|
+
files: {
|
|
1114
|
+
async createUpload({ staffId, name, contentType, size }) {
|
|
1115
|
+
const target = await createUploadTarget(await staffUser(staffId), { filename: name, contentType, size });
|
|
1116
|
+
return { uploadUrl: target.uploadUrl, uploadToken: target.uploadToken, contentType: target.contentType };
|
|
1117
|
+
},
|
|
1118
|
+
async completeUpload({ staffId, uploadToken }) {
|
|
1119
|
+
const file = await completeUpload(await staffUser(staffId), uploadToken);
|
|
1120
|
+
return { fileId: String(file.id), name: file.filename, contentType: file.contentType, size: file.size };
|
|
1121
|
+
},
|
|
1122
|
+
async read({ fileId, staffId }) {
|
|
1123
|
+
const { object } = await openFile(Number(fileId), await staffUser(staffId));
|
|
1124
|
+
return readAll(object.body);
|
|
1125
|
+
},
|
|
1126
|
+
async remove({ fileId, staffId }) {
|
|
1127
|
+
await deleteFile(Number(fileId), await staffUser(staffId));
|
|
1128
|
+
},
|
|
1129
|
+
},
|
|
1130
|
+
};
|
|
1131
|
+
```
|
|
1132
|
+
|
|
1133
|
+
A `FileServiceError` from `createUploadTarget` or `completeUpload` (too large for `FILE_MAX_SIZE_MB`, a file that was not uploaded) reaches the inbox route as an unexpected error (500, "Er ging iets mis"); the package's own limits (20 MB together, 10 files) are checked first and give a clear message. `deleteFile` removes the `files` row only; the object stays in the bucket under the template's retention model.
|
|
1134
|
+
|
|
1135
|
+
`src/lib/helpdesk/service.ts`: setup hooks and the sync cron (one run at a time; per mailbox: `connectMailbox` (idempotent), `syncMailbox`, `sweepStuckDrafts`).
|
|
1136
|
+
|
|
1137
|
+
```ts
|
|
1138
|
+
import "server-only";
|
|
1139
|
+
import {
|
|
1140
|
+
connectMailbox,
|
|
1141
|
+
isPaused,
|
|
1142
|
+
isSyncFailing,
|
|
1143
|
+
reconcileUnknownSends,
|
|
1144
|
+
sweepStuckDrafts,
|
|
1145
|
+
syncMailbox,
|
|
1146
|
+
} from "@dxv-systems/helpdesk";
|
|
1147
|
+
import type { M365Connection } from "@dxv-systems/mail-graph/setup";
|
|
1148
|
+
import { db } from "@/lib/db";
|
|
1149
|
+
import { helpdeskSyncStates } from "@/lib/db/schema";
|
|
1150
|
+
import { notifyUsers } from "@/lib/notifications/service";
|
|
1151
|
+
import { getHelpdeskDeps } from "./deps";
|
|
1152
|
+
import { claimSyncLease, releaseSyncLease } from "./settings";
|
|
1153
|
+
|
|
1154
|
+
/** Longer than the cron route's maxDuration, so a dead run's lease expires on its own. */
|
|
1155
|
+
const SYNC_LEASE_MS = 6 * 60_000;
|
|
1156
|
+
|
|
1157
|
+
/** Setup `onConnected`: start each mailbox from now. Quick DB work only; the cron syncs. */
|
|
1158
|
+
export async function onHelpdeskConnected(connection: M365Connection): Promise<void> {
|
|
1159
|
+
const deps = await getHelpdeskDeps();
|
|
1160
|
+
if (!deps) return;
|
|
1161
|
+
for (const mailbox of connection.mailboxes) await connectMailbox(deps, mailbox);
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
/** Setup `onReset`: forget delta positions; tickets stay. Tells the admin who reset. */
|
|
1165
|
+
export async function onHelpdeskReset(adminId: number | null): Promise<void> {
|
|
1166
|
+
await db.delete(helpdeskSyncStates);
|
|
1167
|
+
if (adminId !== null) {
|
|
1168
|
+
await notifyUsers([adminId], {
|
|
1169
|
+
type: "helpdesk.disconnected",
|
|
1170
|
+
title: "Microsoft 365 is ontkoppeld",
|
|
1171
|
+
body: "De helpdesk haalt geen mail meer op tot de koppeling opnieuw is ingesteld.",
|
|
1172
|
+
href: "/dashboard/microsoft-365",
|
|
1173
|
+
});
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
export type HelpdeskSyncOutcome = "not_connected" | "busy" | "paused" | "done";
|
|
1178
|
+
|
|
1179
|
+
/** Cron: one run at a time (lease). Per mailbox: sync, then fail draft runs that never reported. */
|
|
1180
|
+
export async function runHelpdeskSync(): Promise<HelpdeskSyncOutcome> {
|
|
1181
|
+
const deps = await getHelpdeskDeps();
|
|
1182
|
+
if (!deps) return "not_connected";
|
|
1183
|
+
if (!(await claimSyncLease(SYNC_LEASE_MS))) return "busy";
|
|
1184
|
+
try {
|
|
1185
|
+
let paused = false;
|
|
1186
|
+
for (const mailbox of deps.config.connectedMailboxes) {
|
|
1187
|
+
// connectMailbox is idempotent; it covers a mailbox added after onConnected.
|
|
1188
|
+
await connectMailbox(deps, mailbox);
|
|
1189
|
+
const result = await syncMailbox(deps, mailbox);
|
|
1190
|
+
if (isPaused(result)) {
|
|
1191
|
+
paused = true;
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
if (isSyncFailing(result)) {
|
|
1195
|
+
// Microsoft unreachable: one error when it starts, then one short warning per run.
|
|
1196
|
+
const line = { mailbox, failures: result.failures, since: result.failingSince, error: result.error };
|
|
1197
|
+
if (result.failures === 1) console.error("helpdesk sync: Microsoft 365 unreachable", line);
|
|
1198
|
+
else console.warn("helpdesk sync: Microsoft 365 still unreachable", line);
|
|
1199
|
+
continue;
|
|
1200
|
+
}
|
|
1201
|
+
await sweepStuckDrafts(deps, mailbox);
|
|
1202
|
+
await reconcileUnknownSends(deps, mailbox);
|
|
1203
|
+
}
|
|
1204
|
+
return paused ? "paused" : "done";
|
|
1205
|
+
} finally {
|
|
1206
|
+
await releaseSyncLease();
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
```
|
|
1210
|
+
|
|
1211
|
+
`src/lib/helpdesk/queries.ts` (guarded reads for the pages)
|
|
1212
|
+
|
|
1213
|
+
```ts
|
|
1214
|
+
import "server-only";
|
|
1215
|
+
import { requirePermission } from "@/lib/auth/dal";
|
|
1216
|
+
import { getHelpdeskDeps } from "./deps";
|
|
1217
|
+
import { readHelpdeskSettings, type HelpdeskSettingsView } from "./settings";
|
|
1218
|
+
|
|
1219
|
+
export async function getHelpdeskSettingsForAdmin(): Promise<HelpdeskSettingsView> {
|
|
1220
|
+
await requirePermission("m365:manage");
|
|
1221
|
+
return readHelpdeskSettings();
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
/** Whether the inbox can work: Microsoft 365 on and the connection `connected`. */
|
|
1225
|
+
export async function isHelpdeskConnected(): Promise<boolean> {
|
|
1226
|
+
await requirePermission("helpdesk:use");
|
|
1227
|
+
return (await getHelpdeskDeps()) !== null;
|
|
1228
|
+
}
|
|
1229
|
+
```
|
|
1230
|
+
|
|
1231
|
+
`src/lib/helpdesk/actions.ts`
|
|
1232
|
+
|
|
1233
|
+
```ts
|
|
1234
|
+
"use server";
|
|
1235
|
+
|
|
1236
|
+
import { revalidatePath } from "next/cache";
|
|
1237
|
+
import { z } from "zod";
|
|
1238
|
+
import { requirePermission } from "@/lib/auth/dal";
|
|
1239
|
+
import type { FormState } from "@/lib/forms";
|
|
1240
|
+
import { saveHelpdeskSettings } from "./settings";
|
|
1241
|
+
|
|
1242
|
+
const settingsSchema = z.object({
|
|
1243
|
+
paused: z.enum(["on", "off"], { message: "Kies aan of uit." }),
|
|
1244
|
+
});
|
|
1245
|
+
|
|
1246
|
+
/** The pause switch; it applies on the next helpdesk call, no redeploy. */
|
|
1247
|
+
export async function updateHelpdeskSettings(_prev: FormState, formData: FormData): Promise<FormState> {
|
|
1248
|
+
const user = await requirePermission("m365:manage");
|
|
1249
|
+
const parsed = settingsSchema.safeParse({ paused: formData.get("paused") });
|
|
1250
|
+
if (!parsed.success) return { errors: parsed.error.flatten().fieldErrors };
|
|
1251
|
+
await saveHelpdeskSettings({ paused: parsed.data.paused === "on" }, user.id);
|
|
1252
|
+
revalidatePath("/dashboard/helpdesk/instellingen");
|
|
1253
|
+
return { success: true, message: "Helpdesk-instellingen opgeslagen." };
|
|
1254
|
+
}
|
|
1255
|
+
```
|
|
1256
|
+
|
|
1257
|
+
## 7. Routes
|
|
1258
|
+
|
|
1259
|
+
`src/app/api/m365/[...path]/route.ts` (the setup; the consent callback `/api/m365/consent/callback` is fixed: DXV's infrastructure registers it as the redirect URI)
|
|
1260
|
+
|
|
1261
|
+
```ts
|
|
1262
|
+
import { SETUP_ERROR_MESSAGES } from "@dxv-systems/mail-graph/setup";
|
|
1263
|
+
import { getM365Setup } from "@/lib/m365/setup";
|
|
1264
|
+
|
|
1265
|
+
async function handle(request: Request): Promise<Response> {
|
|
1266
|
+
const setup = getM365Setup();
|
|
1267
|
+
if (!setup) {
|
|
1268
|
+
return Response.json(
|
|
1269
|
+
{ error: "not_configured", message: SETUP_ERROR_MESSAGES.not_configured },
|
|
1270
|
+
{ status: 503, headers: { "Cache-Control": "no-store" } },
|
|
1271
|
+
);
|
|
1272
|
+
}
|
|
1273
|
+
return setup.handle(request);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
export { handle as GET, handle as POST, handle as DELETE };
|
|
1277
|
+
```
|
|
1278
|
+
|
|
1279
|
+
`src/app/api/helpdesk/[...path]/route.ts` (the staff inbox)
|
|
1280
|
+
|
|
1281
|
+
```ts
|
|
1282
|
+
import { createHelpdeskHandlers } from "@dxv-systems/helpdesk/server";
|
|
1283
|
+
import { getVerifiedUser } from "@/lib/auth/dal";
|
|
1284
|
+
import { hasPermission } from "@/lib/auth/permissions";
|
|
1285
|
+
import { getHelpdeskDeps } from "@/lib/helpdesk/deps";
|
|
1286
|
+
import { helpdeskInbox } from "@/lib/helpdesk/inbox";
|
|
1287
|
+
|
|
1288
|
+
async function handle(request: Request): Promise<Response> {
|
|
1289
|
+
// Built per request: the mailbox scope and the switches come from the database.
|
|
1290
|
+
const deps = await getHelpdeskDeps();
|
|
1291
|
+
if (!deps) {
|
|
1292
|
+
return Response.json(
|
|
1293
|
+
{ error: "not_configured", message: "De helpdesk is nog niet gekoppeld aan Microsoft 365." },
|
|
1294
|
+
{ status: 503, headers: { "Cache-Control": "no-store" } },
|
|
1295
|
+
);
|
|
1296
|
+
}
|
|
1297
|
+
const { handle: inbox } = createHelpdeskHandlers({
|
|
1298
|
+
deps,
|
|
1299
|
+
inbox: helpdeskInbox,
|
|
1300
|
+
isProduction: true,
|
|
1301
|
+
async getStaff() {
|
|
1302
|
+
const user = await getVerifiedUser();
|
|
1303
|
+
return user && hasPermission(user.role, "helpdesk:use")
|
|
1304
|
+
? { id: String(user.id), name: user.name, email: user.email }
|
|
1305
|
+
: null;
|
|
1306
|
+
},
|
|
1307
|
+
});
|
|
1308
|
+
return inbox(request);
|
|
1309
|
+
}
|
|
1310
|
+
|
|
1311
|
+
export { handle as GET, handle as POST, handle as PUT, handle as DELETE };
|
|
1312
|
+
```
|
|
1313
|
+
|
|
1314
|
+
`src/app/api/cron/m365-access/route.ts`
|
|
1315
|
+
|
|
1316
|
+
```ts
|
|
1317
|
+
import { isCronRequest } from "@/lib/m365/cron";
|
|
1318
|
+
import { getM365Setup } from "@/lib/m365/setup";
|
|
1319
|
+
|
|
1320
|
+
export const maxDuration = 60;
|
|
1321
|
+
|
|
1322
|
+
/** Re-runs the access check (pending grants, and a scope leak after connecting). */
|
|
1323
|
+
export async function GET(request: Request): Promise<Response> {
|
|
1324
|
+
if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
|
|
1325
|
+
const setup = getM365Setup();
|
|
1326
|
+
if (!setup) return Response.json({ outcome: "not_configured" });
|
|
1327
|
+
const connection = await setup.runAccessCheck();
|
|
1328
|
+
return Response.json({ outcome: connection?.step ?? "nothing_to_check" });
|
|
1329
|
+
}
|
|
1330
|
+
```
|
|
1331
|
+
|
|
1332
|
+
`src/app/api/cron/helpdesk-sync/route.ts`
|
|
1333
|
+
|
|
1334
|
+
```ts
|
|
1335
|
+
import { runHelpdeskSync } from "@/lib/helpdesk/service";
|
|
1336
|
+
import { isCronRequest } from "@/lib/m365/cron";
|
|
1337
|
+
|
|
1338
|
+
// The sync lease (6 min) outlasts this, so a run killed at the limit frees itself.
|
|
1339
|
+
export const maxDuration = 300;
|
|
1340
|
+
|
|
1341
|
+
/** Delta sync of every connected mailbox; a no-op unless the connection is `connected`. */
|
|
1342
|
+
export async function GET(request: Request): Promise<Response> {
|
|
1343
|
+
if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
|
|
1344
|
+
return Response.json({ outcome: await runHelpdeskSync() });
|
|
1345
|
+
}
|
|
1346
|
+
```
|
|
1347
|
+
|
|
1348
|
+
`vercel.json`:
|
|
1349
|
+
|
|
1350
|
+
```json
|
|
1351
|
+
{
|
|
1352
|
+
"framework": "nextjs",
|
|
1353
|
+
"crons": [
|
|
1354
|
+
{ "path": "/api/cron/helpdesk-sync", "schedule": "*/5 * * * *" },
|
|
1355
|
+
{ "path": "/api/cron/m365-access", "schedule": "*/10 * * * *" }
|
|
1356
|
+
]
|
|
1357
|
+
}
|
|
1358
|
+
```
|
|
1359
|
+
|
|
1360
|
+
## 8. Pages and components
|
|
1361
|
+
|
|
1362
|
+
Both package components render their own `<h1>`, so connected pages have no `PageHeader`.
|
|
1363
|
+
|
|
1364
|
+
`src/components/m365/m365-not-enabled.tsx`
|
|
1365
|
+
|
|
1366
|
+
```tsx
|
|
1367
|
+
import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
|
1368
|
+
|
|
1369
|
+
/** Shown instead of the setup, IT link and inbox pages while Microsoft 365 is off. */
|
|
1370
|
+
export function M365NotEnabled({ title, description }: { title: string; description: string }) {
|
|
1371
|
+
return (
|
|
1372
|
+
<Card className="mx-auto w-full max-w-3xl">
|
|
1373
|
+
<CardHeader>
|
|
1374
|
+
<CardTitle>{title}</CardTitle>
|
|
1375
|
+
<CardDescription>{description}</CardDescription>
|
|
1376
|
+
</CardHeader>
|
|
1377
|
+
</Card>
|
|
1378
|
+
);
|
|
1379
|
+
}
|
|
1380
|
+
```
|
|
1381
|
+
|
|
1382
|
+
`src/components/helpdesk/helpdesk-settings-form.tsx`
|
|
1383
|
+
|
|
1384
|
+
```tsx
|
|
1385
|
+
"use client";
|
|
1386
|
+
|
|
1387
|
+
import { useActionState, useEffect } from "react";
|
|
1388
|
+
import { toast } from "sonner";
|
|
1389
|
+
import { updateHelpdeskSettings } from "@/lib/helpdesk/actions";
|
|
1390
|
+
import type { FormState } from "@/lib/forms";
|
|
1391
|
+
import { SubmitButton } from "@/components/submit-button";
|
|
1392
|
+
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
|
|
1393
|
+
|
|
1394
|
+
export function HelpdeskSettingsForm({ paused }: { paused: boolean }) {
|
|
1395
|
+
const [state, formAction] = useActionState<FormState, FormData>(updateHelpdeskSettings, {});
|
|
1396
|
+
|
|
1397
|
+
useEffect(() => {
|
|
1398
|
+
if (state.success) toast.success(state.message ?? "Opgeslagen.");
|
|
1399
|
+
else if (state.message) toast.error(state.message);
|
|
1400
|
+
}, [state]);
|
|
1401
|
+
|
|
1402
|
+
return (
|
|
1403
|
+
<Card className="mx-auto w-full max-w-3xl">
|
|
1404
|
+
<CardHeader>
|
|
1405
|
+
<CardTitle>Helpdesk</CardTitle>
|
|
1406
|
+
<CardDescription>
|
|
1407
|
+
Een medewerker keurt elk antwoord goed in de helpdesk; daarna verstuurt de helpdesk het vanuit de mailbox.
|
|
1408
|
+
Pauzeren geldt direct.
|
|
1409
|
+
</CardDescription>
|
|
1410
|
+
</CardHeader>
|
|
1411
|
+
<form action={formAction}>
|
|
1412
|
+
<CardContent className="space-y-4">
|
|
1413
|
+
<fieldset className="space-y-2">
|
|
1414
|
+
<legend className="text-sm font-semibold">Pauze (noodstop)</legend>
|
|
1415
|
+
{(["off", "on"] as const).map((value) => (
|
|
1416
|
+
<label key={value} className="flex min-h-11 items-center gap-3">
|
|
1417
|
+
<input type="radio" name="paused" value={value} defaultChecked={paused === (value === "on")} className="size-4 accent-primary" />
|
|
1418
|
+
{value === "on" ? "Gepauzeerd: niets ophalen, niets versturen" : "Actief"}
|
|
1419
|
+
</label>
|
|
1420
|
+
))}
|
|
1421
|
+
</fieldset>
|
|
1422
|
+
</CardContent>
|
|
1423
|
+
<CardFooter className="justify-end">
|
|
1424
|
+
<SubmitButton pendingText="Opslaan…">Opslaan</SubmitButton>
|
|
1425
|
+
</CardFooter>
|
|
1426
|
+
</form>
|
|
1427
|
+
</Card>
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
```
|
|
1431
|
+
|
|
1432
|
+
`src/components/helpdesk/helpdesk-inbox-view.tsx`
|
|
1433
|
+
|
|
1434
|
+
```tsx
|
|
1435
|
+
"use client";
|
|
1436
|
+
|
|
1437
|
+
import { HelpdeskInbox } from "@dxv-systems/helpdesk/react";
|
|
1438
|
+
|
|
1439
|
+
/** Keeps the open ticket in the URL (`?ticket=`), so notification links open it. */
|
|
1440
|
+
export function HelpdeskInboxView({ initialThreadId }: { initialThreadId?: string }) {
|
|
1441
|
+
return (
|
|
1442
|
+
<HelpdeskInbox
|
|
1443
|
+
initialThreadId={initialThreadId}
|
|
1444
|
+
onThreadChange={(threadId) => {
|
|
1445
|
+
const url = new URL(window.location.href);
|
|
1446
|
+
if (threadId) url.searchParams.set("ticket", threadId);
|
|
1447
|
+
else url.searchParams.delete("ticket");
|
|
1448
|
+
window.history.replaceState(null, "", url);
|
|
1449
|
+
}}
|
|
1450
|
+
/>
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
```
|
|
1454
|
+
|
|
1455
|
+
Admin setup page `src/app/(app)/dashboard/microsoft-365/page.tsx` (the setup redirects back here after consent):
|
|
1456
|
+
|
|
1457
|
+
```tsx
|
|
1458
|
+
import type { Metadata } from "next";
|
|
1459
|
+
import { M365SetupPage } from "@dxv-systems/mail-graph/setup/react";
|
|
1460
|
+
|
|
1461
|
+
import { requirePermission } from "@/lib/auth/dal";
|
|
1462
|
+
import { readM365Env } from "@/lib/m365/config";
|
|
1463
|
+
import { PageHeader } from "@/components/app/page-header";
|
|
1464
|
+
import { M365NotEnabled } from "@/components/m365/m365-not-enabled";
|
|
1465
|
+
|
|
1466
|
+
export const metadata: Metadata = { title: "Microsoft 365" };
|
|
1467
|
+
|
|
1468
|
+
export default async function MicrosoftSetupPage() {
|
|
1469
|
+
await requirePermission("m365:manage");
|
|
1470
|
+
|
|
1471
|
+
if (!readM365Env()) {
|
|
1472
|
+
return (
|
|
1473
|
+
<div className="space-y-6">
|
|
1474
|
+
<PageHeader title="Microsoft 365" />
|
|
1475
|
+
<M365NotEnabled
|
|
1476
|
+
title="Microsoft 365 is niet ingeschakeld"
|
|
1477
|
+
description="Deze app is nog niet voorbereid op een koppeling met Microsoft 365. Neem contact op met DXV."
|
|
1478
|
+
/>
|
|
1479
|
+
</div>
|
|
1480
|
+
);
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
// Mount the page as is: it takes no styling or copy, so every app runs the same setup.
|
|
1484
|
+
return <M365SetupPage helpdeskHref="/dashboard/helpdesk" settingsHref="/dashboard/helpdesk/instellingen" />;
|
|
1485
|
+
}
|
|
1486
|
+
```
|
|
1487
|
+
|
|
1488
|
+
Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode; admins only, linked from the inbox and the setup page):
|
|
1489
|
+
|
|
1490
|
+
```tsx
|
|
1491
|
+
import type { Metadata } from "next";
|
|
1492
|
+
|
|
1493
|
+
import { requirePermission } from "@/lib/auth/dal";
|
|
1494
|
+
import { getHelpdeskSettingsForAdmin } from "@/lib/helpdesk/queries";
|
|
1495
|
+
import { PageHeader } from "@/components/app/page-header";
|
|
1496
|
+
import { HelpdeskSettingsForm } from "@/components/helpdesk/helpdesk-settings-form";
|
|
1497
|
+
|
|
1498
|
+
export const metadata: Metadata = { title: "Helpdesk-instellingen" };
|
|
1499
|
+
|
|
1500
|
+
export default async function HelpdeskSettingsPage() {
|
|
1501
|
+
await requirePermission("m365:manage");
|
|
1502
|
+
const settings = await getHelpdeskSettingsForAdmin();
|
|
1503
|
+
return (
|
|
1504
|
+
<div className="space-y-6">
|
|
1505
|
+
<PageHeader title="Helpdesk-instellingen" />
|
|
1506
|
+
<HelpdeskSettingsForm paused={settings.paused} />
|
|
1507
|
+
</div>
|
|
1508
|
+
);
|
|
1509
|
+
}
|
|
1510
|
+
```
|
|
1511
|
+
|
|
1512
|
+
Staff inbox `src/app/(app)/dashboard/helpdesk/page.tsx` (`?ticket=<id>` opens a ticket; notifications link there):
|
|
1513
|
+
|
|
1514
|
+
```tsx
|
|
1515
|
+
import type { Metadata } from "next";
|
|
1516
|
+
import Link from "next/link";
|
|
1517
|
+
|
|
1518
|
+
import { requirePermission } from "@/lib/auth/dal";
|
|
1519
|
+
import { hasPermission } from "@/lib/auth/permissions";
|
|
1520
|
+
import { isHelpdeskConnected } from "@/lib/helpdesk/queries";
|
|
1521
|
+
import { PageHeader } from "@/components/app/page-header";
|
|
1522
|
+
import { HelpdeskInboxView } from "@/components/helpdesk/helpdesk-inbox-view";
|
|
1523
|
+
import { M365NotEnabled } from "@/components/m365/m365-not-enabled";
|
|
1524
|
+
|
|
1525
|
+
export const metadata: Metadata = { title: "Helpdesk" };
|
|
1526
|
+
|
|
1527
|
+
export default async function HelpdeskPage({
|
|
1528
|
+
searchParams,
|
|
1529
|
+
}: {
|
|
1530
|
+
searchParams: Promise<{ ticket?: string | string[] }>;
|
|
1531
|
+
}) {
|
|
1532
|
+
const user = await requirePermission("helpdesk:use");
|
|
1533
|
+
|
|
1534
|
+
if (!(await isHelpdeskConnected())) {
|
|
1535
|
+
const admin = hasPermission(user.role, "m365:manage");
|
|
1536
|
+
return (
|
|
1537
|
+
<div className="space-y-6">
|
|
1538
|
+
<PageHeader title="Helpdesk" />
|
|
1539
|
+
<M365NotEnabled
|
|
1540
|
+
title="De helpdesk is nog niet gekoppeld"
|
|
1541
|
+
description={
|
|
1542
|
+
admin
|
|
1543
|
+
? "Koppel eerst Microsoft 365 onder Beheer → Microsoft 365."
|
|
1544
|
+
: "Een beheerder moet de helpdesk eerst koppelen aan Microsoft 365."
|
|
1545
|
+
}
|
|
1546
|
+
/>
|
|
1547
|
+
</div>
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
const { ticket } = await searchParams;
|
|
1552
|
+
return (
|
|
1553
|
+
<div className="space-y-4">
|
|
1554
|
+
{hasPermission(user.role, "m365:manage") && (
|
|
1555
|
+
<div className="flex justify-end">
|
|
1556
|
+
<Link href="/dashboard/helpdesk/instellingen" className="text-sm font-medium underline-offset-4 hover:underline">
|
|
1557
|
+
Instellingen
|
|
1558
|
+
</Link>
|
|
1559
|
+
</div>
|
|
1560
|
+
)}
|
|
1561
|
+
<HelpdeskInboxView initialThreadId={typeof ticket === "string" ? ticket : undefined} />
|
|
1562
|
+
</div>
|
|
1563
|
+
);
|
|
1564
|
+
}
|
|
1565
|
+
```
|
|
1566
|
+
|
|
1567
|
+
Add `loading.tsx` next to both pages (copy `src/app/(app)/dashboard/users/loading.tsx`).
|
|
1568
|
+
|
|
1569
|
+
Public IT link page `src/app/microsoft-365/koppelen/[token]/page.tsx` (outside `/dashboard`, so the proxy lets it through without a session; the token is the only credential):
|
|
1570
|
+
|
|
1571
|
+
```tsx
|
|
1572
|
+
import type { Metadata } from "next";
|
|
1573
|
+
import { M365SetupPage } from "@dxv-systems/mail-graph/setup/react";
|
|
1574
|
+
|
|
1575
|
+
import { readM365Env } from "@/lib/m365/config";
|
|
1576
|
+
import { M365NotEnabled } from "@/components/m365/m365-not-enabled";
|
|
1577
|
+
|
|
1578
|
+
// Public: the signed token is the only credential. Referrer-Policy no-referrer is set
|
|
1579
|
+
// for this path in next.config.ts, so the token never leaks to Microsoft's pages.
|
|
1580
|
+
export const metadata: Metadata = {
|
|
1581
|
+
title: "Microsoft 365 koppelen",
|
|
1582
|
+
referrer: "no-referrer",
|
|
1583
|
+
robots: { index: false, follow: false },
|
|
1584
|
+
};
|
|
1585
|
+
|
|
1586
|
+
export default async function M365ItLinkPage({ params }: { params: Promise<{ token: string }> }) {
|
|
1587
|
+
const { token } = await params;
|
|
1588
|
+
return (
|
|
1589
|
+
<main className="px-gutter py-10">
|
|
1590
|
+
{readM365Env() ? (
|
|
1591
|
+
<M365SetupPage linkToken={token} />
|
|
1592
|
+
) : (
|
|
1593
|
+
<M365NotEnabled
|
|
1594
|
+
title="Microsoft 365 is niet ingeschakeld"
|
|
1595
|
+
description="Deze koppeling is (nog) niet beschikbaar. Neem contact op met de beheerder van de app."
|
|
1596
|
+
/>
|
|
1597
|
+
)}
|
|
1598
|
+
</main>
|
|
1599
|
+
);
|
|
1600
|
+
}
|
|
1601
|
+
```
|
|
1602
|
+
|
|
1603
|
+
`Referrer-Policy: no-referrer` for that path, in `next.config.ts` `headers()` (after the catch-all entry, so it wins):
|
|
1604
|
+
|
|
1605
|
+
```ts
|
|
1606
|
+
return [
|
|
1607
|
+
{ source: "/(.*)", headers: SECURITY_HEADERS },
|
|
1608
|
+
// The IT link carries a signed token in its path: never send it on as a referrer.
|
|
1609
|
+
{
|
|
1610
|
+
source: "/microsoft-365/koppelen/:token*",
|
|
1611
|
+
headers: [{ key: "Referrer-Policy", value: "no-referrer" }],
|
|
1612
|
+
},
|
|
1613
|
+
];
|
|
1614
|
+
```
|
|
1615
|
+
|
|
1616
|
+
## 9. Navigation — `src/components/app/nav.ts`
|
|
1617
|
+
|
|
1618
|
+
Import `Cloud` and `Inbox` from `lucide-react`. Add a top-level entry after "Meldingen":
|
|
1619
|
+
|
|
1620
|
+
```ts
|
|
1621
|
+
{
|
|
1622
|
+
href: "/dashboard/helpdesk",
|
|
1623
|
+
label: "Helpdesk",
|
|
1624
|
+
icon: Inbox,
|
|
1625
|
+
permission: "helpdesk:use",
|
|
1626
|
+
mobileTab: true,
|
|
1627
|
+
},
|
|
1628
|
+
```
|
|
1629
|
+
|
|
1630
|
+
and as the last child of "Beheer":
|
|
1631
|
+
|
|
1632
|
+
```ts
|
|
1633
|
+
{
|
|
1634
|
+
href: "/dashboard/microsoft-365",
|
|
1635
|
+
label: "Microsoft 365",
|
|
1636
|
+
icon: Cloud,
|
|
1637
|
+
permission: "m365:manage",
|
|
1638
|
+
},
|
|
1639
|
+
```
|
|
1640
|
+
|
|
1641
|
+
## 10. Tailwind — `src/app/globals.css`
|
|
1642
|
+
|
|
1643
|
+
Tailwind v4 skips `node_modules`; the package components need their classes scanned. Below the `@import` lines:
|
|
1644
|
+
|
|
1645
|
+
```css
|
|
1646
|
+
@source "../../node_modules/@dxv-systems/mail-graph/dist";
|
|
1647
|
+
@source "../../node_modules/@dxv-systems/helpdesk/dist";
|
|
1648
|
+
```
|
|
1649
|
+
|
|
1650
|
+
## 11. Test — `src/lib/helpdesk/store.db.test.ts`
|
|
1651
|
+
|
|
1652
|
+
Runs the real domain flow against the store on PGlite with the package's fake mailbox and no drafter: ingest to review, staff-written reply, single send, paging, assignment, dismissal, transaction rollback.
|
|
1653
|
+
|
|
1654
|
+
```ts
|
|
1655
|
+
import { beforeAll, describe, expect, it, vi } from "vitest";
|
|
1656
|
+
|
|
1657
|
+
vi.setConfig({ testTimeout: 60_000, hookTimeout: 60_000 });
|
|
1658
|
+
|
|
1659
|
+
vi.mock("server-only", () => ({}));
|
|
1660
|
+
vi.mock("@/lib/db", async () => {
|
|
1661
|
+
const { PGlite } = await import("@electric-sql/pglite");
|
|
1662
|
+
const { drizzle } = await import("drizzle-orm/pglite");
|
|
1663
|
+
const { applyMigrations } = await import("@/lib/db/run-migrations");
|
|
1664
|
+
const schema = await import("@/lib/db/schema");
|
|
1665
|
+
const client = new PGlite();
|
|
1666
|
+
await applyMigrations(
|
|
1667
|
+
{
|
|
1668
|
+
async query(text: string, params?: unknown[]) {
|
|
1669
|
+
if (params) return { rows: (await client.query(text, params)).rows as Record<string, unknown>[] };
|
|
1670
|
+
const results = await client.exec(text);
|
|
1671
|
+
return { rows: (results.at(-1)?.rows ?? []) as Record<string, unknown>[] };
|
|
1672
|
+
},
|
|
1673
|
+
},
|
|
1674
|
+
"drizzle",
|
|
1675
|
+
);
|
|
1676
|
+
return { db: drizzle(client, { schema }) };
|
|
1677
|
+
});
|
|
1678
|
+
|
|
1679
|
+
import {
|
|
1680
|
+
approveAndSend,
|
|
1681
|
+
connectMailbox,
|
|
1682
|
+
dismissThread,
|
|
1683
|
+
editDraft,
|
|
1684
|
+
syncMailbox,
|
|
1685
|
+
type HelpdeskDeps,
|
|
1686
|
+
} from "@dxv-systems/helpdesk";
|
|
1687
|
+
import { createFakeMailbox } from "@dxv-systems/helpdesk/testing";
|
|
1688
|
+
import { db } from "@/lib/db";
|
|
1689
|
+
import { users } from "@/lib/db/schema";
|
|
1690
|
+
import { helpdeskInbox } from "./inbox";
|
|
1691
|
+
import { helpdeskReplyFiles } from "./reply-files";
|
|
1692
|
+
import { helpdeskStore } from "./store";
|
|
1693
|
+
|
|
1694
|
+
const MAILBOX = "info@klant.test";
|
|
1695
|
+
const mailbox = createFakeMailbox(MAILBOX);
|
|
1696
|
+
const deps: HelpdeskDeps = {
|
|
1697
|
+
store: helpdeskStore,
|
|
1698
|
+
gatewayFor: () => mailbox,
|
|
1699
|
+
clock: { now: () => new Date() },
|
|
1700
|
+
config: { ownAddresses: ["noreply@app.test"], connectedMailboxes: [MAILBOX] },
|
|
1701
|
+
controls: { paused: false, writeMode: "approve_and_send" },
|
|
1702
|
+
};
|
|
1703
|
+
const soon = (ms: number) => new Date(Date.now() + ms).toISOString();
|
|
1704
|
+
|
|
1705
|
+
describe("helpdesk store on Postgres", () => {
|
|
1706
|
+
let staffId = 0;
|
|
1707
|
+
|
|
1708
|
+
beforeAll(async () => {
|
|
1709
|
+
const [user] = await db
|
|
1710
|
+
.insert(users)
|
|
1711
|
+
.values({ username: "mia", passwordHash: "x", name: "Medewerker Mia", email: "mia@app.test", role: "manager" })
|
|
1712
|
+
.returning({ id: users.id });
|
|
1713
|
+
staffId = user!.id;
|
|
1714
|
+
await connectMailbox(deps, MAILBOX);
|
|
1715
|
+
});
|
|
1716
|
+
|
|
1717
|
+
it("ingests, lets staff write the reply, and sends it once", async () => {
|
|
1718
|
+
mailbox.deliver({ id: "m1", from: "klant@example.test", subject: "Vraag over levering", conversationId: "c1", internetMessageId: "<m1@example.test>", receivedDateTime: soon(1_000) });
|
|
1719
|
+
await syncMailbox(deps, MAILBOX);
|
|
1720
|
+
await syncMailbox(deps, MAILBOX);
|
|
1721
|
+
|
|
1722
|
+
const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
|
|
1723
|
+
expect(rows).toHaveLength(1);
|
|
1724
|
+
const thread = rows[0]!.thread;
|
|
1725
|
+
expect(thread).toMatchObject({ state: "review", reviewReason: "no_draft" });
|
|
1726
|
+
expect(await helpdeskStore.getLatestDraftRunForThread(thread.id)).toBeNull();
|
|
1727
|
+
|
|
1728
|
+
await editDraft(deps, { threadId: thread.id, text: "Hallo, de levering is morgen." });
|
|
1729
|
+
const outcome = await approveAndSend(deps, { threadId: thread.id, approvedBy: String(staffId) });
|
|
1730
|
+
expect(outcome.status).toBe("sent");
|
|
1731
|
+
expect(mailbox.sent).toHaveLength(1);
|
|
1732
|
+
expect(await helpdeskStore.getLatestDraftRunForThread(thread.id)).toMatchObject({ status: "succeeded", text: null, reason: "staff" });
|
|
1733
|
+
expect((await approveAndSend(deps, { threadId: thread.id, approvedBy: String(staffId) })).status).toBe("already_sent");
|
|
1734
|
+
});
|
|
1735
|
+
|
|
1736
|
+
it("dismisses, assigns and pages threads", async () => {
|
|
1737
|
+
mailbox.deliver({ id: "m2", from: "ander@example.test", subject: "Bedankt", conversationId: "c2", receivedDateTime: soon(2_000) });
|
|
1738
|
+
mailbox.deliver({ id: "m3", from: "derde@example.test", subject: "Offerte", conversationId: "c3", receivedDateTime: soon(3_000) });
|
|
1739
|
+
await syncMailbox(deps, MAILBOX);
|
|
1740
|
+
|
|
1741
|
+
const first = await helpdeskInbox.listThreads({ states: ["review"], mailbox: MAILBOX, cursor: null, limit: 1 });
|
|
1742
|
+
expect(first.rows).toHaveLength(1);
|
|
1743
|
+
const second = await helpdeskInbox.listThreads({ states: ["review"], mailbox: MAILBOX, cursor: first.nextCursor, limit: 1 });
|
|
1744
|
+
expect(second.rows).toHaveLength(1);
|
|
1745
|
+
expect(second.nextCursor).toBeNull();
|
|
1746
|
+
expect(second.rows[0]!.thread.id).not.toBe(first.rows[0]!.thread.id);
|
|
1747
|
+
|
|
1748
|
+
const target = first.rows[0]!.thread.id;
|
|
1749
|
+
await helpdeskInbox.setAssignee(target, { id: String(staffId), name: "Medewerker Mia" });
|
|
1750
|
+
const mine = await helpdeskInbox.listThreads({ states: null, mailbox: null, assigneeId: String(staffId), cursor: null, limit: 10 });
|
|
1751
|
+
expect(mine.rows.map((r) => r.assignee?.name)).toEqual(["Medewerker Mia"]);
|
|
1752
|
+
|
|
1753
|
+
await dismissThread(deps, { threadId: target, dismissedBy: String(staffId) });
|
|
1754
|
+
const dismissed = await helpdeskStore.getThread(target);
|
|
1755
|
+
expect(dismissed).toMatchObject({ state: "ignored", dismissedBy: String(staffId) });
|
|
1756
|
+
});
|
|
1757
|
+
|
|
1758
|
+
it("keeps createThread and appendMessage atomic", async () => {
|
|
1759
|
+
const message = (await helpdeskInbox.listMessages((await helpdeskStore.findThreadsByConversationId(MAILBOX, "c1"))[0]!.id))[0]!;
|
|
1760
|
+
const thread = (await helpdeskStore.getThread(message.threadId))!;
|
|
1761
|
+
expect(await helpdeskStore.createThread({ ...thread, id: "copy" }, message)).toBe("duplicate");
|
|
1762
|
+
expect(await helpdeskStore.getThread("copy")).toBeNull();
|
|
1763
|
+
|
|
1764
|
+
const fresh = { ...message, id: "m-new" };
|
|
1765
|
+
const stale = await helpdeskStore.appendMessage(fresh, { threadId: thread.id, expectedState: "review", patch: {} });
|
|
1766
|
+
expect(stale).toBe("stale");
|
|
1767
|
+
expect(await helpdeskStore.getMessage(MAILBOX, "m-new")).toBeNull();
|
|
1768
|
+
});
|
|
1769
|
+
|
|
1770
|
+
it("keeps reply attachments in order and never removes a sent one", async () => {
|
|
1771
|
+
const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
|
|
1772
|
+
const threadId = rows[0]!.thread.id;
|
|
1773
|
+
const store = helpdeskReplyFiles.store;
|
|
1774
|
+
const base = { threadId, mailbox: MAILBOX, contentType: "application/pdf", size: 10, addedBy: String(staffId), placedDraftId: null, sentIntentId: null };
|
|
1775
|
+
await store.add({ ...base, id: "b", fileId: "2", name: "b.pdf", createdAt: "2026-11-11T10:00:00.000Z" });
|
|
1776
|
+
await store.add({ ...base, id: "a", fileId: "1", name: "a.pdf", createdAt: "2026-11-11T10:00:00.000Z" });
|
|
1777
|
+
await store.add({ ...base, id: "c", fileId: "3", name: "c.pdf", createdAt: "2026-11-11T09:00:00.000Z" });
|
|
1778
|
+
expect((await store.listForThread(threadId)).map((a) => a.id)).toEqual(["c", "a", "b"]);
|
|
1779
|
+
|
|
1780
|
+
await store.update("a", {});
|
|
1781
|
+
await store.update("a", { sentIntentId: "intent-1" });
|
|
1782
|
+
expect(await store.removeUnsent("a")).toBeNull();
|
|
1783
|
+
expect(await store.removeUnsent("b")).toMatchObject({ id: "b", fileId: "2", createdAt: "2026-11-11T10:00:00.000Z" });
|
|
1784
|
+
expect((await store.listForThread(threadId)).map((a) => [a.id, a.sentIntentId])).toEqual([
|
|
1785
|
+
["c", null],
|
|
1786
|
+
["a", "intent-1"],
|
|
1787
|
+
]);
|
|
1788
|
+
});
|
|
1789
|
+
|
|
1790
|
+
it("keeps the outage counters on the sync state and lists send intents by status", async () => {
|
|
1791
|
+
const state = (await helpdeskStore.getSyncState(MAILBOX))!;
|
|
1792
|
+
await helpdeskStore.saveSyncState(MAILBOX, { ...state, failingSince: "2026-11-12T18:00:00.000Z", failures: 3, lastError: "502" });
|
|
1793
|
+
expect(await helpdeskStore.getSyncState(MAILBOX)).toMatchObject({ failingSince: "2026-11-12T18:00:00.000Z", failures: 3, lastError: "502" });
|
|
1794
|
+
await helpdeskStore.saveSyncState(MAILBOX, { ...state, failingSince: null, failures: 0, lastError: null });
|
|
1795
|
+
expect(await helpdeskStore.getSyncState(MAILBOX)).toMatchObject({ failingSince: null, failures: 0, lastError: null });
|
|
1796
|
+
|
|
1797
|
+
const { rows } = await helpdeskInbox.listThreads({ states: null, mailbox: null, cursor: null, limit: 10 });
|
|
1798
|
+
const now = new Date().toISOString();
|
|
1799
|
+
const intent = { id: "send-x", mailbox: MAILBOX, threadId: rows[0]!.thread.id, draftId: "d-x", approvedBy: String(staffId), status: "unknown" as const, createdAt: now, updatedAt: now, error: null };
|
|
1800
|
+
await helpdeskStore.createSendIntentIfAbsent(intent);
|
|
1801
|
+
expect((await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "unknown")).map((i) => i.id)).toEqual(["send-x"]);
|
|
1802
|
+
expect(await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "failed")).toEqual([]);
|
|
1803
|
+
});
|
|
1804
|
+
});
|
|
1805
|
+
```
|
|
1806
|
+
|
|
1807
|
+
## 12. Verify
|
|
1808
|
+
|
|
1809
|
+
1. `npm run typecheck && npm run lint && npm test`, `DATABASE_URL=postgres://ci:ci@localhost/ci npm run knip`, and `DATABASE_URL=postgres://ci:ci@localhost:5432/ci npm run db:generate` produces no new migration. `npx next build` succeeds without env.
|
|
1810
|
+
2. Preview (no Microsoft 365): `/dashboard/microsoft-365` (admin) and `/dashboard/helpdesk` (manager) show the "niet ingeschakeld" / "nog niet gekoppeld" cards; an employee sees neither nav item and is redirected; `GET /api/m365/status` and `GET /api/helpdesk/threads` answer 503 `not_configured`; the cron routes answer 401 without the bearer token.
|
|
1811
|
+
3. Production, manual flow (test tenant): Beheer → Microsoft 365 → enter mailbox(es) and a check mailbox → "Koppelen met Microsoft" (a Global Administrator signs in and consents for the organisation) → back on the page the setup is already at the access check, with no script; wait for "Gekoppeld" (up to ~2 h; the 10-minute cron keeps checking with the page closed). Also try "Liever met een PowerShell-script" once: consent, Object ID filled, run the downloaded script, "Script is uitgevoerd". Also open the IT link in a private window: it works without an account and the response has `Referrer-Policy: no-referrer`.
|
|
1812
|
+
4. Send a mail to the connected mailbox. Within 5 minutes it appears under Helpdesk as "Te beoordelen" ("Zelf antwoorden") with an empty "Jouw antwoord" box and a notification. Type a reply, "Goedkeuren en versturen" → the reply is in the mailbox's Sent Items, threaded under the customer's mail with the quote kept.
|
|
1813
|
+
5. Pause on the admin page → the inbox shows the pause banner and the next cron returns `paused`. Unpause.
|
|
1814
|
+
6. Files on a reply (production): open a ticket, "Bijlage toevoegen" with a PDF of a few MB and one over 4.5 MB, then "Goedkeuren en versturen". The reply in Outlook's Sent Items carries both files; the ticket shows them on the sent reply in the conversation. A file above 20 MB is refused with the limit message before any upload.
|