Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
+103
@@ -0,0 +1,103 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · compose view-model (M09 Block G). Pure: reply/forward prefill is
|
||||
* computed here from the (already sanitized) original; the route passes the
|
||||
* SAFE quoted html in. Sending itself is the action's job.
|
||||
*/
|
||||
|
||||
export interface ComposeMailboxOption {
|
||||
readonly id: string;
|
||||
readonly emailAddress: string;
|
||||
readonly provider: EmailMailboxProvider;
|
||||
readonly isDefaultForUser: boolean;
|
||||
}
|
||||
|
||||
export interface ComposeTemplateOption {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly subject: string;
|
||||
readonly htmlBody: string;
|
||||
}
|
||||
|
||||
export interface ComposePrefill {
|
||||
readonly to: string;
|
||||
readonly subject: string;
|
||||
/** SANITIZED quoted body html ("" for a blank compose). */
|
||||
readonly quotedHtml: string;
|
||||
readonly replyToMessageId: string | null;
|
||||
}
|
||||
|
||||
export interface EmailComposeData {
|
||||
readonly mailboxes: readonly ComposeMailboxOption[];
|
||||
readonly defaultMailboxId: string | null;
|
||||
readonly templates: readonly ComposeTemplateOption[];
|
||||
readonly prefill: ComposePrefill;
|
||||
readonly backHref: string;
|
||||
readonly noMailboxKey: string;
|
||||
}
|
||||
|
||||
export type EmailComposeVM = VMState<EmailComposeData>;
|
||||
|
||||
export interface BuildComposePrefillInput {
|
||||
readonly mode: "blank" | "reply" | "forward";
|
||||
readonly original: {
|
||||
readonly id: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly fromAddress: string;
|
||||
readonly fromName: string | null;
|
||||
readonly toSummary: string;
|
||||
readonly subject: string | null;
|
||||
readonly sentAtIso: string;
|
||||
/** SANITIZED body html of the original (never raw provider html). */
|
||||
readonly safeBodyHtml: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function prefixedSubject(prefix: "Re:" | "Fwd:", subject: string | null): string {
|
||||
const base = (subject ?? "").trim();
|
||||
if (!base) return prefix;
|
||||
return base.toLowerCase().startsWith(prefix.toLowerCase()) ? base : `${prefix} ${base}`;
|
||||
}
|
||||
|
||||
function quoted(original: NonNullable<BuildComposePrefillInput["original"]>): string {
|
||||
const who = original.fromName ? `${original.fromName} <${original.fromAddress}>` : original.fromAddress;
|
||||
return `<br><br><blockquote style="border-left:2px solid #ccc;margin:0;padding-left:8px"><p>${who} — ${original.sentAtIso}:</p>${original.safeBodyHtml}</blockquote>`;
|
||||
}
|
||||
|
||||
export function buildComposePrefill(input: BuildComposePrefillInput): ComposePrefill {
|
||||
if (!input.original || input.mode === "blank") {
|
||||
return { to: "", subject: "", quotedHtml: "", replyToMessageId: null };
|
||||
}
|
||||
if (input.mode === "reply") {
|
||||
return {
|
||||
// Reply to an inbound mail → answer the sender; to our own outbound
|
||||
// mirror → keep the original recipients.
|
||||
to: input.original.direction === "inbound" ? input.original.fromAddress : input.original.toSummary,
|
||||
subject: prefixedSubject("Re:", input.original.subject),
|
||||
quotedHtml: quoted(input.original),
|
||||
replyToMessageId: input.original.id,
|
||||
};
|
||||
}
|
||||
return {
|
||||
to: "",
|
||||
subject: prefixedSubject("Fwd:", input.original.subject),
|
||||
quotedHtml: quoted(input.original),
|
||||
// A forward starts a new thread — no reply threading headers.
|
||||
replyToMessageId: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildEmailComposeVM(data: Omit<EmailComposeData, "noMailboxKey">): EmailComposeVM {
|
||||
return { status: "ready", data: { ...data, noMailboxKey: "emailInbox.compose.noMailbox" } };
|
||||
}
|
||||
|
||||
/** Parse a comma/semicolon separated recipient input into address objects. */
|
||||
export function parseRecipients(value: string): Array<{ address: string }> {
|
||||
return value
|
||||
.split(/[,;]/)
|
||||
.map((part) => part.trim().toLowerCase())
|
||||
.filter((part) => part.includes("@"))
|
||||
.map((address) => ({ address }));
|
||||
}
|
||||
+223
@@ -0,0 +1,223 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
aggregateInitialSync,
|
||||
buildEmailMailboxListVM,
|
||||
emailInitialSyncStatusKey,
|
||||
emailMailboxProviderKey,
|
||||
emailMailboxStatusKey,
|
||||
type EmailMailboxRow,
|
||||
} from "./mailbox-list.vm.js";
|
||||
import { buildEmailInboxListVM, decodeInboxCursor, encodeInboxCursor, parseInboxFilters, type EmailInboxRow } from "./inbox-list.vm.js";
|
||||
import { buildComposePrefill, parseRecipients } from "./compose.vm.js";
|
||||
|
||||
// VA-P23 — pure VM builder tests (DoD 18). No React/Prisma imports.
|
||||
|
||||
function rowFixture(overrides: Partial<EmailMailboxRow> = {}): EmailMailboxRow {
|
||||
return {
|
||||
id: "mb1",
|
||||
provider: "gmail",
|
||||
providerKey: emailMailboxProviderKey("gmail"),
|
||||
emailAddress: "max@handwerk.de",
|
||||
displayName: "Max",
|
||||
isDefaultForUser: true,
|
||||
isOwn: true,
|
||||
status: "active",
|
||||
statusKey: emailMailboxStatusKey("active"),
|
||||
lastSyncAt: "2026-07-01T10:00:00.000Z",
|
||||
lastErrorText: null,
|
||||
initialSync: { status: "completed", statusKey: emailInitialSyncStatusKey("completed"), progressPercent: 100, fetchedCount: 12 },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildEmailMailboxListVM", () => {
|
||||
it("is always ready and carries the Klartext keys for the empty state", () => {
|
||||
const vm = buildEmailMailboxListVM({ rows: [], canConnect: true, configuredProviders: { gmail: true, microsoft: false } });
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows).toEqual([]);
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("emailInbox.settings.empty.headline");
|
||||
expect(vm.data?.emptyBodyKey).toBe("emailInbox.settings.empty.body");
|
||||
expect(vm.data?.notConfiguredKey).toBe("emailInbox.settings.notConfigured");
|
||||
expect(vm.data?.configuredProviders).toEqual({ gmail: true, microsoft: false });
|
||||
});
|
||||
|
||||
it("passes rows through untouched (loader owns the mapping)", () => {
|
||||
const row = rowFixture();
|
||||
const vm = buildEmailMailboxListVM({ rows: [row], canConnect: false, configuredProviders: { gmail: true, microsoft: true } });
|
||||
expect(vm.data?.rows[0]).toBe(row);
|
||||
expect(vm.data?.canConnect).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("aggregateInitialSync", () => {
|
||||
it("defaults to pending when no cursor rows exist yet", () => {
|
||||
expect(aggregateInitialSync([])).toEqual({
|
||||
status: "pending",
|
||||
statusKey: "emailInbox.settings.initialSync.pending",
|
||||
progressPercent: null,
|
||||
fetchedCount: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("lets the worst folder status win (failed > running > pending > completed)", () => {
|
||||
const status = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "completed", initialSyncProgress: null },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
]);
|
||||
expect(status.status).toBe("running");
|
||||
const failed = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "failed", initialSyncProgress: null },
|
||||
]);
|
||||
expect(failed.status).toBe("failed");
|
||||
});
|
||||
|
||||
it("averages folder percents only when every folder reports one", () => {
|
||||
const both = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 40, fetchedCount: 40 } },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 60, fetchedCount: 20 } },
|
||||
]);
|
||||
expect(both.progressPercent).toBe(50);
|
||||
expect(both.fetchedCount).toBe(60);
|
||||
|
||||
const partial = aggregateInitialSync([
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 40 } },
|
||||
{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: null },
|
||||
]);
|
||||
expect(partial.progressPercent).toBeNull();
|
||||
});
|
||||
|
||||
it("reports 100% when everything completed", () => {
|
||||
const done = aggregateInitialSync([{ mailboxId: "mb1", initialSyncStatus: "completed", initialSyncProgress: null }]);
|
||||
expect(done.progressPercent).toBe(100);
|
||||
});
|
||||
|
||||
it("clamps out-of-range percents", () => {
|
||||
const clamped = aggregateInitialSync([{ mailboxId: "mb1", initialSyncStatus: "running", initialSyncProgress: { percent: 250 } }]);
|
||||
expect(clamped.progressPercent).toBe(100);
|
||||
});
|
||||
});
|
||||
|
||||
describe("inbox cursor", () => {
|
||||
it("round-trips a keyset cursor", () => {
|
||||
const cursor = encodeInboxCursor("2026-07-01T10:00:00.000Z", "msg-1");
|
||||
expect(decodeInboxCursor(cursor)).toEqual({ sentAtIso: "2026-07-01T10:00:00.000Z", id: "msg-1" });
|
||||
});
|
||||
|
||||
it("rejects malformed cursors defensively", () => {
|
||||
expect(decodeInboxCursor(null)).toBeNull();
|
||||
expect(decodeInboxCursor("garbage")).toBeNull();
|
||||
expect(decodeInboxCursor(encodeURIComponent("not-a-date~id"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseInboxFilters", () => {
|
||||
it("parses valid params and falls back on garbage", () => {
|
||||
const params = new URLSearchParams("mailbox=mb1&direction=inbound&linked=unlinked&read=nonsense&q=+wartung+&archived=1");
|
||||
expect(parseInboxFilters(params)).toEqual({
|
||||
mailboxId: "mb1",
|
||||
direction: "inbound",
|
||||
linked: "unlinked",
|
||||
read: "all",
|
||||
q: "wartung",
|
||||
showArchived: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults everything when params are absent", () => {
|
||||
expect(parseInboxFilters(new URLSearchParams())).toEqual({
|
||||
mailboxId: null,
|
||||
direction: "all",
|
||||
linked: "all",
|
||||
read: "all",
|
||||
q: "",
|
||||
showArchived: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildEmailInboxListVM", () => {
|
||||
it("is ready and carries the Klartext empty/no-mailbox keys", () => {
|
||||
const row: EmailInboxRow = {
|
||||
id: "m1",
|
||||
detailHref: "/acme/emails/m1",
|
||||
fromName: "Max",
|
||||
fromAddress: "max@kunde.de",
|
||||
subject: "Anfrage",
|
||||
snippet: "Hallo",
|
||||
sentAt: "2026-07-01T10:00:00.000Z",
|
||||
direction: "inbound",
|
||||
isRead: false,
|
||||
hasAttachments: true,
|
||||
isNewsletter: false,
|
||||
mailbox: { id: "mb1", emailAddress: "info@handwerk.de", provider: "gmail" },
|
||||
links: [{ type: "kontakt", id: "k1", href: "/acme/contacts/k1" }],
|
||||
};
|
||||
const vm = buildEmailInboxListVM({
|
||||
rows: [row],
|
||||
filters: parseInboxFilters(new URLSearchParams()),
|
||||
mailboxOptions: [{ id: "mb1", emailAddress: "info@handwerk.de" }],
|
||||
nextCursor: "abc",
|
||||
canWrite: true,
|
||||
composeHref: "/acme/emails/new",
|
||||
settingsHref: "/acme/settings/integrations/email",
|
||||
hasAnyMailbox: true,
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.rows[0]).toBe(row);
|
||||
expect(vm.data?.emptyHeadlineKey).toBe("emailInbox.list.empty.headline");
|
||||
expect(vm.data?.noMailboxHeadlineKey).toBe("emailInbox.list.noMailbox.headline");
|
||||
expect(vm.data?.nextCursor).toBe("abc");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildComposePrefill", () => {
|
||||
const original = {
|
||||
id: "m1",
|
||||
direction: "inbound" as const,
|
||||
fromAddress: "max@kunde.de",
|
||||
fromName: "Max",
|
||||
toSummary: "info@handwerk.de",
|
||||
subject: "Anfrage Wartung",
|
||||
sentAtIso: "2026-07-01T10:00:00.000Z",
|
||||
safeBodyHtml: "<p>Hallo</p>",
|
||||
};
|
||||
|
||||
it("reply to inbound answers the sender with Re: and quotes the original", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original });
|
||||
expect(prefill.to).toBe("max@kunde.de");
|
||||
expect(prefill.subject).toBe("Re: Anfrage Wartung");
|
||||
expect(prefill.quotedHtml).toContain("<blockquote");
|
||||
expect(prefill.quotedHtml).toContain("<p>Hallo</p>");
|
||||
expect(prefill.replyToMessageId).toBe("m1");
|
||||
});
|
||||
|
||||
it("does not stack Re: prefixes", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original: { ...original, subject: "Re: Anfrage Wartung" } });
|
||||
expect(prefill.subject).toBe("Re: Anfrage Wartung");
|
||||
});
|
||||
|
||||
it("reply to an own outbound mirror keeps the original recipients", () => {
|
||||
const prefill = buildComposePrefill({ mode: "reply", original: { ...original, direction: "outbound" } });
|
||||
expect(prefill.to).toBe("info@handwerk.de");
|
||||
});
|
||||
|
||||
it("forward starts a new thread with Fwd: and empty recipients", () => {
|
||||
const prefill = buildComposePrefill({ mode: "forward", original });
|
||||
expect(prefill.to).toBe("");
|
||||
expect(prefill.subject).toBe("Fwd: Anfrage Wartung");
|
||||
expect(prefill.replyToMessageId).toBeNull();
|
||||
});
|
||||
|
||||
it("blank compose is empty", () => {
|
||||
expect(buildComposePrefill({ mode: "blank", original: null })).toEqual({ to: "", subject: "", quotedHtml: "", replyToMessageId: null });
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseRecipients", () => {
|
||||
it("splits on commas/semicolons and drops garbage", () => {
|
||||
expect(parseRecipients(" Max@Kunde.de ; second@firma.de,, kein-at ")).toEqual([{ address: "max@kunde.de" }, { address: "second@firma.de" }]);
|
||||
expect(parseRecipients("")).toEqual([]);
|
||||
});
|
||||
});
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · inbox list view-model (M09 Block F). Pure (DoD A.3): the loader
|
||||
* resolves the visible messages (read_own → only the user's own mailboxes;
|
||||
* read_all → every tenant mailbox), applies filters/search/cursor server-side
|
||||
* and this shapes the rows. NO bodies here — the list carries the snippet only.
|
||||
*/
|
||||
|
||||
export type EmailDirectionFilter = "all" | "inbound" | "outbound";
|
||||
export type EmailLinkedFilter = "all" | "linked" | "unlinked";
|
||||
export type EmailReadFilter = "all" | "read" | "unread";
|
||||
|
||||
export interface EmailInboxFilters {
|
||||
readonly mailboxId: string | null;
|
||||
readonly direction: EmailDirectionFilter;
|
||||
readonly linked: EmailLinkedFilter;
|
||||
readonly read: EmailReadFilter;
|
||||
readonly q: string;
|
||||
readonly showArchived: boolean;
|
||||
}
|
||||
|
||||
export interface EmailLinkBadge {
|
||||
readonly type: "kontakt" | "lead" | "projekt";
|
||||
readonly id: string;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface EmailInboxRow {
|
||||
readonly id: string;
|
||||
readonly detailHref: string;
|
||||
readonly fromName: string | null;
|
||||
readonly fromAddress: string;
|
||||
readonly subject: string | null;
|
||||
readonly snippet: string | null;
|
||||
/** ISO timestamp (list shows relative <7d, absolute otherwise — UI concern). */
|
||||
readonly sentAt: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly isRead: boolean;
|
||||
readonly hasAttachments: boolean;
|
||||
readonly isNewsletter: boolean;
|
||||
readonly mailbox: { readonly id: string; readonly emailAddress: string; readonly provider: EmailMailboxProvider };
|
||||
readonly links: readonly EmailLinkBadge[];
|
||||
}
|
||||
|
||||
export interface EmailInboxListData {
|
||||
readonly rows: readonly EmailInboxRow[];
|
||||
readonly filters: EmailInboxFilters;
|
||||
readonly mailboxOptions: ReadonlyArray<{ readonly id: string; readonly emailAddress: string }>;
|
||||
/** Opaque cursor for the next page, or null on the last page. */
|
||||
readonly nextCursor: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly composeHref: string;
|
||||
readonly settingsHref: string;
|
||||
readonly hasAnyMailbox: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly noMailboxHeadlineKey: string;
|
||||
readonly noMailboxBodyKey: string;
|
||||
}
|
||||
|
||||
export type EmailInboxListVM = VMState<EmailInboxListData>;
|
||||
|
||||
export interface BuildEmailInboxListInput {
|
||||
readonly rows: readonly EmailInboxRow[];
|
||||
readonly filters: EmailInboxFilters;
|
||||
readonly mailboxOptions: ReadonlyArray<{ readonly id: string; readonly emailAddress: string }>;
|
||||
readonly nextCursor: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly composeHref: string;
|
||||
readonly settingsHref: string;
|
||||
readonly hasAnyMailbox: boolean;
|
||||
}
|
||||
|
||||
export function buildEmailInboxListVM(input: BuildEmailInboxListInput): EmailInboxListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...input,
|
||||
emptyHeadlineKey: "emailInbox.list.empty.headline",
|
||||
emptyBodyKey: "emailInbox.list.empty.body",
|
||||
noMailboxHeadlineKey: "emailInbox.list.noMailbox.headline",
|
||||
noMailboxBodyKey: "emailInbox.list.noMailbox.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode/decode the keyset cursor `(sentAt, id)` — sorted newest first, the
|
||||
* cursor is the last row of the page. Runtime-agnostic (no Buffer — VMs are
|
||||
* pure and browser-safe); the shape is validated defensively on decode.
|
||||
*/
|
||||
export function encodeInboxCursor(sentAtIso: string, id: string): string {
|
||||
return encodeURIComponent(`${sentAtIso}~${id}`);
|
||||
}
|
||||
|
||||
export function decodeInboxCursor(cursor: string | null | undefined): { sentAtIso: string; id: string } | null {
|
||||
if (!cursor) return null;
|
||||
try {
|
||||
const raw = decodeURIComponent(cursor);
|
||||
const separator = raw.lastIndexOf("~");
|
||||
if (separator <= 0 || separator === raw.length - 1) {
|
||||
return null;
|
||||
}
|
||||
const sentAtIso = raw.slice(0, separator);
|
||||
const id = raw.slice(separator + 1);
|
||||
if (Number.isNaN(Date.parse(sentAtIso))) {
|
||||
return null;
|
||||
}
|
||||
return { sentAtIso, id };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse the filter query params (defensive — bad values fall back to defaults). */
|
||||
export function parseInboxFilters(searchParams: URLSearchParams): EmailInboxFilters {
|
||||
const direction = searchParams.get("direction");
|
||||
const linked = searchParams.get("linked");
|
||||
const read = searchParams.get("read");
|
||||
return {
|
||||
mailboxId: searchParams.get("mailbox") || null,
|
||||
direction: direction === "inbound" || direction === "outbound" ? direction : "all",
|
||||
linked: linked === "linked" || linked === "unlinked" ? linked : "all",
|
||||
read: read === "read" || read === "unread" ? read : "all",
|
||||
q: (searchParams.get("q") ?? "").trim(),
|
||||
showArchived: searchParams.get("archived") === "1",
|
||||
};
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · mailbox connect-settings view-model (M09 Block B/D). Pure (DoD A.3):
|
||||
* the loader resolves the CURRENT user's own mailboxes (read_all admins see all)
|
||||
* and this builds the settings list. NO tokens/credentials/clientState ever
|
||||
* appear here. `configuredProviders` reflects the OAuth env presence so the UI
|
||||
* shows a Klartext "not configured" hint instead of a dead connect button.
|
||||
* `initialSync` aggregates the per-folder cursor rows into one progress line.
|
||||
*/
|
||||
|
||||
export type EmailMailboxProvider = "gmail" | "microsoft";
|
||||
export type EmailMailboxStatus = "connecting" | "active" | "paused" | "error" | "revoked";
|
||||
export type EmailInitialSyncStatus = "pending" | "running" | "completed" | "failed";
|
||||
|
||||
export interface EmailMailboxInitialSync {
|
||||
readonly status: EmailInitialSyncStatus;
|
||||
/** i18n key, e.g. `emailInbox.settings.initialSync.running`. */
|
||||
readonly statusKey: string;
|
||||
/** 0–100 when derivable from the cursor progress rows, else null. */
|
||||
readonly progressPercent: number | null;
|
||||
/** Fetched message count when known (Klartext progress line). */
|
||||
readonly fetchedCount: number | null;
|
||||
}
|
||||
|
||||
export interface EmailMailboxRow {
|
||||
readonly id: string;
|
||||
readonly provider: EmailMailboxProvider;
|
||||
/** i18n key for the provider label (brand names route through i18n, M003). */
|
||||
readonly providerKey: string;
|
||||
readonly emailAddress: string;
|
||||
readonly displayName: string | null;
|
||||
readonly isDefaultForUser: boolean;
|
||||
/** True when the row belongs to the current user (owner actions enabled). */
|
||||
readonly isOwn: boolean;
|
||||
readonly status: EmailMailboxStatus;
|
||||
/** i18n key for the status pill (e.g. `emailInbox.mailbox.status.active`). */
|
||||
readonly statusKey: string;
|
||||
/** ISO timestamp of the last successful sync, or null. */
|
||||
readonly lastSyncAt: string | null;
|
||||
/** Klartext error i18n key/text when status = error (M002), else null. */
|
||||
readonly lastErrorText: string | null;
|
||||
readonly initialSync: EmailMailboxInitialSync;
|
||||
}
|
||||
|
||||
export interface EmailMailboxListData {
|
||||
readonly rows: readonly EmailMailboxRow[];
|
||||
/** True when the user may connect a mailbox (email.write bundles it). */
|
||||
readonly canConnect: boolean;
|
||||
readonly configuredProviders: { readonly gmail: boolean; readonly microsoft: boolean };
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly notConfiguredKey: string;
|
||||
}
|
||||
|
||||
export type EmailMailboxListVM = VMState<EmailMailboxListData>;
|
||||
|
||||
export function emailMailboxStatusKey(status: EmailMailboxStatus): string {
|
||||
return `emailInbox.mailbox.status.${status}`;
|
||||
}
|
||||
|
||||
export function emailMailboxProviderKey(provider: EmailMailboxProvider): string {
|
||||
return `emailInbox.provider.${provider}`;
|
||||
}
|
||||
|
||||
export function emailInitialSyncStatusKey(status: EmailInitialSyncStatus): string {
|
||||
return `emailInbox.settings.initialSync.${status}`;
|
||||
}
|
||||
|
||||
/** One per-folder cursor row as the loader reads it (progress is JSONB). */
|
||||
export interface EmailSyncCursorInput {
|
||||
readonly mailboxId: string;
|
||||
readonly initialSyncStatus: EmailInitialSyncStatus;
|
||||
readonly initialSyncProgress: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Aggregate the per-folder cursor rows of ONE mailbox into a single progress
|
||||
* line: worst status wins (failed > running > pending > completed); percent is
|
||||
* the mean of folder percents when every folder reports one.
|
||||
*/
|
||||
export function aggregateInitialSync(cursors: readonly EmailSyncCursorInput[]): EmailMailboxInitialSync {
|
||||
if (cursors.length === 0) {
|
||||
return { status: "pending", statusKey: emailInitialSyncStatusKey("pending"), progressPercent: null, fetchedCount: null };
|
||||
}
|
||||
const order: Record<EmailInitialSyncStatus, number> = { failed: 3, running: 2, pending: 1, completed: 0 };
|
||||
let status: EmailInitialSyncStatus = "completed";
|
||||
let fetchedCount = 0;
|
||||
let sawFetched = false;
|
||||
const percents: number[] = [];
|
||||
for (const cursor of cursors) {
|
||||
if (order[cursor.initialSyncStatus] > order[status]) {
|
||||
status = cursor.initialSyncStatus;
|
||||
}
|
||||
const progress = cursor.initialSyncProgress as { percent?: unknown; fetchedCount?: unknown } | null;
|
||||
if (progress && typeof progress.percent === "number") {
|
||||
percents.push(Math.max(0, Math.min(100, progress.percent)));
|
||||
}
|
||||
if (progress && typeof progress.fetchedCount === "number") {
|
||||
fetchedCount += progress.fetchedCount;
|
||||
sawFetched = true;
|
||||
}
|
||||
}
|
||||
const progressPercent =
|
||||
status === "completed" ? 100 : percents.length === cursors.length && percents.length > 0 ? Math.round(percents.reduce((a, b) => a + b, 0) / percents.length) : null;
|
||||
return {
|
||||
status,
|
||||
statusKey: emailInitialSyncStatusKey(status),
|
||||
progressPercent,
|
||||
fetchedCount: sawFetched ? fetchedCount : null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface BuildEmailMailboxListInput {
|
||||
readonly rows: readonly EmailMailboxRow[];
|
||||
readonly canConnect: boolean;
|
||||
readonly configuredProviders: { readonly gmail: boolean; readonly microsoft: boolean };
|
||||
}
|
||||
|
||||
export function buildEmailMailboxListVM(input: BuildEmailMailboxListInput): EmailMailboxListVM {
|
||||
// Always "ready" (mirrors the calendar connection VM): the UI renders the
|
||||
// empty-state from the keys when `rows` is empty, keeping the connect
|
||||
// affordance + config hint available.
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canConnect: input.canConnect,
|
||||
configuredProviders: input.configuredProviders,
|
||||
emptyHeadlineKey: "emailInbox.settings.empty.headline",
|
||||
emptyBodyKey: "emailInbox.settings.empty.body",
|
||||
notConfiguredKey: "emailInbox.settings.notConfigured",
|
||||
},
|
||||
};
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { EmailMailboxProvider } from "./mailbox-list.vm.js";
|
||||
import type { EmailLinkBadge } from "./inbox-list.vm.js";
|
||||
|
||||
/**
|
||||
* VA-P23 · message/thread detail view-model (M09 Block F detail). Pure: the
|
||||
* loader sanitizes the bodies SERVER-SIDE (emailHtmlSanitizer) and passes the
|
||||
* safe HTML in — this VM never sees raw provider HTML. Thread = every mirror
|
||||
* with the same providerThreadId, chronological; all but the focused message
|
||||
* collapse by default.
|
||||
*/
|
||||
|
||||
export interface EmailThreadMessageVM {
|
||||
readonly id: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly fromName: string | null;
|
||||
readonly fromAddress: string;
|
||||
readonly toSummary: string;
|
||||
readonly ccSummary: string | null;
|
||||
readonly subject: string | null;
|
||||
/** SANITIZED html (or escaped plain-text render) — safe to inject. */
|
||||
readonly safeBodyHtml: string;
|
||||
readonly blockedImageCount: number;
|
||||
readonly sentAt: string;
|
||||
readonly isRead: boolean;
|
||||
readonly isFocused: boolean;
|
||||
readonly collapsedByDefault: boolean;
|
||||
}
|
||||
|
||||
export interface EmailAttachmentVM {
|
||||
readonly attachmentId: string;
|
||||
readonly filename: string;
|
||||
readonly sizeBytes: number;
|
||||
/** Set once imported into v1-Files (download runs via the Files auth-proxy). */
|
||||
readonly importedFileId: string | null;
|
||||
readonly downloadHref: string | null;
|
||||
}
|
||||
|
||||
export interface EmailMatchStateVM {
|
||||
readonly links: readonly EmailLinkBadge[];
|
||||
readonly confidence: "high" | "medium" | "low" | "manual" | "none";
|
||||
/** i18n key: auto-detected vs manually assigned hint (M09 Block F). */
|
||||
readonly sourceKey: string;
|
||||
readonly isManual: boolean;
|
||||
}
|
||||
|
||||
export interface EmailMessageDetailData {
|
||||
readonly focusedId: string;
|
||||
readonly subject: string | null;
|
||||
readonly mailbox: { readonly emailAddress: string; readonly provider: EmailMailboxProvider };
|
||||
readonly thread: readonly EmailThreadMessageVM[];
|
||||
readonly attachments: readonly EmailAttachmentVM[];
|
||||
readonly match: EmailMatchStateVM;
|
||||
readonly canWrite: boolean;
|
||||
readonly replyHref: string;
|
||||
readonly forwardHref: string;
|
||||
readonly backHref: string;
|
||||
readonly allowExternalImages: boolean;
|
||||
}
|
||||
|
||||
export type EmailMessageDetailVM = VMState<EmailMessageDetailData>;
|
||||
|
||||
export function emailMatchSourceKey(confidence: EmailMatchStateVM["confidence"]): string {
|
||||
return confidence === "manual" ? "emailInbox.detail.match.manual" : confidence === "none" ? "emailInbox.detail.match.none" : "emailInbox.detail.match.auto";
|
||||
}
|
||||
|
||||
export function buildEmailMessageDetailVM(data: EmailMessageDetailData): EmailMessageDetailVM {
|
||||
return { status: "ready", data };
|
||||
}
|
||||
|
||||
/** Address list → compact display summary ("Max <max@x.de>, anna@y.de"). */
|
||||
export function summarizeAddresses(list: unknown): string {
|
||||
if (!Array.isArray(list)) return "";
|
||||
return list
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== "object") return "";
|
||||
const address = String((entry as { address?: unknown }).address ?? "");
|
||||
const name = (entry as { name?: unknown }).name;
|
||||
return typeof name === "string" && name.trim() ? `${name} <${address}>` : address;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(", ");
|
||||
}
|
||||
Reference in new issue
Block a user