@dxv-systems/mail-graph 0.1.4 → 0.2.1

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 CHANGED
@@ -92,13 +92,20 @@ await support.sendDraft(draft.id); // threads nativ
92
92
  await support.markRead(id); // markRead(id, false) to unread
93
93
  await support.setCategories(id, ["Handled"]); // replaces all categories
94
94
  await support.listFolders("inbox"); // children of the inbox; "root" for top level
95
+ await support.listChildFolders(folderId); // children of any folder (id or well-known name)
96
+ await support.getWellKnownFolderIds(); // { inbox, archive, deleteditems, sentitems, drafts, junkemail }: id or null
97
+ await support.listFolderMessages(folderId); // one page, newest first: { items, nextLink }; pass { link: nextLink } for older mail
95
98
  await support.getInboxFolderId();
96
99
  await support.createInboxFolder("Handled");
97
- await support.moveMessage(id, folderId);
100
+ await support.moveMessage(id, folderId); // or a well-known name: "archive", "deleteditems", "inbox"; the id stays the same
98
101
  await support.forward(id, { to: ["a@b.example"], comment: "" });
99
102
  await support.sendMail({ to, subject, body: { contentType: "html", content }, attachments }); // saveToSentItems: true
100
103
  ```
101
104
 
105
+ Message summaries (delta, folder pages, `getMessage`) carry `bodyPreview`: Graph's first 255 characters of the body as plain text.
106
+
107
+ "Delete" for customer mail is `moveMessage(id, "deleteditems")`, the same as Delete in Outlook. `listFolderMessages` is for folders a caller reads live (Archive, Deleted Items, custom folders); the Inbox and Sent Items go through `delta`.
108
+
102
109
  `sendMail` attachments must total under 3 MB (a Graph request limit); for larger files create a draft by replying, or forward.
103
110
 
104
111
  ### Access check
package/dist/index.d.ts CHANGED
@@ -6,4 +6,4 @@ export { LARGE_ATTACHMENT_THRESHOLD } from "./mailbox";
6
6
  export type { MailboxClient } from "./mailbox";
7
7
  export { GraphAuthError, GraphDeltaExpiredError, GraphError, GraphUsageError } from "./errors";
8
8
  export type { GraphErrorInit, UsageErrorCode } from "./errors";
9
- export type { AccessCheckResult, AccessStatus, AttachmentInfo, AttachmentKind, BodyType, CreateReplyOptions, DeltaItem, DeltaOptions, DeltaPage, ForwardInput, GetMessageOptions, InternetMessageHeader, MailAddress, MailFolder, Message, MessageBody, MessageSummary, OutgoingAttachment, Recipient, SendMailInput, } from "./types";
9
+ export type { AccessCheckResult, AccessStatus, AttachmentInfo, AttachmentKind, BodyType, CreateReplyOptions, DeltaItem, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, InternetMessageHeader, MailAddress, MailFolder, Message, MessageBody, MessageSummary, OutgoingAttachment, Recipient, SendMailInput, WellKnownFolder, WellKnownFolderIds, } from "./types";
package/dist/mailbox.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Http } from "./http";
2
- import type { AccessCheckResult, AttachmentInfo, CreateReplyOptions, DeltaOptions, DeltaPage, ForwardInput, GetMessageOptions, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput } from "./types";
2
+ import type { AccessCheckResult, AttachmentInfo, CreateReplyOptions, DeltaOptions, DeltaPage, FolderMessagesOptions, FolderMessagesPage, ForwardInput, GetMessageOptions, MailFolder, Message, MessageBody, OutgoingAttachment, SendMailInput, WellKnownFolderIds } from "./types";
3
3
  export declare const LARGE_ATTACHMENT_THRESHOLD: number;
4
4
  export interface MailboxClient {
5
5
  readonly address: string;
@@ -19,6 +19,9 @@ export interface MailboxClient {
19
19
  markRead(messageId: string, isRead?: boolean): Promise<void>;
20
20
  setCategories(messageId: string, categories: string[]): Promise<void>;
21
21
  listFolders(parent: "inbox" | "root"): Promise<MailFolder[]>;
22
+ listChildFolders(folderId: string): Promise<MailFolder[]>;
23
+ getWellKnownFolderIds(): Promise<WellKnownFolderIds>;
24
+ listFolderMessages(folderId: string, options?: FolderMessagesOptions): Promise<FolderMessagesPage>;
22
25
  getInboxFolderId(): Promise<string>;
23
26
  createInboxFolder(displayName: string): Promise<MailFolder>;
24
27
  moveMessage(messageId: string, destinationFolderId: string): Promise<{
package/dist/mailbox.js CHANGED
@@ -7,7 +7,8 @@ exports.LARGE_ATTACHMENT_THRESHOLD = 3 * 1024 * 1024;
7
7
  const MAX_ATTACHMENT_BYTES = 150 * 1024 * 1024;
8
8
  const UPLOAD_CHUNK_BYTES = 12 * 320 * 1024;
9
9
  const MAX_PAGES = 100;
10
- const SUMMARY_SELECT = "id,subject,from,receivedDateTime,internetMessageId,conversationId,hasAttachments,isRead,isDraft,parentFolderId,categories";
10
+ const SUMMARY_SELECT = "id,subject,from,receivedDateTime,internetMessageId,conversationId,hasAttachments,isRead,isDraft,parentFolderId,categories,bodyPreview";
11
+ const WELL_KNOWN_FOLDERS = ["inbox", "archive", "deleteditems", "sentitems", "drafts", "junkemail"];
11
12
  const FOLDER_SELECT = "id,displayName,parentFolderId,childFolderCount";
12
13
  function toAddress(raw) {
13
14
  const address = raw?.emailAddress?.address;
@@ -41,6 +42,8 @@ function toSummary(raw) {
41
42
  summary.parentFolderId = raw.parentFolderId;
42
43
  if (raw.categories !== undefined)
43
44
  summary.categories = raw.categories;
45
+ if (raw.bodyPreview !== undefined)
46
+ summary.bodyPreview = raw.bodyPreview;
44
47
  return summary;
45
48
  }
46
49
  function toMessage(raw, includeHeaders) {
@@ -349,6 +352,41 @@ function createMailboxClient(http, address) {
349
352
  const base = parent === "inbox" ? `${user}/mailFolders/inbox/childFolders` : `${user}/mailFolders`;
350
353
  return collect(`${base}${query({ $top: 200, $select: FOLDER_SELECT })}`);
351
354
  },
355
+ async listChildFolders(folderId) {
356
+ return collect(`${user}/mailFolders/${requireId(folderId, "folder id")}/childFolders${query({ $top: 200, $select: FOLDER_SELECT })}`);
357
+ },
358
+ async getWellKnownFolderIds() {
359
+ const ids = {};
360
+ for (const name of WELL_KNOWN_FOLDERS) {
361
+ try {
362
+ const folder = await getJson(`${user}/mailFolders/${name}${query({ $select: "id" })}`);
363
+ ids[name] = folder.id ?? null;
364
+ }
365
+ catch (error) {
366
+ if (error instanceof errors_1.GraphError && error.status === 404) {
367
+ ids[name] = null;
368
+ continue;
369
+ }
370
+ throw error;
371
+ }
372
+ }
373
+ return ids;
374
+ },
375
+ async listFolderMessages(folderId, options = {}) {
376
+ const result = options.link
377
+ ? await http.request({ mailbox: address, method: "GET", link: options.link })
378
+ : await http.request({
379
+ mailbox: address,
380
+ method: "GET",
381
+ path: `${user}/mailFolders/${requireId(folderId, "folder id")}/messages${query({
382
+ $select: SUMMARY_SELECT,
383
+ $orderby: "receivedDateTime desc",
384
+ $top: Math.min(100, Math.max(1, Math.floor(options.pageSize ?? 50))),
385
+ })}`,
386
+ });
387
+ const page = (result.data ?? {});
388
+ return { items: (page.value ?? []).map(toSummary), nextLink: page["@odata.nextLink"] ?? null };
389
+ },
352
390
  async getInboxFolderId() {
353
391
  const folder = await getJson(`${user}/mailFolders/inbox${query({ $select: "id" })}`);
354
392
  if (!folder.id)
package/dist/types.d.ts CHANGED
@@ -20,6 +20,7 @@ export interface MessageSummary {
20
20
  isDraft?: boolean;
21
21
  parentFolderId?: string;
22
22
  categories?: string[];
23
+ bodyPreview?: string;
23
24
  }
24
25
  export interface DeltaItem extends MessageSummary {
25
26
  removed: boolean;
@@ -80,6 +81,16 @@ export interface MailFolder {
80
81
  parentFolderId?: string;
81
82
  childFolderCount?: number;
82
83
  }
84
+ export type WellKnownFolder = "inbox" | "archive" | "deleteditems" | "sentitems" | "drafts" | "junkemail";
85
+ export type WellKnownFolderIds = Record<WellKnownFolder, string | null>;
86
+ export interface FolderMessagesOptions {
87
+ link?: string;
88
+ pageSize?: number;
89
+ }
90
+ export interface FolderMessagesPage {
91
+ items: MessageSummary[];
92
+ nextLink: string | null;
93
+ }
83
94
  export interface ForwardInput {
84
95
  to: Recipient[];
85
96
  comment?: string;
@@ -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.1.4 @dxv-systems/helpdesk@0.5.0 @vercel/oidc@4.0.1
20
+ npm install --save-exact @dxv-systems/mail-graph@0.2.1 @dxv-systems/helpdesk@0.10.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.
@@ -78,6 +78,7 @@ import type { M365Connection } from "@dxv-systems/mail-graph/setup";
78
78
  import type {
79
79
  DraftRunStatus,
80
80
  MessageDirection,
81
+ MessageLocation,
81
82
  NoiseReason,
82
83
  ReviewReason,
83
84
  SendStatus,
@@ -184,6 +185,12 @@ export const helpdeskMessages = pgTable(
184
185
  removedAt: timestamp("removed_at", { withTimezone: true }),
185
186
  /** `outbound`: a reply synced from Sent Items (display only). */
186
187
  direction: text("direction").$type<MessageDirection>().notNull().default("inbound"),
188
+ /** Mailbox state (helpdesk 0.6); null on rows stored before. */
189
+ fromName: text("from_name"),
190
+ preview: text("preview"),
191
+ hasAttachments: boolean("has_attachments"),
192
+ isRead: boolean("is_read"),
193
+ location: text("location").$type<MessageLocation>(),
187
194
  },
188
195
  (table) => [
189
196
  primaryKey({ columns: [table.mailbox, table.id] }),
@@ -269,7 +276,7 @@ export const helpdeskReplyAttachments = pgTable(
269
276
  );
270
277
  ```
271
278
 
272
- 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).
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` (see the helpdesk README, Upgrading from 0.5).
273
280
 
274
281
  ## 5. `src/lib/m365/` (Graph sign-in and the guided setup)
275
282
 
@@ -502,6 +509,11 @@ export function toMessage(row: MessageRow): StoredMessage {
502
509
  suppressAutoResponse: row.suppressAutoResponse,
503
510
  removedAt: isoOrNull(row.removedAt),
504
511
  direction: row.direction,
512
+ fromName: row.fromName,
513
+ preview: row.preview,
514
+ hasAttachments: row.hasAttachments,
515
+ isRead: row.isRead,
516
+ location: row.location,
505
517
  };
506
518
  }
507
519
 
@@ -606,10 +618,13 @@ export const helpdeskStore: HelpdeskStore = {
606
618
  return row ? toMessage(row) : null;
607
619
  },
608
620
 
609
- async markMessageRemoved(mailbox, id, at) {
621
+ async updateMessageState(mailbox, id, patch) {
622
+ const { removedAt, ...rest } = patch;
623
+ const set = removedAt === undefined ? rest : { ...rest, removedAt: dateOrNull(removedAt) };
624
+ if (Object.keys(set).length === 0) return;
610
625
  await db
611
626
  .update(helpdeskMessages)
612
- .set({ removedAt: date(at) })
627
+ .set(set)
613
628
  .where(and(eq(helpdeskMessages.mailbox, mailbox), eq(helpdeskMessages.id, id)));
614
629
  },
615
630
 
@@ -821,8 +836,8 @@ export const helpdeskStore: HelpdeskStore = {
821
836
 
822
837
  ```ts
823
838
  import "server-only";
824
- import { and, asc, desc, eq, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
825
- import type { HelpdeskInboxQueries } from "@dxv-systems/helpdesk/server";
839
+ import { and, asc, desc, eq, ilike, inArray, isNull, or, sql, type SQL } from "drizzle-orm";
840
+ import type { HelpdeskInboxQueries, InboxFolder } from "@dxv-systems/helpdesk/server";
826
841
  import { rolesWithPermission } from "@/lib/auth/permissions";
827
842
  import { db } from "@/lib/db";
828
843
  import { helpdeskMessages, helpdeskThreads, users } from "@/lib/db/schema";
@@ -846,28 +861,51 @@ function decodeCursor(cursor: string): [Date, string] | null {
846
861
  }
847
862
  }
848
863
 
864
+ // The viewer's mailboxes (may be empty) OR assigned to the viewer, plus the shared filters.
865
+ // Null: nothing can match. Filtered in SQL so pages stay full.
866
+ function threadFilters(query: {
867
+ mailboxes: string[];
868
+ viewerId: string;
869
+ mailbox: string | null;
870
+ assigneeId?: string | null;
871
+ cursor: string | null;
872
+ }): SQL[] | null {
873
+ const access: SQL[] = [];
874
+ if (query.mailboxes.length > 0) access.push(inArray(helpdeskThreads.mailbox, query.mailboxes));
875
+ const viewer = Number(query.viewerId);
876
+ if (Number.isInteger(viewer)) access.push(eq(helpdeskThreads.assigneeId, viewer));
877
+ if (access.length === 0) return null;
878
+ const where: SQL[] = [or(...access)!];
879
+ if (query.mailbox) where.push(eq(helpdeskThreads.mailbox, query.mailbox));
880
+ if (query.assigneeId === null) where.push(isNull(helpdeskThreads.assigneeId));
881
+ else if (query.assigneeId !== undefined) {
882
+ const assignee = Number(query.assigneeId);
883
+ if (!Number.isInteger(assignee)) return null;
884
+ where.push(eq(helpdeskThreads.assigneeId, assignee));
885
+ }
886
+ if (query.cursor) {
887
+ const cursor = decodeCursor(query.cursor);
888
+ if (!cursor) return null;
889
+ where.push(sql`(${helpdeskThreads.lastActivityAt}, ${helpdeskThreads.id}) < (${cursor[0]}, ${cursor[1]})`);
890
+ }
891
+ return where;
892
+ }
893
+
894
+ const m = helpdeskMessages;
895
+ // Customer mail in a folder; a row from before helpdesk 0.6 (no location) counts as Inbox until removed.
896
+ const customerIn = (folder: InboxFolder) =>
897
+ sql`${m.direction} = 'inbound' and coalesce(${m.location}, case when ${m.removedAt} is null then 'inbox' end) = ${folder}`;
898
+ const present = sql`coalesce(${m.location}, '') <> 'gone'`;
899
+ const ofThread = sql`${m.threadId} = ${helpdeskThreads.id}`;
900
+ 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`);
902
+ const likePattern = (q: string) => `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
903
+
849
904
  export const helpdeskInbox: HelpdeskInboxQueries = {
850
905
  async listThreads(query) {
851
- // The viewer's mailboxes (may be empty) OR assigned to the viewer. Filtered here so pages stay full.
852
- const access: SQL[] = [];
853
- if (query.mailboxes.length > 0) access.push(inArray(helpdeskThreads.mailbox, query.mailboxes));
854
- const viewer = Number(query.viewerId);
855
- if (Number.isInteger(viewer)) access.push(eq(helpdeskThreads.assigneeId, viewer));
856
- if (access.length === 0) return { rows: [], nextCursor: null };
857
- const where: SQL[] = [or(...access)!];
906
+ const where = threadFilters(query);
907
+ if (!where) return { rows: [], nextCursor: null };
858
908
  if (query.states) where.push(inArray(helpdeskThreads.state, query.states));
859
- if (query.mailbox) where.push(eq(helpdeskThreads.mailbox, query.mailbox));
860
- if (query.assigneeId === null) where.push(isNull(helpdeskThreads.assigneeId));
861
- else if (query.assigneeId !== undefined) {
862
- const assignee = Number(query.assigneeId);
863
- if (!Number.isInteger(assignee)) return { rows: [], nextCursor: null };
864
- where.push(eq(helpdeskThreads.assigneeId, assignee));
865
- }
866
- if (query.cursor) {
867
- const cursor = decodeCursor(query.cursor);
868
- if (!cursor) return { rows: [], nextCursor: null };
869
- where.push(sql`(${helpdeskThreads.lastActivityAt}, ${helpdeskThreads.id}) < (${cursor[0]}, ${cursor[1]})`);
870
- }
871
909
  const rows = await db
872
910
  .select({ thread: helpdeskThreads, assigneeName: users.name })
873
911
  .from(helpdeskThreads)
@@ -889,6 +927,72 @@ export const helpdeskInbox: HelpdeskInboxQueries = {
889
927
  };
890
928
  },
891
929
 
930
+ async listConversations(query) {
931
+ const where = threadFilters(query);
932
+ if (!where) return { rows: [], nextCursor: null };
933
+ where.push(exists(customerIn(query.folder)));
934
+ if (query.unread) where.push(unreadIn(query.folder));
935
+ if (query.hasAttachments) where.push(exists(sql`${present} and ${m.hasAttachments} = true`));
936
+ if (query.q) {
937
+ const like = likePattern(query.q);
938
+ where.push(
939
+ or(
940
+ ilike(helpdeskThreads.subject, like),
941
+ exists(sql`(${m.fromAddress} ilike ${like} or ${m.fromName} ilike ${like} or ${m.preview} ilike ${like})`),
942
+ )!,
943
+ );
944
+ }
945
+ const rows = await db
946
+ .select({
947
+ thread: helpdeskThreads,
948
+ assigneeName: users.name,
949
+ unread: sql<boolean>`${unreadIn(query.folder)}`,
950
+ hasAttachments: sql<boolean>`${exists(sql`${present} and ${m.hasAttachments} = true`)}`,
951
+ messageCount: sql<number>`(select count(*)::int from ${m} where ${ofThread} and ${present})`,
952
+ latest: sql<{ fromAddress: string; fromName: string | null; preview: string | null; receivedAt: string } | null>`(
953
+ select json_build_object('fromAddress', ${m.fromAddress}, 'fromName', ${m.fromName}, 'preview', ${m.preview}, 'receivedAt', ${m.receivedAt})
954
+ from ${m} where ${ofThread} and ${m.direction} = 'inbound' and ${present}
955
+ order by ${m.receivedAt} desc limit 1)`,
956
+ })
957
+ .from(helpdeskThreads)
958
+ .leftJoin(users, eq(users.id, helpdeskThreads.assigneeId))
959
+ .where(and(...where))
960
+ .orderBy(desc(helpdeskThreads.lastActivityAt), desc(helpdeskThreads.id))
961
+ .limit(query.limit + 1);
962
+ const page = rows.slice(0, query.limit);
963
+ const last = page.at(-1);
964
+ return {
965
+ rows: page.map((r) => ({
966
+ thread: toThread(r.thread),
967
+ assignee:
968
+ r.thread.assigneeId !== null && r.assigneeName !== null
969
+ ? { id: String(r.thread.assigneeId), name: r.assigneeName }
970
+ : null,
971
+ unread: r.unread,
972
+ hasAttachments: r.hasAttachments,
973
+ messageCount: r.messageCount,
974
+ latest: r.latest ? { ...r.latest, receivedAt: new Date(r.latest.receivedAt).toISOString() } : null,
975
+ })),
976
+ nextCursor: rows.length > query.limit && last ? encodeCursor(last.thread.lastActivityAt, last.thread.id) : null,
977
+ };
978
+ },
979
+
980
+ async countUnread({ mailboxes, viewerId }) {
981
+ const where = threadFilters({ mailboxes, viewerId, mailbox: null, cursor: null });
982
+ if (!where) return { byMailbox: {}, assignedToMe: 0, total: 0 };
983
+ const rows = await db
984
+ .select({ mailbox: helpdeskThreads.mailbox, assigneeId: helpdeskThreads.assigneeId })
985
+ .from(helpdeskThreads)
986
+ .where(and(...where, unreadIn("inbox")));
987
+ const byMailbox: Record<string, number> = {};
988
+ let assignedToMe = 0;
989
+ for (const row of rows) {
990
+ if (mailboxes.includes(row.mailbox)) byMailbox[row.mailbox] = (byMailbox[row.mailbox] ?? 0) + 1;
991
+ if (String(row.assigneeId) === viewerId) assignedToMe++;
992
+ }
993
+ return { byMailbox, assignedToMe, total: rows.length };
994
+ },
995
+
892
996
  async listMessages(threadId) {
893
997
  const rows = await db
894
998
  .select()
@@ -1015,10 +1119,6 @@ import { helpdeskStore } from "./store";
1015
1119
 
1016
1120
  const notifier: Notifier = {
1017
1121
  async notify(event) {
1018
- const staff = await db
1019
- .select({ id: users.id })
1020
- .from(users)
1021
- .where(inArray(users.role, rolesWithPermission("helpdesk:use")));
1022
1122
  if (event.type === "assigned") {
1023
1123
  await notifyUsers([Number(event.assigneeId)], {
1024
1124
  type: "helpdesk.assigned",
@@ -1029,6 +1129,10 @@ const notifier: Notifier = {
1029
1129
  });
1030
1130
  return;
1031
1131
  }
1132
+ const staff = await db
1133
+ .select({ id: users.id })
1134
+ .from(users)
1135
+ .where(inArray(users.role, rolesWithPermission("helpdesk:use")));
1032
1136
  if (event.type === "sync_failing" || event.type === "sync_recovered") {
1033
1137
  const failing = event.type === "sync_failing";
1034
1138
  await notifyUsers(
@@ -1318,6 +1422,10 @@ import { getVerifiedUser } from "@/lib/auth/dal";
1318
1422
  import { hasPermission } from "@/lib/auth/permissions";
1319
1423
  import { getHelpdeskDeps } from "@/lib/helpdesk/deps";
1320
1424
  import { helpdeskInbox } from "@/lib/helpdesk/inbox";
1425
+ import { runHelpdeskSync } from "@/lib/helpdesk/service";
1426
+
1427
+ // Pull to refresh runs the cron's sync in the request.
1428
+ export const maxDuration = 60;
1321
1429
 
1322
1430
  async function handle(request: Request): Promise<Response> {
1323
1431
  // Built per request: the mailbox scope and the switches come from the database.
@@ -1339,6 +1447,11 @@ async function handle(request: Request): Promise<Response> {
1339
1447
  // Per-person access: resolve the list from the app's own assignment instead.
1340
1448
  return { id: String(user.id), name: user.name, email: user.email, mailboxes: deps.config.connectedMailboxes };
1341
1449
  },
1450
+ // The cron's run, under the same lease: a pull during a cron run answers "busy".
1451
+ async syncNow() {
1452
+ const outcome = await runHelpdeskSync();
1453
+ return outcome === "not_connected" ? "failing" : outcome;
1454
+ },
1342
1455
  });
1343
1456
  return inbox(request);
1344
1457
  }
@@ -1841,6 +1954,22 @@ describe("helpdesk store on Postgres", () => {
1841
1954
  expect((await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "unknown")).map((i) => i.id)).toEqual(["send-x"]);
1842
1955
  expect(await helpdeskStore.listSendIntentsByStatus!(MAILBOX, "failed")).toEqual([]);
1843
1956
  });
1957
+
1958
+ it("lists conversations by folder with unread, preview and search, and counts unread", async () => {
1959
+ mailbox.deliver({ id: "m9", from: "trap@example.test", fromName: "Trap & Co", subject: "Leuning 50%", conversationId: "c9", receivedDateTime: soon(9_000), bodyText: "Graag een offerte" });
1960
+ await syncMailbox(deps, MAILBOX);
1961
+ const base = { mailboxes: [MAILBOX], viewerId: String(staffId), mailbox: null, folder: "inbox" as const, unread: false, hasAttachments: false, q: null, cursor: null, limit: 50 };
1962
+ const found = await helpdeskInbox.listConversations({ ...base, q: "50%" });
1963
+ expect(found.rows).toHaveLength(1);
1964
+ expect(found.rows[0]).toMatchObject({ unread: true, messageCount: 1, latest: { fromName: "Trap & Co", preview: "Graag een offerte" } });
1965
+ expect((await helpdeskInbox.listConversations({ ...base, q: "5_%" })).rows).toHaveLength(0);
1966
+ const threadId = found.rows[0]!.thread.id;
1967
+ expect((await helpdeskInbox.countUnread({ mailboxes: [MAILBOX], viewerId: String(staffId) })).byMailbox[MAILBOX]).toBeGreaterThan(0);
1968
+
1969
+ await helpdeskStore.updateMessageState(MAILBOX, "m9", { location: "archive", removedAt: new Date().toISOString() });
1970
+ expect((await helpdeskInbox.listConversations({ ...base, q: "leuning" })).rows).toHaveLength(0);
1971
+ expect((await helpdeskInbox.listConversations({ ...base, folder: "archive" })).rows.map((r) => r.thread.id)).toEqual([threadId]);
1972
+ });
1844
1973
  });
1845
1974
  ```
1846
1975
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dxv-systems/mail-graph",
3
- "version": "0.1.4",
3
+ "version": "0.2.1",
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",