@dxv-systems/mail-graph 0.3.1 → 0.3.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.
@@ -17,7 +17,7 @@ The code below was compiled, linted, knip-checked, built and tested against a fr
17
17
  ## 1. Install
18
18
 
19
19
  ```bash
20
- npm install --save-exact @dxv-systems/mail-graph@0.3.1 @dxv-systems/helpdesk@0.10.1 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.3.3 @dxv-systems/helpdesk@0.13.0 @vercel/oidc@4.0.1
21
21
  ```
22
22
 
23
23
  Use the published versions (exact, never a range; upgrading is a deliberate change). **Vendored variant** (before publication, e.g. the rehearsal): `npm pack` each package into `vendor/` and install `file:vendor/dxv-systems-mail-graph-<version>.tgz file:vendor/dxv-systems-helpdesk-<version>.tgz` instead; commit the tarballs with `package.json` and the lockfile.
@@ -77,6 +77,7 @@ Extend the `drizzle-orm/pg-core` import with `boolean, doublePrecision, primaryK
77
77
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
78
78
  import type {
79
79
  DraftRunStatus,
80
+ HistoryState,
80
81
  MessageDirection,
81
82
  MessageLocation,
82
83
  NoiseReason,
@@ -111,6 +112,8 @@ export const helpdeskSettings = pgTable(
111
112
  paused: boolean("paused").notNull().default(false),
112
113
  /** Lease of the sync cron: a run starts only when this is null or past. */
113
114
  syncLeaseUntil: timestamp("sync_lease_until", { withTimezone: true }),
115
+ /** Lease of the history cron, apart from the sync's, so neither waits for the other. */
116
+ historyLeaseUntil: timestamp("history_lease_until", { withTimezone: true }),
114
117
  updatedBy: integer("updated_by").references(() => users.id, { onDelete: "set null" }),
115
118
  updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
116
119
  },
@@ -132,6 +135,13 @@ export const helpdeskSyncStates = pgTable("helpdesk_sync_states", {
132
135
  lastError: text("last_error"),
133
136
  });
134
137
 
138
+ /** History import progress per mailbox (`HistoryState`), apart from the sync state so neither overwrites the other. */
139
+ export const helpdeskHistoryStates = pgTable("helpdesk_history_states", {
140
+ mailbox: varchar("mailbox", { length: 320 }).primaryKey(),
141
+ state: jsonb("state").$type<HistoryState>().notNull(),
142
+ updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(),
143
+ });
144
+
135
145
  /** Tickets (`Thread`), plus the inbox's assignment (app data). */
136
146
  export const helpdeskThreads = pgTable(
137
147
  "helpdesk_threads",
@@ -276,7 +286,7 @@ export const helpdeskReplyAttachments = pgTable(
276
286
  );
277
287
  ```
278
288
 
279
- Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (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). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5).
289
+ Every column maps one field of the package types (`M365Connection`, `SyncState`, `Thread` incl. `dismissedBy`, `StoredMessage`, `DraftRun`, `SendIntent`, `ReplyAttachment`); `assignee_id`, `assignment_note` and `assigned_by` are the inbox's assignment, `seq` orders draft runs, `sync_lease_until` guards cron overlap. Then run `npm run db:generate`, review the SQL (nine `CREATE TABLE`s, foreign keys, nine indexes, no `DROP`) and commit it with its snapshot and journal entry. An app on helpdesk 0.2 upgrades with one generated migration: `direction` on `helpdesk_messages` (default `inbound`) and `sent_link`, `sent_last_received_at` on `helpdesk_sync_states` (see the helpdesk README, Upgrading from 0.2). An app on helpdesk 0.4 upgrades with one generated migration too: `assignment_note` and `assigned_by` on `helpdesk_threads`, both nullable (see the helpdesk README, Upgrading from 0.4). An app on helpdesk 0.5 upgrades with one generated migration: `from_name`, `preview`, `has_attachments`, `is_read` and `location` on `helpdesk_messages`, all nullable, and its store's `markMessageRemoved` becomes `updateMessageState`. Add `update helpdesk_sync_states set link = null, sent_link = null;` to the end of that generated migration, so the next sync fills the new fields of mail already stored (see the helpdesk README, Upgrading from 0.5). An app on helpdesk 0.11 upgrades with one generated migration: the table `helpdesk_history_states` and `history_lease_until` on `helpdesk_settings`, nothing dropped (see the helpdesk README, Upgrading from 0.11).
280
290
 
281
291
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
282
292
 
@@ -441,6 +451,7 @@ import { and, asc, desc, eq, gte, inArray, lt } from "drizzle-orm";
441
451
  import type {
442
452
  DraftRun,
443
453
  HelpdeskStore,
454
+ HistoryState,
444
455
  SendIntent,
445
456
  StoredMessage,
446
457
  SyncState,
@@ -450,6 +461,7 @@ import type {
450
461
  import { db, type DbClient } from "@/lib/db";
451
462
  import {
452
463
  helpdeskDraftRuns,
464
+ helpdeskHistoryStates,
453
465
  helpdeskMessages,
454
466
  helpdeskSendIntents,
455
467
  helpdeskSyncStates,
@@ -609,6 +621,22 @@ export const helpdeskStore: HelpdeskStore = {
609
621
  .onConflictDoUpdate({ target: helpdeskSyncStates.mailbox, set: values });
610
622
  },
611
623
 
624
+ async getHistoryState(mailbox): Promise<HistoryState | null> {
625
+ const [row] = await db
626
+ .select({ state: helpdeskHistoryStates.state })
627
+ .from(helpdeskHistoryStates)
628
+ .where(eq(helpdeskHistoryStates.mailbox, mailbox))
629
+ .limit(1);
630
+ return row?.state ?? null;
631
+ },
632
+
633
+ async saveHistoryState(mailbox, state) {
634
+ await db
635
+ .insert(helpdeskHistoryStates)
636
+ .values({ mailbox, state })
637
+ .onConflictDoUpdate({ target: helpdeskHistoryStates.mailbox, set: { state, updatedAt: new Date() } });
638
+ },
639
+
612
640
  async getMessage(mailbox, id) {
613
641
  const [row] = await db
614
642
  .select()
@@ -837,6 +865,7 @@ export const helpdeskStore: HelpdeskStore = {
837
865
  ```ts
838
866
  import "server-only";
839
867
  import { and, asc, desc, eq, ilike, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
868
+ import { UNREAD_WINDOW_DAYS } from "@dxv-systems/helpdesk";
840
869
  import type { HelpdeskInboxQueries, InboxFolder } from "@dxv-systems/helpdesk/server";
841
870
  import { rolesWithPermission } from "@/lib/auth/permissions";
842
871
  import { db } from "@/lib/db";
@@ -898,7 +927,9 @@ const customerIn = (folder: InboxFolder) =>
898
927
  const present = sql`coalesce(${m.location}, '') <> 'gone'`;
899
928
  const ofThread = sql`${m.threadId} = ${helpdeskThreads.id}`;
900
929
  const exists = (condition: SQL) => sql`exists (select 1 from ${m} where ${ofThread} and ${condition})`;
901
- const unreadIn = (folder: InboxFolder) => exists(sql`${customerIn(folder)} and ${m.isRead} = false`);
930
+ // Older unread mail (imported history) does not count as unread.
931
+ const unreadIn = (folder: InboxFolder) =>
932
+ exists(sql`${customerIn(folder)} and ${m.isRead} = false and ${m.receivedAt} >= now() - make_interval(days => ${UNREAD_WINDOW_DAYS})`);
902
933
  const likePattern = (q: string) => `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
903
934
 
904
935
  export const helpdeskInbox: HelpdeskInboxQueries = {
@@ -1096,6 +1127,27 @@ export async function claimSyncLease(ms: number): Promise<boolean> {
1096
1127
  export async function releaseSyncLease(): Promise<void> {
1097
1128
  await db.update(helpdeskSettings).set({ syncLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1098
1129
  }
1130
+
1131
+ /** Claims the history cron's lease, the same way. */
1132
+ export async function claimHistoryLease(ms: number): Promise<boolean> {
1133
+ await db.insert(helpdeskSettings).values({ id: 1 }).onConflictDoNothing();
1134
+ const now = new Date();
1135
+ const claimed = await db
1136
+ .update(helpdeskSettings)
1137
+ .set({ historyLeaseUntil: new Date(now.getTime() + ms) })
1138
+ .where(
1139
+ and(
1140
+ eq(helpdeskSettings.id, 1),
1141
+ or(isNull(helpdeskSettings.historyLeaseUntil), lt(helpdeskSettings.historyLeaseUntil, now)),
1142
+ ),
1143
+ )
1144
+ .returning({ id: helpdeskSettings.id });
1145
+ return claimed.length > 0;
1146
+ }
1147
+
1148
+ export async function releaseHistoryLease(): Promise<void> {
1149
+ await db.update(helpdeskSettings).set({ historyLeaseUntil: null }).where(eq(helpdeskSettings.id, 1));
1150
+ }
1099
1151
  ```
1100
1152
 
1101
1153
  **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.
@@ -1281,15 +1333,16 @@ import {
1281
1333
  isPaused,
1282
1334
  isSyncFailing,
1283
1335
  reconcileUnknownSends,
1336
+ runHistory,
1284
1337
  sweepStuckDrafts,
1285
1338
  syncMailbox,
1286
1339
  } from "@dxv-systems/helpdesk";
1287
1340
  import type { M365Connection } from "@dxv-systems/mail-graph/setup";
1288
1341
  import { db } from "@/lib/db";
1289
- import { helpdeskSyncStates } from "@/lib/db/schema";
1342
+ import { helpdeskHistoryStates, helpdeskSyncStates } from "@/lib/db/schema";
1290
1343
  import { notifyUsers } from "@/lib/notifications/service";
1291
1344
  import { getHelpdeskDeps } from "./deps";
1292
- import { claimSyncLease, releaseSyncLease } from "./settings";
1345
+ import { claimHistoryLease, claimSyncLease, releaseHistoryLease, releaseSyncLease } from "./settings";
1293
1346
 
1294
1347
  /** Longer than the cron route's maxDuration, so a dead run's lease expires on its own. */
1295
1348
  const SYNC_LEASE_MS = 6 * 60_000;
@@ -1301,9 +1354,10 @@ export async function onHelpdeskConnected(connection: M365Connection): Promise<v
1301
1354
  for (const mailbox of connection.mailboxes) await connectMailbox(deps, mailbox);
1302
1355
  }
1303
1356
 
1304
- /** Setup `onReset`: forget delta positions; tickets stay. Tells the admin who reset. */
1357
+ /** Setup `onReset`: forget delta and history positions; tickets stay. Tells the admin who reset. */
1305
1358
  export async function onHelpdeskReset(adminId: number | null): Promise<void> {
1306
1359
  await db.delete(helpdeskSyncStates);
1360
+ await db.delete(helpdeskHistoryStates);
1307
1361
  if (adminId !== null) {
1308
1362
  await notifyUsers([adminId], {
1309
1363
  type: "helpdesk.disconnected",
@@ -1346,6 +1400,25 @@ export async function runHelpdeskSync(): Promise<HelpdeskSyncOutcome> {
1346
1400
  await releaseSyncLease();
1347
1401
  }
1348
1402
  }
1403
+
1404
+ /** Cron: the history import (off until started per mailbox), one run at a time, apart from the sync. */
1405
+ export async function runHelpdeskHistory(): Promise<HelpdeskSyncOutcome> {
1406
+ const deps = await getHelpdeskDeps();
1407
+ if (!deps) return "not_connected";
1408
+ if (!(await claimHistoryLease(SYNC_LEASE_MS))) return "busy";
1409
+ try {
1410
+ for (const mailbox of deps.config.connectedMailboxes) {
1411
+ const result = await runHistory(deps, mailbox);
1412
+ if (isPaused(result)) return "paused";
1413
+ if (result.status === "throttled") {
1414
+ console.warn("helpdesk history: Microsoft asked to wait", { mailbox, retryAfter: result.retryAfter, error: result.error });
1415
+ }
1416
+ }
1417
+ return "done";
1418
+ } finally {
1419
+ await releaseHistoryLease();
1420
+ }
1421
+ }
1349
1422
  ```
1350
1423
 
1351
1424
  `src/lib/helpdesk/queries.ts` (guarded reads for the pages)
@@ -1361,6 +1434,12 @@ export async function getHelpdeskSettingsForAdmin(): Promise<HelpdeskSettingsVie
1361
1434
  return readHelpdeskSettings();
1362
1435
  }
1363
1436
 
1437
+ /** The mailboxes whose history import the settings page shows: the connected ones the routes serve. */
1438
+ export async function getHistoryMailboxesForAdmin(): Promise<string[]> {
1439
+ await requirePermission("m365:manage");
1440
+ return (await getHelpdeskDeps())?.config.connectedMailboxes ?? [];
1441
+ }
1442
+
1364
1443
  /** Whether the inbox can work: Microsoft 365 on and at least one mailbox whose access works (`activeScope`). */
1365
1444
  export async function isHelpdeskConnected(): Promise<boolean> {
1366
1445
  await requirePermission("helpdesk:use");
@@ -1495,6 +1574,21 @@ export async function GET(request: Request): Promise<Response> {
1495
1574
  }
1496
1575
  ```
1497
1576
 
1577
+ `src/app/api/cron/helpdesk-history/route.ts`
1578
+
1579
+ ```ts
1580
+ import { runHelpdeskHistory } from "@/lib/helpdesk/service";
1581
+ import { isCronRequest } from "@/lib/m365/cron";
1582
+
1583
+ export const maxDuration = 300;
1584
+
1585
+ /** History import of the mailboxes where it was started; idle otherwise. */
1586
+ export async function GET(request: Request): Promise<Response> {
1587
+ if (!isCronRequest(request)) return new Response("Unauthorized", { status: 401 });
1588
+ return Response.json({ outcome: await runHelpdeskHistory() });
1589
+ }
1590
+ ```
1591
+
1498
1592
  `vercel.json`:
1499
1593
 
1500
1594
  ```json
@@ -1502,6 +1596,7 @@ export async function GET(request: Request): Promise<Response> {
1502
1596
  "framework": "nextjs",
1503
1597
  "crons": [
1504
1598
  { "path": "/api/cron/helpdesk-sync", "schedule": "*/5 * * * *" },
1599
+ { "path": "/api/cron/helpdesk-history", "schedule": "2-59/5 * * * *" },
1505
1600
  { "path": "/api/cron/m365-access", "schedule": "*/10 * * * *" }
1506
1601
  ]
1507
1602
  }
@@ -1635,25 +1730,176 @@ export default async function MicrosoftSetupPage() {
1635
1730
  }
1636
1731
  ```
1637
1732
 
1638
- Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode; admins only, linked from the inbox and the setup page):
1733
+ `src/components/helpdesk/mail-history-settings.tsx` (the history import per mailbox; the package works out the stage and how far it got, the cron does the work, and nothing starts until an admin presses Starten):
1734
+
1735
+ ```tsx
1736
+ "use client";
1737
+
1738
+ import { useCallback, useEffect, useState } from "react";
1739
+ import { toast } from "sonner";
1740
+ import { createHelpdeskClient, HelpdeskClientError } from "@dxv-systems/helpdesk/client";
1741
+ import type { InboxHistory } from "@dxv-systems/helpdesk/server";
1742
+ import { Button } from "@/components/ui/button";
1743
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
1744
+
1745
+ const helpdesk = createHelpdeskClient();
1746
+
1747
+ const STAGE_LABELS: Record<InboxHistory["stage"], string> = {
1748
+ not_started: "Niet gestart",
1749
+ running: "Bezig met ophalen",
1750
+ waiting: "Wacht op Microsoft",
1751
+ paused: "Gepauzeerd",
1752
+ done: "Klaar",
1753
+ };
1754
+
1755
+ const FOLDERS = [
1756
+ { key: "inbox", label: "Postvak IN" },
1757
+ { key: "sentitems", label: "Verzonden" },
1758
+ ] as const;
1759
+
1760
+ const date = (iso: string) => new Date(iso).toLocaleDateString("nl-NL", { day: "numeric", month: "long", year: "numeric" });
1761
+ const time = (iso: string) => new Date(iso).toLocaleTimeString("nl-NL", { hour: "2-digit", minute: "2-digit" });
1762
+
1763
+ function errorText(error: unknown): string {
1764
+ if (error instanceof HelpdeskClientError && error.status === 403) {
1765
+ return "Je hebt zelf geen toegang tot deze mailbox. Geef jezelf toegang om de historie te zien en te starten.";
1766
+ }
1767
+ return error instanceof HelpdeskClientError ? error.message : "De stand kon niet worden geladen. Probeer het opnieuw.";
1768
+ }
1769
+
1770
+ function MailboxHistory({ mailbox }: { mailbox: string }) {
1771
+ const [history, setHistory] = useState<InboxHistory | null>(null);
1772
+ const [error, setError] = useState<string | null>(null);
1773
+ const [busy, setBusy] = useState(false);
1774
+
1775
+ const load = useCallback(async () => {
1776
+ try {
1777
+ setHistory(await helpdesk.history(mailbox));
1778
+ setError(null);
1779
+ } catch (e) {
1780
+ setError(errorText(e));
1781
+ }
1782
+ }, [mailbox]);
1783
+
1784
+ useEffect(() => {
1785
+ void load();
1786
+ // The cron imports every few minutes: refresh the counts while the page is open.
1787
+ const timer = window.setInterval(() => void load(), 60_000);
1788
+ return () => window.clearInterval(timer);
1789
+ }, [load]);
1790
+
1791
+ async function run(action: "start" | "pause") {
1792
+ setBusy(true);
1793
+ try {
1794
+ setHistory(action === "start" ? await helpdesk.startHistory(mailbox) : await helpdesk.pauseHistory(mailbox));
1795
+ toast.success(action === "start" ? "Het ophalen loopt. De eerste mail verschijnt binnen enkele minuten." : "Gepauzeerd.");
1796
+ } catch (e) {
1797
+ toast.error(errorText(e));
1798
+ } finally {
1799
+ setBusy(false);
1800
+ }
1801
+ }
1802
+
1803
+ const state = history?.state ?? null;
1804
+ return (
1805
+ <Card>
1806
+ <CardHeader>
1807
+ <CardTitle className="break-all">{mailbox}</CardTitle>
1808
+ <CardDescription>
1809
+ Haalt de mail van de laatste 6 maanden vóór de koppeling op uit Postvak IN en Verzonden. Alleen lezen: in Outlook
1810
+ verandert niets. Opgehaalde gesprekken komen binnen als afgesloten tickets.
1811
+ </CardDescription>
1812
+ </CardHeader>
1813
+ <CardContent className="space-y-4 text-sm">
1814
+ {error && <p className="text-muted-foreground">{error}</p>}
1815
+ {!error && !history && <p className="text-muted-foreground">Laden…</p>}
1816
+ {!error && history && !history.supported && (
1817
+ <p className="text-muted-foreground">Mailhistorie ophalen is voor deze mailbox niet beschikbaar.</p>
1818
+ )}
1819
+ {!error && history?.supported && (
1820
+ <>
1821
+ <div className="space-y-1">
1822
+ <p className="font-medium">{STAGE_LABELS[history.stage]}</p>
1823
+ {history.retryAfter && (
1824
+ <p className="text-muted-foreground">
1825
+ Microsoft vraagt even te wachten. Het ophalen gaat vanzelf verder na {time(history.retryAfter)}.
1826
+ </p>
1827
+ )}
1828
+ {history.completeUntil && <p className="text-muted-foreground">Compleet tot {date(history.completeUntil)}</p>}
1829
+ </div>
1830
+ {state && (
1831
+ <table className="w-full max-w-sm">
1832
+ <thead className="text-left text-muted-foreground">
1833
+ <tr>
1834
+ <th className="py-1 pr-3 font-normal">Map</th>
1835
+ <th className="py-1 text-right font-normal">Opgehaald</th>
1836
+ </tr>
1837
+ </thead>
1838
+ <tbody>
1839
+ {FOLDERS.map(({ key, label }) => (
1840
+ <tr key={key} className="border-t">
1841
+ <td className="py-1 pr-3">
1842
+ {label}
1843
+ {state.folders[key].doneAt ? " ✓" : ""}
1844
+ </td>
1845
+ <td className="py-1 text-right tabular-nums">{state.folders[key].imported.toLocaleString("nl-NL")}</td>
1846
+ </tr>
1847
+ ))}
1848
+ </tbody>
1849
+ </table>
1850
+ )}
1851
+ {(history.stage === "not_started" || history.stage === "paused") && (
1852
+ <Button size="sm" disabled={busy} onClick={() => void run("start")}>
1853
+ {history.stage === "paused" ? "Hervatten" : "Starten"}
1854
+ </Button>
1855
+ )}
1856
+ {(history.stage === "running" || history.stage === "waiting") && (
1857
+ <Button size="sm" variant="outline" disabled={busy} onClick={() => void run("pause")}>
1858
+ Pauzeren
1859
+ </Button>
1860
+ )}
1861
+ </>
1862
+ )}
1863
+ </CardContent>
1864
+ </Card>
1865
+ );
1866
+ }
1867
+
1868
+ /** One card per connected mailbox; nothing when there is none. */
1869
+ export function MailHistorySettings({ mailboxes }: { mailboxes: string[] }) {
1870
+ if (mailboxes.length === 0) return null;
1871
+ return (
1872
+ <section className="space-y-4">
1873
+ <h2 className="text-lg font-semibold">Mailhistorie</h2>
1874
+ {mailboxes.map((mailbox) => (
1875
+ <MailboxHistory key={mailbox} mailbox={mailbox} />
1876
+ ))}
1877
+ </section>
1878
+ );
1879
+ }
1880
+ ```
1881
+
1882
+ Helpdesk settings `src/app/(app)/dashboard/helpdesk/instellingen/page.tsx` (pause and write mode, and the history import; admins only, linked from the inbox and the setup page):
1639
1883
 
1640
1884
  ```tsx
1641
1885
  import type { Metadata } from "next";
1642
1886
 
1643
1887
  import { requirePermission } from "@/lib/auth/dal";
1644
- import { getHelpdeskSettingsForAdmin } from "@/lib/helpdesk/queries";
1888
+ import { getHelpdeskSettingsForAdmin, getHistoryMailboxesForAdmin } from "@/lib/helpdesk/queries";
1645
1889
  import { PageHeader } from "@/components/app/page-header";
1646
1890
  import { HelpdeskSettingsForm } from "@/components/helpdesk/helpdesk-settings-form";
1891
+ import { MailHistorySettings } from "@/components/helpdesk/mail-history-settings";
1647
1892
 
1648
1893
  export const metadata: Metadata = { title: "Helpdesk-instellingen" };
1649
1894
 
1650
1895
  export default async function HelpdeskSettingsPage() {
1651
1896
  await requirePermission("m365:manage");
1652
- const settings = await getHelpdeskSettingsForAdmin();
1897
+ const [settings, historyMailboxes] = await Promise.all([getHelpdeskSettingsForAdmin(), getHistoryMailboxesForAdmin()]);
1653
1898
  return (
1654
1899
  <div className="space-y-6">
1655
1900
  <PageHeader title="Helpdesk-instellingen" />
1656
1901
  <HelpdeskSettingsForm paused={settings.paused} />
1902
+ <MailHistorySettings mailboxes={historyMailboxes} />
1657
1903
  </div>
1658
1904
  );
1659
1905
  }
@@ -1957,6 +2203,23 @@ describe("helpdesk store on Postgres", () => {
1957
2203
  expect(await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "failed")).toEqual([]);
1958
2204
  });
1959
2205
 
2206
+ it("keeps the history state apart from the sync state", async () => {
2207
+ const sync = (await helpdeskStore.getSyncState(MAILBOX))!;
2208
+ const folder = { link: null, oldest: null, imported: 0, doneAt: null };
2209
+ const history = {
2210
+ since: "2026-05-01T00:00:00.000Z",
2211
+ startedAt: "2026-11-01T00:00:00.000Z",
2212
+ pausedAt: null,
2213
+ retryAfter: null,
2214
+ lastError: null,
2215
+ lastRunAt: null,
2216
+ folders: { inbox: folder, sentitems: folder },
2217
+ };
2218
+ await helpdeskStore.saveHistoryState!(MAILBOX, history);
2219
+ expect(await helpdeskStore.getHistoryState!(MAILBOX)).toEqual(history);
2220
+ expect(await helpdeskStore.getSyncState(MAILBOX)).toEqual(sync);
2221
+ });
2222
+
1960
2223
  it("lists conversations by folder with unread, preview and search, and counts unread", async () => {
1961
2224
  mailbox.deliver({ id: "m9", from: "trap@example.test", fromName: "Trap & Co", subject: "Leuning 50%", conversationId: "c9", receivedDateTime: soon(9_000), bodyText: "Graag een offerte" });
1962
2225
  await syncMailbox(deps, MAILBOX);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
5
5
  "keywords": [
6
6
  "dxv",