@dxv-systems/mail-graph 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/docs/app-integration.md +158 -29
- package/package.json +1 -1
package/docs/app-integration.md
CHANGED
|
@@ -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.2.
|
|
20
|
+
npm install --save-exact @dxv-systems/mail-graph@0.2.2 @dxv-systems/helpdesk@0.10.1 @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`. 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).
|
|
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
|
|
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(
|
|
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
|
-
|
|
852
|
-
|
|
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.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "Microsoft Graph mail for DXV apps — app-only auth via a caller-supplied client assertion (federated or certificate), per-mailbox delta sync, messages, attachments, threaded replies, folders, forward and send. Never deletes. Guided Microsoft 365 setup (route handlers and a React page) under ./setup. Zero runtime dependencies.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dxv",
|