Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+147
@@ -0,0 +1,147 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminLeadManualFormSchema,
|
||||
adminLeadMutationFormSchema,
|
||||
buildAdminLeadDetailVM,
|
||||
buildAdminLeadListVM,
|
||||
buildAdminLeadSourcesVM,
|
||||
} from "./platform-leads.vm.js";
|
||||
|
||||
describe("platform lead view-models", () => {
|
||||
it("builds a serializable list with status labels, summaries and stable display fallbacks", () => {
|
||||
const vm = buildAdminLeadListVM({
|
||||
rows: [
|
||||
{
|
||||
id: "lead_1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.test",
|
||||
phone: null,
|
||||
company: "Analytical Engines",
|
||||
status: "qualified",
|
||||
sourceId: "source_1",
|
||||
sourceDisplayName: "HiveGrid Website",
|
||||
assignedToAdminUserId: "user_1",
|
||||
assigneeLabel: "Haris",
|
||||
duplicateHintOfLeadId: null,
|
||||
capturedAt: "2026-07-16T10:00:00.000Z",
|
||||
archivedAt: null,
|
||||
},
|
||||
{
|
||||
id: "lead_2",
|
||||
firstName: null,
|
||||
lastName: null,
|
||||
email: null,
|
||||
phone: "+49 123",
|
||||
company: null,
|
||||
status: "new",
|
||||
sourceId: "source_2",
|
||||
sourceDisplayName: "Partner Website",
|
||||
assignedToAdminUserId: null,
|
||||
assigneeLabel: null,
|
||||
duplicateHintOfLeadId: "lead_1",
|
||||
capturedAt: "2026-07-16T11:00:00.000Z",
|
||||
archivedAt: null,
|
||||
},
|
||||
],
|
||||
sourceOptions: [
|
||||
{ id: "source_2", label: "Partner Website" },
|
||||
{ id: "source_1", label: "HiveGrid Website" },
|
||||
],
|
||||
assigneeOptions: [{ id: "user_1", label: "Haris" }],
|
||||
summary: { total: 101, newCount: 50, qualifiedCount: 25, unassignedCount: 12, archivedCount: 14 },
|
||||
pagination: { hasPrevious: true, nextCursor: "lead_2" },
|
||||
permissions: { canCreate: true, canWrite: true, canAdminSources: false },
|
||||
});
|
||||
|
||||
expect(vm.rows[0]).toMatchObject({ displayName: "Ada Lovelace", statusLabelKey: "admin.platformLeads.status.qualified", statusTone: "subtle-positive" });
|
||||
expect(vm.rows[1]?.displayName).toBe("+49 123");
|
||||
expect(vm.summary).toEqual({ total: 101, newCount: 50, qualifiedCount: 25, unassignedCount: 12, archivedCount: 14 });
|
||||
expect(vm.pagination).toEqual({ hasPrevious: true, nextCursor: "lead_2" });
|
||||
expect(JSON.parse(JSON.stringify(vm))).toEqual(vm);
|
||||
});
|
||||
|
||||
it("sorts the detail timeline newest first and keeps notes explicit", () => {
|
||||
const vm = buildAdminLeadDetailVM({
|
||||
lead: {
|
||||
id: "lead_1",
|
||||
firstName: "Ada",
|
||||
lastName: null,
|
||||
email: "ada@example.test",
|
||||
phone: null,
|
||||
company: null,
|
||||
message: "Rueckruf",
|
||||
status: "contacted",
|
||||
sourceId: "source_1",
|
||||
sourceDisplayName: "Website",
|
||||
sourceDetail: null,
|
||||
externalId: "form_1",
|
||||
assignedToAdminUserId: null,
|
||||
assigneeLabel: null,
|
||||
duplicateHintOfLeadId: null,
|
||||
capturedAt: "2026-07-16T10:00:00.000Z",
|
||||
createdAt: "2026-07-16T10:00:00.000Z",
|
||||
updatedAt: "2026-07-16T11:00:00.000Z",
|
||||
archivedAt: null,
|
||||
attribution: { utmSource: null, utmMedium: null, utmCampaign: null, utmTerm: null, utmContent: null, referrer: null, landingPage: null },
|
||||
qualification: null,
|
||||
duplicateCandidates: [],
|
||||
conversion: { companyId: null, contactId: null, dealId: null },
|
||||
activities: [
|
||||
{ id: "a1", type: "captured", actorAdminUserId: null, actorLabel: null, note: null, createdAt: "2026-07-16T10:00:00.000Z" },
|
||||
{ id: "a2", type: "note_added", actorAdminUserId: "user_1", actorLabel: "Haris", note: "Angerufen", createdAt: "2026-07-16T11:00:00.000Z" },
|
||||
],
|
||||
},
|
||||
assigneeOptions: [],
|
||||
permissions: { canWrite: true, canAssign: true, canMerge: true },
|
||||
});
|
||||
|
||||
expect(vm.activities.map((activity) => activity.id)).toEqual(["a2", "a1"]);
|
||||
expect(vm.activities[0]).toMatchObject({ labelKey: "admin.platformLeads.activity.note_added", note: "Angerufen" });
|
||||
});
|
||||
|
||||
it("counts only active source credentials and never persists a revealed key in a row", () => {
|
||||
const vm = buildAdminLeadSourcesVM({
|
||||
rows: [
|
||||
{
|
||||
id: "source_1",
|
||||
key: "hivegrid-website",
|
||||
displayName: "HiveGrid Website",
|
||||
enabled: true,
|
||||
defaultAssigneeAdminUserId: "user_1",
|
||||
defaultAssigneeLabel: "Haris",
|
||||
notifyAdminUserIds: ["user_1"],
|
||||
notifyAdminUserLabels: ["Haris"],
|
||||
rateLimitPerMinute: 60,
|
||||
leadCount: 3,
|
||||
credentials: [
|
||||
{ id: "active", keyPrefix: "hg_live_1234", createdAt: "2026-07-16T10:00:00.000Z", expiresAt: null, revokedAt: null, lastUsedAt: null },
|
||||
{
|
||||
id: "revoked",
|
||||
keyPrefix: "hg_live_9876",
|
||||
createdAt: "2026-07-15T10:00:00.000Z",
|
||||
expiresAt: null,
|
||||
revokedAt: "2026-07-16T10:00:00.000Z",
|
||||
lastUsedAt: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
assigneeOptions: [{ id: "user_1", label: "Haris" }],
|
||||
canAdmin: true,
|
||||
now: "2026-07-16T12:00:00.000Z",
|
||||
revealedCredential: { sourceId: "source_1", plaintext: "shown-once" },
|
||||
});
|
||||
|
||||
expect(vm.rows[0]?.activeCredentialCount).toBe(1);
|
||||
expect(vm.rows[0]).not.toHaveProperty("plaintext");
|
||||
expect(vm.revealedCredential?.plaintext).toBe("shown-once");
|
||||
});
|
||||
|
||||
it("validates manual intake without requiring email and rejects empty contacts", () => {
|
||||
expect(adminLeadManualFormSchema.parse({ sourceId: "source_1", phone: "+49 30 123" })).toMatchObject({ phone: "+49 30 123" });
|
||||
expect(adminLeadManualFormSchema.safeParse({ sourceId: "source_1" }).success).toBe(false);
|
||||
expect(adminLeadMutationFormSchema.safeParse({ intent: "note", note: "" }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
+407
@@ -0,0 +1,407 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminLeadStatuses = ["new", "contacted", "qualified", "disqualified"] as const;
|
||||
export type AdminLeadStatus = (typeof adminLeadStatuses)[number];
|
||||
|
||||
export const adminLeadActivityTypes = [
|
||||
"captured",
|
||||
"imported",
|
||||
"manually_created",
|
||||
"status_changed",
|
||||
"assigned",
|
||||
"note_added",
|
||||
"archived",
|
||||
"restored",
|
||||
"duplicate_hint_recorded",
|
||||
"legacy_event",
|
||||
] as const;
|
||||
export type AdminLeadActivityType = (typeof adminLeadActivityTypes)[number];
|
||||
|
||||
const optionalTrimmedString = (maximum: number) =>
|
||||
z.preprocess((value) => (typeof value === "string" && value.trim() === "" ? undefined : value), z.string().trim().max(maximum).optional());
|
||||
|
||||
export const adminLeadManualFormSchema = z
|
||||
.object({
|
||||
sourceId: z.string().trim().min(1).max(191),
|
||||
firstName: optionalTrimmedString(200),
|
||||
lastName: optionalTrimmedString(200),
|
||||
email: z.preprocess((value) => (typeof value === "string" && value.trim() === "" ? undefined : value), z.string().trim().email().max(320).optional()),
|
||||
phone: optionalTrimmedString(100),
|
||||
company: optionalTrimmedString(300),
|
||||
message: optionalTrimmedString(8_000),
|
||||
sourceDetail: optionalTrimmedString(500),
|
||||
assignedToAdminUserId: optionalTrimmedString(191),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (![value.firstName, value.lastName, value.email, value.phone, value.company, value.message].some(Boolean)) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, path: ["message"], message: "admin.platformLeads.errors.contactRequired" });
|
||||
}
|
||||
});
|
||||
|
||||
export const adminLeadMutationFormSchema = z.discriminatedUnion("intent", [
|
||||
z.object({ intent: z.literal("status"), status: z.enum(adminLeadStatuses) }),
|
||||
z.object({ intent: z.literal("assign"), assignedToAdminUserId: z.string().trim().max(191).nullable() }),
|
||||
z.object({ intent: z.literal("note"), note: z.string().trim().min(1).max(8_000) }),
|
||||
z.object({ intent: z.literal("archive") }),
|
||||
z.object({ intent: z.literal("restore") }),
|
||||
]);
|
||||
|
||||
export const adminLeadAdvancedMutationFormSchema = z.discriminatedUnion("intent", [
|
||||
z.object({ intent: z.literal("auto-assign") }),
|
||||
z.object({ intent: z.literal("score") }),
|
||||
z.object({ intent: z.literal("detect-duplicates") }),
|
||||
z.object({
|
||||
intent: z.literal("enrich"),
|
||||
provider: z.string().trim().min(1).max(120),
|
||||
companyName: optionalTrimmedString(200),
|
||||
domain: optionalTrimmedString(253),
|
||||
website: optionalTrimmedString(2_048),
|
||||
region: optionalTrimmedString(120),
|
||||
countryCode: optionalTrimmedString(2),
|
||||
industry: optionalTrimmedString(120),
|
||||
employeeRange: optionalTrimmedString(80),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("dismiss-duplicate"),
|
||||
candidateId: z.string().trim().min(1).max(191),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("merge"),
|
||||
candidateId: z.string().trim().min(1).max(191),
|
||||
survivorLeadId: z.string().trim().min(1).max(191),
|
||||
mergedLeadId: z.string().trim().min(1).max(191),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("convert"),
|
||||
companyName: z.string().trim().min(1).max(200),
|
||||
firstName: z.string().trim().min(1).max(120),
|
||||
lastName: z.string().trim().min(1).max(120),
|
||||
dealTitle: z.string().trim().min(1).max(200),
|
||||
ownerAdminUserId: z.string().trim().min(1).max(191),
|
||||
amountCents: z.preprocess(
|
||||
(value) => (value === "" || value === null ? undefined : value),
|
||||
z.coerce.number().int().min(0).optional()
|
||||
),
|
||||
expectedCloseDate: z.preprocess(
|
||||
(value) => (value === "" || value === null ? undefined : value),
|
||||
z.coerce.date().optional()
|
||||
),
|
||||
nextStep: optionalTrimmedString(2_000),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const adminLeadSourceFormSchema = z.discriminatedUnion("intent", [
|
||||
z.object({
|
||||
intent: z.literal("create-source"),
|
||||
key: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2)
|
||||
.max(100)
|
||||
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),
|
||||
displayName: z.string().trim().min(1).max(200),
|
||||
defaultAssigneeAdminUserId: optionalTrimmedString(191),
|
||||
notifyAdminUserIds: z.array(z.string().trim().min(1).max(191)).max(20).default([]),
|
||||
rateLimitPerMinute: z.coerce.number().int().min(1).max(10_000),
|
||||
}),
|
||||
z.object({ intent: z.literal("set-enabled"), sourceId: z.string().trim().min(1).max(191), enabled: z.boolean() }),
|
||||
z.object({
|
||||
intent: z.literal("update-routing"),
|
||||
sourceId: z.string().trim().min(1).max(191),
|
||||
defaultAssigneeAdminUserId: optionalTrimmedString(191),
|
||||
notifyAdminUserIds: z.array(z.string().trim().min(1).max(191)).max(20).default([]),
|
||||
rateLimitPerMinute: z.coerce.number().int().min(1).max(10_000),
|
||||
}),
|
||||
z.object({ intent: z.literal("create-credential"), sourceId: z.string().trim().min(1).max(191), expiresAt: z.coerce.date().optional() }),
|
||||
z.object({
|
||||
intent: z.literal("rotate-credential"),
|
||||
sourceId: z.string().trim().min(1).max(191),
|
||||
credentialId: z.string().trim().min(1).max(191),
|
||||
expiresAt: z.coerce.date().optional(),
|
||||
}),
|
||||
z.object({ intent: z.literal("revoke-credential"), sourceId: z.string().trim().min(1).max(191), credentialId: z.string().trim().min(1).max(191) }),
|
||||
]);
|
||||
|
||||
export type AdminLeadOption = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
};
|
||||
|
||||
export type AdminLeadListInputRow = {
|
||||
readonly id: string;
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly company: string | null;
|
||||
readonly status: AdminLeadStatus;
|
||||
readonly sourceId: string;
|
||||
readonly sourceDisplayName: string;
|
||||
readonly assignedToAdminUserId: string | null;
|
||||
readonly assigneeLabel: string | null;
|
||||
readonly duplicateHintOfLeadId: string | null;
|
||||
readonly capturedAt: string;
|
||||
readonly archivedAt: string | null;
|
||||
};
|
||||
|
||||
export type AdminLeadListRow = AdminLeadListInputRow & {
|
||||
readonly displayName: string;
|
||||
readonly contactLine: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly statusTone: "subtle-neutral" | "subtle-warning" | "subtle-positive" | "subtle-negative";
|
||||
};
|
||||
|
||||
export type AdminLeadListVM = {
|
||||
readonly rows: readonly AdminLeadListRow[];
|
||||
readonly sourceOptions: readonly AdminLeadOption[];
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly filters: {
|
||||
readonly query: string;
|
||||
readonly status: AdminLeadStatus | "all";
|
||||
readonly sourceId: string | "all";
|
||||
readonly assignedToAdminUserId: string | "all" | "unassigned";
|
||||
readonly archive: "active" | "archived" | "all";
|
||||
};
|
||||
readonly summary: {
|
||||
readonly total: number;
|
||||
readonly newCount: number;
|
||||
readonly qualifiedCount: number;
|
||||
readonly unassignedCount: number;
|
||||
readonly archivedCount: number;
|
||||
};
|
||||
readonly pagination: {
|
||||
readonly hasPrevious: boolean;
|
||||
readonly nextCursor: string | null;
|
||||
};
|
||||
readonly permissions: {
|
||||
readonly canCreate: boolean;
|
||||
readonly canWrite: boolean;
|
||||
readonly canAdminSources: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export function buildAdminLeadListVM(input: {
|
||||
readonly rows: readonly AdminLeadListInputRow[];
|
||||
readonly sourceOptions: readonly AdminLeadOption[];
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly filters?: Partial<AdminLeadListVM["filters"]>;
|
||||
readonly summary?: Partial<AdminLeadListVM["summary"]>;
|
||||
readonly pagination?: Partial<AdminLeadListVM["pagination"]>;
|
||||
readonly permissions: AdminLeadListVM["permissions"];
|
||||
}): AdminLeadListVM {
|
||||
const rows = input.rows.map(
|
||||
(row): AdminLeadListRow => ({
|
||||
...row,
|
||||
displayName: leadDisplayName(row),
|
||||
contactLine: [row.email, row.phone].filter(Boolean).join(" · "),
|
||||
statusLabelKey: `admin.platformLeads.status.${row.status}`,
|
||||
statusTone: adminLeadStatusTone(row.status),
|
||||
})
|
||||
);
|
||||
return {
|
||||
rows,
|
||||
sourceOptions: [...input.sourceOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
assigneeOptions: [...input.assigneeOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
filters: {
|
||||
query: input.filters?.query ?? "",
|
||||
status: input.filters?.status ?? "all",
|
||||
sourceId: input.filters?.sourceId ?? "all",
|
||||
assignedToAdminUserId: input.filters?.assignedToAdminUserId ?? "all",
|
||||
archive: input.filters?.archive ?? "active",
|
||||
},
|
||||
summary: {
|
||||
total: input.summary?.total ?? rows.length,
|
||||
newCount: input.summary?.newCount ?? rows.filter((row) => row.status === "new" && !row.archivedAt).length,
|
||||
qualifiedCount: input.summary?.qualifiedCount ?? rows.filter((row) => row.status === "qualified" && !row.archivedAt).length,
|
||||
unassignedCount: input.summary?.unassignedCount ?? rows.filter((row) => !row.assignedToAdminUserId && !row.archivedAt).length,
|
||||
archivedCount: input.summary?.archivedCount ?? rows.filter((row) => Boolean(row.archivedAt)).length,
|
||||
},
|
||||
pagination: {
|
||||
hasPrevious: input.pagination?.hasPrevious ?? false,
|
||||
nextCursor: input.pagination?.nextCursor ?? null,
|
||||
},
|
||||
permissions: input.permissions,
|
||||
};
|
||||
}
|
||||
|
||||
export type AdminLeadDetailInput = {
|
||||
readonly id: string;
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly company: string | null;
|
||||
readonly message: string | null;
|
||||
readonly status: AdminLeadStatus;
|
||||
readonly sourceId: string;
|
||||
readonly sourceDisplayName: string;
|
||||
readonly sourceDetail: string | null;
|
||||
readonly externalId: string | null;
|
||||
readonly assignedToAdminUserId: string | null;
|
||||
readonly assigneeLabel: string | null;
|
||||
readonly duplicateHintOfLeadId: string | null;
|
||||
readonly capturedAt: string;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
readonly archivedAt: string | null;
|
||||
readonly attribution: {
|
||||
readonly utmSource: string | null;
|
||||
readonly utmMedium: string | null;
|
||||
readonly utmCampaign: string | null;
|
||||
readonly utmTerm: string | null;
|
||||
readonly utmContent: string | null;
|
||||
readonly referrer: string | null;
|
||||
readonly landingPage: string | null;
|
||||
};
|
||||
readonly qualification: {
|
||||
readonly score: number;
|
||||
readonly scoreBand: string;
|
||||
readonly scoreVersion: number;
|
||||
readonly enrichmentStatus: "pending" | "complete" | "unavailable" | "failed";
|
||||
readonly enrichmentProvider: string | null;
|
||||
readonly enrichmentData: Record<string, unknown> | null;
|
||||
readonly enrichedAt: string | null;
|
||||
} | null;
|
||||
readonly duplicateCandidates: readonly {
|
||||
readonly id: string;
|
||||
readonly primaryLeadId: string;
|
||||
readonly duplicateLeadId: string;
|
||||
readonly status: "open" | "dismissed" | "merged";
|
||||
readonly matchKeys: readonly string[];
|
||||
readonly confidenceBasisPoints: number;
|
||||
}[];
|
||||
readonly conversion: {
|
||||
readonly companyId: string | null;
|
||||
readonly contactId: string | null;
|
||||
readonly dealId: string | null;
|
||||
};
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly type: AdminLeadActivityType;
|
||||
readonly actorAdminUserId: string | null;
|
||||
readonly actorLabel: string | null;
|
||||
readonly note: string | null;
|
||||
readonly createdAt: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AdminLeadDetailVM = Omit<AdminLeadDetailInput, "activities"> & {
|
||||
readonly displayName: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly statusTone: AdminLeadListRow["statusTone"];
|
||||
readonly activities: readonly (AdminLeadDetailInput["activities"][number] & { readonly labelKey: string })[];
|
||||
readonly duplicates: readonly (AdminLeadDetailInput["duplicateCandidates"][number] & {
|
||||
readonly candidateLeadId: string;
|
||||
readonly confidencePercent: number;
|
||||
})[];
|
||||
readonly enrichmentRows: readonly {
|
||||
readonly key: string;
|
||||
readonly value: string;
|
||||
}[];
|
||||
readonly converted: boolean;
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly permissions: {
|
||||
readonly canWrite: boolean;
|
||||
readonly canAssign: boolean;
|
||||
readonly canMerge: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export function buildAdminLeadDetailVM(input: {
|
||||
readonly lead: AdminLeadDetailInput;
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly permissions: AdminLeadDetailVM["permissions"];
|
||||
}): AdminLeadDetailVM {
|
||||
return {
|
||||
...input.lead,
|
||||
displayName: leadDisplayName(input.lead),
|
||||
statusLabelKey: `admin.platformLeads.status.${input.lead.status}`,
|
||||
statusTone: adminLeadStatusTone(input.lead.status),
|
||||
activities: [...input.lead.activities]
|
||||
.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
|
||||
.map((activity) => ({ ...activity, labelKey: `admin.platformLeads.activity.${activity.type}` })),
|
||||
duplicates: input.lead.duplicateCandidates.map((candidate) => ({
|
||||
...candidate,
|
||||
candidateLeadId:
|
||||
candidate.primaryLeadId === input.lead.id ? candidate.duplicateLeadId : candidate.primaryLeadId,
|
||||
confidencePercent: Math.round(candidate.confidenceBasisPoints / 100),
|
||||
})),
|
||||
enrichmentRows: Object.entries(input.lead.qualification?.enrichmentData ?? {})
|
||||
.filter((entry): entry is [string, string | number | boolean] =>
|
||||
["string", "number", "boolean"].includes(typeof entry[1])
|
||||
)
|
||||
.map(([key, value]) => ({ key, value: String(value) }))
|
||||
.sort((a, b) => a.key.localeCompare(b.key, "de")),
|
||||
converted: Boolean(
|
||||
input.lead.conversion.companyId &&
|
||||
input.lead.conversion.contactId &&
|
||||
input.lead.conversion.dealId
|
||||
),
|
||||
assigneeOptions: [...input.assigneeOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
permissions: input.permissions,
|
||||
};
|
||||
}
|
||||
|
||||
export type AdminLeadSourceInput = {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly displayName: string;
|
||||
readonly enabled: boolean;
|
||||
readonly defaultAssigneeAdminUserId: string | null;
|
||||
readonly defaultAssigneeLabel: string | null;
|
||||
readonly notifyAdminUserIds: readonly string[];
|
||||
readonly notifyAdminUserLabels: readonly string[];
|
||||
readonly rateLimitPerMinute: number;
|
||||
readonly leadCount: number;
|
||||
readonly credentials: readonly {
|
||||
readonly id: string;
|
||||
readonly keyPrefix: string;
|
||||
readonly createdAt: string;
|
||||
readonly expiresAt: string | null;
|
||||
readonly revokedAt: string | null;
|
||||
readonly lastUsedAt: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AdminLeadSourcesVM = {
|
||||
readonly rows: readonly (AdminLeadSourceInput & { readonly activeCredentialCount: number })[];
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly canAdmin: boolean;
|
||||
readonly revealedCredential: { readonly sourceId: string; readonly plaintext: string } | null;
|
||||
};
|
||||
|
||||
export function buildAdminLeadSourcesVM(input: {
|
||||
readonly rows: readonly AdminLeadSourceInput[];
|
||||
readonly assigneeOptions: readonly AdminLeadOption[];
|
||||
readonly canAdmin: boolean;
|
||||
readonly now: string;
|
||||
readonly revealedCredential?: AdminLeadSourcesVM["revealedCredential"];
|
||||
}): AdminLeadSourcesVM {
|
||||
const now = Date.parse(input.now);
|
||||
if (!Number.isFinite(now)) throw new TypeError("Admin lead source VM requires a valid now timestamp.");
|
||||
return {
|
||||
rows: [...input.rows]
|
||||
.sort((a, b) => a.displayName.localeCompare(b.displayName, "de"))
|
||||
.map((row) => ({
|
||||
...row,
|
||||
credentials: [...row.credentials].sort((a, b) => b.createdAt.localeCompare(a.createdAt)),
|
||||
activeCredentialCount: row.credentials.filter(
|
||||
(credential) => !credential.revokedAt && (!credential.expiresAt || Date.parse(credential.expiresAt) > now)
|
||||
).length,
|
||||
})),
|
||||
assigneeOptions: [...input.assigneeOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
canAdmin: input.canAdmin,
|
||||
revealedCredential: input.revealedCredential ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function adminLeadStatusTone(status: AdminLeadStatus): AdminLeadListRow["statusTone"] {
|
||||
if (status === "qualified") return "subtle-positive";
|
||||
if (status === "contacted") return "subtle-warning";
|
||||
if (status === "disqualified") return "subtle-negative";
|
||||
return "subtle-neutral";
|
||||
}
|
||||
|
||||
function leadDisplayName(lead: Pick<AdminLeadListInputRow, "firstName" | "lastName" | "company" | "email" | "phone">): string {
|
||||
return [[lead.firstName, lead.lastName].filter(Boolean).join(" "), lead.company, lead.email, lead.phone].find(Boolean) ?? "";
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminSecurityProfileVM } from "./admin-security.vm.js";
|
||||
|
||||
describe("admin security profile VM", () => {
|
||||
it("derives Authentik assurance and sorts roles and sessions deterministically", () => {
|
||||
const vm = buildAdminSecurityProfileVM({
|
||||
identity: {
|
||||
id: "admin-1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
status: "active",
|
||||
authentikSubject: "subject-1",
|
||||
lastSsoLoginAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
},
|
||||
roles: [
|
||||
{ id: "2", name: "Support", systemKey: "support" },
|
||||
{ id: "1", name: "Super Admin", systemKey: "super_admin" },
|
||||
],
|
||||
sessions: [
|
||||
{
|
||||
id: "old",
|
||||
createdAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-24T08:30:00.000Z"),
|
||||
expiresAt: new Date("2026-07-24T16:00:00.000Z"),
|
||||
approxLocation: null,
|
||||
userAgent: null,
|
||||
mfaAssuredAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
},
|
||||
{
|
||||
id: "current",
|
||||
createdAt: new Date("2026-07-24T09:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-24T09:30:00.000Z"),
|
||||
expiresAt: new Date("2026-07-24T17:00:00.000Z"),
|
||||
approxLocation: "Germany",
|
||||
userAgent: "Browser",
|
||||
mfaAssuredAt: new Date("2026-07-24T09:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
currentSessionId: "current",
|
||||
});
|
||||
|
||||
expect(vm.identity).toMatchObject({
|
||||
displayName: "Ada Lovelace",
|
||||
authentikConnected: true,
|
||||
mfaAssured: true,
|
||||
});
|
||||
expect(vm.roles.map((role) => role.name)).toEqual(["Super Admin", "Support"]);
|
||||
expect(vm.sessions.map((session) => session.id)).toEqual(["current", "old"]);
|
||||
expect(vm.sessions[0]?.current).toBe(true);
|
||||
});
|
||||
});
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminSecurityProfileVMSchema = z.object({
|
||||
identity: z.object({
|
||||
id: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
displayName: z.string().min(1),
|
||||
status: z.enum(["active", "disabled", "locked"]),
|
||||
authentikConnected: z.boolean(),
|
||||
mfaAssured: z.boolean(),
|
||||
lastSsoLoginAt: z.string().datetime().nullable(),
|
||||
}),
|
||||
roles: z.array(z.object({ id: z.string().min(1), name: z.string().min(1), systemKey: z.string().nullable() })),
|
||||
sessions: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
current: z.boolean(),
|
||||
createdAt: z.string().datetime(),
|
||||
lastSeenAt: z.string().datetime(),
|
||||
expiresAt: z.string().datetime(),
|
||||
approxLocation: z.string().nullable(),
|
||||
userAgent: z.string().nullable(),
|
||||
mfaAssured: z.boolean(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type AdminSecurityProfileVM = z.infer<typeof adminSecurityProfileVMSchema>;
|
||||
|
||||
export type AdminSecurityProfileInput = {
|
||||
identity: {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
status: "active" | "disabled" | "locked";
|
||||
authentikSubject: string | null;
|
||||
lastSsoLoginAt: Date | null;
|
||||
};
|
||||
roles: readonly { id: string; name: string; systemKey: string | null }[];
|
||||
sessions: readonly {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
lastSeenAt: Date;
|
||||
expiresAt: Date;
|
||||
approxLocation: string | null;
|
||||
userAgent: string | null;
|
||||
mfaAssuredAt: Date | null;
|
||||
}[];
|
||||
currentSessionId: string;
|
||||
};
|
||||
|
||||
export function buildAdminSecurityProfileVM(input: AdminSecurityProfileInput): AdminSecurityProfileVM {
|
||||
const displayName = [input.identity.firstName, input.identity.lastName].filter(Boolean).join(" ").trim() || input.identity.email;
|
||||
return adminSecurityProfileVMSchema.parse({
|
||||
identity: {
|
||||
id: input.identity.id,
|
||||
email: input.identity.email,
|
||||
displayName,
|
||||
status: input.identity.status,
|
||||
authentikConnected: Boolean(input.identity.authentikSubject),
|
||||
mfaAssured: input.sessions.some((session) => session.id === input.currentSessionId && session.mfaAssuredAt !== null),
|
||||
lastSsoLoginAt: input.identity.lastSsoLoginAt?.toISOString() ?? null,
|
||||
},
|
||||
roles: [...input.roles].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
sessions: [...input.sessions]
|
||||
.sort((a, b) => b.lastSeenAt.getTime() - a.lastSeenAt.getTime())
|
||||
.map((session) => ({
|
||||
id: session.id,
|
||||
current: session.id === input.currentSessionId,
|
||||
createdAt: session.createdAt.toISOString(),
|
||||
lastSeenAt: session.lastSeenAt.toISOString(),
|
||||
expiresAt: session.expiresAt.toISOString(),
|
||||
approxLocation: session.approxLocation,
|
||||
userAgent: session.userAgent,
|
||||
mfaAssured: session.mfaAssuredAt !== null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminRoleEditorVM, buildAdminUserDetailVM, buildAdminUserListVM } from "./admin-users.vm.js";
|
||||
|
||||
const user = {
|
||||
id: "admin-1",
|
||||
email: "ada@example.test",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
status: "active" as const,
|
||||
authentikSubject: "subject-1",
|
||||
lastSsoLoginAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
roles: [
|
||||
{
|
||||
role: {
|
||||
id: "role-1",
|
||||
name: "Sales",
|
||||
systemKey: "sales",
|
||||
permissions: [
|
||||
{ permission: { name: "admin.dashboard.view" } },
|
||||
{ permission: { name: "admin_sales.crm.read" } },
|
||||
{ permission: { name: "admin_sales.email.send" } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("admin user view models", () => {
|
||||
it("builds deterministic list summary and last activity", () => {
|
||||
const vm = buildAdminUserListVM(
|
||||
[
|
||||
{ ...user, sessions: [{ lastSeenAt: new Date("2026-07-24T09:00:00.000Z") }] },
|
||||
{
|
||||
...user,
|
||||
id: "admin-2",
|
||||
email: "locked@example.test",
|
||||
firstName: "",
|
||||
lastName: "",
|
||||
status: "locked",
|
||||
authentikSubject: null,
|
||||
sessions: [],
|
||||
},
|
||||
],
|
||||
[
|
||||
{ id: "role-viewer", name: "Viewer", systemKey: "viewer" },
|
||||
{ id: "role-sales", name: "Sales", systemKey: "sales" },
|
||||
]
|
||||
);
|
||||
expect(vm.summary).toEqual({ total: 2, active: 1, locked: 1 });
|
||||
expect(vm.users[0]).toMatchObject({ displayName: "Ada Lovelace", lastActiveAt: "2026-07-24T09:00:00.000Z" });
|
||||
expect(vm.availableRoles.map((role) => role.systemKey)).toEqual(["sales", "viewer"]);
|
||||
});
|
||||
|
||||
it("marks the current identity and current session in detail", () => {
|
||||
const vm = buildAdminUserDetailVM({
|
||||
user,
|
||||
sessions: [
|
||||
{
|
||||
id: "session-1",
|
||||
createdAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
lastSeenAt: new Date("2026-07-24T09:00:00.000Z"),
|
||||
expiresAt: new Date("2026-07-24T16:00:00.000Z"),
|
||||
approxLocation: "Deutschland",
|
||||
userAgent: "Browser",
|
||||
mfaAssuredAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
availableRoles: [user.roles[0]!.role],
|
||||
audit: [{ id: "audit-1", action: "admin.role.updated", createdAt: new Date("2026-07-24T09:00:00.000Z"), summaryText: null }],
|
||||
currentAdminUserId: "admin-1",
|
||||
currentSessionId: "session-1",
|
||||
});
|
||||
expect(vm.self).toBe(true);
|
||||
expect(vm.sessions[0]).toMatchObject({ current: true, mfaAssured: true });
|
||||
expect(vm.effectiveAreas).toEqual(["overview_reporting", "sales_crm", "communication_booking"]);
|
||||
});
|
||||
|
||||
it("keeps role permissions sorted", () => {
|
||||
const vm = buildAdminRoleEditorVM({
|
||||
roles: [
|
||||
{
|
||||
id: "role-1",
|
||||
name: "Sales",
|
||||
description: "Sales role",
|
||||
systemKey: "sales",
|
||||
isSystem: true,
|
||||
permissions: [
|
||||
{ permission: { name: "admin_sales.crm.write" } },
|
||||
{ permission: { name: "admin_sales.crm.read" } },
|
||||
],
|
||||
_count: { users: 2 },
|
||||
},
|
||||
],
|
||||
permissions: [
|
||||
{ name: "admin_sales.crm.write", description: "Write" },
|
||||
{ name: "admin_sales.crm.read", description: "Read" },
|
||||
],
|
||||
});
|
||||
expect(vm.roles[0]?.permissions).toEqual(["admin_sales.crm.read", "admin_sales.crm.write"]);
|
||||
expect(vm.permissions.map((permission) => permission.name)).toEqual([
|
||||
"admin_sales.crm.read",
|
||||
"admin_sales.crm.write",
|
||||
]);
|
||||
});
|
||||
|
||||
it("groups technical permissions into understandable workspace areas", () => {
|
||||
const vm = buildAdminRoleEditorVM({
|
||||
roles: [],
|
||||
permissions: [
|
||||
{ name: "admin_identity.users.manage", description: "Manage staff" },
|
||||
{ name: "admin_sales.crm.read_all", description: "Read team CRM" },
|
||||
{ name: "admin_sales.phone.recording", description: "Read recordings" },
|
||||
{ name: "admin.featureFlags.manage", description: "Manage flags" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.permissionGroups).toEqual([
|
||||
{
|
||||
key: "employee_access",
|
||||
permissions: [
|
||||
{
|
||||
name: "admin_identity.users.manage",
|
||||
description: "Manage staff",
|
||||
resource: "admin_identity.users",
|
||||
action: "manage",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "sales_crm",
|
||||
permissions: [
|
||||
{
|
||||
name: "admin_sales.crm.read_all",
|
||||
description: "Read team CRM",
|
||||
resource: "admin_sales.crm",
|
||||
action: "read_all",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "communication_booking",
|
||||
permissions: [
|
||||
{
|
||||
name: "admin_sales.phone.recording",
|
||||
description: "Read recordings",
|
||||
resource: "admin_sales.phone",
|
||||
action: "recording",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "engineering_operations",
|
||||
permissions: [
|
||||
{
|
||||
name: "admin.featureFlags.manage",
|
||||
description: "Manage flags",
|
||||
resource: "admin.featureFlags",
|
||||
action: "manage",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
+310
@@ -0,0 +1,310 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const statusSchema = z.enum(["active", "disabled", "locked"]);
|
||||
const roleSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
systemKey: z.string().nullable(),
|
||||
});
|
||||
const permissionGroupKeySchema = z.enum([
|
||||
"overview_reporting",
|
||||
"employee_access",
|
||||
"customers_support",
|
||||
"sales_crm",
|
||||
"communication_booking",
|
||||
"engineering_operations",
|
||||
"platform_configuration",
|
||||
"marketing_content",
|
||||
]);
|
||||
const permissionGroupOrder = permissionGroupKeySchema.options;
|
||||
|
||||
export function adminPermissionGroupKey(permission: string): z.infer<typeof permissionGroupKeySchema> {
|
||||
if (
|
||||
permission === "admin.dashboard.view" ||
|
||||
permission.startsWith("admin.metrics.") ||
|
||||
permission.startsWith("admin_sales.reporting.")
|
||||
) {
|
||||
return "overview_reporting";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin_identity.") ||
|
||||
permission.startsWith("admin.roles.") ||
|
||||
permission.startsWith("admin.auditTrails.")
|
||||
) {
|
||||
return "employee_access";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin.accounts.") ||
|
||||
permission.startsWith("admin.account.") ||
|
||||
permission.startsWith("admin.users.") ||
|
||||
permission.startsWith("admin.relationships.") ||
|
||||
permission.startsWith("admin.blacklist.") ||
|
||||
permission.startsWith("admin.tenantIpAddress.")
|
||||
) {
|
||||
return "customers_support";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin_sales.crm.") ||
|
||||
permission.startsWith("admin_sales.quote.") ||
|
||||
permission.startsWith("admin_sales.signature.")
|
||||
) {
|
||||
return "sales_crm";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin_sales.email.") ||
|
||||
permission.startsWith("admin_sales.communication.") ||
|
||||
permission.startsWith("admin_sales.phone.") ||
|
||||
permission.startsWith("admin_sales.sequence.") ||
|
||||
permission.startsWith("admin_sales.booking.") ||
|
||||
permission.startsWith("admin.emails.") ||
|
||||
permission.startsWith("admin.notifications.")
|
||||
) {
|
||||
return "communication_booking";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin.apiKeys.") ||
|
||||
permission.startsWith("admin.events.") ||
|
||||
permission.startsWith("admin.featureFlags.") ||
|
||||
permission.startsWith("admin_sales.automation.") ||
|
||||
permission.startsWith("admin_sales.integrations.") ||
|
||||
permission.startsWith("admin.marketing.integrations.")
|
||||
) {
|
||||
return "engineering_operations";
|
||||
}
|
||||
if (
|
||||
permission.startsWith("admin.marketing.") ||
|
||||
permission.startsWith("admin.leads.") ||
|
||||
permission.startsWith("admin.kb.") ||
|
||||
permission.startsWith("admin.prompts.")
|
||||
) {
|
||||
return "marketing_content";
|
||||
}
|
||||
return "platform_configuration";
|
||||
}
|
||||
|
||||
export function adminPermissionPresentation(permission: { name: string; description: string }) {
|
||||
const parts = permission.name.split(".");
|
||||
const resource = parts.slice(0, -1).join(".");
|
||||
return {
|
||||
name: permission.name,
|
||||
description: permission.description,
|
||||
resource: resource === "admin.account" ? "admin.accounts" : resource,
|
||||
action: parts.at(-1) ?? "view",
|
||||
};
|
||||
}
|
||||
|
||||
function effectiveAreas(
|
||||
roles: readonly { role: { permissions?: readonly { permission: { name: string } }[] } }[]
|
||||
) {
|
||||
const areas = new Set<z.infer<typeof permissionGroupKeySchema>>();
|
||||
for (const assignment of roles) {
|
||||
for (const grant of assignment.role.permissions ?? []) {
|
||||
areas.add(adminPermissionGroupKey(grant.permission.name));
|
||||
}
|
||||
}
|
||||
return permissionGroupOrder.filter((key) => areas.has(key));
|
||||
}
|
||||
|
||||
export const adminUserListVMSchema = z.object({
|
||||
summary: z.object({
|
||||
total: z.number().int().nonnegative(),
|
||||
active: z.number().int().nonnegative(),
|
||||
locked: z.number().int().nonnegative(),
|
||||
}),
|
||||
users: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
displayName: z.string().min(1),
|
||||
status: statusSchema,
|
||||
authentikConnected: z.boolean(),
|
||||
lastActiveAt: z.string().datetime().nullable(),
|
||||
roles: z.array(roleSchema),
|
||||
})
|
||||
),
|
||||
availableRoles: z.array(roleSchema),
|
||||
});
|
||||
|
||||
export const adminUserDetailVMSchema = z.object({
|
||||
user: adminUserListVMSchema.shape.users.element,
|
||||
effectiveAreas: z.array(permissionGroupKeySchema),
|
||||
sessions: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
current: z.boolean(),
|
||||
createdAt: z.string().datetime(),
|
||||
lastSeenAt: z.string().datetime(),
|
||||
expiresAt: z.string().datetime(),
|
||||
approxLocation: z.string().nullable(),
|
||||
userAgent: z.string().nullable(),
|
||||
mfaAssured: z.boolean(),
|
||||
})
|
||||
),
|
||||
availableRoles: z.array(roleSchema),
|
||||
audit: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
action: z.string().min(1),
|
||||
createdAt: z.string().datetime(),
|
||||
summary: z.string().min(1),
|
||||
})
|
||||
),
|
||||
self: z.boolean(),
|
||||
});
|
||||
|
||||
export const adminRoleEditorVMSchema = z.object({
|
||||
roles: z.array(
|
||||
roleSchema.extend({
|
||||
description: z.string(),
|
||||
isSystem: z.boolean(),
|
||||
permissions: z.array(z.string().min(1)),
|
||||
assignedUsers: z.number().int().nonnegative(),
|
||||
})
|
||||
),
|
||||
permissions: z.array(z.object({ name: z.string().min(1), description: z.string() })),
|
||||
permissionGroups: z.array(
|
||||
z.object({
|
||||
key: permissionGroupKeySchema,
|
||||
permissions: z.array(
|
||||
z.object({
|
||||
name: z.string().min(1),
|
||||
description: z.string(),
|
||||
resource: z.string().min(1),
|
||||
action: z.string().min(1),
|
||||
})
|
||||
),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type AdminUserListVM = z.infer<typeof adminUserListVMSchema>;
|
||||
export type AdminUserDetailVM = z.infer<typeof adminUserDetailVMSchema>;
|
||||
export type AdminRoleEditorVM = z.infer<typeof adminRoleEditorVMSchema>;
|
||||
|
||||
type AdminUserInput = {
|
||||
id: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
status: "active" | "disabled" | "locked";
|
||||
authentikSubject: string | null;
|
||||
lastSsoLoginAt: Date | null;
|
||||
roles: readonly {
|
||||
role: {
|
||||
id: string;
|
||||
name: string;
|
||||
systemKey: string | null;
|
||||
permissions?: readonly { permission: { name: string } }[];
|
||||
};
|
||||
}[];
|
||||
sessions?: readonly { lastSeenAt: Date }[];
|
||||
};
|
||||
|
||||
function mapAdminUser(user: AdminUserInput) {
|
||||
const displayName = [user.firstName, user.lastName].filter(Boolean).join(" ").trim() || user.email;
|
||||
const latestSession = [...(user.sessions ?? [])].sort((a, b) => b.lastSeenAt.getTime() - a.lastSeenAt.getTime())[0];
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
displayName,
|
||||
status: user.status,
|
||||
authentikConnected: Boolean(user.authentikSubject),
|
||||
lastActiveAt: (latestSession?.lastSeenAt ?? user.lastSsoLoginAt)?.toISOString() ?? null,
|
||||
roles: user.roles.map((assignment) => assignment.role).sort((a, b) => a.name.localeCompare(b.name)),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAdminUserListVM(
|
||||
users: readonly AdminUserInput[],
|
||||
availableRoles: readonly z.input<typeof roleSchema>[] = []
|
||||
): AdminUserListVM {
|
||||
const mapped = users.map(mapAdminUser).sort((a, b) => a.displayName.localeCompare(b.displayName));
|
||||
return adminUserListVMSchema.parse({
|
||||
summary: {
|
||||
total: mapped.length,
|
||||
active: mapped.filter((user) => user.status === "active").length,
|
||||
locked: mapped.filter((user) => user.status === "locked").length,
|
||||
},
|
||||
users: mapped,
|
||||
availableRoles: [...availableRoles].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
});
|
||||
}
|
||||
|
||||
export function buildAdminUserDetailVM(input: {
|
||||
user: AdminUserInput;
|
||||
sessions: readonly {
|
||||
id: string;
|
||||
createdAt: Date;
|
||||
lastSeenAt: Date;
|
||||
expiresAt: Date;
|
||||
approxLocation: string | null;
|
||||
userAgent: string | null;
|
||||
mfaAssuredAt: Date | null;
|
||||
}[];
|
||||
availableRoles: readonly { id: string; name: string; systemKey: string | null }[];
|
||||
audit: readonly { id: string; action: string; createdAt: Date; summaryText: string | null }[];
|
||||
currentAdminUserId: string;
|
||||
currentSessionId: string;
|
||||
}): AdminUserDetailVM {
|
||||
return adminUserDetailVMSchema.parse({
|
||||
user: mapAdminUser(input.user),
|
||||
effectiveAreas: effectiveAreas(input.user.roles),
|
||||
sessions: [...input.sessions]
|
||||
.sort((a, b) => b.lastSeenAt.getTime() - a.lastSeenAt.getTime())
|
||||
.map((session) => ({
|
||||
id: session.id,
|
||||
current: session.id === input.currentSessionId,
|
||||
createdAt: session.createdAt.toISOString(),
|
||||
lastSeenAt: session.lastSeenAt.toISOString(),
|
||||
expiresAt: session.expiresAt.toISOString(),
|
||||
approxLocation: session.approxLocation,
|
||||
userAgent: session.userAgent,
|
||||
mfaAssured: session.mfaAssuredAt !== null,
|
||||
})),
|
||||
availableRoles: [...input.availableRoles].sort((a, b) => a.name.localeCompare(b.name)),
|
||||
audit: input.audit.map((event) => ({
|
||||
id: event.id,
|
||||
action: event.action,
|
||||
createdAt: event.createdAt.toISOString(),
|
||||
summary: event.summaryText ?? event.action,
|
||||
})),
|
||||
self: input.user.id === input.currentAdminUserId,
|
||||
});
|
||||
}
|
||||
|
||||
export function buildAdminRoleEditorVM(input: {
|
||||
roles: readonly {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
systemKey: string | null;
|
||||
isSystem: boolean;
|
||||
permissions: readonly { permission: { name: string } }[];
|
||||
_count: { users: number };
|
||||
}[];
|
||||
permissions: readonly { name: string; description: string }[];
|
||||
}): AdminRoleEditorVM {
|
||||
const permissions = [...input.permissions].sort((a, b) => a.name.localeCompare(b.name));
|
||||
return adminRoleEditorVMSchema.parse({
|
||||
roles: input.roles
|
||||
.map((role) => ({
|
||||
id: role.id,
|
||||
name: role.name,
|
||||
description: role.description,
|
||||
systemKey: role.systemKey,
|
||||
isSystem: role.isSystem,
|
||||
permissions: role.permissions.map((row) => row.permission.name).sort(),
|
||||
assignedUsers: role._count.users,
|
||||
}))
|
||||
.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
permissions,
|
||||
permissionGroups: permissionGroupOrder
|
||||
.map((key) => ({
|
||||
key,
|
||||
permissions: permissions
|
||||
.filter((permission) => adminPermissionGroupKey(permission.name) === key)
|
||||
.map(adminPermissionPresentation),
|
||||
}))
|
||||
.filter((group) => group.permissions.length > 0),
|
||||
});
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAdminBookingSettingsVM } from "./booking-settings.vm.js";
|
||||
|
||||
describe("buildAdminBookingSettingsVM", () => {
|
||||
it("serializes host labels, rules and date overrides", () => {
|
||||
const vm = buildAdminBookingSettingsVM({
|
||||
meetingTypes: [{
|
||||
id: "type-1",
|
||||
name: "Demo",
|
||||
slug: "demo",
|
||||
durationMinutes: 45,
|
||||
active: true,
|
||||
hostAdminUserIds: ["admin-1"],
|
||||
}],
|
||||
pages: [{
|
||||
id: "page-1",
|
||||
meetingTypeId: "type-1",
|
||||
title: "Demo",
|
||||
slug: "demo",
|
||||
published: true,
|
||||
}],
|
||||
hosts: [{
|
||||
id: "admin-1",
|
||||
firstName: "Raffael",
|
||||
lastName: "Sheikh",
|
||||
email: "admin@email.com",
|
||||
}],
|
||||
rules: [{
|
||||
dayOfWeek: "monday",
|
||||
startMinutes: 540,
|
||||
endMinutes: 1020,
|
||||
timeZone: "Europe/Berlin",
|
||||
}],
|
||||
overrides: [{
|
||||
date: new Date("2026-08-03T00:00:00.000Z"),
|
||||
kind: "unavailable",
|
||||
startMinutes: null,
|
||||
endMinutes: null,
|
||||
reason: "Urlaub",
|
||||
timeZone: "Europe/Berlin",
|
||||
}],
|
||||
});
|
||||
expect(vm.hosts[0]?.label).toBe("Raffael Sheikh");
|
||||
expect(vm.availability.overrides[0]?.date).toBe("2026-08-03");
|
||||
expect(vm.availability.timeZone).toBe("Europe/Berlin");
|
||||
});
|
||||
});
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const daySchema = z.enum([
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
"sunday",
|
||||
]);
|
||||
|
||||
export const adminBookingSettingsVMSchema = z.object({
|
||||
meetingTypes: z.array(z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
slug: z.string(),
|
||||
durationMinutes: z.number().int(),
|
||||
active: z.boolean(),
|
||||
hostAdminUserIds: z.array(z.string()),
|
||||
})),
|
||||
pages: z.array(z.object({
|
||||
id: z.string(),
|
||||
meetingTypeId: z.string(),
|
||||
title: z.string(),
|
||||
slug: z.string(),
|
||||
published: z.boolean(),
|
||||
})),
|
||||
hosts: z.array(z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
})),
|
||||
availability: z.object({
|
||||
timeZone: z.string(),
|
||||
rules: z.array(z.object({
|
||||
dayOfWeek: daySchema,
|
||||
startMinutes: z.number().int(),
|
||||
endMinutes: z.number().int(),
|
||||
})),
|
||||
overrides: z.array(z.object({
|
||||
date: z.string(),
|
||||
kind: z.enum(["unavailable", "custom_window"]),
|
||||
startMinutes: z.number().int().nullable(),
|
||||
endMinutes: z.number().int().nullable(),
|
||||
reason: z.string().nullable(),
|
||||
})),
|
||||
}),
|
||||
});
|
||||
|
||||
export type AdminBookingSettingsVM = z.infer<
|
||||
typeof adminBookingSettingsVMSchema
|
||||
>;
|
||||
|
||||
export const adminBookingSettingsActionSchema = z.discriminatedUnion(
|
||||
"intent",
|
||||
[
|
||||
z.object({
|
||||
intent: z.literal("save-meeting-type"),
|
||||
id: z.string().nullable().optional(),
|
||||
name: z.string().min(1).max(120),
|
||||
slug: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
durationMinutes: z.number().int().positive().max(480),
|
||||
bufferBeforeMinutes: z.number().int().nonnegative().max(240),
|
||||
bufferAfterMinutes: z.number().int().nonnegative().max(240),
|
||||
slotIncrementMinutes: z.number().int().positive().max(240),
|
||||
minimumNoticeMinutes: z.number().int().nonnegative().max(43200),
|
||||
bookingHorizonDays: z.number().int().positive().max(365),
|
||||
hostAdminUserIds: z.array(z.string().min(1)).min(1),
|
||||
reminderOffsetsMinutes: z.array(z.number().int().positive()),
|
||||
active: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-booking-page"),
|
||||
id: z.string().nullable().optional(),
|
||||
meetingTypeId: z.string().min(1),
|
||||
slug: z.string().min(1).max(120),
|
||||
title: z.string().min(1).max(120),
|
||||
description: z.string().max(2000).nullable().optional(),
|
||||
published: z.boolean(),
|
||||
maxBookingsPerEmailPerDay: z.number().int().positive().max(100),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("replace-availability"),
|
||||
timeZone: z.string().min(1).max(100),
|
||||
rules: z.array(z.object({
|
||||
dayOfWeek: daySchema,
|
||||
startMinutes: z.number().int().nonnegative().max(1439),
|
||||
endMinutes: z.number().int().positive().max(1440),
|
||||
})),
|
||||
overrides: z.array(z.object({
|
||||
date: z.string().date(),
|
||||
kind: z.enum(["unavailable", "custom_window"]),
|
||||
startMinutes: z.number().int().nonnegative().max(1439).nullable().optional(),
|
||||
endMinutes: z.number().int().positive().max(1440).nullable().optional(),
|
||||
reason: z.string().max(500).nullable().optional(),
|
||||
})),
|
||||
}),
|
||||
]
|
||||
);
|
||||
|
||||
export function buildAdminBookingSettingsVM(input: {
|
||||
readonly meetingTypes: readonly {
|
||||
readonly id: string; readonly name: string; readonly slug: string;
|
||||
readonly durationMinutes: number; readonly active: boolean;
|
||||
readonly hostAdminUserIds: readonly string[];
|
||||
}[];
|
||||
readonly pages: readonly {
|
||||
readonly id: string; readonly meetingTypeId: string;
|
||||
readonly title: string; readonly slug: string; readonly published: boolean;
|
||||
}[];
|
||||
readonly hosts: readonly {
|
||||
readonly id: string; readonly firstName: string; readonly lastName: string; readonly email: string;
|
||||
}[];
|
||||
readonly rules: readonly {
|
||||
readonly dayOfWeek: z.infer<typeof daySchema>;
|
||||
readonly startMinutes: number; readonly endMinutes: number; readonly timeZone: string;
|
||||
}[];
|
||||
readonly overrides: readonly {
|
||||
readonly date: Date; readonly kind: "unavailable" | "custom_window";
|
||||
readonly startMinutes: number | null; readonly endMinutes: number | null;
|
||||
readonly reason: string | null; readonly timeZone: string;
|
||||
}[];
|
||||
}): AdminBookingSettingsVM {
|
||||
return adminBookingSettingsVMSchema.parse({
|
||||
meetingTypes: input.meetingTypes,
|
||||
pages: input.pages,
|
||||
hosts: input.hosts.map((host) => ({
|
||||
id: host.id,
|
||||
label: `${host.firstName} ${host.lastName}`.trim() || host.email,
|
||||
})),
|
||||
availability: {
|
||||
timeZone:
|
||||
input.rules[0]?.timeZone ??
|
||||
input.overrides[0]?.timeZone ??
|
||||
"Europe/Berlin",
|
||||
rules: input.rules,
|
||||
overrides: input.overrides.map((override) => ({
|
||||
...override,
|
||||
date: override.date.toISOString().slice(0, 10),
|
||||
})),
|
||||
},
|
||||
});
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { buildAdminBookingWorkspaceVM } from "./booking.vm.js";
|
||||
|
||||
describe("admin booking workspace view model", () => {
|
||||
it("projects booking operations without Prisma or client recomputation", () => {
|
||||
vi.setSystemTime(new Date("2026-07-25T12:00:00.000Z"));
|
||||
const vm = buildAdminBookingWorkspaceVM({
|
||||
meetingTypes: [
|
||||
{
|
||||
id: "type-1",
|
||||
name: "Demo",
|
||||
durationMinutes: 45,
|
||||
hostAdminUserIds: ["admin-1", "admin-1"],
|
||||
active: true,
|
||||
},
|
||||
],
|
||||
pages: [
|
||||
{
|
||||
id: "page-1",
|
||||
title: "HiveGrid Demo",
|
||||
slug: "demo",
|
||||
published: true,
|
||||
meetingType: { name: "Demo" },
|
||||
},
|
||||
],
|
||||
bookings: [
|
||||
{
|
||||
id: "booking-1",
|
||||
startsAt: new Date("2026-08-01T10:00:00.000Z"),
|
||||
endsAt: new Date("2026-08-01T10:45:00.000Z"),
|
||||
status: "confirmed",
|
||||
providerSyncedAt: new Date(),
|
||||
contact: { firstName: "Ada", lastName: "Lovelace" },
|
||||
meetingType: { name: "Demo" },
|
||||
},
|
||||
],
|
||||
connectedCalendars: 1,
|
||||
bookingOrigin: "https://meet.hivegrid.de",
|
||||
});
|
||||
|
||||
expect(vm.stats).toEqual({
|
||||
upcoming: 1,
|
||||
publishedPages: 1,
|
||||
activeMeetingTypes: 1,
|
||||
connectedCalendars: 1,
|
||||
});
|
||||
expect(vm.pages[0]?.bookingUrl).toBe(
|
||||
"https://meet.hivegrid.de/demo"
|
||||
);
|
||||
expect(vm.bookings[0]).toMatchObject({
|
||||
contactName: "Ada Lovelace",
|
||||
providerSynced: true,
|
||||
});
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminBookingWorkspaceVMSchema = z.object({
|
||||
stats: z.object({
|
||||
upcoming: z.number().int().nonnegative(),
|
||||
publishedPages: z.number().int().nonnegative(),
|
||||
activeMeetingTypes: z.number().int().nonnegative(),
|
||||
connectedCalendars: z.number().int().nonnegative(),
|
||||
}),
|
||||
meetingTypes: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
durationMinutes: z.number().int().positive(),
|
||||
hostCount: z.number().int().nonnegative(),
|
||||
active: z.boolean(),
|
||||
})
|
||||
),
|
||||
pages: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
slug: z.string().min(1),
|
||||
meetingTypeName: z.string().min(1),
|
||||
published: z.boolean(),
|
||||
bookingUrl: z.string().min(1),
|
||||
})
|
||||
),
|
||||
bookings: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
contactName: z.string().min(1),
|
||||
meetingTypeName: z.string().min(1),
|
||||
startsAt: z.string().datetime(),
|
||||
endsAt: z.string().datetime(),
|
||||
status: z.enum([
|
||||
"reserved",
|
||||
"confirmed",
|
||||
"cancelled",
|
||||
"rescheduled",
|
||||
"completed",
|
||||
"no_show",
|
||||
"provider_sync_failed",
|
||||
]),
|
||||
providerSynced: z.boolean(),
|
||||
})
|
||||
),
|
||||
externalProviderProofPending: z.boolean(),
|
||||
});
|
||||
|
||||
export type AdminBookingWorkspaceVM = z.infer<
|
||||
typeof adminBookingWorkspaceVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminBookingWorkspaceVM(input: {
|
||||
readonly meetingTypes: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly durationMinutes: number;
|
||||
readonly hostAdminUserIds: readonly string[];
|
||||
readonly active: boolean;
|
||||
}[];
|
||||
readonly pages: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly slug: string;
|
||||
readonly published: boolean;
|
||||
readonly meetingType: { readonly name: string };
|
||||
}[];
|
||||
readonly bookings: readonly {
|
||||
readonly id: string;
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
readonly status:
|
||||
| "reserved"
|
||||
| "confirmed"
|
||||
| "cancelled"
|
||||
| "rescheduled"
|
||||
| "completed"
|
||||
| "no_show"
|
||||
| "provider_sync_failed";
|
||||
readonly providerSyncedAt: Date | null;
|
||||
readonly contact: {
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
};
|
||||
readonly meetingType: { readonly name: string };
|
||||
}[];
|
||||
readonly connectedCalendars: number;
|
||||
readonly bookingOrigin: string;
|
||||
readonly externalProviderProofPending?: boolean;
|
||||
}): AdminBookingWorkspaceVM {
|
||||
const now = Date.now();
|
||||
return adminBookingWorkspaceVMSchema.parse({
|
||||
stats: {
|
||||
upcoming: input.bookings.filter(
|
||||
(booking) =>
|
||||
booking.startsAt.getTime() >= now &&
|
||||
!["cancelled", "rescheduled"].includes(booking.status)
|
||||
).length,
|
||||
publishedPages: input.pages.filter((page) => page.published).length,
|
||||
activeMeetingTypes: input.meetingTypes.filter((type) => type.active)
|
||||
.length,
|
||||
connectedCalendars: input.connectedCalendars,
|
||||
},
|
||||
meetingTypes: input.meetingTypes.map((type) => ({
|
||||
id: type.id,
|
||||
name: type.name,
|
||||
durationMinutes: type.durationMinutes,
|
||||
hostCount: new Set(type.hostAdminUserIds).size,
|
||||
active: type.active,
|
||||
})),
|
||||
pages: input.pages.map((page) => ({
|
||||
id: page.id,
|
||||
title: page.title,
|
||||
slug: page.slug,
|
||||
meetingTypeName: page.meetingType.name,
|
||||
published: page.published,
|
||||
bookingUrl: `${input.bookingOrigin.replace(/\/$/u, "")}/${encodeURIComponent(page.slug)}`,
|
||||
})),
|
||||
bookings: input.bookings.map((booking) => ({
|
||||
id: booking.id,
|
||||
contactName:
|
||||
`${booking.contact.firstName} ${booking.contact.lastName}`.trim(),
|
||||
meetingTypeName: booking.meetingType.name,
|
||||
startsAt: booking.startsAt.toISOString(),
|
||||
endsAt: booking.endsAt.toISOString(),
|
||||
status: booking.status,
|
||||
providerSynced: Boolean(booking.providerSyncedAt),
|
||||
})),
|
||||
externalProviderProofPending:
|
||||
input.externalProviderProofPending ?? true,
|
||||
});
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAdminCalendarConnectionsVM } from "./calendar-connections.vm.js";
|
||||
|
||||
describe("buildAdminCalendarConnectionsVM", () => {
|
||||
it("exposes readiness and owner-scoped health", () => {
|
||||
const vm = buildAdminCalendarConnectionsVM({
|
||||
calendars: [{
|
||||
id: "calendar-1",
|
||||
dataConnectionId: "connection-1",
|
||||
dataConnection: {
|
||||
provider: "google_calendar",
|
||||
externalAccountEmail: "sales@example.test",
|
||||
},
|
||||
externalCalendarLabel: "Sales",
|
||||
timeZone: "Europe/Berlin",
|
||||
status: "active",
|
||||
lastSyncAt: new Date("2026-07-25T08:00:00.000Z"),
|
||||
healthMessageKey: "admin.sales.booking.calendars.health.synced",
|
||||
}],
|
||||
providerConfiguration: {
|
||||
google_calendar: true,
|
||||
microsoft_calendar: false,
|
||||
},
|
||||
});
|
||||
expect(vm.providers.map(({ connected }) => connected)).toEqual([
|
||||
true,
|
||||
false,
|
||||
]);
|
||||
expect(vm.calendars[0]?.lastSyncAt).toBe(
|
||||
"2026-07-25T08:00:00.000Z"
|
||||
);
|
||||
});
|
||||
});
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const providerSchema = z.enum(["google_calendar", "microsoft_calendar"]);
|
||||
|
||||
export const adminCalendarConnectionsVMSchema = z.object({
|
||||
calendars: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
dataConnectionId: z.string(),
|
||||
provider: providerSchema,
|
||||
accountEmail: z.string().email().nullable(),
|
||||
label: z.string().nullable(),
|
||||
timeZone: z.string(),
|
||||
status: z.enum([
|
||||
"active",
|
||||
"degraded",
|
||||
"reconnect_required",
|
||||
"revoked",
|
||||
]),
|
||||
lastSyncAt: z.string().datetime().nullable(),
|
||||
healthMessageKey: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
providers: z.array(
|
||||
z.object({
|
||||
provider: providerSchema,
|
||||
configured: z.boolean(),
|
||||
connected: z.boolean(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const adminCalendarConnectionActionSchema = z.object({
|
||||
intent: z.literal("disconnect"),
|
||||
calendarConnectionId: z.string().min(1).max(191),
|
||||
dataConnectionId: z.string().min(1).max(191),
|
||||
});
|
||||
|
||||
export type AdminCalendarConnectionsVM = z.infer<
|
||||
typeof adminCalendarConnectionsVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminCalendarConnectionsVM(input: {
|
||||
readonly calendars: readonly {
|
||||
readonly id: string;
|
||||
readonly dataConnectionId: string;
|
||||
readonly dataConnection: {
|
||||
readonly provider: string;
|
||||
readonly externalAccountEmail: string | null;
|
||||
};
|
||||
readonly externalCalendarLabel: string | null;
|
||||
readonly timeZone: string;
|
||||
readonly status:
|
||||
| "active"
|
||||
| "degraded"
|
||||
| "reconnect_required"
|
||||
| "revoked";
|
||||
readonly lastSyncAt: Date | null;
|
||||
readonly healthMessageKey: string | null;
|
||||
}[];
|
||||
readonly providerConfiguration: Readonly<
|
||||
Record<"google_calendar" | "microsoft_calendar", boolean>
|
||||
>;
|
||||
}): AdminCalendarConnectionsVM {
|
||||
const calendars = input.calendars.map((calendar) => ({
|
||||
id: calendar.id,
|
||||
dataConnectionId: calendar.dataConnectionId,
|
||||
provider: calendar.dataConnection.provider,
|
||||
accountEmail: calendar.dataConnection.externalAccountEmail,
|
||||
label: calendar.externalCalendarLabel,
|
||||
timeZone: calendar.timeZone,
|
||||
status: calendar.status,
|
||||
lastSyncAt: calendar.lastSyncAt?.toISOString() ?? null,
|
||||
healthMessageKey: calendar.healthMessageKey,
|
||||
}));
|
||||
return adminCalendarConnectionsVMSchema.parse({
|
||||
calendars,
|
||||
providers: (["google_calendar", "microsoft_calendar"] as const).map(
|
||||
(provider) => ({
|
||||
provider,
|
||||
configured: input.providerConfiguration[provider],
|
||||
connected: calendars.some(
|
||||
(calendar) =>
|
||||
calendar.provider === provider &&
|
||||
calendar.status !== "revoked"
|
||||
),
|
||||
})
|
||||
),
|
||||
});
|
||||
}
|
||||
+189
@@ -0,0 +1,189 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminSalesBulkContactsActionSchema,
|
||||
buildAdminSalesCompanyDetailVM,
|
||||
buildAdminSalesDataManagementVM,
|
||||
} from "./data-management.vm.js";
|
||||
|
||||
describe("admin sales data management view model", () => {
|
||||
it("builds serializable contacts, metrics and expiring job states", () => {
|
||||
const vm = buildAdminSalesDataManagementVM({
|
||||
source: {
|
||||
companies: [
|
||||
{
|
||||
id: "company_1",
|
||||
name: "Analytical Engines",
|
||||
legalName: null,
|
||||
domain: "analytical.example",
|
||||
phone: null,
|
||||
region: "London",
|
||||
countryCode: "GB",
|
||||
industry: "Technology",
|
||||
contactCount: 1,
|
||||
dealCount: 2,
|
||||
},
|
||||
],
|
||||
contacts: [
|
||||
{
|
||||
id: "contact_1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.com",
|
||||
phone: null,
|
||||
locale: "de-DE",
|
||||
company: { name: "Analytical Engines" },
|
||||
tags: [{ id: "tag_1", name: "VIP", color: "#2563eb" }],
|
||||
customFields: [
|
||||
{
|
||||
definitionId: "field_1",
|
||||
label: "Kundenstufe",
|
||||
type: "single_select",
|
||||
value: "A",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
tags: [{ id: "tag_1", name: "VIP", color: "#2563eb" }],
|
||||
customFields: [
|
||||
{
|
||||
id: "field_1",
|
||||
target: "contact",
|
||||
key: "customer_tier",
|
||||
label: "Kundenstufe",
|
||||
type: "single_select",
|
||||
options: ["A", "B"],
|
||||
required: true,
|
||||
position: 0,
|
||||
},
|
||||
],
|
||||
importJobs: [
|
||||
{
|
||||
id: "import_1",
|
||||
createdAt: new Date("2026-07-24T10:00:00Z"),
|
||||
fileName: "kontakte.csv",
|
||||
status: "pending",
|
||||
totalRows: 0,
|
||||
acceptedRows: 0,
|
||||
rejectedRows: 0,
|
||||
errorReportKey: null,
|
||||
},
|
||||
],
|
||||
exportJobs: [],
|
||||
},
|
||||
buildContactHref: (id) => `/sales/contacts/${id}`,
|
||||
buildCompanyHref: (id) => `/sales/companies/${id}`,
|
||||
permissions: { canRead: true, canWrite: true, canExport: true },
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
status: "ready",
|
||||
summary: {
|
||||
contactCount: 1,
|
||||
taggedContactCount: 1,
|
||||
customFieldCount: 1,
|
||||
activeJobCount: 1,
|
||||
},
|
||||
contacts: [
|
||||
{
|
||||
name: "Ada Lovelace",
|
||||
initials: "AL",
|
||||
companyName: "Analytical Engines",
|
||||
detailHref: "/sales/contacts/contact_1",
|
||||
customFields: [{ valueLabel: "A" }],
|
||||
},
|
||||
],
|
||||
companies: [
|
||||
{
|
||||
name: "Analytical Engines",
|
||||
locationLabel: "London, GB",
|
||||
detailHref: "/sales/companies/company_1",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(vm)).toContain("2026-07-24T10:00:00.000Z");
|
||||
});
|
||||
|
||||
it("bounds bulk edits before they reach the route action", () => {
|
||||
expect(() =>
|
||||
adminSalesBulkContactsActionSchema.parse({
|
||||
contactIds: [],
|
||||
locale: null,
|
||||
addTagIds: [],
|
||||
removeTagIds: [],
|
||||
reason: "Kontakte aktualisieren",
|
||||
})
|
||||
).toThrow();
|
||||
expect(
|
||||
adminSalesBulkContactsActionSchema.parse({
|
||||
contactIds: ["contact_1"],
|
||||
locale: "de-DE",
|
||||
addTagIds: ["tag_1"],
|
||||
removeTagIds: [],
|
||||
reason: "Kontakte aktualisieren",
|
||||
})
|
||||
).toMatchObject({ contactIds: ["contact_1"], locale: "de-DE" });
|
||||
});
|
||||
|
||||
it("builds a serializable company detail with contact, deal and activity links", () => {
|
||||
const vm = buildAdminSalesCompanyDetailVM({
|
||||
source: {
|
||||
id: "company_1",
|
||||
name: "Analytical Engines",
|
||||
legalName: "Analytical Engines Ltd.",
|
||||
domain: "analytical.example",
|
||||
website: "https://analytical.example",
|
||||
phone: "+44 20 0000",
|
||||
region: "London",
|
||||
countryCode: "GB",
|
||||
industry: "Technology",
|
||||
employeeRange: "11-50",
|
||||
contacts: [
|
||||
{
|
||||
id: "contact_1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
jobTitle: "Founder",
|
||||
email: "ada@analytical.example",
|
||||
phone: null,
|
||||
},
|
||||
],
|
||||
deals: [
|
||||
{
|
||||
id: "deal_1",
|
||||
title: "Enterprise",
|
||||
status: "open",
|
||||
amountCents: 12_500,
|
||||
currencyCode: "EUR",
|
||||
stageName: "Demo",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: "activity_1",
|
||||
type: "deal_created",
|
||||
summary: "Deal angelegt",
|
||||
occurredAt: new Date("2026-07-24T12:00:00.000Z"),
|
||||
contactId: null,
|
||||
dealId: "deal_1",
|
||||
},
|
||||
],
|
||||
},
|
||||
locale: "de-DE",
|
||||
buildContactHref: (id) => `/sales/contacts/${id}`,
|
||||
buildDealHref: (id) => `/sales/deals/${id}`,
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
locationLabel: "London, GB",
|
||||
contacts: [{ name: "Ada Lovelace", href: "/sales/contacts/contact_1" }],
|
||||
deals: [{ stageName: "Demo", href: "/sales/deals/deal_1" }],
|
||||
activities: [
|
||||
{
|
||||
occurredAtIso: "2026-07-24T12:00:00.000Z",
|
||||
href: "/sales/deals/deal_1",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
+437
@@ -0,0 +1,437 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const identifierSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(191)
|
||||
.regex(/^[A-Za-z0-9_:-]+$/u);
|
||||
|
||||
export const adminSalesTagActionSchema = z.object({
|
||||
name: z.string().trim().min(1).max(100),
|
||||
color: z
|
||||
.string()
|
||||
.trim()
|
||||
.regex(/^#[0-9a-f]{6}$/iu)
|
||||
.nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminSalesCustomFieldActionSchema = z.object({
|
||||
target: z.enum(["contact", "deal"]),
|
||||
key: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(2)
|
||||
.max(63)
|
||||
.regex(/^[a-z][a-z0-9_]+$/u),
|
||||
label: z.string().trim().min(1).max(200),
|
||||
type: z.enum(["text", "number", "boolean", "date", "single_select"]),
|
||||
options: z.array(z.string().trim().min(1).max(200)).max(100),
|
||||
required: z.boolean(),
|
||||
position: z.number().int().min(0).max(10_000),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminSalesBulkContactsActionSchema = z.object({
|
||||
contactIds: z.array(identifierSchema).min(1).max(100),
|
||||
locale: z.string().trim().max(20).nullable(),
|
||||
addTagIds: z.array(identifierSchema).max(100),
|
||||
removeTagIds: z.array(identifierSchema).max(100),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminSalesContactNoteActionSchema = z.object({
|
||||
contactId: identifierSchema,
|
||||
body: z.string().trim().min(1).max(10_000),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminSalesImportConfirmActionSchema = z.object({
|
||||
importJobId: identifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminSalesExportActionSchema = z.object({
|
||||
contactIds: z.array(identifierSchema).max(500),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export type AdminSalesImportPreviewVM = {
|
||||
readonly jobId: string;
|
||||
readonly fileName: string;
|
||||
readonly rowCount: number;
|
||||
readonly headers: readonly string[];
|
||||
readonly mapping: readonly string[];
|
||||
};
|
||||
|
||||
export type AdminSalesDataManagementVM = {
|
||||
readonly status: "ready" | "empty";
|
||||
readonly titleKey: "admin.sales.data.title";
|
||||
readonly summary: {
|
||||
readonly contactCount: number;
|
||||
readonly taggedContactCount: number;
|
||||
readonly customFieldCount: number;
|
||||
readonly activeJobCount: number;
|
||||
};
|
||||
readonly companies: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly legalName: string | null;
|
||||
readonly domain: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locationLabel: string;
|
||||
readonly industry: string | null;
|
||||
readonly contactCount: number;
|
||||
readonly dealCount: number;
|
||||
readonly detailHref: string;
|
||||
}[];
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly initials: string;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locale: string | null;
|
||||
readonly companyName: string | null;
|
||||
readonly detailHref: string;
|
||||
readonly tags: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly color: string | null;
|
||||
}[];
|
||||
readonly customFields: readonly {
|
||||
readonly definitionId: string;
|
||||
readonly label: string;
|
||||
readonly type: "text" | "number" | "boolean" | "date" | "single_select";
|
||||
readonly valueLabel: string;
|
||||
}[];
|
||||
}[];
|
||||
readonly tags: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly color: string | null;
|
||||
}[];
|
||||
readonly customFields: readonly {
|
||||
readonly id: string;
|
||||
readonly target: "contact" | "deal";
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly type: "text" | "number" | "boolean" | "date" | "single_select";
|
||||
readonly options: readonly string[];
|
||||
readonly required: boolean;
|
||||
readonly position: number;
|
||||
}[];
|
||||
readonly importJobs: readonly {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly fileName: string;
|
||||
readonly status: string;
|
||||
readonly totalRows: number;
|
||||
readonly acceptedRows: number;
|
||||
readonly rejectedRows: number;
|
||||
readonly hasErrorReport: boolean;
|
||||
readonly errorReportHref: string | null;
|
||||
}[];
|
||||
readonly exportJobs: readonly {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly status: string;
|
||||
readonly rowCount: number;
|
||||
readonly hasArtifact: boolean;
|
||||
readonly expiresAtIso: string | null;
|
||||
readonly artifactHref: string | null;
|
||||
}[];
|
||||
readonly permissions: {
|
||||
readonly canRead: boolean;
|
||||
readonly canWrite: boolean;
|
||||
readonly canExport: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export type AdminSalesDataManagementSource = {
|
||||
readonly companies: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly legalName: string | null;
|
||||
readonly domain: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly region: string | null;
|
||||
readonly countryCode: string | null;
|
||||
readonly industry: string | null;
|
||||
readonly contactCount: number;
|
||||
readonly dealCount: number;
|
||||
}[];
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locale: string | null;
|
||||
readonly company: { readonly name: string } | null;
|
||||
readonly tags: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly color: string | null;
|
||||
}[];
|
||||
readonly customFields: readonly {
|
||||
readonly definitionId: string;
|
||||
readonly label: string;
|
||||
readonly type: "text" | "number" | "boolean" | "date" | "single_select";
|
||||
readonly value: string | number | boolean | Date | null;
|
||||
}[];
|
||||
}[];
|
||||
readonly tags: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly color: string | null;
|
||||
}[];
|
||||
readonly customFields: readonly {
|
||||
readonly id: string;
|
||||
readonly target: "contact" | "deal";
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly type: "text" | "number" | "boolean" | "date" | "single_select";
|
||||
readonly options: readonly string[];
|
||||
readonly required: boolean;
|
||||
readonly position: number;
|
||||
}[];
|
||||
readonly importJobs: readonly {
|
||||
readonly id: string;
|
||||
readonly createdAt: Date;
|
||||
readonly fileName: string;
|
||||
readonly status: string;
|
||||
readonly totalRows: number;
|
||||
readonly acceptedRows: number;
|
||||
readonly rejectedRows: number;
|
||||
readonly errorReportKey: string | null;
|
||||
}[];
|
||||
readonly exportJobs: readonly {
|
||||
readonly id: string;
|
||||
readonly createdAt: Date;
|
||||
readonly status: string;
|
||||
readonly rowCount: number;
|
||||
readonly artifactKey: string | null;
|
||||
readonly expiresAt: Date | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export function buildAdminSalesDataManagementVM(input: {
|
||||
readonly source: AdminSalesDataManagementSource;
|
||||
readonly buildContactHref: (contactId: string) => string;
|
||||
readonly buildCompanyHref?: (companyId: string) => string;
|
||||
readonly buildImportErrorHref?: (jobId: string) => string;
|
||||
readonly buildExportHref?: (jobId: string) => string;
|
||||
readonly permissions: AdminSalesDataManagementVM["permissions"];
|
||||
}): AdminSalesDataManagementVM {
|
||||
const contacts = input.source.contacts.map((contact) => {
|
||||
const name = `${contact.firstName} ${contact.lastName}`.trim();
|
||||
return {
|
||||
id: contact.id,
|
||||
name,
|
||||
initials: `${contact.firstName[0] ?? ""}${contact.lastName[0] ?? ""}`
|
||||
.toLocaleUpperCase("de-DE")
|
||||
.slice(0, 2),
|
||||
email: contact.email,
|
||||
phone: contact.phone,
|
||||
locale: contact.locale,
|
||||
companyName: contact.company?.name ?? null,
|
||||
detailHref: input.buildContactHref(contact.id),
|
||||
tags: contact.tags.map((tag) => ({ ...tag })),
|
||||
customFields: contact.customFields.map((field) => ({
|
||||
definitionId: field.definitionId,
|
||||
label: field.label,
|
||||
type: field.type,
|
||||
valueLabel: formatValue(field.value),
|
||||
})),
|
||||
};
|
||||
});
|
||||
return {
|
||||
status: contacts.length === 0 ? "empty" : "ready",
|
||||
titleKey: "admin.sales.data.title",
|
||||
summary: {
|
||||
contactCount: contacts.length,
|
||||
taggedContactCount: contacts.filter((contact) => contact.tags.length > 0)
|
||||
.length,
|
||||
customFieldCount: input.source.customFields.length,
|
||||
activeJobCount:
|
||||
input.source.importJobs.filter((job) =>
|
||||
["pending", "running"].includes(job.status)
|
||||
).length +
|
||||
input.source.exportJobs.filter((job) =>
|
||||
["pending", "running"].includes(job.status)
|
||||
).length,
|
||||
},
|
||||
companies: input.source.companies.map((company) => ({
|
||||
...company,
|
||||
locationLabel: [company.region, company.countryCode]
|
||||
.filter(Boolean)
|
||||
.join(", "),
|
||||
detailHref: input.buildCompanyHref?.(company.id) ?? "",
|
||||
})),
|
||||
contacts,
|
||||
tags: input.source.tags.map((tag) => ({ ...tag })),
|
||||
customFields: input.source.customFields.map((field) => ({
|
||||
...field,
|
||||
options: [...field.options],
|
||||
})),
|
||||
importJobs: input.source.importJobs.map((job) => ({
|
||||
id: job.id,
|
||||
createdAtIso: job.createdAt.toISOString(),
|
||||
fileName: job.fileName,
|
||||
status: job.status,
|
||||
totalRows: job.totalRows,
|
||||
acceptedRows: job.acceptedRows,
|
||||
rejectedRows: job.rejectedRows,
|
||||
hasErrorReport: Boolean(job.errorReportKey),
|
||||
errorReportHref: job.errorReportKey
|
||||
? input.buildImportErrorHref?.(job.id) ?? null
|
||||
: null,
|
||||
})),
|
||||
exportJobs: input.source.exportJobs.map((job) => ({
|
||||
id: job.id,
|
||||
createdAtIso: job.createdAt.toISOString(),
|
||||
status: job.status,
|
||||
rowCount: job.rowCount,
|
||||
hasArtifact: Boolean(job.artifactKey),
|
||||
expiresAtIso: job.expiresAt?.toISOString() ?? null,
|
||||
artifactHref: job.artifactKey
|
||||
? input.buildExportHref?.(job.id) ?? null
|
||||
: null,
|
||||
})),
|
||||
permissions: { ...input.permissions },
|
||||
};
|
||||
}
|
||||
|
||||
export type AdminSalesCompanyDetailVM = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly legalName: string | null;
|
||||
readonly domain: string | null;
|
||||
readonly website: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locationLabel: string;
|
||||
readonly industry: string | null;
|
||||
readonly employeeRange: string | null;
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly jobTitle: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly href: string;
|
||||
}[];
|
||||
readonly deals: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: "open" | "won" | "lost";
|
||||
readonly amountLabel: string;
|
||||
readonly stageName: string;
|
||||
readonly href: string;
|
||||
}[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAtIso: string;
|
||||
readonly href: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AdminSalesCompanyDetailSource = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly legalName: string | null;
|
||||
readonly domain: string | null;
|
||||
readonly website: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly region: string | null;
|
||||
readonly countryCode: string | null;
|
||||
readonly industry: string | null;
|
||||
readonly employeeRange: string | null;
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly jobTitle: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
}[];
|
||||
readonly deals: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: "open" | "won" | "lost";
|
||||
readonly amountCents: number | null;
|
||||
readonly currencyCode: string;
|
||||
readonly stageName: string;
|
||||
}[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAt: Date;
|
||||
readonly contactId: string | null;
|
||||
readonly dealId: string | null;
|
||||
}[];
|
||||
};
|
||||
|
||||
export function buildAdminSalesCompanyDetailVM(input: {
|
||||
readonly source: AdminSalesCompanyDetailSource;
|
||||
readonly locale: string;
|
||||
readonly buildContactHref: (contactId: string) => string;
|
||||
readonly buildDealHref: (dealId: string) => string;
|
||||
}): AdminSalesCompanyDetailVM {
|
||||
return {
|
||||
id: input.source.id,
|
||||
name: input.source.name,
|
||||
legalName: input.source.legalName,
|
||||
domain: input.source.domain,
|
||||
website: input.source.website,
|
||||
phone: input.source.phone,
|
||||
locationLabel: [input.source.region, input.source.countryCode]
|
||||
.filter(Boolean)
|
||||
.join(", "),
|
||||
industry: input.source.industry,
|
||||
employeeRange: input.source.employeeRange,
|
||||
contacts: input.source.contacts.map((contact) => ({
|
||||
id: contact.id,
|
||||
name: `${contact.firstName} ${contact.lastName}`.trim(),
|
||||
jobTitle: contact.jobTitle,
|
||||
email: contact.email,
|
||||
phone: contact.phone,
|
||||
href: input.buildContactHref(contact.id),
|
||||
})),
|
||||
deals: input.source.deals.map((deal) => ({
|
||||
id: deal.id,
|
||||
title: deal.title,
|
||||
status: deal.status,
|
||||
amountLabel:
|
||||
deal.amountCents === null
|
||||
? ""
|
||||
: new Intl.NumberFormat(input.locale, {
|
||||
style: "currency",
|
||||
currency: deal.currencyCode,
|
||||
}).format(deal.amountCents / 100),
|
||||
stageName: deal.stageName,
|
||||
href: input.buildDealHref(deal.id),
|
||||
})),
|
||||
activities: input.source.activities.map((activity) => ({
|
||||
id: activity.id,
|
||||
type: activity.type,
|
||||
summary: activity.summary,
|
||||
occurredAtIso: activity.occurredAt.toISOString(),
|
||||
href: activity.dealId
|
||||
? input.buildDealHref(activity.dealId)
|
||||
: activity.contactId
|
||||
? input.buildContactHref(activity.contactId)
|
||||
: null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
function formatValue(value: string | number | boolean | Date | null): string {
|
||||
if (value === null) return "";
|
||||
if (value instanceof Date) return value.toISOString();
|
||||
return String(value);
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminDealBuyingCenterActionSchema,
|
||||
adminDealMoveActionSchema,
|
||||
adminDealTenantPromotionActionSchema,
|
||||
buildAdminDealDetailVM,
|
||||
buildAdminDealPipelineVM,
|
||||
} from "./deal-pipeline.vm.js";
|
||||
|
||||
const now = new Date("2026-07-24T12:00:00.000Z");
|
||||
|
||||
describe("buildAdminDealPipelineVM", () => {
|
||||
it("builds deterministic totals, weighted forecast and stage aging", () => {
|
||||
const vm = buildAdminDealPipelineVM({
|
||||
now,
|
||||
locale: "de-DE",
|
||||
pipelines: [{ id: "pipeline_1", name: "SaaS", isDefault: true }],
|
||||
board: {
|
||||
pipeline: { id: "pipeline_1", name: "SaaS", description: "Vertrieb" },
|
||||
stages: [
|
||||
{
|
||||
id: "demo",
|
||||
name: "Demo",
|
||||
kind: "open",
|
||||
probabilityBasisPoints: 3_000,
|
||||
agingThresholdDays: 7,
|
||||
color: "#2563eb",
|
||||
requiredFields: ["nextStep"],
|
||||
deals: [
|
||||
{
|
||||
id: "deal_1",
|
||||
title: "Muster GmbH",
|
||||
companyName: "Muster GmbH",
|
||||
ownerAdminUserId: "admin_1",
|
||||
amountCents: 10_000_00,
|
||||
currencyCode: "EUR",
|
||||
probabilityBasisPoints: 3_000,
|
||||
expectedCloseDate: new Date("2026-08-15T00:00:00.000Z"),
|
||||
nextStep: "Demo durchführen",
|
||||
nextStepDueAt: new Date("2026-07-28T09:00:00.000Z"),
|
||||
stageEnteredAt: new Date("2026-07-14T12:00:00.000Z"),
|
||||
lossReasonLabel: null,
|
||||
contacts: [{ name: "Ada Lovelace", isPrimary: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "won",
|
||||
name: "Abschluss",
|
||||
kind: "won",
|
||||
probabilityBasisPoints: 10_000,
|
||||
agingThresholdDays: null,
|
||||
color: "#16a34a",
|
||||
requiredFields: [],
|
||||
deals: [],
|
||||
},
|
||||
],
|
||||
lossReasons: [{ id: "reason_1", label: "Kein Budget" }],
|
||||
},
|
||||
buildDealHref: (id) => `/sales/deals/${id}`,
|
||||
permissions: { canRead: true, canWrite: true, canConfigure: true },
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.summary).toMatchObject({ dealCount: 1, overdueCount: 1 });
|
||||
expect(vm.summary.pipelineValue).toContain("10.000");
|
||||
expect(vm.summary.weightedForecast).toContain("3.000");
|
||||
expect(vm.columns[0]?.cards[0]).toMatchObject({
|
||||
id: "deal_1",
|
||||
detailHref: "/sales/deals/deal_1",
|
||||
ageDays: 10,
|
||||
isOverdue: true,
|
||||
primaryContactName: "Ada Lovelace",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns an actionable empty state without inventing a pipeline", () => {
|
||||
const vm = buildAdminDealPipelineVM({
|
||||
now,
|
||||
locale: "de-DE",
|
||||
pipelines: [],
|
||||
board: null,
|
||||
buildDealHref: () => "/sales/deals/unused",
|
||||
permissions: { canRead: true, canWrite: false, canConfigure: false },
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
status: "empty",
|
||||
pipelineId: null,
|
||||
columns: [],
|
||||
permissions: { canWrite: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminDealDetailVM", () => {
|
||||
it("keeps buying center, history and activity in chronological view data", () => {
|
||||
const vm = buildAdminDealDetailVM({
|
||||
now,
|
||||
locale: "de-DE",
|
||||
deal: {
|
||||
id: "deal_1",
|
||||
title: "Muster GmbH",
|
||||
status: "open",
|
||||
pipelineId: "pipeline_1",
|
||||
pipelineName: "SaaS",
|
||||
stageId: "demo",
|
||||
stageName: "Demo",
|
||||
companyName: "Muster GmbH",
|
||||
amountCents: 100_000,
|
||||
currencyCode: "EUR",
|
||||
probabilityBasisPoints: 3_000,
|
||||
expectedCloseDate: null,
|
||||
nextStep: "Demo",
|
||||
nextStepDueAt: null,
|
||||
stageEnteredAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
lossReasonLabel: null,
|
||||
lossReasonNote: null,
|
||||
promotedTenantId: null,
|
||||
promotedTenantName: null,
|
||||
promotedAt: null,
|
||||
contacts: [
|
||||
{
|
||||
id: "contact_1",
|
||||
name: "Ada Lovelace",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
email: "ada@example.test",
|
||||
role: "Champion",
|
||||
isPrimary: true,
|
||||
},
|
||||
],
|
||||
history: [
|
||||
{
|
||||
id: "history_1",
|
||||
fromStageName: "Lead",
|
||||
toStageName: "Demo",
|
||||
actorAdminUserId: "admin_1",
|
||||
enteredAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
reason: "Demo vereinbart",
|
||||
},
|
||||
],
|
||||
activities: [
|
||||
{
|
||||
id: "activity_1",
|
||||
type: "deal_stage_changed",
|
||||
summary: "Deal verschoben",
|
||||
occurredAt: new Date("2026-07-20T12:00:00.000Z"),
|
||||
},
|
||||
],
|
||||
},
|
||||
stages: [{ id: "demo", name: "Demo", kind: "open", requiredFields: [] }],
|
||||
lossReasons: [],
|
||||
contactOptions: [{ id: "contact_1", name: "Ada Lovelace", companyName: "Muster GmbH" }],
|
||||
tenantOptions: [{ id: "tenant_1", name: "Bestandskunde GmbH", slug: "bestandskunde" }],
|
||||
buildTenantHref: (id) => `/accounts/${id}`,
|
||||
canWrite: true,
|
||||
});
|
||||
|
||||
expect(vm.contacts[0]).toMatchObject({ role: "Champion", isPrimary: true });
|
||||
expect(vm.history[0]?.transitionLabel).toBe("Lead → Demo");
|
||||
expect(vm.activities[0]?.typeLabelKey).toBe("admin.sales.activities.deal_stage_changed");
|
||||
expect(vm.stageAgeDays).toBe(4);
|
||||
expect(vm.canPromoteTenant).toBe(false);
|
||||
expect(vm.tenantPromotionDefaults).toEqual({
|
||||
tenantName: "Muster GmbH",
|
||||
tenantSlug: "muster-gmbh",
|
||||
ownerEmail: "ada@example.test",
|
||||
ownerFirstName: "Ada",
|
||||
ownerLastName: "Lovelace",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("admin deal action schemas", () => {
|
||||
it("requires an explicit audit reason and a primary contact inside the buying center", () => {
|
||||
expect(adminDealMoveActionSchema.safeParse({ dealId: "deal_1", targetStageId: "demo", reason: "x" }).success).toBe(false);
|
||||
expect(
|
||||
adminDealBuyingCenterActionSchema.safeParse({
|
||||
dealId: "deal_1",
|
||||
contactIds: ["contact_1"],
|
||||
primaryContactId: "contact_2",
|
||||
roles: {},
|
||||
reason: "Buying Center aktualisiert",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("requires explicit confirmation and complete mode-specific tenant data", () => {
|
||||
expect(
|
||||
adminDealTenantPromotionActionSchema.safeParse({
|
||||
dealId: "deal_1",
|
||||
mode: "link_existing",
|
||||
tenantId: "tenant_1",
|
||||
tenantName: null,
|
||||
tenantSlug: null,
|
||||
ownerEmail: null,
|
||||
ownerFirstName: null,
|
||||
ownerLastName: null,
|
||||
confirmed: true,
|
||||
reason: "Gewonnenen Deal bewusst verknüpfen",
|
||||
}).success
|
||||
).toBe(true);
|
||||
expect(
|
||||
adminDealTenantPromotionActionSchema.safeParse({
|
||||
dealId: "deal_1",
|
||||
mode: "create_new",
|
||||
tenantId: null,
|
||||
tenantName: "Muster GmbH",
|
||||
tenantSlug: "muster-gmbh",
|
||||
ownerEmail: "ada@example.test",
|
||||
ownerFirstName: "Ada",
|
||||
ownerLastName: "Lovelace",
|
||||
confirmed: false,
|
||||
reason: "Gewonnenen Deal bewusst anlegen",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+538
@@ -0,0 +1,538 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const identifierSchema = z.string().trim().min(1).max(191).regex(/^[A-Za-z0-9_:-]+$/u);
|
||||
export type AdminDealRequiredFieldKeyVM =
|
||||
| "amountCents"
|
||||
| "expectedCloseDate"
|
||||
| "nextStep"
|
||||
| "companyId"
|
||||
| "primaryContactId"
|
||||
| "lossReasonId";
|
||||
|
||||
export const adminDealMoveActionSchema = z.object({
|
||||
dealId: identifierSchema,
|
||||
targetStageId: identifierSchema,
|
||||
lossReasonId: identifierSchema.nullable().optional(),
|
||||
lossReasonNote: z.string().trim().max(2_000).nullable().optional(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminDealUpdateActionSchema = z.object({
|
||||
dealId: identifierSchema,
|
||||
amountCents: z.number().int().min(0).nullable(),
|
||||
currencyCode: z.string().trim().length(3).transform((value) => value.toUpperCase()),
|
||||
expectedCloseDate: z.string().date().nullable(),
|
||||
nextStep: z.string().trim().max(2_000).nullable(),
|
||||
nextStepDueAt: z.string().datetime({ offset: true }).nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export const adminDealBuyingCenterActionSchema = z.object({
|
||||
dealId: identifierSchema,
|
||||
contactIds: z.array(identifierSchema).max(100),
|
||||
primaryContactId: identifierSchema.nullable(),
|
||||
roles: z.record(identifierSchema, z.string().trim().min(1).max(120)),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}).superRefine((value, context) => {
|
||||
if (value.primaryContactId && !value.contactIds.includes(value.primaryContactId)) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["primaryContactId"],
|
||||
message: "admin.sales.deals.errors.primaryContactRequired",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const adminDealTenantPromotionActionSchema = z
|
||||
.object({
|
||||
dealId: identifierSchema,
|
||||
mode: z.enum(["link_existing", "create_new"]),
|
||||
tenantId: identifierSchema.nullable(),
|
||||
tenantName: z.string().trim().max(200).nullable(),
|
||||
tenantSlug: z
|
||||
.string()
|
||||
.trim()
|
||||
.max(80)
|
||||
.regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u)
|
||||
.nullable(),
|
||||
ownerEmail: z.string().trim().email().max(320).nullable(),
|
||||
ownerFirstName: z.string().trim().max(120).nullable(),
|
||||
ownerLastName: z.string().trim().max(120).nullable(),
|
||||
confirmed: z.literal(true),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (value.mode === "link_existing" && !value.tenantId) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["tenantId"],
|
||||
message: "admin.sales.deals.errors.tenantRequired",
|
||||
});
|
||||
}
|
||||
if (
|
||||
value.mode === "create_new" &&
|
||||
(!value.tenantName ||
|
||||
!value.tenantSlug ||
|
||||
!value.ownerEmail ||
|
||||
!value.ownerFirstName ||
|
||||
!value.ownerLastName)
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["tenantName"],
|
||||
message: "admin.sales.deals.errors.tenantOwnerRequired",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const adminPipelineCreateActionSchema = z.object({
|
||||
name: z.string().trim().min(1).max(160),
|
||||
description: z.string().trim().max(1_000).nullable(),
|
||||
isDefault: z.boolean(),
|
||||
lossReasons: z.array(z.string().trim().min(1).max(120)).max(50),
|
||||
stages: z.array(
|
||||
z.object({
|
||||
name: z.string().trim().min(1).max(120),
|
||||
position: z.number().int().min(0),
|
||||
kind: z.enum(["open", "won", "lost"]),
|
||||
probabilityBasisPoints: z.number().int().min(0).max(10_000),
|
||||
agingThresholdDays: z.number().int().min(1).max(365).nullable(),
|
||||
requiredFields: z.array(z.enum(["amountCents", "expectedCloseDate", "nextStep", "companyId", "primaryContactId", "lossReasonId"])),
|
||||
})
|
||||
).min(2).max(30),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}).superRefine((value, context) => {
|
||||
if (value.stages.filter((stage) => stage.kind === "won").length !== 1 || value.stages.filter((stage) => stage.kind === "lost").length !== 1) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["stages"],
|
||||
message: "admin.sales.pipelineSettings.errors.terminalStages",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type AdminDealPipelineVM = {
|
||||
readonly status: "ready" | "empty";
|
||||
readonly titleKey: "admin.sales.deals.title";
|
||||
readonly pipelineId: string | null;
|
||||
readonly pipelineName: string | null;
|
||||
readonly pipelineDescription: string | null;
|
||||
readonly pipelineOptions: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly isDefault: boolean;
|
||||
}[];
|
||||
readonly columns: readonly AdminDealPipelineColumnVM[];
|
||||
readonly stages: readonly AdminDealStageOptionVM[];
|
||||
readonly lossReasons: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly summary: {
|
||||
readonly dealCount: number;
|
||||
readonly pipelineValue: string;
|
||||
readonly weightedForecast: string;
|
||||
readonly overdueCount: number;
|
||||
};
|
||||
readonly permissions: {
|
||||
readonly canRead: boolean;
|
||||
readonly canWrite: boolean;
|
||||
readonly canConfigure: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export type AdminDealPipelineColumnVM = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly kind: "open" | "won" | "lost";
|
||||
readonly color: string | null;
|
||||
readonly probabilityLabel: string;
|
||||
readonly amountLabel: string;
|
||||
readonly dealCount: number;
|
||||
readonly cards: readonly AdminDealPipelineCardVM[];
|
||||
};
|
||||
|
||||
export type AdminDealPipelineCardVM = {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly detailHref: string;
|
||||
readonly companyName: string | null;
|
||||
readonly amountLabel: string;
|
||||
readonly weightedAmountLabel: string;
|
||||
readonly expectedCloseDateLabel: string | null;
|
||||
readonly nextStep: string | null;
|
||||
readonly nextStepDueAtLabel: string | null;
|
||||
readonly ageDays: number;
|
||||
readonly isOverdue: boolean;
|
||||
readonly contactCount: number;
|
||||
readonly primaryContactName: string | null;
|
||||
readonly ownerAdminUserId: string;
|
||||
readonly lossReasonLabel: string | null;
|
||||
};
|
||||
|
||||
export type AdminDealStageOptionVM = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly kind: "open" | "won" | "lost";
|
||||
readonly requiredFields: readonly string[];
|
||||
};
|
||||
|
||||
export type BuildAdminDealPipelineVMInput = {
|
||||
readonly now: Date;
|
||||
readonly locale: string;
|
||||
readonly pipelines: readonly { readonly id: string; readonly name: string; readonly isDefault: boolean }[];
|
||||
readonly board: {
|
||||
readonly pipeline: { readonly id: string; readonly name: string; readonly description: string | null };
|
||||
readonly stages: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly kind: "open" | "won" | "lost";
|
||||
readonly probabilityBasisPoints: number;
|
||||
readonly agingThresholdDays: number | null;
|
||||
readonly color: string | null;
|
||||
readonly requiredFields: readonly string[];
|
||||
readonly deals: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly companyName: string | null;
|
||||
readonly ownerAdminUserId: string;
|
||||
readonly amountCents: number | null;
|
||||
readonly currencyCode: string;
|
||||
readonly probabilityBasisPoints: number;
|
||||
readonly expectedCloseDate: Date | null;
|
||||
readonly nextStep: string | null;
|
||||
readonly nextStepDueAt: Date | null;
|
||||
readonly stageEnteredAt: Date;
|
||||
readonly lossReasonLabel: string | null;
|
||||
readonly contacts: readonly {
|
||||
readonly name: string;
|
||||
readonly isPrimary: boolean;
|
||||
}[];
|
||||
}[];
|
||||
}[];
|
||||
readonly lossReasons: readonly { readonly id: string; readonly label: string }[];
|
||||
} | null;
|
||||
readonly buildDealHref: (dealId: string) => string;
|
||||
readonly permissions: AdminDealPipelineVM["permissions"];
|
||||
};
|
||||
|
||||
export function buildAdminDealPipelineVM(input: BuildAdminDealPipelineVMInput): AdminDealPipelineVM {
|
||||
if (!input.board) {
|
||||
return {
|
||||
status: "empty",
|
||||
titleKey: "admin.sales.deals.title",
|
||||
pipelineId: null,
|
||||
pipelineName: null,
|
||||
pipelineDescription: null,
|
||||
pipelineOptions: input.pipelines.map((pipeline) => ({ ...pipeline })),
|
||||
columns: [],
|
||||
stages: [],
|
||||
lossReasons: [],
|
||||
summary: { dealCount: 0, pipelineValue: formatMoney(0, "EUR", input.locale), weightedForecast: formatMoney(0, "EUR", input.locale), overdueCount: 0 },
|
||||
permissions: { ...input.permissions },
|
||||
};
|
||||
}
|
||||
|
||||
let totalCents = 0;
|
||||
let weightedCents = 0;
|
||||
let dealCount = 0;
|
||||
let overdueCount = 0;
|
||||
const columns = input.board.stages.map((stage): AdminDealPipelineColumnVM => {
|
||||
let stageCents = 0;
|
||||
const cards = stage.deals.map((deal): AdminDealPipelineCardVM => {
|
||||
const amountCents = deal.amountCents ?? 0;
|
||||
const ageDays = Math.max(0, Math.floor((input.now.getTime() - deal.stageEnteredAt.getTime()) / 86_400_000));
|
||||
const isOverdue = stage.agingThresholdDays !== null && ageDays > stage.agingThresholdDays;
|
||||
totalCents += amountCents;
|
||||
stageCents += amountCents;
|
||||
weightedCents += Math.round((amountCents * deal.probabilityBasisPoints) / 10_000);
|
||||
dealCount += 1;
|
||||
if (isOverdue) overdueCount += 1;
|
||||
return {
|
||||
id: deal.id,
|
||||
title: deal.title,
|
||||
detailHref: input.buildDealHref(deal.id),
|
||||
companyName: deal.companyName,
|
||||
amountLabel: formatMoney(amountCents, deal.currencyCode, input.locale),
|
||||
weightedAmountLabel: formatMoney(Math.round((amountCents * deal.probabilityBasisPoints) / 10_000), deal.currencyCode, input.locale),
|
||||
expectedCloseDateLabel: deal.expectedCloseDate ? formatDate(deal.expectedCloseDate, input.locale) : null,
|
||||
nextStep: deal.nextStep,
|
||||
nextStepDueAtLabel: deal.nextStepDueAt ? formatDate(deal.nextStepDueAt, input.locale) : null,
|
||||
ageDays,
|
||||
isOverdue,
|
||||
contactCount: deal.contacts.length,
|
||||
primaryContactName: deal.contacts.find((contact) => contact.isPrimary)?.name ?? null,
|
||||
ownerAdminUserId: deal.ownerAdminUserId,
|
||||
lossReasonLabel: deal.lossReasonLabel,
|
||||
};
|
||||
});
|
||||
return {
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
kind: stage.kind,
|
||||
color: stage.color,
|
||||
probabilityLabel: formatPercent(stage.probabilityBasisPoints, input.locale),
|
||||
amountLabel: formatMoney(stageCents, stage.deals[0]?.currencyCode ?? "EUR", input.locale),
|
||||
dealCount: cards.length,
|
||||
cards,
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
titleKey: "admin.sales.deals.title",
|
||||
pipelineId: input.board.pipeline.id,
|
||||
pipelineName: input.board.pipeline.name,
|
||||
pipelineDescription: input.board.pipeline.description,
|
||||
pipelineOptions: input.pipelines.map((pipeline) => ({ ...pipeline })),
|
||||
columns,
|
||||
stages: input.board.stages.map((stage) => ({
|
||||
id: stage.id,
|
||||
name: stage.name,
|
||||
kind: stage.kind,
|
||||
requiredFields: [...stage.requiredFields],
|
||||
})),
|
||||
lossReasons: input.board.lossReasons.map((reason) => ({ ...reason })),
|
||||
summary: {
|
||||
dealCount,
|
||||
pipelineValue: formatMoney(totalCents, "EUR", input.locale),
|
||||
weightedForecast: formatMoney(weightedCents, "EUR", input.locale),
|
||||
overdueCount,
|
||||
},
|
||||
permissions: { ...input.permissions },
|
||||
};
|
||||
}
|
||||
|
||||
export type AdminDealDetailVM = {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: "open" | "won" | "lost";
|
||||
readonly statusLabelKey: string;
|
||||
readonly pipelineId: string;
|
||||
readonly pipelineName: string;
|
||||
readonly stageId: string;
|
||||
readonly stageName: string;
|
||||
readonly companyName: string | null;
|
||||
readonly amountLabel: string;
|
||||
readonly amountCents: number | null;
|
||||
readonly currencyCode: string;
|
||||
readonly probabilityLabel: string;
|
||||
readonly expectedCloseDate: string | null;
|
||||
readonly nextStep: string | null;
|
||||
readonly nextStepDueAt: string | null;
|
||||
readonly stageAgeDays: number;
|
||||
readonly lossReasonLabel: string | null;
|
||||
readonly lossReasonNote: string | null;
|
||||
readonly promotedTenantId: string | null;
|
||||
readonly promotedTenantName: string | null;
|
||||
readonly promotedTenantHref: string | null;
|
||||
readonly promotedAtLabel: string | null;
|
||||
readonly canPromoteTenant: boolean;
|
||||
readonly tenantOptions: readonly {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
}[];
|
||||
readonly tenantPromotionDefaults: {
|
||||
readonly tenantName: string;
|
||||
readonly tenantSlug: string;
|
||||
readonly ownerEmail: string;
|
||||
readonly ownerFirstName: string;
|
||||
readonly ownerLastName: string;
|
||||
};
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly href: string | null;
|
||||
readonly role: string | null;
|
||||
readonly isPrimary: boolean;
|
||||
}[];
|
||||
readonly contactOptions: readonly {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly companyName: string | null;
|
||||
}[];
|
||||
readonly history: readonly {
|
||||
readonly id: string;
|
||||
readonly transitionLabel: string;
|
||||
readonly actorAdminUserId: string;
|
||||
readonly enteredAtLabel: string;
|
||||
readonly reason: string | null;
|
||||
}[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly typeLabelKey: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAtLabel: string;
|
||||
}[];
|
||||
readonly stages: readonly AdminDealStageOptionVM[];
|
||||
readonly lossReasons: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly canWrite: boolean;
|
||||
};
|
||||
|
||||
export function buildAdminDealDetailVM(input: {
|
||||
readonly now: Date;
|
||||
readonly locale: string;
|
||||
readonly deal: {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: "open" | "won" | "lost";
|
||||
readonly pipelineId: string;
|
||||
readonly pipelineName: string;
|
||||
readonly stageId: string;
|
||||
readonly stageName: string;
|
||||
readonly companyName: string | null;
|
||||
readonly amountCents: number | null;
|
||||
readonly currencyCode: string;
|
||||
readonly probabilityBasisPoints: number;
|
||||
readonly expectedCloseDate: Date | null;
|
||||
readonly nextStep: string | null;
|
||||
readonly nextStepDueAt: Date | null;
|
||||
readonly stageEnteredAt: Date;
|
||||
readonly lossReasonLabel: string | null;
|
||||
readonly lossReasonNote: string | null;
|
||||
readonly promotedTenantId: string | null;
|
||||
readonly promotedTenantName: string | null;
|
||||
readonly promotedAt: Date | null;
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly email: string | null;
|
||||
readonly phone?: string | null;
|
||||
readonly role: string | null;
|
||||
readonly isPrimary: boolean;
|
||||
}[];
|
||||
readonly history: readonly {
|
||||
readonly id: string;
|
||||
readonly fromStageName: string | null;
|
||||
readonly toStageName: string;
|
||||
readonly actorAdminUserId: string;
|
||||
readonly enteredAt: Date;
|
||||
readonly reason: string | null;
|
||||
}[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAt: Date;
|
||||
}[];
|
||||
};
|
||||
readonly stages: readonly AdminDealStageOptionVM[];
|
||||
readonly lossReasons: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly contactOptions: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly companyName: string | null;
|
||||
}[];
|
||||
readonly tenantOptions: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
}[];
|
||||
readonly buildContactHref?: (contactId: string) => string;
|
||||
readonly buildTenantHref?: (tenantId: string) => string;
|
||||
readonly canWrite: boolean;
|
||||
}): AdminDealDetailVM {
|
||||
const primaryContact = input.deal.contacts.find((contact) => contact.isPrimary);
|
||||
return {
|
||||
id: input.deal.id,
|
||||
title: input.deal.title,
|
||||
status: input.deal.status,
|
||||
statusLabelKey: `admin.sales.deals.status.${input.deal.status}`,
|
||||
pipelineId: input.deal.pipelineId,
|
||||
pipelineName: input.deal.pipelineName,
|
||||
stageId: input.deal.stageId,
|
||||
stageName: input.deal.stageName,
|
||||
companyName: input.deal.companyName,
|
||||
amountLabel: formatMoney(input.deal.amountCents ?? 0, input.deal.currencyCode, input.locale),
|
||||
amountCents: input.deal.amountCents,
|
||||
currencyCode: input.deal.currencyCode,
|
||||
probabilityLabel: formatPercent(input.deal.probabilityBasisPoints, input.locale),
|
||||
expectedCloseDate: input.deal.expectedCloseDate?.toISOString().slice(0, 10) ?? null,
|
||||
nextStep: input.deal.nextStep,
|
||||
nextStepDueAt: input.deal.nextStepDueAt?.toISOString() ?? null,
|
||||
stageAgeDays: Math.max(0, Math.floor((input.now.getTime() - input.deal.stageEnteredAt.getTime()) / 86_400_000)),
|
||||
lossReasonLabel: input.deal.lossReasonLabel,
|
||||
lossReasonNote: input.deal.lossReasonNote,
|
||||
promotedTenantId: input.deal.promotedTenantId,
|
||||
promotedTenantName: input.deal.promotedTenantName,
|
||||
promotedTenantHref:
|
||||
input.deal.promotedTenantId && input.buildTenantHref
|
||||
? input.buildTenantHref(input.deal.promotedTenantId)
|
||||
: null,
|
||||
promotedAtLabel: input.deal.promotedAt
|
||||
? formatDateTime(input.deal.promotedAt, input.locale)
|
||||
: null,
|
||||
canPromoteTenant:
|
||||
input.canWrite &&
|
||||
input.deal.status === "won" &&
|
||||
input.deal.promotedTenantId === null,
|
||||
tenantOptions: input.tenantOptions.map((tenant) => ({
|
||||
id: tenant.id,
|
||||
label: `${tenant.name} (${tenant.slug})`,
|
||||
})),
|
||||
tenantPromotionDefaults: {
|
||||
tenantName: input.deal.companyName ?? input.deal.title,
|
||||
tenantSlug: slugify(input.deal.companyName ?? input.deal.title),
|
||||
ownerEmail: primaryContact?.email ?? "",
|
||||
ownerFirstName: primaryContact?.firstName ?? "",
|
||||
ownerLastName: primaryContact?.lastName ?? "",
|
||||
},
|
||||
contacts: input.deal.contacts.map((contact) => ({
|
||||
id: contact.id,
|
||||
name: contact.name,
|
||||
email: contact.email,
|
||||
phone: contact.phone ?? null,
|
||||
role: contact.role,
|
||||
isPrimary: contact.isPrimary,
|
||||
href: input.buildContactHref?.(contact.id) ?? null,
|
||||
})),
|
||||
contactOptions: input.contactOptions.map((contact) => ({
|
||||
id: contact.id,
|
||||
label: contact.name,
|
||||
companyName: contact.companyName,
|
||||
})),
|
||||
history: input.deal.history.map((entry) => ({
|
||||
id: entry.id,
|
||||
transitionLabel: entry.fromStageName ? `${entry.fromStageName} → ${entry.toStageName}` : entry.toStageName,
|
||||
actorAdminUserId: entry.actorAdminUserId,
|
||||
enteredAtLabel: formatDateTime(entry.enteredAt, input.locale),
|
||||
reason: entry.reason,
|
||||
})),
|
||||
activities: input.deal.activities.map((activity) => ({
|
||||
id: activity.id,
|
||||
typeLabelKey: `admin.sales.activities.${activity.type}`,
|
||||
summary: activity.summary,
|
||||
occurredAtLabel: formatDateTime(activity.occurredAt, input.locale),
|
||||
})),
|
||||
stages: input.stages.map((stage) => ({ ...stage, requiredFields: [...stage.requiredFields] })),
|
||||
lossReasons: input.lossReasons.map((reason) => ({ ...reason })),
|
||||
canWrite: input.canWrite,
|
||||
};
|
||||
}
|
||||
|
||||
function slugify(value: string): string {
|
||||
return value
|
||||
.normalize("NFKD")
|
||||
.replace(/\p{Diacritic}/gu, "")
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/gu, "-")
|
||||
.replace(/^-+|-+$/gu, "")
|
||||
.slice(0, 80) || "kunde";
|
||||
}
|
||||
|
||||
function formatMoney(cents: number, currency: string, locale: string): string {
|
||||
return new Intl.NumberFormat(locale, { style: "currency", currency }).format(cents / 100);
|
||||
}
|
||||
|
||||
function formatPercent(basisPoints: number, locale: string): string {
|
||||
return new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 1 }).format(basisPoints / 10_000);
|
||||
}
|
||||
|
||||
function formatDate(value: Date, locale: string): string {
|
||||
return new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeZone: "Europe/Berlin" }).format(value);
|
||||
}
|
||||
|
||||
function formatDateTime(value: Date, locale: string): string {
|
||||
return new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short", timeZone: "Europe/Berlin" }).format(value);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminEmailConnectionsVM } from "./email-connections.vm.js";
|
||||
|
||||
describe("admin email connections view model", () => {
|
||||
it("sorts accounts and derives provider capability state", () => {
|
||||
const vm = buildAdminEmailConnectionsVM({
|
||||
accounts: [
|
||||
{
|
||||
id: "mailbox-2",
|
||||
connectionId: "connection-2",
|
||||
provider: "microsoft_mail",
|
||||
emailAddress: "z@example.com",
|
||||
displayName: null,
|
||||
status: "active",
|
||||
lastSyncAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
healthMessageKey: null,
|
||||
},
|
||||
{
|
||||
id: "mailbox-1",
|
||||
connectionId: "connection-1",
|
||||
provider: "google_mail",
|
||||
emailAddress: "a@example.com",
|
||||
displayName: "A",
|
||||
status: "revoked",
|
||||
lastSyncAt: null,
|
||||
healthMessageKey: "admin.sales.email.connections.health.revoked",
|
||||
},
|
||||
],
|
||||
providerConfiguration: {
|
||||
google_mail: true,
|
||||
microsoft_mail: false,
|
||||
},
|
||||
});
|
||||
|
||||
expect(vm.accounts.map((account) => account.id)).toEqual([
|
||||
"mailbox-1",
|
||||
"mailbox-2",
|
||||
]);
|
||||
expect(vm.providers).toEqual([
|
||||
{
|
||||
provider: "google_mail",
|
||||
configured: true,
|
||||
connected: false,
|
||||
},
|
||||
{
|
||||
provider: "microsoft_mail",
|
||||
configured: false,
|
||||
connected: true,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const providerSchema = z.enum(["google_mail", "microsoft_mail"]);
|
||||
|
||||
export const adminEmailConnectionsVMSchema = z.object({
|
||||
accounts: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
connectionId: z.string().min(1),
|
||||
provider: providerSchema,
|
||||
emailAddress: z.string().email(),
|
||||
displayName: z.string().nullable(),
|
||||
status: z.enum(["connecting", "active", "degraded", "revoked"]),
|
||||
lastSyncAt: z.string().datetime().nullable(),
|
||||
healthMessageKey: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
providers: z.array(
|
||||
z.object({
|
||||
provider: providerSchema,
|
||||
configured: z.boolean(),
|
||||
connected: z.boolean(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const adminEmailConnectionActionSchema = z.object({
|
||||
intent: z.literal("disconnect"),
|
||||
mailboxId: z.string().min(1).max(128),
|
||||
connectionId: z.string().min(1).max(128),
|
||||
provider: providerSchema,
|
||||
});
|
||||
|
||||
export type AdminEmailConnectionsVM = z.infer<
|
||||
typeof adminEmailConnectionsVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminEmailConnectionsVM(input: {
|
||||
readonly accounts: readonly {
|
||||
readonly id: string;
|
||||
readonly connectionId: string;
|
||||
readonly provider: "google_mail" | "microsoft_mail";
|
||||
readonly emailAddress: string;
|
||||
readonly displayName: string | null;
|
||||
readonly status: "connecting" | "active" | "degraded" | "revoked";
|
||||
readonly lastSyncAt: Date | null;
|
||||
readonly healthMessageKey: string | null;
|
||||
}[];
|
||||
readonly providerConfiguration: Readonly<
|
||||
Record<"google_mail" | "microsoft_mail", boolean>
|
||||
>;
|
||||
}): AdminEmailConnectionsVM {
|
||||
const accounts = [...input.accounts]
|
||||
.sort((left, right) =>
|
||||
left.emailAddress.localeCompare(right.emailAddress)
|
||||
)
|
||||
.map((account) => ({
|
||||
...account,
|
||||
lastSyncAt: account.lastSyncAt?.toISOString() ?? null,
|
||||
}));
|
||||
|
||||
return adminEmailConnectionsVMSchema.parse({
|
||||
accounts,
|
||||
providers: (["google_mail", "microsoft_mail"] as const).map(
|
||||
(provider) => ({
|
||||
provider,
|
||||
configured: input.providerConfiguration[provider],
|
||||
connected: accounts.some(
|
||||
(account) =>
|
||||
account.provider === provider && account.status !== "revoked"
|
||||
),
|
||||
})
|
||||
),
|
||||
});
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { adminEmailWorkspaceActionSchema, buildAdminEmailInboxVM } from "./email-workspace.vm.js";
|
||||
|
||||
describe("admin email workspace view models", () => {
|
||||
it("keeps the assignment queue and selected thread deterministic", () => {
|
||||
const vm = buildAdminEmailInboxVM({
|
||||
stats: { threads: 1, unread: 2, assignmentQueue: 1 },
|
||||
threads: [
|
||||
{
|
||||
id: "thread-1",
|
||||
subject: "Demo",
|
||||
latestMessageAt: "2026-07-24T10:00:00.000Z",
|
||||
messageCount: 2,
|
||||
unreadCount: 2,
|
||||
matchStatus: "ambiguous",
|
||||
preview: "Können wir sprechen?",
|
||||
fromAddress: "buyer@example.com",
|
||||
contactLabel: null,
|
||||
dealLabel: null,
|
||||
eventTypes: ["delivered", "opened"],
|
||||
attachmentCount: 1,
|
||||
},
|
||||
],
|
||||
selectedThread: null,
|
||||
assignmentOptions: { contacts: [], deals: [] },
|
||||
});
|
||||
|
||||
expect(vm.stats.assignmentQueue).toBe(1);
|
||||
expect(vm.threads[0]?.eventTypes).toEqual(["delivered", "opened"]);
|
||||
});
|
||||
|
||||
it("rejects productive sends without an explicit idempotency key", () => {
|
||||
expect(
|
||||
adminEmailWorkspaceActionSchema.safeParse({
|
||||
intent: "queue-email",
|
||||
mailboxId: "mailbox-1",
|
||||
contactId: "contact-1",
|
||||
dealId: null,
|
||||
toAddress: "buyer@example.com",
|
||||
subject: "Demo",
|
||||
body: "Hallo",
|
||||
scheduledFor: "2026-07-24T10:00:00.000Z",
|
||||
timeZone: "Europe/Berlin",
|
||||
noReplyAfterDays: 3,
|
||||
idempotencyKey: "",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const matchStatusSchema = z.enum(["matched", "ambiguous", "unmatched", "manual"]);
|
||||
const scheduledStatusSchema = z.enum(["draft", "blocked", "queued", "sending", "sent", "cancelled", "failed"]);
|
||||
|
||||
export const adminEmailInboxVMSchema = z.object({
|
||||
stats: z.object({
|
||||
threads: z.number().int().nonnegative(),
|
||||
unread: z.number().int().nonnegative(),
|
||||
assignmentQueue: z.number().int().nonnegative(),
|
||||
}),
|
||||
threads: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
subject: z.string(),
|
||||
latestMessageAt: z.string().datetime(),
|
||||
messageCount: z.number().int().nonnegative(),
|
||||
unreadCount: z.number().int().nonnegative(),
|
||||
matchStatus: matchStatusSchema,
|
||||
preview: z.string(),
|
||||
fromAddress: z.string(),
|
||||
contactLabel: z.string().nullable(),
|
||||
dealLabel: z.string().nullable(),
|
||||
eventTypes: z.array(z.string()),
|
||||
attachmentCount: z.number().int().nonnegative(),
|
||||
})
|
||||
),
|
||||
selectedThread: z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
subject: z.string(),
|
||||
messages: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
direction: z.enum(["inbound", "outbound"]),
|
||||
fromAddress: z.string(),
|
||||
sentAt: z.string().datetime(),
|
||||
bodyText: z.string(),
|
||||
eventTypes: z.array(z.string()),
|
||||
attachments: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
filename: z.string(),
|
||||
sizeBytes: z.number().int().nonnegative(),
|
||||
downloadHref: z.string().min(1),
|
||||
})
|
||||
),
|
||||
})
|
||||
),
|
||||
})
|
||||
.nullable(),
|
||||
assignmentOptions: z.object({
|
||||
contacts: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string(),
|
||||
email: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
deals: z.array(z.object({ id: z.string().min(1), label: z.string() })),
|
||||
}),
|
||||
});
|
||||
|
||||
export const adminEmailTemplatesVMSchema = z.object({
|
||||
templates: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string(),
|
||||
subjectTemplate: z.string(),
|
||||
htmlTemplate: z.string(),
|
||||
allowedPlaceholders: z.array(z.string()),
|
||||
version: z.number().int().positive(),
|
||||
updatedAt: z.string().datetime(),
|
||||
})
|
||||
),
|
||||
snippets: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
shortcut: z.string(),
|
||||
title: z.string(),
|
||||
content: z.string(),
|
||||
})
|
||||
),
|
||||
signature: z.object({ html: z.string(), text: z.string().nullable() }).nullable(),
|
||||
});
|
||||
|
||||
export const adminEmailScheduledVMSchema = z.object({
|
||||
outboundLocked: z.boolean(),
|
||||
policy: z
|
||||
.object({
|
||||
timeZone: z.string(),
|
||||
workdayStartMinutes: z.number().int(),
|
||||
workdayEndMinutes: z.number().int(),
|
||||
allowedWeekDays: z.array(z.number().int()),
|
||||
dailySendLimit: z.number().int().positive(),
|
||||
bulkDailySendLimit: z.number().int().positive(),
|
||||
consentRulesConfigured: z.boolean(),
|
||||
trackingEnabled: z.boolean(),
|
||||
liveOpenEnabled: z.boolean(),
|
||||
trackingRetentionDays: z.number().int().positive(),
|
||||
})
|
||||
.nullable(),
|
||||
scheduled: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
subject: z.string(),
|
||||
recipients: z.array(z.string()),
|
||||
scheduledFor: z.string().datetime(),
|
||||
status: scheduledStatusSchema,
|
||||
noReplyAfterDays: z.number().int().positive().nullable(),
|
||||
errorMessageKey: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
bulkRuns: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
name: z.string(),
|
||||
status: z.string(),
|
||||
scheduledFor: z.string().datetime().nullable(),
|
||||
recipientCount: z.number().int().nonnegative(),
|
||||
sentCount: z.number().int().nonnegative(),
|
||||
failedCount: z.number().int().nonnegative(),
|
||||
})
|
||||
),
|
||||
reminders: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
dueAt: z.string().datetime(),
|
||||
status: z.string(),
|
||||
subject: z.string(),
|
||||
taskId: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
mailboxes: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
emailAddress: z.string().email(),
|
||||
displayName: z.string().nullable(),
|
||||
})
|
||||
),
|
||||
contacts: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string(),
|
||||
email: z.string().email(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export const adminEmailDomainsVMSchema = z.object({
|
||||
domains: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
domain: z.string(),
|
||||
status: z.string(),
|
||||
spfStatus: z.string(),
|
||||
dkimStatus: z.string(),
|
||||
spfRecordName: z.string(),
|
||||
spfExpectedValue: z.string(),
|
||||
dkimRecordName: z.string(),
|
||||
dkimExpectedValue: z.string(),
|
||||
lastCheckedAt: z.string().datetime().nullable(),
|
||||
})
|
||||
),
|
||||
bccAddresses: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
mailboxId: z.string().min(1),
|
||||
mailboxLabel: z.string(),
|
||||
displayAddress: z.string(),
|
||||
rotatedAt: z.string().datetime().nullable(),
|
||||
})
|
||||
),
|
||||
tracking: z.object({
|
||||
enabled: z.boolean(),
|
||||
liveOpenEnabled: z.boolean(),
|
||||
retentionDays: z.number().int().positive(),
|
||||
}),
|
||||
});
|
||||
|
||||
export const adminEmailWorkspaceActionSchema = z.discriminatedUnion("intent", [
|
||||
z.object({
|
||||
intent: z.literal("assign-message"),
|
||||
messageId: z.string().min(1).max(128),
|
||||
contactId: z.string().min(1).max(128).nullable(),
|
||||
dealId: z.string().min(1).max(128).nullable(),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("queue-email"),
|
||||
mailboxId: z.string().min(1).max(128),
|
||||
contactId: z.string().min(1).max(128).nullable(),
|
||||
dealId: z.string().min(1).max(128).nullable(),
|
||||
toAddress: z.string().email(),
|
||||
subject: z.string().min(1).max(500),
|
||||
body: z.string().min(1).max(100_000),
|
||||
scheduledFor: z.string().datetime(),
|
||||
timeZone: z.string().min(1).max(120),
|
||||
noReplyAfterDays: z.number().int().min(1).max(90).nullable(),
|
||||
idempotencyKey: z.string().min(1).max(200),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("queue-bulk-email"),
|
||||
mailboxId: z.string().min(1).max(128),
|
||||
name: z.string().min(1).max(160),
|
||||
contactIds: z.array(z.string().min(1).max(128)).min(1).max(250),
|
||||
subjectTemplate: z.string().min(1).max(500),
|
||||
bodyTemplate: z.string().min(1).max(100_000),
|
||||
scheduledFor: z.string().datetime(),
|
||||
timeZone: z.string().min(1).max(120),
|
||||
noReplyAfterDays: z.number().int().min(1).max(90).nullable(),
|
||||
idempotencyKey: z.string().min(1).max(200),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-template"),
|
||||
name: z.string().min(1).max(120),
|
||||
subjectTemplate: z.string().min(1).max(500),
|
||||
htmlTemplate: z.string().min(1).max(100_000),
|
||||
allowedPlaceholders: z.array(z.string().min(1).max(120)).max(30),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-snippet"),
|
||||
shortcut: z.string().min(1).max(40),
|
||||
title: z.string().min(1).max(120),
|
||||
content: z.string().min(1).max(20_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-signature"),
|
||||
html: z.string().min(1).max(50_000),
|
||||
text: z.string().max(50_000).nullable(),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-policy"),
|
||||
timeZone: z.string().min(1).max(120),
|
||||
workdayStartMinutes: z.number().int().min(0).max(1_439),
|
||||
workdayEndMinutes: z.number().int().min(1).max(1_440),
|
||||
allowedWeekDays: z.array(z.number().int().min(0).max(6)).min(1),
|
||||
dailySendLimit: z.number().int().min(1).max(10_000),
|
||||
bulkDailySendLimit: z.number().int().min(1).max(10_000),
|
||||
consentRulesConfigured: z.boolean(),
|
||||
trackingEnabled: z.boolean(),
|
||||
liveOpenEnabled: z.boolean(),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("save-domain"),
|
||||
domain: z.string().min(1).max(253),
|
||||
spfRecordName: z.string().min(1).max(253),
|
||||
spfExpectedValue: z.string().min(1).max(4_096),
|
||||
dkimRecordName: z.string().min(1).max(253),
|
||||
dkimExpectedValue: z.string().min(1).max(4_096),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type AdminEmailInboxVM = z.infer<typeof adminEmailInboxVMSchema>;
|
||||
export type AdminEmailTemplatesVM = z.infer<typeof adminEmailTemplatesVMSchema>;
|
||||
export type AdminEmailScheduledVM = z.infer<typeof adminEmailScheduledVMSchema>;
|
||||
export type AdminEmailDomainsVM = z.infer<typeof adminEmailDomainsVMSchema>;
|
||||
|
||||
export function buildAdminEmailInboxVM(input: z.input<typeof adminEmailInboxVMSchema>): AdminEmailInboxVM {
|
||||
return adminEmailInboxVMSchema.parse(input);
|
||||
}
|
||||
|
||||
export function buildAdminEmailTemplatesVM(input: z.input<typeof adminEmailTemplatesVMSchema>): AdminEmailTemplatesVM {
|
||||
return adminEmailTemplatesVMSchema.parse(input);
|
||||
}
|
||||
|
||||
export function buildAdminEmailScheduledVM(input: z.input<typeof adminEmailScheduledVMSchema>): AdminEmailScheduledVM {
|
||||
return adminEmailScheduledVMSchema.parse(input);
|
||||
}
|
||||
|
||||
export function buildAdminEmailDomainsVM(input: z.input<typeof adminEmailDomainsVMSchema>): AdminEmailDomainsVM {
|
||||
return adminEmailDomainsVMSchema.parse(input);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminFeatureFlagRolloutVM } from "./feature-flag-rollout.vm.js";
|
||||
|
||||
describe("admin feature flag rollout VM", () => {
|
||||
it("joins deterministic decisions onto alphabetically sorted tenants", () => {
|
||||
const vm = buildAdminFeatureFlagRolloutVM({
|
||||
flag: { key: "sales_workspace", label: "Sales", defaultValue: false, lifecycleStage: "beta" },
|
||||
tenants: [
|
||||
{ id: "b", name: "Zulu", slug: "zulu" },
|
||||
{ id: "a", name: "Alpha", slug: "alpha" },
|
||||
],
|
||||
preview: {
|
||||
enabled: 1,
|
||||
disabled: 1,
|
||||
overrides: 1,
|
||||
filtered: 0,
|
||||
defaulted: 1,
|
||||
rows: [
|
||||
{ tenantId: "a", decision: { value: true, source: "override", filterId: null } },
|
||||
{ tenantId: "b", decision: { value: false, source: "default", filterId: null } },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.tenants.map((tenant) => tenant.id)).toEqual(["a", "b"]);
|
||||
expect(vm.data.tenants[0]).toMatchObject({
|
||||
effectiveValue: true,
|
||||
source: "override",
|
||||
sourceLabelKey: "featureFlags.rollout.source.override",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects an incomplete preview instead of rendering a misleading value", () => {
|
||||
expect(() =>
|
||||
buildAdminFeatureFlagRolloutVM({
|
||||
flag: { key: "sales_workspace", label: "Sales", defaultValue: false, lifecycleStage: "beta" },
|
||||
tenants: [{ id: "a", name: "Alpha", slug: "alpha" }],
|
||||
preview: { enabled: 0, disabled: 0, overrides: 0, filtered: 0, defaulted: 0, rows: [] },
|
||||
})
|
||||
).toThrow(/Missing feature flag decision/u);
|
||||
});
|
||||
});
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type AdminFeatureFlagRolloutInput = {
|
||||
readonly updatedCount?: number | null;
|
||||
readonly flag: {
|
||||
readonly key: string;
|
||||
readonly label: string;
|
||||
readonly defaultValue: boolean;
|
||||
readonly lifecycleStage: "beta" | "rollout" | "ga" | "deprecated";
|
||||
};
|
||||
readonly tenants: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly size?: string | null;
|
||||
readonly status?: string | null;
|
||||
}[];
|
||||
readonly preview: {
|
||||
readonly enabled: number;
|
||||
readonly disabled: number;
|
||||
readonly overrides: number;
|
||||
readonly filtered: number;
|
||||
readonly defaulted: number;
|
||||
readonly rows: readonly {
|
||||
readonly tenantId: string;
|
||||
readonly decision: {
|
||||
readonly value: boolean;
|
||||
readonly source: "override" | "filter" | "default";
|
||||
readonly filterId: string | null;
|
||||
};
|
||||
}[];
|
||||
};
|
||||
};
|
||||
|
||||
export type AdminFeatureFlagRolloutData = {
|
||||
readonly updatedCount: number | null;
|
||||
readonly flag: AdminFeatureFlagRolloutInput["flag"];
|
||||
readonly summary: AdminFeatureFlagRolloutInput["preview"] extends infer Preview
|
||||
? Preview extends { rows: unknown }
|
||||
? Omit<Preview, "rows">
|
||||
: never
|
||||
: never;
|
||||
readonly tenants: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly size: string | null;
|
||||
readonly status: string | null;
|
||||
readonly effectiveValue: boolean;
|
||||
readonly source: "override" | "filter" | "default";
|
||||
readonly sourceLabelKey: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type AdminFeatureFlagRolloutVM = VMState<AdminFeatureFlagRolloutData>;
|
||||
|
||||
export function buildAdminFeatureFlagRolloutVM(input: AdminFeatureFlagRolloutInput): AdminFeatureFlagRolloutVM {
|
||||
const decisionByTenant = new Map(input.preview.rows.map((row) => [row.tenantId, row.decision]));
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
updatedCount: input.updatedCount ?? null,
|
||||
flag: input.flag,
|
||||
summary: {
|
||||
enabled: input.preview.enabled,
|
||||
disabled: input.preview.disabled,
|
||||
overrides: input.preview.overrides,
|
||||
filtered: input.preview.filtered,
|
||||
defaulted: input.preview.defaulted,
|
||||
},
|
||||
tenants: [...input.tenants]
|
||||
.sort((left, right) => left.name.localeCompare(right.name) || left.id.localeCompare(right.id))
|
||||
.map((tenant) => {
|
||||
const decision = decisionByTenant.get(tenant.id);
|
||||
if (!decision) throw new Error(`Missing feature flag decision for tenant ${tenant.id}`);
|
||||
return {
|
||||
id: tenant.id,
|
||||
name: tenant.name,
|
||||
slug: tenant.slug,
|
||||
size: tenant.size ?? null,
|
||||
status: tenant.status ?? null,
|
||||
effectiveValue: decision.value,
|
||||
source: decision.source,
|
||||
sourceLabelKey: `featureFlags.rollout.source.${decision.source}`,
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminLeadAutomationFormSchema,
|
||||
buildAdminLeadAutomationVM,
|
||||
} from "./lead-automation.vm.js";
|
||||
|
||||
describe("admin lead automation view model", () => {
|
||||
it("sorts rules deterministically and resolves source and operator labels", () => {
|
||||
const vm = buildAdminLeadAutomationVM({
|
||||
assignmentRules: [
|
||||
{
|
||||
id: "rule-b",
|
||||
name: "Round Robin",
|
||||
priority: 20,
|
||||
active: true,
|
||||
sourceId: "source-web",
|
||||
region: "DACH",
|
||||
strategy: "round_robin",
|
||||
fixedAssigneeAdminUserId: null,
|
||||
roundRobinAdminUserIds: ["admin-b", "admin-a"],
|
||||
nextAssigneeIndex: 1,
|
||||
},
|
||||
{
|
||||
id: "rule-a",
|
||||
name: "Enterprise",
|
||||
priority: 10,
|
||||
active: true,
|
||||
sourceId: null,
|
||||
region: null,
|
||||
strategy: "fixed",
|
||||
fixedAssigneeAdminUserId: "admin-a",
|
||||
roundRobinAdminUserIds: [],
|
||||
nextAssigneeIndex: 0,
|
||||
},
|
||||
],
|
||||
scoreRules: [
|
||||
{
|
||||
id: "score-1",
|
||||
name: "Has email",
|
||||
priority: 10,
|
||||
active: true,
|
||||
field: "has_email",
|
||||
operator: "present",
|
||||
value: null,
|
||||
points: 10,
|
||||
version: 1,
|
||||
},
|
||||
],
|
||||
sourceOptions: [{ id: "source-web", label: "Website" }],
|
||||
assigneeOptions: [
|
||||
{ id: "admin-a", label: "Ada" },
|
||||
{ id: "admin-b", label: "Berta" },
|
||||
],
|
||||
canConfigure: true,
|
||||
});
|
||||
|
||||
expect(vm.assignmentRules.map((rule) => rule.id)).toEqual(["rule-a", "rule-b"]);
|
||||
expect(vm.assignmentRules[0]?.assigneeLabels).toEqual(["Ada"]);
|
||||
expect(vm.assignmentRules[1]).toMatchObject({
|
||||
sourceLabel: "Website",
|
||||
assigneeLabels: ["Berta", "Ada"],
|
||||
});
|
||||
expect(JSON.parse(JSON.stringify(vm))).toEqual(vm);
|
||||
});
|
||||
|
||||
it("requires a deterministic target for both assignment strategies", () => {
|
||||
expect(
|
||||
adminLeadAutomationFormSchema.safeParse({
|
||||
intent: "create-assignment-rule",
|
||||
name: "Fixed",
|
||||
priority: 10,
|
||||
strategy: "fixed",
|
||||
roundRobinAdminUserIds: [],
|
||||
}).success
|
||||
).toBe(false);
|
||||
expect(
|
||||
adminLeadAutomationFormSchema.safeParse({
|
||||
intent: "create-assignment-rule",
|
||||
name: "Round Robin",
|
||||
priority: 10,
|
||||
strategy: "round_robin",
|
||||
roundRobinAdminUserIds: ["admin-a", "admin-b"],
|
||||
}).success
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const optionalText = (max: number) =>
|
||||
z.preprocess(
|
||||
(value) =>
|
||||
value === null || (typeof value === "string" && value.trim() === "")
|
||||
? undefined
|
||||
: value,
|
||||
z.string().trim().max(max).optional()
|
||||
);
|
||||
|
||||
export const adminLeadAutomationFormSchema = z.union([
|
||||
z
|
||||
.object({
|
||||
intent: z.literal("create-assignment-rule"),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
priority: z.coerce.number().int().min(0).max(1_000_000),
|
||||
sourceId: optionalText(191),
|
||||
region: optionalText(120),
|
||||
strategy: z.enum(["fixed", "round_robin"]),
|
||||
fixedAssigneeAdminUserId: optionalText(191),
|
||||
roundRobinAdminUserIds: z.array(z.string().trim().min(1).max(191)).max(100).default([]),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (value.strategy === "fixed" && !value.fixedAssigneeAdminUserId) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["fixedAssigneeAdminUserId"],
|
||||
message: "admin.sales.leadSettings.errors.fixedAssignee",
|
||||
});
|
||||
}
|
||||
if (value.strategy === "round_robin" && value.roundRobinAdminUserIds.length === 0) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["roundRobinAdminUserIds"],
|
||||
message: "admin.sales.leadSettings.errors.roundRobinMembers",
|
||||
});
|
||||
}
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("create-score-rule"),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
priority: z.coerce.number().int().min(0).max(1_000_000),
|
||||
field: z.enum(["source", "region", "country", "company", "has_email", "has_phone"]),
|
||||
operator: z.enum(["equals", "not_equals", "contains", "present"]),
|
||||
value: optionalText(300),
|
||||
points: z.coerce.number().int().min(-1_000).max(1_000),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type AdminLeadAutomationVM = {
|
||||
readonly assignmentRules: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly priority: number;
|
||||
readonly active: boolean;
|
||||
readonly sourceLabel: string | null;
|
||||
readonly region: string | null;
|
||||
readonly strategy: "fixed" | "round_robin";
|
||||
readonly assigneeLabels: readonly string[];
|
||||
readonly nextAssigneeIndex: number;
|
||||
}[];
|
||||
readonly scoreRules: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly priority: number;
|
||||
readonly active: boolean;
|
||||
readonly field: string;
|
||||
readonly operator: string;
|
||||
readonly value: string | null;
|
||||
readonly points: number;
|
||||
readonly version: number;
|
||||
}[];
|
||||
readonly sourceOptions: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly assigneeOptions: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly canConfigure: boolean;
|
||||
};
|
||||
|
||||
export function buildAdminLeadAutomationVM(input: {
|
||||
readonly assignmentRules: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly priority: number;
|
||||
readonly active: boolean;
|
||||
readonly sourceId: string | null;
|
||||
readonly region: string | null;
|
||||
readonly strategy: "fixed" | "round_robin";
|
||||
readonly fixedAssigneeAdminUserId: string | null;
|
||||
readonly roundRobinAdminUserIds: readonly string[];
|
||||
readonly nextAssigneeIndex: number;
|
||||
}[];
|
||||
readonly scoreRules: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly priority: number;
|
||||
readonly active: boolean;
|
||||
readonly field: string;
|
||||
readonly operator: string;
|
||||
readonly value: string | null;
|
||||
readonly points: number;
|
||||
readonly version: number;
|
||||
}[];
|
||||
readonly sourceOptions: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly assigneeOptions: readonly { readonly id: string; readonly label: string }[];
|
||||
readonly canConfigure: boolean;
|
||||
}): AdminLeadAutomationVM {
|
||||
const sourceLabels = new Map(input.sourceOptions.map((option) => [option.id, option.label]));
|
||||
const assigneeLabels = new Map(input.assigneeOptions.map((option) => [option.id, option.label]));
|
||||
return {
|
||||
assignmentRules: [...input.assignmentRules]
|
||||
.sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id))
|
||||
.map((rule) => ({
|
||||
...rule,
|
||||
sourceLabel: rule.sourceId ? (sourceLabels.get(rule.sourceId) ?? rule.sourceId) : null,
|
||||
assigneeLabels: (
|
||||
rule.strategy === "fixed"
|
||||
? [rule.fixedAssigneeAdminUserId].filter((value): value is string => Boolean(value))
|
||||
: rule.roundRobinAdminUserIds
|
||||
).map((id) => assigneeLabels.get(id) ?? id),
|
||||
})),
|
||||
scoreRules: [...input.scoreRules].sort((a, b) => a.priority - b.priority || a.id.localeCompare(b.id)),
|
||||
sourceOptions: [...input.sourceOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
assigneeOptions: [...input.assigneeOptions].sort((a, b) => a.label.localeCompare(b.label, "de")),
|
||||
canConfigure: input.canConfigure,
|
||||
};
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminPublicBookingManageVM } from "./public-booking-manage.vm.js";
|
||||
|
||||
describe("buildAdminPublicBookingManageVM", () => {
|
||||
it("formats the current booking and replacement slots in booker time", () => {
|
||||
const vm = buildAdminPublicBookingManageVM({
|
||||
title: "Demo buchen",
|
||||
meetingTypeName: "Demo",
|
||||
startsAt: new Date("2026-08-01T10:00:00.000Z"),
|
||||
date: "2026-08-02",
|
||||
timeZone: "Europe/Berlin",
|
||||
locale: "de-DE",
|
||||
slots: [
|
||||
{
|
||||
startsAt: new Date("2026-08-02T10:00:00.000Z"),
|
||||
endsAt: new Date("2026-08-02T10:30:00.000Z"),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(vm.currentStartsAtLabel).toContain("12:00");
|
||||
expect(vm.slots[0]).toEqual({
|
||||
value:
|
||||
"2026-08-02T10:00:00.000Z|2026-08-02T10:30:00.000Z",
|
||||
label: expect.stringContaining("12:00"),
|
||||
});
|
||||
});
|
||||
});
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminPublicBookingManageVMSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
meetingTypeName: z.string().min(1),
|
||||
currentStartsAtLabel: z.string().min(1),
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/u),
|
||||
timeZone: z.string().min(1),
|
||||
slots: z.array(
|
||||
z.object({
|
||||
value: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type AdminPublicBookingManageVM = z.infer<
|
||||
typeof adminPublicBookingManageVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminPublicBookingManageVM(input: {
|
||||
readonly title: string;
|
||||
readonly meetingTypeName: string;
|
||||
readonly startsAt: Date;
|
||||
readonly date: string;
|
||||
readonly timeZone: string;
|
||||
readonly locale: string;
|
||||
readonly slots: readonly {
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
}[];
|
||||
}): AdminPublicBookingManageVM {
|
||||
const formatter = new Intl.DateTimeFormat(input.locale, {
|
||||
dateStyle: "full",
|
||||
timeStyle: "short",
|
||||
timeZone: input.timeZone,
|
||||
});
|
||||
return adminPublicBookingManageVMSchema.parse({
|
||||
title: input.title,
|
||||
meetingTypeName: input.meetingTypeName,
|
||||
currentStartsAtLabel: formatter.format(input.startsAt),
|
||||
date: input.date,
|
||||
timeZone: input.timeZone,
|
||||
slots: input.slots.map((slot) => ({
|
||||
value: `${slot.startsAt.toISOString()}|${slot.endsAt.toISOString()}`,
|
||||
label: formatter.format(slot.startsAt),
|
||||
})),
|
||||
});
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminPublicBookingVM } from "./public-booking.vm.js";
|
||||
|
||||
describe("buildAdminPublicBookingVM", () => {
|
||||
it("serializes authoritative slots without leaking host identities", () => {
|
||||
const vm = buildAdminPublicBookingVM({
|
||||
title: "Erstgespräch buchen",
|
||||
description: null,
|
||||
meetingTypeName: "Erstgespräch",
|
||||
durationMinutes: 30,
|
||||
date: "2026-08-03",
|
||||
submissionId: "submission_1",
|
||||
locale: "de-DE",
|
||||
timeZone: "Europe/Berlin",
|
||||
slots: [
|
||||
{
|
||||
startsAt: new Date("2026-08-03T08:00:00.000Z"),
|
||||
endsAt: new Date("2026-08-03T08:30:00.000Z"),
|
||||
},
|
||||
],
|
||||
questions: [
|
||||
{
|
||||
id: "goal",
|
||||
label: "Was möchtest du besprechen?",
|
||||
required: true,
|
||||
type: "textarea",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.slots[0]?.value).toBe(
|
||||
"2026-08-03T08:00:00.000Z|2026-08-03T08:30:00.000Z"
|
||||
);
|
||||
expect(JSON.stringify(vm)).not.toContain("adminUser");
|
||||
expect(vm.questions[0]).toMatchObject({
|
||||
id: "goal",
|
||||
required: true,
|
||||
multiline: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminPublicBookingVMSchema = z.object({
|
||||
title: z.string().min(1),
|
||||
description: z.string().nullable(),
|
||||
meetingTypeName: z.string().min(1),
|
||||
durationMinutes: z.number().int().positive(),
|
||||
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/u),
|
||||
timeZone: z.string().min(1),
|
||||
submissionId: z.string().min(1),
|
||||
slots: z.array(
|
||||
z.object({
|
||||
value: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
})
|
||||
),
|
||||
questions: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
required: z.boolean(),
|
||||
multiline: z.boolean(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type AdminPublicBookingVM = z.infer<
|
||||
typeof adminPublicBookingVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminPublicBookingVM(input: {
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly meetingTypeName: string;
|
||||
readonly durationMinutes: number;
|
||||
readonly date: string;
|
||||
readonly submissionId: string;
|
||||
readonly locale: string;
|
||||
readonly timeZone: string;
|
||||
readonly slots: readonly {
|
||||
readonly startsAt: Date;
|
||||
readonly endsAt: Date;
|
||||
}[];
|
||||
readonly questions: readonly {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly required: boolean;
|
||||
readonly type: "text" | "textarea" | "select";
|
||||
}[];
|
||||
}): AdminPublicBookingVM {
|
||||
const formatter = new Intl.DateTimeFormat(input.locale, {
|
||||
weekday: "short",
|
||||
day: "2-digit",
|
||||
month: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
timeZone: input.timeZone,
|
||||
});
|
||||
return adminPublicBookingVMSchema.parse({
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
meetingTypeName: input.meetingTypeName,
|
||||
durationMinutes: input.durationMinutes,
|
||||
date: input.date,
|
||||
timeZone: input.timeZone,
|
||||
submissionId: input.submissionId,
|
||||
slots: input.slots.map((slot) => ({
|
||||
value: `${slot.startsAt.toISOString()}|${slot.endsAt.toISOString()}`,
|
||||
label: formatter.format(slot.startsAt),
|
||||
})),
|
||||
questions: input.questions.map((question) => ({
|
||||
id: question.id,
|
||||
label: question.label,
|
||||
required: question.required,
|
||||
multiline: question.type === "textarea",
|
||||
})),
|
||||
});
|
||||
}
|
||||
+165
@@ -0,0 +1,165 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminSalesTaskCreateActionSchema,
|
||||
buildAdminSalesContactDetailVM,
|
||||
buildAdminSalesTodayVM,
|
||||
type AdminSalesTaskSource,
|
||||
} from "./tasks.vm.js";
|
||||
|
||||
const now = new Date("2026-07-24T12:00:00.000Z");
|
||||
|
||||
function task(
|
||||
overrides: Partial<AdminSalesTaskSource> = {}
|
||||
): AdminSalesTaskSource {
|
||||
return {
|
||||
id: "task_1",
|
||||
title: "Demo nachfassen",
|
||||
description: null,
|
||||
contactId: "contact_1",
|
||||
contactName: "Ada Lovelace",
|
||||
dealId: "deal_1",
|
||||
dealTitle: "HiveGrid SaaS",
|
||||
assignedToAdminUserId: "admin_1",
|
||||
dueAt: new Date("2026-07-24T14:00:00.000Z"),
|
||||
timeZone: "Europe/Berlin",
|
||||
reminderAt: new Date("2026-07-24T13:00:00.000Z"),
|
||||
priority: "high",
|
||||
status: "open",
|
||||
source: "manual",
|
||||
recurrence: { frequency: "weekly" },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("admin sales task view model", () => {
|
||||
it("groups overdue and today tasks with stable navigation", () => {
|
||||
const vm = buildAdminSalesTodayVM({
|
||||
now,
|
||||
todayStart: new Date("2026-07-23T22:00:00.000Z"),
|
||||
locale: "de-DE",
|
||||
timeZone: "Europe/Berlin",
|
||||
tasks: [
|
||||
task({
|
||||
id: "overdue",
|
||||
dueAt: new Date("2026-07-23T10:00:00.000Z"),
|
||||
priority: "urgent",
|
||||
}),
|
||||
task({ id: "today" }),
|
||||
],
|
||||
buildContactHref: (id) => `/sales/contacts/${id}`,
|
||||
buildDealHref: (id) => `/sales/deals/${id}`,
|
||||
permissions: { canRead: true, canWrite: true },
|
||||
});
|
||||
|
||||
expect(vm.summary).toEqual({
|
||||
openCount: 2,
|
||||
overdueCount: 1,
|
||||
dueTodayCount: 1,
|
||||
urgentCount: 2,
|
||||
});
|
||||
expect(vm.overdue[0]).toMatchObject({
|
||||
id: "overdue",
|
||||
isOverdue: true,
|
||||
contactHref: "/sales/contacts/contact_1",
|
||||
dealHref: "/sales/deals/deal_1",
|
||||
recurrenceLabelKey: "admin.sales.tasks.recurrence.weekly",
|
||||
});
|
||||
expect(vm.dueToday[0]?.priorityLabelKey).toBe(
|
||||
"admin.sales.tasks.priority.high"
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the shared contact timeline without client-side data access", () => {
|
||||
const vm = buildAdminSalesContactDetailVM({
|
||||
now,
|
||||
locale: "de-DE",
|
||||
defaultTimeZone: "Europe/Berlin",
|
||||
contact: {
|
||||
id: "contact_1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
jobTitle: "CTO",
|
||||
email: "ada@example.test",
|
||||
phone: "+49 30 123456",
|
||||
locale: "de-DE",
|
||||
timeZone: null,
|
||||
ownerAdminUserId: "admin_1",
|
||||
company: { id: "company_1", name: "Analytical Engines" },
|
||||
deals: [
|
||||
{
|
||||
id: "deal_1",
|
||||
title: "HiveGrid SaaS",
|
||||
status: "open",
|
||||
stageName: "Demo",
|
||||
isPrimary: true,
|
||||
role: "Entscheiderin",
|
||||
},
|
||||
],
|
||||
tasks: [task()],
|
||||
activities: [
|
||||
{
|
||||
id: "activity_1",
|
||||
type: "call",
|
||||
summary: "Demo besprochen",
|
||||
occurredAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
dealId: "deal_1",
|
||||
recordingId: "recording_1",
|
||||
},
|
||||
],
|
||||
},
|
||||
buildContactHref: (id) => `/sales/contacts/${id}`,
|
||||
buildDealHref: (id) => `/sales/deals/${id}`,
|
||||
buildRecordingHref: (id) => `/sales/calls/recordings/${id}`,
|
||||
canWrite: true,
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
name: "Ada Lovelace",
|
||||
initials: "AL",
|
||||
timeZone: "Europe/Berlin",
|
||||
deals: [
|
||||
expect.objectContaining({
|
||||
href: "/sales/deals/deal_1",
|
||||
statusLabelKey: "admin.sales.deals.status.open",
|
||||
}),
|
||||
],
|
||||
activities: [
|
||||
expect.objectContaining({
|
||||
typeLabelKey: "admin.sales.activities.call",
|
||||
dealHref: "/sales/deals/deal_1",
|
||||
recordingHref: "/sales/calls/recordings/recording_1",
|
||||
}),
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a task without entity context or with an invalid reminder order", () => {
|
||||
const base = {
|
||||
title: "Nachfassen",
|
||||
description: null,
|
||||
contactId: null,
|
||||
dealId: null,
|
||||
assignedToAdminUserId: "admin_1",
|
||||
dueAt: "2026-07-25T08:00:00.000Z",
|
||||
timeZone: "Europe/Berlin",
|
||||
reminderAt: "2026-07-25T09:00:00.000Z",
|
||||
priority: "normal" as const,
|
||||
recurrenceFrequency: null,
|
||||
recurrenceInterval: 1,
|
||||
recurrenceEndsAt: null,
|
||||
reason: "Follow-up planen",
|
||||
};
|
||||
|
||||
const result = adminSalesTaskCreateActionSchema.safeParse(base);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success) {
|
||||
expect(result.error.issues.map((issue) => issue.message)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"admin.sales.tasks.errors.contextRequired",
|
||||
"admin.sales.tasks.errors.reminderBeforeDue",
|
||||
])
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const identifierSchema = z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.max(191)
|
||||
.regex(/^[A-Za-z0-9_:-]+$/u);
|
||||
const nullableIdentifierSchema = identifierSchema.nullable();
|
||||
|
||||
export const adminSalesTaskCreateActionSchema = z
|
||||
.object({
|
||||
title: z.string().trim().min(1).max(240),
|
||||
description: z.string().trim().max(4_000).nullable(),
|
||||
contactId: nullableIdentifierSchema,
|
||||
dealId: nullableIdentifierSchema,
|
||||
assignedToAdminUserId: identifierSchema,
|
||||
dueAt: z.string().datetime({ offset: true }),
|
||||
timeZone: z.string().trim().min(1).max(100),
|
||||
reminderAt: z.string().datetime({ offset: true }).nullable(),
|
||||
priority: z.enum(["low", "normal", "high", "urgent"]),
|
||||
recurrenceFrequency: z
|
||||
.enum(["daily", "weekly", "monthly"])
|
||||
.nullable(),
|
||||
recurrenceInterval: z.number().int().min(1).max(365),
|
||||
recurrenceEndsAt: z.string().datetime({ offset: true }).nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
if (!value.contactId && !value.dealId) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["contactId"],
|
||||
message: "admin.sales.tasks.errors.contextRequired",
|
||||
});
|
||||
}
|
||||
if (
|
||||
value.reminderAt &&
|
||||
new Date(value.reminderAt) >= new Date(value.dueAt)
|
||||
) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
path: ["reminderAt"],
|
||||
message: "admin.sales.tasks.errors.reminderBeforeDue",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export const adminSalesTaskCompleteActionSchema = z.object({
|
||||
taskId: identifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
});
|
||||
|
||||
export type AdminSalesTaskVM = {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly contactId: string | null;
|
||||
readonly contactName: string | null;
|
||||
readonly contactHref: string | null;
|
||||
readonly dealId: string | null;
|
||||
readonly dealTitle: string | null;
|
||||
readonly dealHref: string | null;
|
||||
readonly assignedToAdminUserId: string;
|
||||
readonly dueAtIso: string;
|
||||
readonly dueAtLabel: string;
|
||||
readonly timeZone: string;
|
||||
readonly reminderAtLabel: string | null;
|
||||
readonly priority: "low" | "normal" | "high" | "urgent";
|
||||
readonly priorityLabelKey: string;
|
||||
readonly status: "open" | "completed" | "cancelled";
|
||||
readonly statusLabelKey: string;
|
||||
readonly source: "manual" | "email" | "call";
|
||||
readonly sourceLabelKey: string;
|
||||
readonly recurrenceLabelKey: string | null;
|
||||
readonly isOverdue: boolean;
|
||||
readonly canComplete: boolean;
|
||||
};
|
||||
|
||||
export type AdminSalesTaskSource = {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly contactId: string | null;
|
||||
readonly contactName: string | null;
|
||||
readonly dealId: string | null;
|
||||
readonly dealTitle: string | null;
|
||||
readonly assignedToAdminUserId: string;
|
||||
readonly dueAt: Date;
|
||||
readonly timeZone: string;
|
||||
readonly reminderAt: Date | null;
|
||||
readonly priority: "low" | "normal" | "high" | "urgent";
|
||||
readonly status: "open" | "completed" | "cancelled";
|
||||
readonly source: "manual" | "email" | "call";
|
||||
readonly recurrence: {
|
||||
readonly frequency: "daily" | "weekly" | "monthly";
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type AdminSalesTodayVM = {
|
||||
readonly status: "ready" | "empty";
|
||||
readonly titleKey: "admin.sales.tasks.today.title";
|
||||
readonly subtitleKey: "admin.sales.tasks.today.subtitle";
|
||||
readonly timeZone: string;
|
||||
readonly summary: {
|
||||
readonly openCount: number;
|
||||
readonly overdueCount: number;
|
||||
readonly dueTodayCount: number;
|
||||
readonly urgentCount: number;
|
||||
};
|
||||
readonly overdue: readonly AdminSalesTaskVM[];
|
||||
readonly dueToday: readonly AdminSalesTaskVM[];
|
||||
readonly permissions: {
|
||||
readonly canRead: boolean;
|
||||
readonly canWrite: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export type AdminSalesContactDetailVM = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly initials: string;
|
||||
readonly jobTitle: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locale: string | null;
|
||||
readonly timeZone: string;
|
||||
readonly ownerAdminUserId: string | null;
|
||||
readonly company: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
} | null;
|
||||
readonly deals: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly href: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly stageName: string;
|
||||
readonly isPrimary: boolean;
|
||||
readonly role: string | null;
|
||||
}[];
|
||||
readonly tasks: readonly AdminSalesTaskVM[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly typeLabelKey: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAtLabel: string;
|
||||
readonly dealHref: string | null;
|
||||
readonly recordingHref: string | null;
|
||||
}[];
|
||||
readonly canWrite: boolean;
|
||||
};
|
||||
|
||||
export function buildAdminSalesTodayVM(input: {
|
||||
readonly now: Date;
|
||||
readonly todayStart: Date;
|
||||
readonly locale: string;
|
||||
readonly timeZone: string;
|
||||
readonly tasks: readonly AdminSalesTaskSource[];
|
||||
readonly buildContactHref: (contactId: string) => string;
|
||||
readonly buildDealHref: (dealId: string) => string;
|
||||
readonly permissions: AdminSalesTodayVM["permissions"];
|
||||
}): AdminSalesTodayVM {
|
||||
const rows = buildAdminSalesTaskRows({
|
||||
now: input.now,
|
||||
locale: input.locale,
|
||||
tasks: input.tasks,
|
||||
buildContactHref: input.buildContactHref,
|
||||
buildDealHref: input.buildDealHref,
|
||||
canWrite: input.permissions.canWrite,
|
||||
});
|
||||
const overdue = rows.filter(
|
||||
(task) =>
|
||||
task.status === "open" &&
|
||||
new Date(task.dueAtIso).getTime() < input.todayStart.getTime()
|
||||
);
|
||||
const dueToday = rows.filter(
|
||||
(task) =>
|
||||
task.status === "open" &&
|
||||
new Date(task.dueAtIso).getTime() >= input.todayStart.getTime()
|
||||
);
|
||||
return {
|
||||
status: rows.length === 0 ? "empty" : "ready",
|
||||
titleKey: "admin.sales.tasks.today.title",
|
||||
subtitleKey: "admin.sales.tasks.today.subtitle",
|
||||
timeZone: input.timeZone,
|
||||
summary: {
|
||||
openCount: rows.length,
|
||||
overdueCount: overdue.length,
|
||||
dueTodayCount: dueToday.length,
|
||||
urgentCount: rows.filter(
|
||||
(task) => task.priority === "urgent" || task.priority === "high"
|
||||
).length,
|
||||
},
|
||||
overdue,
|
||||
dueToday,
|
||||
permissions: { ...input.permissions },
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAdminSalesTaskRows(input: {
|
||||
readonly now: Date;
|
||||
readonly locale: string;
|
||||
readonly tasks: readonly AdminSalesTaskSource[];
|
||||
readonly buildContactHref: (contactId: string) => string;
|
||||
readonly buildDealHref: (dealId: string) => string;
|
||||
readonly canWrite: boolean;
|
||||
}): AdminSalesTaskVM[] {
|
||||
return input.tasks.map((task) => ({
|
||||
id: task.id,
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
contactId: task.contactId,
|
||||
contactName: task.contactName,
|
||||
contactHref: task.contactId ? input.buildContactHref(task.contactId) : null,
|
||||
dealId: task.dealId,
|
||||
dealTitle: task.dealTitle,
|
||||
dealHref: task.dealId ? input.buildDealHref(task.dealId) : null,
|
||||
assignedToAdminUserId: task.assignedToAdminUserId,
|
||||
dueAtIso: task.dueAt.toISOString(),
|
||||
dueAtLabel: formatDateTime(task.dueAt, input.locale, task.timeZone),
|
||||
timeZone: task.timeZone,
|
||||
reminderAtLabel: task.reminderAt
|
||||
? formatDateTime(task.reminderAt, input.locale, task.timeZone)
|
||||
: null,
|
||||
priority: task.priority,
|
||||
priorityLabelKey: `admin.sales.tasks.priority.${task.priority}`,
|
||||
status: task.status,
|
||||
statusLabelKey: `admin.sales.tasks.status.${task.status}`,
|
||||
source: task.source,
|
||||
sourceLabelKey: `admin.sales.tasks.source.${task.source}`,
|
||||
recurrenceLabelKey: task.recurrence
|
||||
? `admin.sales.tasks.recurrence.${task.recurrence.frequency}`
|
||||
: null,
|
||||
isOverdue:
|
||||
task.status === "open" && task.dueAt.getTime() < input.now.getTime(),
|
||||
canComplete: input.canWrite && task.status === "open",
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildAdminSalesContactDetailVM(input: {
|
||||
readonly now: Date;
|
||||
readonly locale: string;
|
||||
readonly defaultTimeZone: string;
|
||||
readonly contact: {
|
||||
readonly id: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly jobTitle: string | null;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
readonly locale: string | null;
|
||||
readonly timeZone: string | null;
|
||||
readonly ownerAdminUserId: string | null;
|
||||
readonly company: { readonly id: string; readonly name: string } | null;
|
||||
readonly deals: readonly {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly status: "open" | "won" | "lost";
|
||||
readonly stageName: string;
|
||||
readonly isPrimary: boolean;
|
||||
readonly role: string | null;
|
||||
}[];
|
||||
readonly tasks: readonly AdminSalesTaskSource[];
|
||||
readonly activities: readonly {
|
||||
readonly id: string;
|
||||
readonly type: string;
|
||||
readonly summary: string;
|
||||
readonly occurredAt: Date;
|
||||
readonly dealId: string | null;
|
||||
readonly recordingId?: string | null;
|
||||
}[];
|
||||
};
|
||||
readonly buildContactHref: (contactId: string) => string;
|
||||
readonly buildDealHref: (dealId: string) => string;
|
||||
readonly buildRecordingHref: (recordingId: string) => string;
|
||||
readonly canWrite: boolean;
|
||||
}): AdminSalesContactDetailVM {
|
||||
const timeZone = input.contact.timeZone ?? input.defaultTimeZone;
|
||||
const name = `${input.contact.firstName} ${input.contact.lastName}`.trim();
|
||||
return {
|
||||
id: input.contact.id,
|
||||
name,
|
||||
initials: [input.contact.firstName, input.contact.lastName]
|
||||
.map((part) => part.trim().charAt(0).toUpperCase())
|
||||
.join(""),
|
||||
jobTitle: input.contact.jobTitle,
|
||||
email: input.contact.email,
|
||||
phone: input.contact.phone,
|
||||
locale: input.contact.locale,
|
||||
timeZone,
|
||||
ownerAdminUserId: input.contact.ownerAdminUserId,
|
||||
company: input.contact.company ? { ...input.contact.company } : null,
|
||||
deals: input.contact.deals.map((deal) => ({
|
||||
...deal,
|
||||
href: input.buildDealHref(deal.id),
|
||||
statusLabelKey: `admin.sales.deals.status.${deal.status}`,
|
||||
})),
|
||||
tasks: buildAdminSalesTaskRows({
|
||||
now: input.now,
|
||||
locale: input.locale,
|
||||
tasks: input.contact.tasks,
|
||||
buildContactHref: input.buildContactHref,
|
||||
buildDealHref: input.buildDealHref,
|
||||
canWrite: input.canWrite,
|
||||
}),
|
||||
activities: input.contact.activities.map((activity) => ({
|
||||
id: activity.id,
|
||||
typeLabelKey: `admin.sales.activities.${activity.type}`,
|
||||
summary: activity.summary,
|
||||
occurredAtLabel: formatDateTime(
|
||||
activity.occurredAt,
|
||||
input.locale,
|
||||
timeZone
|
||||
),
|
||||
dealHref: activity.dealId
|
||||
? input.buildDealHref(activity.dealId)
|
||||
: null,
|
||||
recordingHref: activity.recordingId
|
||||
? input.buildRecordingHref(activity.recordingId)
|
||||
: null,
|
||||
})),
|
||||
canWrite: input.canWrite,
|
||||
};
|
||||
}
|
||||
|
||||
function formatDateTime(
|
||||
value: Date,
|
||||
locale: string,
|
||||
timeZone: string
|
||||
): string {
|
||||
return new Intl.DateTimeFormat(locale, {
|
||||
dateStyle: "medium",
|
||||
timeStyle: "short",
|
||||
timeZone,
|
||||
}).format(value);
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildAdminTelephonySettingsVM } from "./telephony-settings.vm.js";
|
||||
|
||||
describe("admin telephony settings view model", () => {
|
||||
it("sorts connections and exposes only serializable webhook readiness", () => {
|
||||
const vm = buildAdminTelephonySettingsVM({
|
||||
providerConfigured: true,
|
||||
connections: [
|
||||
{
|
||||
id: "phone-2",
|
||||
connectionId: "connection-2",
|
||||
providerUserEmail: "z@example.test",
|
||||
defaultPhoneNumberId: null,
|
||||
webhookVerifiedAt: null,
|
||||
lastEventAt: null,
|
||||
connection: {
|
||||
label: "Zulu",
|
||||
status: "degraded",
|
||||
webhookRegistrationId: null,
|
||||
},
|
||||
phoneNumbers: [],
|
||||
},
|
||||
{
|
||||
id: "phone-1",
|
||||
connectionId: "connection-1",
|
||||
providerUserEmail: "a@example.test",
|
||||
defaultPhoneNumberId: "number-1",
|
||||
webhookVerifiedAt: new Date("2026-07-24T10:00:00.000Z"),
|
||||
lastEventAt: new Date("2026-07-24T11:00:00.000Z"),
|
||||
connection: {
|
||||
label: "Alpha",
|
||||
status: "active",
|
||||
webhookRegistrationId: "webhook-1",
|
||||
},
|
||||
phoneNumbers: [
|
||||
{
|
||||
id: "number-1",
|
||||
label: "Berlin",
|
||||
e164: "+493012345678",
|
||||
selected: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.connections.map((connection) => connection.id)).toEqual([
|
||||
"phone-1",
|
||||
"phone-2",
|
||||
]);
|
||||
expect(vm.connections[0]).toMatchObject({
|
||||
webhookReady: true,
|
||||
lastEventAt: "2026-07-24T11:00:00.000Z",
|
||||
});
|
||||
});
|
||||
});
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const adminTelephonySettingsVMSchema = z.object({
|
||||
providerConfigured: z.boolean(),
|
||||
connections: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
connectionId: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
status: z.enum(["pending", "active", "degraded", "revoked"]),
|
||||
providerUserEmail: z.string().email().nullable(),
|
||||
defaultPhoneNumberId: z.string().nullable(),
|
||||
phoneNumbers: z.array(
|
||||
z.object({
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
e164: z.string().min(2),
|
||||
selected: z.boolean(),
|
||||
})
|
||||
),
|
||||
webhookReady: z.boolean(),
|
||||
lastEventAt: z.string().datetime().nullable(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
export type AdminTelephonySettingsVM = z.infer<
|
||||
typeof adminTelephonySettingsVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminTelephonySettingsVM(input: {
|
||||
readonly providerConfigured: boolean;
|
||||
readonly connections: readonly {
|
||||
readonly id: string;
|
||||
readonly connectionId: string;
|
||||
readonly providerUserEmail: string | null;
|
||||
readonly defaultPhoneNumberId: string | null;
|
||||
readonly webhookVerifiedAt: Date | null;
|
||||
readonly lastEventAt: Date | null;
|
||||
readonly connection: {
|
||||
readonly label: string;
|
||||
readonly status: "pending" | "active" | "degraded" | "revoked";
|
||||
readonly webhookRegistrationId: string | null;
|
||||
};
|
||||
readonly phoneNumbers: readonly {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly e164: string;
|
||||
readonly selected: boolean;
|
||||
}[];
|
||||
}[];
|
||||
}): AdminTelephonySettingsVM {
|
||||
return adminTelephonySettingsVMSchema.parse({
|
||||
providerConfigured: input.providerConfigured,
|
||||
connections: [...input.connections]
|
||||
.sort((left, right) =>
|
||||
left.connection.label.localeCompare(right.connection.label)
|
||||
)
|
||||
.map((row) => ({
|
||||
id: row.id,
|
||||
connectionId: row.connectionId,
|
||||
label: row.connection.label,
|
||||
status: row.connection.status,
|
||||
providerUserEmail: row.providerUserEmail,
|
||||
defaultPhoneNumberId: row.defaultPhoneNumberId,
|
||||
phoneNumbers: [...row.phoneNumbers],
|
||||
webhookReady: Boolean(
|
||||
row.webhookVerifiedAt &&
|
||||
row.connection.webhookRegistrationId
|
||||
),
|
||||
lastEventAt: row.lastEventAt?.toISOString() ?? null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
adminTelephonyActionSchema,
|
||||
buildAdminTelephonyWorkspaceVM,
|
||||
} from "./telephony.vm.js";
|
||||
|
||||
const call = {
|
||||
id: "call-1",
|
||||
direction: "inbound" as const,
|
||||
status: "completed" as const,
|
||||
matchStatus: "ambiguous" as const,
|
||||
externalNumber: "+4930123456",
|
||||
startedAt: new Date("2026-07-24T08:00:00.000Z"),
|
||||
durationSeconds: 180,
|
||||
note: null,
|
||||
dispositionCodeSnapshot: null,
|
||||
callbackTaskId: null,
|
||||
recordingConsentConfirmedAt: null,
|
||||
contactId: null,
|
||||
leadId: null,
|
||||
dealId: null,
|
||||
contact: null,
|
||||
lead: null,
|
||||
deal: null,
|
||||
recording: {
|
||||
status: "clean" as const,
|
||||
retainedUntil: new Date("2026-10-22T08:00:00.000Z"),
|
||||
},
|
||||
matchCandidates: [
|
||||
{
|
||||
id: "candidate-1",
|
||||
contactId: "contact-1",
|
||||
leadId: null,
|
||||
confidenceBasisPoints: 9_000,
|
||||
matchReason: "suffix",
|
||||
contact: {
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
deals: [{ dealId: "deal-1" }],
|
||||
},
|
||||
lead: null,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("admin telephony workspace view model", () => {
|
||||
it("builds assignment, recording, outbound-lock and dialer state", () => {
|
||||
const vm = buildAdminTelephonyWorkspaceVM({
|
||||
calls: [call],
|
||||
selectedCallId: call.id,
|
||||
dispositions: [{ code: "reached" }],
|
||||
contacts: [
|
||||
{
|
||||
id: "contact-1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
normalizedPhone: "+4930123456",
|
||||
doNotCall: false,
|
||||
deals: [{ dealId: "deal-1" }],
|
||||
},
|
||||
],
|
||||
policy: {
|
||||
outboundEnabled: false,
|
||||
dailyCallLimit: null,
|
||||
workDayStartMinutes: null,
|
||||
workDayEndMinutes: null,
|
||||
workDays: [],
|
||||
timeZone: null,
|
||||
recordingEnabled: false,
|
||||
recordingRetentionDays: 90,
|
||||
recordingConsentText: null,
|
||||
recordingConsentVersion: null,
|
||||
},
|
||||
dialerLists: [
|
||||
{
|
||||
id: "dialer-1",
|
||||
name: "Demo Follow-up",
|
||||
status: "active",
|
||||
entries: [
|
||||
{
|
||||
id: "entry-1",
|
||||
status: "active",
|
||||
callSessionId: null,
|
||||
contact: {
|
||||
id: "contact-1",
|
||||
firstName: "Ada",
|
||||
lastName: "Lovelace",
|
||||
normalizedPhone: "+4930123456",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
permissions: {
|
||||
canCall: true,
|
||||
canManageSettings: true,
|
||||
canManageRecording: true,
|
||||
},
|
||||
});
|
||||
|
||||
expect(vm.summary).toEqual({
|
||||
calls: 1,
|
||||
inbound: 1,
|
||||
outbound: 0,
|
||||
assignmentQueue: 1,
|
||||
});
|
||||
expect(vm.selectedCall?.candidates[0]).toMatchObject({
|
||||
label: "Ada Lovelace",
|
||||
dealId: "deal-1",
|
||||
});
|
||||
expect(vm.policy).toMatchObject({
|
||||
outboundEnabled: false,
|
||||
complete: false,
|
||||
recordingRetentionDays: 90,
|
||||
});
|
||||
expect(vm.dialerLists[0]?.activeEntry?.contactLabel).toBe(
|
||||
"Ada Lovelace"
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects a silently created unknown caller lead action", () => {
|
||||
expect(
|
||||
adminTelephonyActionSchema.safeParse({
|
||||
intent: "create-lead",
|
||||
phone: "+4930123456",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+464
@@ -0,0 +1,464 @@
|
||||
import { z } from "zod";
|
||||
|
||||
const identifierSchema = z.string().trim().min(1).max(191);
|
||||
const nullableIdentifierSchema = identifierSchema.nullable();
|
||||
|
||||
export const adminTelephonyActionSchema = z.discriminatedUnion("intent", [
|
||||
z.object({
|
||||
intent: z.literal("save-outcome"),
|
||||
callSessionId: identifierSchema,
|
||||
dispositionCode: identifierSchema,
|
||||
note: z.string().trim().max(2_000).nullable(),
|
||||
callbackTitle: z.string().trim().max(160).nullable(),
|
||||
callbackDueAt: z.string().datetime({ offset: true }).nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("confirm-match"),
|
||||
callSessionId: identifierSchema,
|
||||
contactId: nullableIdentifierSchema,
|
||||
leadId: nullableIdentifierSchema,
|
||||
dealId: nullableIdentifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("queue-call"),
|
||||
contactId: identifierSchema,
|
||||
dealId: nullableIdentifierSchema,
|
||||
dialerEntryId: nullableIdentifierSchema,
|
||||
idempotencyKey: identifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("create-dialer"),
|
||||
name: z.string().trim().min(1).max(160),
|
||||
contactIds: z.array(identifierSchema).min(1).max(1_000),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("next-dialer"),
|
||||
dialerListId: identifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("finish-dialer"),
|
||||
dialerEntryId: identifierSchema,
|
||||
outcome: z.enum(["completed", "skipped"]),
|
||||
callSessionId: nullableIdentifierSchema,
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("update-policy"),
|
||||
outboundEnabled: z.boolean(),
|
||||
dailyCallLimit: z.number().int().min(1).max(10_000).nullable(),
|
||||
workDayStartMinutes: z.number().int().min(0).max(1_439).nullable(),
|
||||
workDayEndMinutes: z.number().int().min(1).max(1_440).nullable(),
|
||||
workDays: z.array(z.number().int().min(0).max(6)).max(7),
|
||||
timeZone: z.string().trim().min(1).max(100).nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("update-recording-policy"),
|
||||
enabled: z.boolean(),
|
||||
accepted: z.boolean(),
|
||||
consentText: z.string().trim().max(2_000).nullable(),
|
||||
consentVersion: z.string().trim().max(120).nullable(),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
z.object({
|
||||
intent: z.literal("confirm-recording-consent"),
|
||||
callSessionId: identifierSchema,
|
||||
confirmed: z.literal(true),
|
||||
reason: z.string().trim().min(5).max(2_000),
|
||||
}),
|
||||
]);
|
||||
|
||||
export type AdminTelephonyAction = z.infer<
|
||||
typeof adminTelephonyActionSchema
|
||||
>;
|
||||
|
||||
const callStatusSchema = z.enum([
|
||||
"ringing",
|
||||
"answered",
|
||||
"completed",
|
||||
"missed",
|
||||
"failed",
|
||||
]);
|
||||
const matchStatusSchema = z.enum([
|
||||
"unmatched",
|
||||
"unique",
|
||||
"ambiguous",
|
||||
"confirmed",
|
||||
]);
|
||||
|
||||
export const adminTelephonyWorkspaceVMSchema = z.object({
|
||||
status: z.enum(["ready", "empty"]),
|
||||
summary: z.object({
|
||||
calls: z.number().int().min(0),
|
||||
inbound: z.number().int().min(0),
|
||||
outbound: z.number().int().min(0),
|
||||
assignmentQueue: z.number().int().min(0),
|
||||
}),
|
||||
calls: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
direction: z.enum(["inbound", "outbound"]),
|
||||
status: callStatusSchema,
|
||||
matchStatus: matchStatusSchema,
|
||||
externalNumber: z.string(),
|
||||
startedAt: z.string().datetime(),
|
||||
durationSeconds: z.number().int().min(0).nullable(),
|
||||
contactLabel: z.string().nullable(),
|
||||
leadLabel: z.string().nullable(),
|
||||
dealLabel: z.string().nullable(),
|
||||
dispositionCode: z.string().nullable(),
|
||||
recordingStatus: z
|
||||
.enum(["pending", "processing", "clean", "rejected", "expired", "deleted"])
|
||||
.nullable(),
|
||||
})
|
||||
),
|
||||
selectedCall: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
direction: z.enum(["inbound", "outbound"]),
|
||||
status: callStatusSchema,
|
||||
matchStatus: matchStatusSchema,
|
||||
externalNumber: z.string(),
|
||||
startedAt: z.string().datetime(),
|
||||
durationSeconds: z.number().int().min(0).nullable(),
|
||||
note: z.string().nullable(),
|
||||
dispositionCode: z.string().nullable(),
|
||||
callbackTaskId: z.string().nullable(),
|
||||
contactId: z.string().nullable(),
|
||||
leadId: z.string().nullable(),
|
||||
dealId: z.string().nullable(),
|
||||
recordingStatus: z
|
||||
.enum(["pending", "processing", "clean", "rejected", "expired", "deleted"])
|
||||
.nullable(),
|
||||
recordingRetainedUntil: z.string().datetime().nullable(),
|
||||
recordingConsentConfirmedAt: z.string().datetime().nullable(),
|
||||
candidates: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
contactId: z.string().nullable(),
|
||||
leadId: z.string().nullable(),
|
||||
label: z.string(),
|
||||
dealId: z.string().nullable(),
|
||||
confidencePercent: z.number().int().min(0).max(100),
|
||||
reason: z.string(),
|
||||
})
|
||||
),
|
||||
})
|
||||
.nullable(),
|
||||
dispositions: z.array(
|
||||
z.object({
|
||||
code: z.string(),
|
||||
labelKey: z.string(),
|
||||
})
|
||||
),
|
||||
contacts: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
label: z.string(),
|
||||
phone: z.string(),
|
||||
dealId: z.string().nullable(),
|
||||
doNotCall: z.boolean(),
|
||||
})
|
||||
),
|
||||
policy: z
|
||||
.object({
|
||||
outboundEnabled: z.boolean(),
|
||||
complete: z.boolean(),
|
||||
dailyCallLimit: z.number().int().positive().nullable(),
|
||||
workDayStartMinutes: z.number().int().nullable(),
|
||||
workDayEndMinutes: z.number().int().nullable(),
|
||||
workDays: z.array(z.number().int()),
|
||||
timeZone: z.string().nullable(),
|
||||
recordingEnabled: z.boolean(),
|
||||
recordingRetentionDays: z.number().int().positive(),
|
||||
recordingConsentText: z.string().nullable(),
|
||||
recordingConsentVersion: z.string().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
dialerLists: z.array(
|
||||
z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
status: z.enum(["draft", "active", "paused", "completed"]),
|
||||
total: z.number().int().min(0),
|
||||
pending: z.number().int().min(0),
|
||||
completed: z.number().int().min(0),
|
||||
blocked: z.number().int().min(0),
|
||||
activeEntry: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
contactId: z.string(),
|
||||
contactLabel: z.string(),
|
||||
phone: z.string().nullable(),
|
||||
callSessionId: z.string().nullable(),
|
||||
})
|
||||
.nullable(),
|
||||
})
|
||||
),
|
||||
permissions: z.object({
|
||||
canCall: z.boolean(),
|
||||
canManageSettings: z.boolean(),
|
||||
canManageRecording: z.boolean(),
|
||||
}),
|
||||
});
|
||||
|
||||
export type AdminTelephonyWorkspaceVM = z.infer<
|
||||
typeof adminTelephonyWorkspaceVMSchema
|
||||
>;
|
||||
|
||||
export function buildAdminTelephonyWorkspaceVM(input: {
|
||||
readonly calls: readonly {
|
||||
readonly id: string;
|
||||
readonly direction: "inbound" | "outbound";
|
||||
readonly status: z.infer<typeof callStatusSchema>;
|
||||
readonly matchStatus: z.infer<typeof matchStatusSchema>;
|
||||
readonly externalNumber: string;
|
||||
readonly startedAt: Date;
|
||||
readonly durationSeconds: number | null;
|
||||
readonly note: string | null;
|
||||
readonly dispositionCodeSnapshot: string | null;
|
||||
readonly callbackTaskId: string | null;
|
||||
readonly recordingConsentConfirmedAt: Date | null;
|
||||
readonly contactId: string | null;
|
||||
readonly leadId: string | null;
|
||||
readonly dealId: string | null;
|
||||
readonly contact: {
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
} | null;
|
||||
readonly lead: {
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string | null;
|
||||
} | null;
|
||||
readonly deal: { readonly title: string } | null;
|
||||
readonly recording: {
|
||||
readonly status:
|
||||
| "pending"
|
||||
| "processing"
|
||||
| "clean"
|
||||
| "rejected"
|
||||
| "expired"
|
||||
| "deleted";
|
||||
readonly retainedUntil: Date;
|
||||
} | null;
|
||||
readonly matchCandidates: readonly {
|
||||
readonly id: string;
|
||||
readonly contactId: string | null;
|
||||
readonly leadId: string | null;
|
||||
readonly confidenceBasisPoints: number;
|
||||
readonly matchReason: string;
|
||||
readonly contact: {
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly deals: readonly { readonly dealId: string }[];
|
||||
} | null;
|
||||
readonly lead: {
|
||||
readonly firstName: string | null;
|
||||
readonly lastName: string | null;
|
||||
readonly email: string | null;
|
||||
} | null;
|
||||
}[];
|
||||
}[];
|
||||
readonly selectedCallId?: string | null;
|
||||
readonly dispositions: readonly { readonly code: string }[];
|
||||
readonly contacts: readonly {
|
||||
readonly id: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly normalizedPhone: string | null;
|
||||
readonly doNotCall: boolean;
|
||||
readonly deals: readonly { readonly dealId: string }[];
|
||||
}[];
|
||||
readonly policy: {
|
||||
readonly outboundEnabled: boolean;
|
||||
readonly dailyCallLimit: number | null;
|
||||
readonly workDayStartMinutes: number | null;
|
||||
readonly workDayEndMinutes: number | null;
|
||||
readonly workDays: readonly number[];
|
||||
readonly timeZone: string | null;
|
||||
readonly recordingEnabled: boolean;
|
||||
readonly recordingRetentionDays: number;
|
||||
readonly recordingConsentText: string | null;
|
||||
readonly recordingConsentVersion: string | null;
|
||||
} | null;
|
||||
readonly dialerLists: readonly {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly status: "draft" | "active" | "paused" | "completed";
|
||||
readonly entries: readonly {
|
||||
readonly id: string;
|
||||
readonly status: "pending" | "active" | "completed" | "skipped" | "blocked";
|
||||
readonly callSessionId: string | null;
|
||||
readonly contact: {
|
||||
readonly id: string;
|
||||
readonly firstName: string;
|
||||
readonly lastName: string;
|
||||
readonly normalizedPhone: string | null;
|
||||
};
|
||||
}[];
|
||||
}[];
|
||||
readonly permissions: {
|
||||
readonly canCall: boolean;
|
||||
readonly canManageSettings: boolean;
|
||||
readonly canManageRecording: boolean;
|
||||
};
|
||||
}): AdminTelephonyWorkspaceVM {
|
||||
const rows = input.calls.map((call) => ({
|
||||
id: call.id,
|
||||
direction: call.direction,
|
||||
status: call.status,
|
||||
matchStatus: call.matchStatus,
|
||||
externalNumber: call.externalNumber,
|
||||
startedAt: call.startedAt.toISOString(),
|
||||
durationSeconds: call.durationSeconds,
|
||||
contactLabel: call.contact
|
||||
? fullName(call.contact.firstName, call.contact.lastName)
|
||||
: null,
|
||||
leadLabel: call.lead
|
||||
? fullName(call.lead.firstName, call.lead.lastName) ||
|
||||
call.lead.email ||
|
||||
call.id
|
||||
: null,
|
||||
dealLabel: call.deal?.title ?? null,
|
||||
dispositionCode: call.dispositionCodeSnapshot,
|
||||
recordingStatus: call.recording?.status ?? null,
|
||||
}));
|
||||
const selectedSource =
|
||||
input.calls.find((call) => call.id === input.selectedCallId) ??
|
||||
input.calls[0] ??
|
||||
null;
|
||||
|
||||
return adminTelephonyWorkspaceVMSchema.parse({
|
||||
status: rows.length === 0 ? "empty" : "ready",
|
||||
summary: {
|
||||
calls: rows.length,
|
||||
inbound: rows.filter((call) => call.direction === "inbound").length,
|
||||
outbound: rows.filter((call) => call.direction === "outbound").length,
|
||||
assignmentQueue: rows.filter(
|
||||
(call) =>
|
||||
call.matchStatus === "unmatched" ||
|
||||
call.matchStatus === "ambiguous"
|
||||
).length,
|
||||
},
|
||||
calls: rows,
|
||||
selectedCall: selectedSource
|
||||
? {
|
||||
id: selectedSource.id,
|
||||
direction: selectedSource.direction,
|
||||
status: selectedSource.status,
|
||||
matchStatus: selectedSource.matchStatus,
|
||||
externalNumber: selectedSource.externalNumber,
|
||||
startedAt: selectedSource.startedAt.toISOString(),
|
||||
durationSeconds: selectedSource.durationSeconds,
|
||||
note: selectedSource.note,
|
||||
dispositionCode: selectedSource.dispositionCodeSnapshot,
|
||||
callbackTaskId: selectedSource.callbackTaskId,
|
||||
contactId: selectedSource.contactId,
|
||||
leadId: selectedSource.leadId,
|
||||
dealId: selectedSource.dealId,
|
||||
recordingStatus: selectedSource.recording?.status ?? null,
|
||||
recordingRetainedUntil:
|
||||
selectedSource.recording?.retainedUntil.toISOString() ?? null,
|
||||
recordingConsentConfirmedAt:
|
||||
selectedSource.recordingConsentConfirmedAt?.toISOString() ??
|
||||
null,
|
||||
candidates: selectedSource.matchCandidates.map((candidate) => ({
|
||||
id: candidate.id,
|
||||
contactId: candidate.contactId,
|
||||
leadId: candidate.leadId,
|
||||
label: candidate.contact
|
||||
? fullName(
|
||||
candidate.contact.firstName,
|
||||
candidate.contact.lastName
|
||||
)
|
||||
: candidate.lead
|
||||
? fullName(
|
||||
candidate.lead.firstName,
|
||||
candidate.lead.lastName
|
||||
) ||
|
||||
candidate.lead.email ||
|
||||
candidate.id
|
||||
: candidate.id,
|
||||
dealId: candidate.contact?.deals[0]?.dealId ?? null,
|
||||
confidencePercent: Math.round(
|
||||
candidate.confidenceBasisPoints / 100
|
||||
),
|
||||
reason: candidate.matchReason,
|
||||
})),
|
||||
}
|
||||
: null,
|
||||
dispositions: input.dispositions.map((item) => ({
|
||||
code: item.code,
|
||||
labelKey: `admin.sales.telephony.dispositions.${item.code}`,
|
||||
})),
|
||||
contacts: input.contacts
|
||||
.filter(
|
||||
(
|
||||
contact
|
||||
): contact is typeof contact & { readonly normalizedPhone: string } =>
|
||||
Boolean(contact.normalizedPhone)
|
||||
)
|
||||
.map((contact) => ({
|
||||
id: contact.id,
|
||||
label: fullName(contact.firstName, contact.lastName),
|
||||
phone: contact.normalizedPhone,
|
||||
dealId: contact.deals[0]?.dealId ?? null,
|
||||
doNotCall: contact.doNotCall,
|
||||
})),
|
||||
policy: input.policy
|
||||
? {
|
||||
...input.policy,
|
||||
workDays: [...input.policy.workDays],
|
||||
complete: Boolean(
|
||||
input.policy.dailyCallLimit &&
|
||||
input.policy.workDayStartMinutes !== null &&
|
||||
input.policy.workDayEndMinutes !== null &&
|
||||
input.policy.workDays.length > 0 &&
|
||||
input.policy.timeZone
|
||||
),
|
||||
}
|
||||
: null,
|
||||
dialerLists: input.dialerLists.map((list) => {
|
||||
const active = list.entries.find((entry) => entry.status === "active");
|
||||
return {
|
||||
id: list.id,
|
||||
name: list.name,
|
||||
status: list.status,
|
||||
total: list.entries.length,
|
||||
pending: list.entries.filter((entry) => entry.status === "pending")
|
||||
.length,
|
||||
completed: list.entries.filter(
|
||||
(entry) => entry.status === "completed"
|
||||
).length,
|
||||
blocked: list.entries.filter((entry) => entry.status === "blocked")
|
||||
.length,
|
||||
activeEntry: active
|
||||
? {
|
||||
id: active.id,
|
||||
contactId: active.contact.id,
|
||||
contactLabel: fullName(
|
||||
active.contact.firstName,
|
||||
active.contact.lastName
|
||||
),
|
||||
phone: active.contact.normalizedPhone,
|
||||
callSessionId: active.callSessionId,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}),
|
||||
permissions: input.permissions,
|
||||
});
|
||||
}
|
||||
|
||||
function fullName(
|
||||
firstName: string | null,
|
||||
lastName: string | null
|
||||
): string {
|
||||
return [firstName, lastName].filter(Boolean).join(" ").trim();
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildAdminDashboardVM } from "./admin-dashboard.vm.js";
|
||||
|
||||
describe("buildAdminDashboardVM", () => {
|
||||
it("deduplicates widgets from combined roles without changing their first position", () => {
|
||||
const vm = buildAdminDashboardVM({
|
||||
roles: ["sales", "sales_manager", "sales"],
|
||||
widgets: [
|
||||
{
|
||||
id: "sales_today",
|
||||
value: "3",
|
||||
href: "/sales/tasks/today",
|
||||
},
|
||||
{
|
||||
id: "sales_team_pipeline",
|
||||
value: "12",
|
||||
href: "/sales/deals",
|
||||
},
|
||||
{
|
||||
id: "sales_today",
|
||||
value: "3",
|
||||
href: "/sales/tasks/today",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.roles).toEqual(["sales", "sales_manager"]);
|
||||
expect(vm.widgets.map((widget) => widget.id)).toEqual([
|
||||
"sales_today",
|
||||
"sales_team_pipeline",
|
||||
]);
|
||||
expect(vm.widgets[0]).toMatchObject({
|
||||
group: "sales",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesToday.title",
|
||||
tone: "neutral",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves server-derived tones and values", () => {
|
||||
const vm = buildAdminDashboardVM({
|
||||
roles: ["engineering"],
|
||||
widgets: [
|
||||
{
|
||||
id: "engineering_errors",
|
||||
value: "4",
|
||||
href: "/events",
|
||||
tone: "critical",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.widgets[0]).toMatchObject({
|
||||
value: "4",
|
||||
href: "/events",
|
||||
tone: "critical",
|
||||
});
|
||||
});
|
||||
});
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const ADMIN_DASHBOARD_WIDGET_IDS = [
|
||||
"sales_own_pipeline",
|
||||
"sales_today",
|
||||
"sales_appointments",
|
||||
"sales_followups",
|
||||
"sales_team_pipeline",
|
||||
"sales_unassigned_leads",
|
||||
"sales_team_activity",
|
||||
"support_inbox",
|
||||
"support_customer_events",
|
||||
"engineering_health",
|
||||
"engineering_queues",
|
||||
"engineering_errors",
|
||||
"engineering_deploy",
|
||||
"executive_forecast",
|
||||
"executive_revenue",
|
||||
"executive_mrr",
|
||||
"executive_arr",
|
||||
"executive_churn",
|
||||
"viewer_reports",
|
||||
"super_platform",
|
||||
] as const;
|
||||
|
||||
export type AdminDashboardWidgetId =
|
||||
(typeof ADMIN_DASHBOARD_WIDGET_IDS)[number];
|
||||
|
||||
export const adminDashboardWidgetVMSchema = z.object({
|
||||
id: z.enum(ADMIN_DASHBOARD_WIDGET_IDS),
|
||||
group: z.enum([
|
||||
"sales",
|
||||
"sales_team",
|
||||
"support",
|
||||
"engineering",
|
||||
"business",
|
||||
"reports",
|
||||
"platform",
|
||||
]),
|
||||
titleKey: z.string().min(1),
|
||||
descriptionKey: z.string().min(1),
|
||||
value: z.string().min(1),
|
||||
href: z.string().min(1),
|
||||
tone: z.enum(["neutral", "positive", "warning", "critical"]),
|
||||
});
|
||||
|
||||
export const adminDashboardVMSchema = z.object({
|
||||
roles: z.array(z.string().min(1)),
|
||||
widgets: z.array(adminDashboardWidgetVMSchema),
|
||||
});
|
||||
|
||||
export type AdminDashboardWidgetVM = z.infer<
|
||||
typeof adminDashboardWidgetVMSchema
|
||||
>;
|
||||
export type AdminDashboardVM = z.infer<typeof adminDashboardVMSchema>;
|
||||
|
||||
export type AdminDashboardWidgetInput = {
|
||||
readonly id: AdminDashboardWidgetId;
|
||||
readonly value: string;
|
||||
readonly href: string;
|
||||
readonly tone?: AdminDashboardWidgetVM["tone"];
|
||||
};
|
||||
|
||||
const WIDGET_PRESENTATION = {
|
||||
sales_own_pipeline: {
|
||||
group: "sales",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesOwnPipeline.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesOwnPipeline.description",
|
||||
},
|
||||
sales_today: {
|
||||
group: "sales",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesToday.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesToday.description",
|
||||
},
|
||||
sales_appointments: {
|
||||
group: "sales",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesAppointments.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesAppointments.description",
|
||||
},
|
||||
sales_followups: {
|
||||
group: "sales",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesFollowups.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesFollowups.description",
|
||||
},
|
||||
sales_team_pipeline: {
|
||||
group: "sales_team",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesTeamPipeline.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesTeamPipeline.description",
|
||||
},
|
||||
sales_unassigned_leads: {
|
||||
group: "sales_team",
|
||||
titleKey:
|
||||
"admin.dashboard.personalized.widgets.salesUnassignedLeads.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesUnassignedLeads.description",
|
||||
},
|
||||
sales_team_activity: {
|
||||
group: "sales_team",
|
||||
titleKey: "admin.dashboard.personalized.widgets.salesTeamActivity.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.salesTeamActivity.description",
|
||||
},
|
||||
support_inbox: {
|
||||
group: "support",
|
||||
titleKey: "admin.dashboard.personalized.widgets.supportInbox.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.supportInbox.description",
|
||||
},
|
||||
support_customer_events: {
|
||||
group: "support",
|
||||
titleKey: "admin.dashboard.personalized.widgets.supportCustomerEvents.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.supportCustomerEvents.description",
|
||||
},
|
||||
engineering_health: {
|
||||
group: "engineering",
|
||||
titleKey: "admin.dashboard.personalized.widgets.engineeringHealth.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.engineeringHealth.description",
|
||||
},
|
||||
engineering_queues: {
|
||||
group: "engineering",
|
||||
titleKey: "admin.dashboard.personalized.widgets.engineeringQueues.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.engineeringQueues.description",
|
||||
},
|
||||
engineering_errors: {
|
||||
group: "engineering",
|
||||
titleKey: "admin.dashboard.personalized.widgets.engineeringErrors.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.engineeringErrors.description",
|
||||
},
|
||||
engineering_deploy: {
|
||||
group: "engineering",
|
||||
titleKey: "admin.dashboard.personalized.widgets.engineeringDeploy.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.engineeringDeploy.description",
|
||||
},
|
||||
executive_forecast: {
|
||||
group: "business",
|
||||
titleKey: "admin.dashboard.personalized.widgets.executiveForecast.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.executiveForecast.description",
|
||||
},
|
||||
executive_revenue: {
|
||||
group: "business",
|
||||
titleKey: "admin.dashboard.personalized.widgets.executiveRevenue.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.executiveRevenue.description",
|
||||
},
|
||||
executive_mrr: {
|
||||
group: "business",
|
||||
titleKey: "admin.dashboard.personalized.widgets.executiveMrr.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.executiveMrr.description",
|
||||
},
|
||||
executive_arr: {
|
||||
group: "business",
|
||||
titleKey: "admin.dashboard.personalized.widgets.executiveArr.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.executiveArr.description",
|
||||
},
|
||||
executive_churn: {
|
||||
group: "business",
|
||||
titleKey: "admin.dashboard.personalized.widgets.executiveChurn.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.executiveChurn.description",
|
||||
},
|
||||
viewer_reports: {
|
||||
group: "reports",
|
||||
titleKey: "admin.dashboard.personalized.widgets.viewerReports.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.viewerReports.description",
|
||||
},
|
||||
super_platform: {
|
||||
group: "platform",
|
||||
titleKey: "admin.dashboard.personalized.widgets.superPlatform.title",
|
||||
descriptionKey:
|
||||
"admin.dashboard.personalized.widgets.superPlatform.description",
|
||||
},
|
||||
} as const satisfies Record<
|
||||
AdminDashboardWidgetId,
|
||||
Pick<AdminDashboardWidgetVM, "group" | "titleKey" | "descriptionKey">
|
||||
>;
|
||||
|
||||
export function buildAdminDashboardVM(input: {
|
||||
readonly roles: readonly string[];
|
||||
readonly widgets: readonly AdminDashboardWidgetInput[];
|
||||
}): AdminDashboardVM {
|
||||
const seen = new Set<AdminDashboardWidgetId>();
|
||||
const widgets = input.widgets.flatMap((widget) => {
|
||||
if (seen.has(widget.id)) return [];
|
||||
seen.add(widget.id);
|
||||
return [
|
||||
{
|
||||
...WIDGET_PRESENTATION[widget.id],
|
||||
...widget,
|
||||
tone: widget.tone ?? "neutral",
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
return adminDashboardVMSchema.parse({
|
||||
roles: [...new Set(input.roles)].sort(),
|
||||
widgets,
|
||||
});
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildApiAdminVM } from "./api-admin.vm.js";
|
||||
|
||||
describe("buildApiAdminVM", () => {
|
||||
it("marks inbound attention when pending registrations or new leads exist", () => {
|
||||
const vm = buildApiAdminVM({
|
||||
metrics: [{ id: "keys", value: 3, labelKey: "admin.apiAdmin.metrics.keys.label", detailKey: "admin.apiAdmin.metrics.keys.detail", tone: "success" }],
|
||||
consumers: [],
|
||||
inbound: {
|
||||
registrationsPending: 1,
|
||||
leadsNew: 2,
|
||||
leadsQualified: 0,
|
||||
recentRegistrations: [],
|
||||
recentLeads: [],
|
||||
},
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.hasInboundAttention).toBe(true);
|
||||
});
|
||||
|
||||
it("returns empty without operational data", () => {
|
||||
expect(
|
||||
buildApiAdminVM({
|
||||
metrics: [],
|
||||
consumers: [],
|
||||
inbound: { registrationsPending: 0, leadsNew: 0, leadsQualified: 0, recentRegistrations: [], recentLeads: [] },
|
||||
}).status
|
||||
).toBe("empty");
|
||||
});
|
||||
});
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type ApiAdminMetricInput = {
|
||||
readonly id: string;
|
||||
readonly value: number;
|
||||
readonly labelKey: string;
|
||||
readonly detailKey: string;
|
||||
readonly tone: "success" | "warning" | "danger" | "neutral";
|
||||
};
|
||||
|
||||
export type ApiAdminConsumerInput = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly keyCount: number;
|
||||
readonly activeKeyCount: number;
|
||||
readonly lastKeyCreatedAt: string | null;
|
||||
};
|
||||
|
||||
export type ApiAdminInboundInput = {
|
||||
readonly registrationsPending: number;
|
||||
readonly leadsNew: number;
|
||||
readonly leadsQualified: number;
|
||||
readonly recentRegistrations: readonly {
|
||||
readonly id: string;
|
||||
readonly email: string;
|
||||
readonly company: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly createdTenantId: string | null;
|
||||
}[];
|
||||
readonly recentLeads: readonly {
|
||||
readonly id: string;
|
||||
readonly email: string | null;
|
||||
readonly company: string | null;
|
||||
readonly source: string | null;
|
||||
readonly status: string;
|
||||
readonly createdAt: string;
|
||||
}[];
|
||||
};
|
||||
|
||||
export type ApiAdminInput = {
|
||||
readonly metrics: readonly ApiAdminMetricInput[];
|
||||
readonly consumers: readonly ApiAdminConsumerInput[];
|
||||
readonly inbound: ApiAdminInboundInput;
|
||||
};
|
||||
|
||||
export type ApiAdminData = ApiAdminInput & {
|
||||
readonly hasInboundAttention: boolean;
|
||||
};
|
||||
|
||||
export type ApiAdminVM = VMState<ApiAdminData>;
|
||||
|
||||
export function buildApiAdminVM(input: ApiAdminInput): ApiAdminVM {
|
||||
if (input.metrics.length === 0 && input.consumers.length === 0 && input.inbound.recentRegistrations.length === 0 && input.inbound.recentLeads.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...input,
|
||||
hasInboundAttention: input.inbound.registrationsPending > 0 || input.inbound.leadsNew > 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
+37
-5
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { billingReadOnlyReasonKey, buildAdminBillingVM, normalizeAdminBillingStatus, type AdminBillingInputRow } from "./billing-admin.vm.js";
|
||||
import { billingReadOnlyReasonKey, buildAdminBillingVM, normalizeAdminBillingStatus, resolveAdminBillingPlanKind, type AdminBillingInputRow } from "./billing-admin.vm.js";
|
||||
|
||||
function row(overrides: Partial<AdminBillingInputRow> = {}): AdminBillingInputRow {
|
||||
return {
|
||||
@@ -42,6 +42,15 @@ describe("billingReadOnlyReasonKey", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAdminBillingPlanKind", () => {
|
||||
it("classifies standard, enterprise, custom, and unassigned plans", () => {
|
||||
expect(resolveAdminBillingPlanKind("business")).toBe("standard");
|
||||
expect(resolveAdminBillingPlanKind("enterprise-2026")).toBe("enterprise");
|
||||
expect(resolveAdminBillingPlanKind("custom-haris")).toBe("custom");
|
||||
expect(resolveAdminBillingPlanKind(null)).toBe("unassigned");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAdminBillingVM", () => {
|
||||
it("returns empty for no tenants", () => {
|
||||
expect(buildAdminBillingVM({ rows: [] })).toEqual({ status: "empty" });
|
||||
@@ -55,9 +64,32 @@ describe("buildAdminBillingVM", () => {
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.totalCount).toBe(2);
|
||||
expect(vm.data?.readOnlyCount).toBe(1);
|
||||
expect(vm.data?.rows[0]?.statusLabelKey).toBe("admin.billing.status.active");
|
||||
expect(vm.data?.rows[0]?.hasLagoReference).toBe(true);
|
||||
expect(vm.data?.rows[1]?.hasMollieReference).toBe(false);
|
||||
expect(vm.data?.rows[1]?.recoveryHintKey).toBe("admin.billing.recoveryHints.pastDue");
|
||||
expect(vm.data?.summary).toMatchObject({
|
||||
totalCount: 2,
|
||||
attentionCount: 1,
|
||||
readOnlyCount: 1,
|
||||
enterpriseCount: 0,
|
||||
customCount: 0,
|
||||
pastDueCount: 1,
|
||||
frozenCount: 0,
|
||||
missingProviderCount: 1,
|
||||
totalSeats: 6,
|
||||
});
|
||||
expect(vm.data?.rows[0]?.tenantId).toBe("tenant_2");
|
||||
expect(vm.data?.rows[0]?.hasMollieReference).toBe(false);
|
||||
expect(vm.data?.rows[0]?.recoveryHintKey).toBe("admin.billing.recoveryHints.pastDue");
|
||||
expect(vm.data?.rows[1]?.statusLabelKey).toBe("admin.billing.status.active");
|
||||
expect(vm.data?.rows[1]?.hasLagoReference).toBe(true);
|
||||
});
|
||||
|
||||
it("surfaces enterprise and custom plan counts", () => {
|
||||
const vm = buildAdminBillingVM({
|
||||
rows: [row({ tenantId: "tenant_1", planCode: "enterprise-2026" }), row({ tenantId: "tenant_2", planCode: "custom-vip" })],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.summary.enterpriseCount).toBe(1);
|
||||
expect(vm.data?.summary.customCount).toBe(1);
|
||||
expect(vm.data?.rows.map((item) => item.planKind).sort()).toEqual(["custom", "enterprise"]);
|
||||
});
|
||||
});
|
||||
+57
-3
@@ -1,6 +1,7 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type AdminBillingStatus = "trial" | "active" | "past_due" | "cancelled" | "frozen";
|
||||
export type AdminBillingPlanKind = "standard" | "enterprise" | "custom" | "unassigned";
|
||||
|
||||
export type AdminBillingInputRow = {
|
||||
readonly tenantId: string;
|
||||
@@ -24,6 +25,8 @@ export type AdminBillingInputRow = {
|
||||
|
||||
export type AdminBillingRow = AdminBillingInputRow & {
|
||||
readonly status: AdminBillingStatus;
|
||||
readonly planKind: AdminBillingPlanKind;
|
||||
readonly planKindLabelKey: string;
|
||||
readonly statusLabelKey: string;
|
||||
readonly readOnlyReasonKey: string;
|
||||
readonly recoveryHintKey: string;
|
||||
@@ -32,8 +35,22 @@ export type AdminBillingRow = AdminBillingInputRow & {
|
||||
readonly hasMollieReference: boolean;
|
||||
};
|
||||
|
||||
export type AdminBillingSummary = {
|
||||
readonly totalCount: number;
|
||||
readonly attentionCount: number;
|
||||
readonly readOnlyCount: number;
|
||||
readonly enterpriseCount: number;
|
||||
readonly customCount: number;
|
||||
readonly pastDueCount: number;
|
||||
readonly frozenCount: number;
|
||||
readonly cancelledCount: number;
|
||||
readonly missingProviderCount: number;
|
||||
readonly totalSeats: number;
|
||||
};
|
||||
|
||||
export type AdminBillingData = {
|
||||
readonly rows: readonly AdminBillingRow[];
|
||||
readonly summary: AdminBillingSummary;
|
||||
readonly totalCount: number;
|
||||
readonly readOnlyCount: number;
|
||||
readonly emptyHeadlineKey: string;
|
||||
@@ -65,6 +82,14 @@ export function billingRecoveryHintKey(status: AdminBillingStatus): string {
|
||||
return "admin.billing.recoveryHints.none";
|
||||
}
|
||||
|
||||
export function resolveAdminBillingPlanKind(planCode: string | null | undefined): AdminBillingPlanKind {
|
||||
const normalized = (planCode ?? "").trim().toLowerCase();
|
||||
if (!normalized) return "unassigned";
|
||||
if (normalized.startsWith("enterprise")) return "enterprise";
|
||||
if (normalized.startsWith("custom") || normalized.startsWith("sonder")) return "custom";
|
||||
return "standard";
|
||||
}
|
||||
|
||||
export function buildAdminBillingVM(input: { readonly rows: readonly AdminBillingInputRow[] }): AdminBillingVM {
|
||||
if (input.rows.length === 0) {
|
||||
return { status: "empty" };
|
||||
@@ -72,9 +97,12 @@ export function buildAdminBillingVM(input: { readonly rows: readonly AdminBillin
|
||||
|
||||
const rows = input.rows.map((row): AdminBillingRow => {
|
||||
const status = normalizeAdminBillingStatus(row.status);
|
||||
const planKind = resolveAdminBillingPlanKind(row.planCode);
|
||||
return {
|
||||
...row,
|
||||
status,
|
||||
planKind,
|
||||
planKindLabelKey: `admin.billing.planKinds.${planKind}`,
|
||||
seatQuantity: row.seatQuantity && row.seatQuantity > 0 ? row.seatQuantity : 1,
|
||||
statusLabelKey: `admin.billing.status.${status}`,
|
||||
readOnlyReasonKey: billingReadOnlyReasonKey({ ...row, status }),
|
||||
@@ -85,14 +113,40 @@ export function buildAdminBillingVM(input: { readonly rows: readonly AdminBillin
|
||||
};
|
||||
});
|
||||
|
||||
const summary = {
|
||||
totalCount: rows.length,
|
||||
attentionCount: rows.filter((row) => row.readOnly || row.status === "past_due" || row.status === "frozen" || !row.hasLagoReference || !row.hasMollieReference).length,
|
||||
readOnlyCount: rows.filter((row) => row.readOnly).length,
|
||||
enterpriseCount: rows.filter((row) => row.planKind === "enterprise").length,
|
||||
customCount: rows.filter((row) => row.planKind === "custom").length,
|
||||
pastDueCount: rows.filter((row) => row.status === "past_due").length,
|
||||
frozenCount: rows.filter((row) => row.status === "frozen").length,
|
||||
cancelledCount: rows.filter((row) => row.status === "cancelled").length,
|
||||
missingProviderCount: rows.filter((row) => !row.hasLagoReference || !row.hasMollieReference).length,
|
||||
totalSeats: rows.reduce((sum, row) => sum + (row.seatQuantity ?? 0), 0),
|
||||
} satisfies AdminBillingSummary;
|
||||
|
||||
const sortedRows = [...rows].sort((a, b) => billingAttentionRank(b) - billingAttentionRank(a));
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows,
|
||||
totalCount: rows.length,
|
||||
readOnlyCount: rows.filter((row) => row.readOnly).length,
|
||||
rows: sortedRows,
|
||||
summary,
|
||||
totalCount: summary.totalCount,
|
||||
readOnlyCount: summary.readOnlyCount,
|
||||
emptyHeadlineKey: "admin.billing.empty.headline",
|
||||
emptyBodyKey: "admin.billing.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function billingAttentionRank(row: AdminBillingRow): number {
|
||||
let rank = 0;
|
||||
if (row.status === "frozen") rank += 50;
|
||||
if (row.status === "past_due") rank += 40;
|
||||
if (row.readOnly) rank += 30;
|
||||
if (!row.hasLagoReference || !row.hasMollieReference) rank += 20;
|
||||
if (row.status === "cancelled") rank += 10;
|
||||
return rank;
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildDeployAdminVM } from "./deploy-admin.vm.js";
|
||||
|
||||
describe("deploy admin view-model", () => {
|
||||
it("summarizes migration state and deploy signals", () => {
|
||||
const vm = buildDeployAdminVM({
|
||||
migrationDbReachable: true,
|
||||
metadata: {
|
||||
environment: "staging",
|
||||
nodeEnv: "production",
|
||||
release: "abc123",
|
||||
revision: "abc123",
|
||||
branch: "main",
|
||||
image: "hivegrid-web:abc123",
|
||||
buildTime: "2026-07-09T00:00:00.000Z",
|
||||
},
|
||||
migrations: [
|
||||
{ name: "20260701000000_init", state: "applied", appliedAt: "2026-07-09T00:00:00.000Z" },
|
||||
{ name: "20260702000000_next", state: "pending" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.migrationSummary).toMatchObject({ total: 2, applied: 1, pending: 1, failed: 0 });
|
||||
expect(vm.data.signals.find((signal) => signal.id === "migrations")).toMatchObject({ status: "warning", value: "1/2" });
|
||||
expect(vm.data.overallStatus).toBe("warning");
|
||||
});
|
||||
|
||||
it("surfaces failed migrations as critical", () => {
|
||||
const vm = buildDeployAdminVM({
|
||||
migrationDbReachable: true,
|
||||
metadata: {
|
||||
environment: "production",
|
||||
nodeEnv: "production",
|
||||
release: "abc123",
|
||||
revision: "abc123",
|
||||
branch: "main",
|
||||
image: "unknown",
|
||||
buildTime: "unknown",
|
||||
},
|
||||
migrations: [{ name: "20260701000000_failed", state: "failed" }],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.overallStatus).toBe("critical");
|
||||
});
|
||||
});
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type DeploySignalStatus = "ok" | "warning" | "critical" | "unknown";
|
||||
export type DeploySignalTone = "success" | "warning" | "danger" | "neutral";
|
||||
export type MigrationState = "applied" | "pending" | "failed" | "rolledBack" | "unknown";
|
||||
|
||||
export type DeployMetadata = {
|
||||
readonly environment: string;
|
||||
readonly nodeEnv: string;
|
||||
readonly release: string;
|
||||
readonly revision: string;
|
||||
readonly branch: string;
|
||||
readonly image: string;
|
||||
readonly buildTime: string;
|
||||
};
|
||||
|
||||
export type DeployMigrationInput = {
|
||||
readonly name: string;
|
||||
readonly state: MigrationState;
|
||||
readonly appliedAt?: string | null;
|
||||
};
|
||||
|
||||
export type DeploySnapshotInput = {
|
||||
readonly metadata: DeployMetadata;
|
||||
readonly migrations: readonly DeployMigrationInput[];
|
||||
readonly migrationDbReachable: boolean;
|
||||
};
|
||||
|
||||
export type DeploySignal = {
|
||||
readonly id: string;
|
||||
readonly labelKey: string;
|
||||
readonly detailKey: string;
|
||||
readonly value: string;
|
||||
readonly status: DeploySignalStatus;
|
||||
readonly tone: DeploySignalTone;
|
||||
};
|
||||
|
||||
export type DeployAdminData = {
|
||||
readonly metadata: DeployMetadata;
|
||||
readonly signals: readonly DeploySignal[];
|
||||
readonly migrations: readonly DeployMigrationInput[];
|
||||
readonly migrationSummary: {
|
||||
readonly total: number;
|
||||
readonly applied: number;
|
||||
readonly pending: number;
|
||||
readonly failed: number;
|
||||
readonly rolledBack: number;
|
||||
readonly unknown: number;
|
||||
};
|
||||
readonly overallStatus: DeploySignalStatus;
|
||||
readonly overallLabelKey: string;
|
||||
};
|
||||
|
||||
export type DeployAdminVM = VMState<DeployAdminData>;
|
||||
|
||||
export function deploySignalTone(status: DeploySignalStatus): DeploySignalTone {
|
||||
if (status === "ok") return "success";
|
||||
if (status === "warning") return "warning";
|
||||
if (status === "critical") return "danger";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
const STATUS_SEVERITY: Record<DeploySignalStatus, number> = {
|
||||
ok: 0,
|
||||
unknown: 1,
|
||||
warning: 2,
|
||||
critical: 3,
|
||||
};
|
||||
|
||||
export function buildDeployAdminVM(input: DeploySnapshotInput): DeployAdminVM {
|
||||
const summary = input.migrations.reduce(
|
||||
(counts, migration) => ({
|
||||
...counts,
|
||||
[migration.state]: counts[migration.state] + 1,
|
||||
}),
|
||||
{ total: input.migrations.length, applied: 0, pending: 0, failed: 0, rolledBack: 0, unknown: 0 }
|
||||
);
|
||||
|
||||
const signals: DeploySignal[] = [
|
||||
buildSignal({
|
||||
id: "release",
|
||||
labelKey: "admin.deploys.signals.release.label",
|
||||
detailKey: input.metadata.release === "unknown" || input.metadata.release === "local" ? "admin.deploys.signals.release.detailMissing" : "admin.deploys.signals.release.detailOk",
|
||||
value: input.metadata.release,
|
||||
status: input.metadata.release === "unknown" ? "warning" : "ok",
|
||||
}),
|
||||
buildSignal({
|
||||
id: "image",
|
||||
labelKey: "admin.deploys.signals.image.label",
|
||||
detailKey: input.metadata.image === "unknown" ? "admin.deploys.signals.image.detailMissing" : "admin.deploys.signals.image.detailOk",
|
||||
value: input.metadata.image,
|
||||
status: input.metadata.image === "unknown" ? "warning" : "ok",
|
||||
}),
|
||||
buildSignal({
|
||||
id: "migrations",
|
||||
labelKey: "admin.deploys.signals.migrations.label",
|
||||
detailKey: !input.migrationDbReachable
|
||||
? "admin.deploys.signals.migrations.detailUnknown"
|
||||
: summary.failed > 0
|
||||
? "admin.deploys.signals.migrations.detailFailed"
|
||||
: summary.pending > 0
|
||||
? "admin.deploys.signals.migrations.detailPending"
|
||||
: "admin.deploys.signals.migrations.detailOk",
|
||||
value: `${summary.applied}/${summary.total}`,
|
||||
status: !input.migrationDbReachable ? "unknown" : summary.failed > 0 ? "critical" : summary.pending > 0 ? "warning" : "ok",
|
||||
}),
|
||||
];
|
||||
|
||||
const overallStatus = signals.reduce<DeploySignalStatus>(
|
||||
(worst, signal) => (STATUS_SEVERITY[signal.status] > STATUS_SEVERITY[worst] ? signal.status : worst),
|
||||
"ok"
|
||||
);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
metadata: input.metadata,
|
||||
signals,
|
||||
migrations: input.migrations,
|
||||
migrationSummary: summary,
|
||||
overallStatus,
|
||||
overallLabelKey: `admin.deploys.status.${overallStatus}`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildSignal(input: Omit<DeploySignal, "tone">): DeploySignal {
|
||||
return {
|
||||
...input,
|
||||
tone: deploySignalTone(input.status),
|
||||
};
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildFeatureFlagStudioVM, deriveFeatureFlagRisk } from "./feature-flag-studio.vm.js";
|
||||
|
||||
describe("feature flag studio view-model", () => {
|
||||
it("classifies global enabled flags without targeting as high risk", () => {
|
||||
expect(
|
||||
deriveFeatureFlagRisk({
|
||||
id: "flag_1",
|
||||
name: "maintenance",
|
||||
description: "Maintenance",
|
||||
enabled: true,
|
||||
scope: "global",
|
||||
filtersCount: 0,
|
||||
eventsCount: 0,
|
||||
rulesConfigured: false,
|
||||
variantsCount: 0,
|
||||
})
|
||||
).toBe("high");
|
||||
});
|
||||
|
||||
it("builds rollout summary and top flags", () => {
|
||||
const vm = buildFeatureFlagStudioVM({
|
||||
flags: [
|
||||
{
|
||||
id: "flag_a",
|
||||
name: "a",
|
||||
description: "A",
|
||||
enabled: true,
|
||||
scope: "global",
|
||||
filtersCount: 0,
|
||||
eventsCount: 3,
|
||||
rulesConfigured: false,
|
||||
variantsCount: 0,
|
||||
},
|
||||
{
|
||||
id: "flag_b",
|
||||
name: "b",
|
||||
description: "B",
|
||||
enabled: true,
|
||||
scope: "tenant",
|
||||
tenantId: "tenant_1",
|
||||
filtersCount: 1,
|
||||
eventsCount: 9,
|
||||
rulesConfigured: true,
|
||||
variantsCount: 2,
|
||||
enabledFrom: "2026-07-09T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
id: "flag_c",
|
||||
name: "c",
|
||||
description: "C",
|
||||
enabled: false,
|
||||
scope: "global",
|
||||
filtersCount: 0,
|
||||
eventsCount: 1,
|
||||
rulesConfigured: false,
|
||||
variantsCount: 0,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.summary).toMatchObject({
|
||||
flagsTotal: 3,
|
||||
flagsEnabled: 2,
|
||||
flagsDisabled: 1,
|
||||
triggersTotal: 13,
|
||||
scopedFlags: 1,
|
||||
targetedFlags: 1,
|
||||
scheduledFlags: 1,
|
||||
highRiskFlags: 1,
|
||||
});
|
||||
expect(vm.data.topFlags[0]?.name).toBe("b");
|
||||
});
|
||||
});
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type FeatureFlagStudioRisk = "low" | "medium" | "high";
|
||||
|
||||
export type FeatureFlagStudioFlagInput = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly enabled: boolean;
|
||||
readonly scope?: string | null;
|
||||
readonly tenantId?: string | null;
|
||||
readonly userId?: string | null;
|
||||
readonly filtersCount: number;
|
||||
readonly eventsCount: number;
|
||||
readonly rulesConfigured: boolean;
|
||||
readonly variantsCount: number;
|
||||
readonly parentFlagId?: string | null;
|
||||
readonly enabledFrom?: string | null;
|
||||
readonly enabledUntil?: string | null;
|
||||
};
|
||||
|
||||
export type FeatureFlagStudioFlag = FeatureFlagStudioFlagInput & {
|
||||
readonly risk: FeatureFlagStudioRisk;
|
||||
readonly riskLabelKey: string;
|
||||
};
|
||||
|
||||
export type FeatureFlagStudioData = {
|
||||
readonly flags: readonly FeatureFlagStudioFlag[];
|
||||
readonly summary: {
|
||||
readonly flagsTotal: number;
|
||||
readonly flagsEnabled: number;
|
||||
readonly flagsDisabled: number;
|
||||
readonly triggersTotal: number;
|
||||
readonly scopedFlags: number;
|
||||
readonly targetedFlags: number;
|
||||
readonly scheduledFlags: number;
|
||||
readonly highRiskFlags: number;
|
||||
};
|
||||
readonly topFlags: readonly FeatureFlagStudioFlag[];
|
||||
};
|
||||
|
||||
export type FeatureFlagStudioVM = VMState<FeatureFlagStudioData>;
|
||||
|
||||
export function deriveFeatureFlagRisk(flag: FeatureFlagStudioFlagInput): FeatureFlagStudioRisk {
|
||||
if (flag.enabled && (flag.scope === "global" || !flag.scope) && flag.filtersCount === 0 && !flag.rulesConfigured) {
|
||||
return "high";
|
||||
}
|
||||
if (flag.enabled && (flag.filtersCount > 0 || flag.rulesConfigured || flag.variantsCount > 0 || flag.parentFlagId)) {
|
||||
return "medium";
|
||||
}
|
||||
return "low";
|
||||
}
|
||||
|
||||
export function buildFeatureFlagStudioVM(input: { readonly flags: readonly FeatureFlagStudioFlagInput[] }): FeatureFlagStudioVM {
|
||||
const flags = input.flags.map<FeatureFlagStudioFlag>((flag) => {
|
||||
const risk = deriveFeatureFlagRisk(flag);
|
||||
return {
|
||||
...flag,
|
||||
risk,
|
||||
riskLabelKey: `featureFlags.studio.risk.${risk}`,
|
||||
};
|
||||
});
|
||||
|
||||
const summary = {
|
||||
flagsTotal: flags.length,
|
||||
flagsEnabled: flags.filter((flag) => flag.enabled).length,
|
||||
flagsDisabled: flags.filter((flag) => !flag.enabled).length,
|
||||
triggersTotal: flags.reduce((sum, flag) => sum + flag.eventsCount, 0),
|
||||
scopedFlags: flags.filter((flag) => flag.scope && flag.scope !== "global").length,
|
||||
targetedFlags: flags.filter((flag) => flag.filtersCount > 0 || flag.rulesConfigured || flag.variantsCount > 0).length,
|
||||
scheduledFlags: flags.filter((flag) => flag.enabledFrom || flag.enabledUntil).length,
|
||||
highRiskFlags: flags.filter((flag) => flag.risk === "high").length,
|
||||
};
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
flags,
|
||||
summary,
|
||||
topFlags: [...flags].sort((a, b) => b.eventsCount - a.eventsCount || a.name.localeCompare(b.name)).slice(0, 5),
|
||||
},
|
||||
};
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildKwpContractAdminVM } from "./kwp-contract-admin.vm.js";
|
||||
|
||||
describe("buildKwpContractAdminVM", () => {
|
||||
it("returns the explicit empty state without paused capabilities", () => {
|
||||
expect(buildKwpContractAdminVM([])).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("orders redacted alarms by pause time without altering their diff", () => {
|
||||
const vm = buildKwpContractAdminVM([
|
||||
{
|
||||
id: "old",
|
||||
tenantId: "tenant-1",
|
||||
tenantName: "Alpha",
|
||||
connectionId: "connection-1",
|
||||
reasonCode: "contract_drift",
|
||||
observedFingerprint: "abc",
|
||||
adapterRevision: "v1",
|
||||
capabilityRevision: 2,
|
||||
pausedAt: "2026-07-20T10:00:00.000Z",
|
||||
lastCheckedAt: null,
|
||||
lastValidatedAt: null,
|
||||
diff: null,
|
||||
},
|
||||
{
|
||||
id: "new",
|
||||
tenantId: "tenant-2",
|
||||
tenantName: "Beta",
|
||||
connectionId: "connection-2",
|
||||
reasonCode: "response_schema_invalid",
|
||||
observedFingerprint: "def",
|
||||
adapterRevision: "v2",
|
||||
capabilityRevision: 4,
|
||||
pausedAt: "2026-07-22T10:00:00.000Z",
|
||||
lastCheckedAt: "2026-07-22T10:01:00.000Z",
|
||||
lastValidatedAt: "2026-07-21T10:00:00.000Z",
|
||||
diff: { added: ["/project/newField"], removed: [], changed: [], truncated: false },
|
||||
},
|
||||
]);
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready VM");
|
||||
expect(vm.data.alarmCount).toBe(2);
|
||||
expect(vm.data.alarms.map((row) => row.id)).toEqual(["new", "old"]);
|
||||
expect(vm.data.alarms[0]?.diff?.added).toEqual(["/project/newField"]);
|
||||
});
|
||||
});
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type KwpContractDiffVM = {
|
||||
readonly added: readonly string[];
|
||||
readonly removed: readonly string[];
|
||||
readonly changed: readonly string[];
|
||||
readonly truncated: boolean;
|
||||
};
|
||||
|
||||
export type KwpContractAlarmInput = {
|
||||
readonly id: string;
|
||||
readonly tenantId: string;
|
||||
readonly tenantName: string;
|
||||
readonly connectionId: string;
|
||||
readonly reasonCode: string | null;
|
||||
readonly observedFingerprint: string | null;
|
||||
readonly adapterRevision: string;
|
||||
readonly capabilityRevision: number;
|
||||
readonly pausedAt: string | null;
|
||||
readonly lastCheckedAt: string | null;
|
||||
readonly lastValidatedAt: string | null;
|
||||
readonly diff: KwpContractDiffVM | null;
|
||||
};
|
||||
|
||||
export type KwpContractAdminData = {
|
||||
readonly alarms: readonly KwpContractAlarmInput[];
|
||||
readonly alarmCount: number;
|
||||
};
|
||||
|
||||
export type KwpContractAdminVM = VMState<KwpContractAdminData>;
|
||||
|
||||
export function buildKwpContractAdminVM(
|
||||
input: readonly KwpContractAlarmInput[],
|
||||
): KwpContractAdminVM {
|
||||
if (input.length === 0) return { status: "empty" };
|
||||
const alarms = [...input].sort((left, right) => {
|
||||
const leftTime = left.pausedAt ?? left.lastCheckedAt ?? "";
|
||||
const rightTime = right.pausedAt ?? right.lastCheckedAt ?? "";
|
||||
return rightTime.localeCompare(leftTime);
|
||||
});
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
alarms,
|
||||
alarmCount: alarms.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildOperatorHealthVM, operatorHealthTone, type OperatorHealthInput } from "./operator-health.vm.js";
|
||||
|
||||
function baseInput(overrides: Partial<OperatorHealthInput> = {}): OperatorHealthInput {
|
||||
return {
|
||||
subsystems: [
|
||||
{ id: "system", status: "ok", href: "/admin/system" },
|
||||
{ id: "deploy", status: "ok", href: "/admin/deploys" },
|
||||
{ id: "queues", status: "ok", href: "/admin/jobs" },
|
||||
{ id: "webhooks", status: "ok", href: "/admin/webhooks" },
|
||||
{ id: "billing", status: "ok", href: "/admin/accounts/billing" },
|
||||
],
|
||||
deploy: { environment: "production", release: "abc123", revision: "abc123", branch: "main" },
|
||||
signals: { failedJobsTotal: 0, pausedQueues: 0, webhookFailures: 0, billingErrors: 0 },
|
||||
links: { jobs: "/admin/jobs", webhooks: "/admin/webhooks", billing: "/admin/accounts/billing" },
|
||||
billingErrors: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("operator health view-model", () => {
|
||||
it("maps status to tone", () => {
|
||||
expect(operatorHealthTone("ok")).toBe("success");
|
||||
expect(operatorHealthTone("warning")).toBe("warning");
|
||||
expect(operatorHealthTone("critical")).toBe("danger");
|
||||
expect(operatorHealthTone("unknown")).toBe("neutral");
|
||||
});
|
||||
|
||||
it("returns empty when there are no subsystems", () => {
|
||||
expect(buildOperatorHealthVM(baseInput({ subsystems: [] })).status).toBe("empty");
|
||||
});
|
||||
|
||||
it("labels subsystems and produces an all-clear when healthy", () => {
|
||||
const vm = buildOperatorHealthVM(baseInput());
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.overallStatus).toBe("ok");
|
||||
expect(vm.data.overallLabelKey).toBe("admin.health.status.ok");
|
||||
expect(vm.data.summary).toEqual({ total: 5, ok: 5, warning: 0, critical: 0, unknown: 0 });
|
||||
expect(vm.data.attention).toEqual([]);
|
||||
const system = vm.data.subsystems.find((s) => s.id === "system");
|
||||
expect(system?.labelKey).toBe("admin.health.subsystems.system.label");
|
||||
expect(system?.detailKey).toBe("admin.health.subsystems.system.detail");
|
||||
expect(system?.statusLabelKey).toBe("admin.health.status.ok");
|
||||
expect(system?.tone).toBe("success");
|
||||
});
|
||||
|
||||
it("takes the worst subsystem status as overall", () => {
|
||||
const vm = buildOperatorHealthVM(
|
||||
baseInput({
|
||||
subsystems: [
|
||||
{ id: "system", status: "critical", href: "/admin/system" },
|
||||
{ id: "deploy", status: "warning", href: "/admin/deploys" },
|
||||
{ id: "queues", status: "unknown", href: "/admin/jobs" },
|
||||
{ id: "webhooks", status: "ok", href: "/admin/webhooks" },
|
||||
{ id: "billing", status: "ok", href: "/admin/accounts/billing" },
|
||||
],
|
||||
})
|
||||
);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.overallStatus).toBe("critical");
|
||||
expect(vm.data.summary).toEqual({ total: 5, ok: 2, warning: 1, critical: 1, unknown: 1 });
|
||||
});
|
||||
|
||||
it("builds an attention list from signals with the right links and tones", () => {
|
||||
const billingError = { id: "log_1", eventType: "invoice.payment_failed", error: "boom", createdAt: "2026-07-09T00:00:00.000Z", relatedTenantId: "tenant_1" };
|
||||
const vm = buildOperatorHealthVM(
|
||||
baseInput({
|
||||
signals: { failedJobsTotal: 3, pausedQueues: 1, webhookFailures: 2, billingErrors: 1 },
|
||||
billingErrors: [billingError],
|
||||
})
|
||||
);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.attention).toEqual([
|
||||
{ id: "failedJobs", tone: "warning", labelKey: "admin.health.attention.failedJobs", count: 3, href: "/admin/jobs" },
|
||||
{ id: "pausedQueues", tone: "warning", labelKey: "admin.health.attention.pausedQueues", count: 1, href: "/admin/jobs" },
|
||||
{ id: "webhookFailures", tone: "warning", labelKey: "admin.health.attention.webhookFailures", count: 2, href: "/admin/webhooks" },
|
||||
{ id: "billingErrors", tone: "danger", labelKey: "admin.health.attention.billingErrors", count: 1, href: "/admin/accounts/billing" },
|
||||
]);
|
||||
expect(vm.data.billingErrors).toEqual([billingError]);
|
||||
});
|
||||
});
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Operator health overview (Welle 4, Deliverable 2).
|
||||
*
|
||||
* Pure aggregation view-model: the `/admin/health` loader composes the existing
|
||||
* system-health, deploy and queue snapshots (+ a small billing-webhook error
|
||||
* read) into {@link OperatorHealthInput} and this function turns that into a
|
||||
* "is the environment roughly healthy?" overview — one traffic light per
|
||||
* subsystem, the deploy version line and an "attention needed" list. It does
|
||||
* NOT re-implement any snapshot; it only ranks and labels already-derived
|
||||
* signals (DoD A.3 — no React/Prisma here).
|
||||
*/
|
||||
|
||||
export type OperatorHealthStatus = "ok" | "warning" | "critical" | "unknown";
|
||||
export type OperatorHealthTone = "success" | "warning" | "danger" | "neutral";
|
||||
export type OperatorHealthSubsystemId = "system" | "deploy" | "queues" | "webhooks" | "billing";
|
||||
|
||||
/** Per-subsystem input: overall status already derived by the caller + a link. */
|
||||
export type OperatorHealthSubsystemInput = {
|
||||
readonly id: OperatorHealthSubsystemId;
|
||||
readonly status: OperatorHealthStatus;
|
||||
readonly href: string;
|
||||
};
|
||||
|
||||
export type OperatorHealthBillingError = {
|
||||
readonly id: string;
|
||||
readonly eventType: string;
|
||||
readonly error: string;
|
||||
readonly createdAt: string;
|
||||
readonly relatedTenantId: string | null;
|
||||
};
|
||||
|
||||
export type OperatorHealthDeploy = {
|
||||
readonly environment: string;
|
||||
readonly release: string;
|
||||
readonly revision: string;
|
||||
readonly branch: string;
|
||||
};
|
||||
|
||||
export type OperatorHealthInput = {
|
||||
readonly subsystems: readonly OperatorHealthSubsystemInput[];
|
||||
readonly deploy: OperatorHealthDeploy;
|
||||
readonly signals: {
|
||||
readonly failedJobsTotal: number;
|
||||
readonly pausedQueues: number;
|
||||
readonly webhookFailures: number;
|
||||
readonly billingErrors: number;
|
||||
};
|
||||
/** Hrefs the attention rows link to (computed server-side via adminPath). */
|
||||
readonly links: {
|
||||
readonly jobs: string;
|
||||
readonly webhooks: string;
|
||||
readonly billing: string;
|
||||
};
|
||||
readonly billingErrors: readonly OperatorHealthBillingError[];
|
||||
};
|
||||
|
||||
export type OperatorHealthSubsystem = OperatorHealthSubsystemInput & {
|
||||
readonly tone: OperatorHealthTone;
|
||||
readonly labelKey: string;
|
||||
readonly detailKey: string;
|
||||
readonly statusLabelKey: string;
|
||||
};
|
||||
|
||||
export type OperatorHealthAttention = {
|
||||
readonly id: string;
|
||||
readonly tone: OperatorHealthTone;
|
||||
readonly labelKey: string;
|
||||
readonly count: number;
|
||||
readonly href: string;
|
||||
};
|
||||
|
||||
export type OperatorHealthData = {
|
||||
readonly overallStatus: OperatorHealthStatus;
|
||||
readonly overallLabelKey: string;
|
||||
readonly subsystems: readonly OperatorHealthSubsystem[];
|
||||
readonly summary: {
|
||||
readonly total: number;
|
||||
readonly ok: number;
|
||||
readonly warning: number;
|
||||
readonly critical: number;
|
||||
readonly unknown: number;
|
||||
};
|
||||
readonly attention: readonly OperatorHealthAttention[];
|
||||
readonly deploy: OperatorHealthDeploy;
|
||||
readonly billingErrors: readonly OperatorHealthBillingError[];
|
||||
};
|
||||
|
||||
export type OperatorHealthVM = VMState<OperatorHealthData>;
|
||||
|
||||
const STATUS_SEVERITY: Record<OperatorHealthStatus, number> = {
|
||||
ok: 0,
|
||||
unknown: 1,
|
||||
warning: 2,
|
||||
critical: 3,
|
||||
};
|
||||
|
||||
export function operatorHealthTone(status: OperatorHealthStatus): OperatorHealthTone {
|
||||
if (status === "ok") return "success";
|
||||
if (status === "warning") return "warning";
|
||||
if (status === "critical") return "danger";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
export function buildOperatorHealthVM(input: OperatorHealthInput): OperatorHealthVM {
|
||||
if (input.subsystems.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
const subsystems = input.subsystems.map<OperatorHealthSubsystem>((subsystem) => ({
|
||||
...subsystem,
|
||||
tone: operatorHealthTone(subsystem.status),
|
||||
labelKey: `admin.health.subsystems.${subsystem.id}.label`,
|
||||
detailKey: `admin.health.subsystems.${subsystem.id}.detail`,
|
||||
statusLabelKey: `admin.health.status.${subsystem.status}`,
|
||||
}));
|
||||
|
||||
const summary = subsystems.reduce(
|
||||
(counts, subsystem) => ({ ...counts, [subsystem.status]: counts[subsystem.status] + 1 }),
|
||||
{ total: subsystems.length, ok: 0, warning: 0, critical: 0, unknown: 0 }
|
||||
);
|
||||
|
||||
const overallStatus = subsystems.reduce<OperatorHealthStatus>(
|
||||
(worst, subsystem) => (STATUS_SEVERITY[subsystem.status] > STATUS_SEVERITY[worst] ? subsystem.status : worst),
|
||||
"ok"
|
||||
);
|
||||
|
||||
const attention: OperatorHealthAttention[] = [];
|
||||
if (input.signals.failedJobsTotal > 0) {
|
||||
attention.push({ id: "failedJobs", tone: "warning", labelKey: "admin.health.attention.failedJobs", count: input.signals.failedJobsTotal, href: input.links.jobs });
|
||||
}
|
||||
if (input.signals.pausedQueues > 0) {
|
||||
attention.push({ id: "pausedQueues", tone: "warning", labelKey: "admin.health.attention.pausedQueues", count: input.signals.pausedQueues, href: input.links.jobs });
|
||||
}
|
||||
if (input.signals.webhookFailures > 0) {
|
||||
attention.push({ id: "webhookFailures", tone: "warning", labelKey: "admin.health.attention.webhookFailures", count: input.signals.webhookFailures, href: input.links.webhooks });
|
||||
}
|
||||
if (input.signals.billingErrors > 0) {
|
||||
attention.push({ id: "billingErrors", tone: "danger", labelKey: "admin.health.attention.billingErrors", count: input.signals.billingErrors, href: input.links.billing });
|
||||
}
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
overallStatus,
|
||||
overallLabelKey: `admin.health.status.${overallStatus}`,
|
||||
subsystems,
|
||||
summary,
|
||||
attention,
|
||||
deploy: input.deploy,
|
||||
billingErrors: input.billingErrors,
|
||||
},
|
||||
};
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSystemHealthVM, deriveSystemHealthStatus } from "./system-health.vm.js";
|
||||
|
||||
describe("system health view-model", () => {
|
||||
it("derives clear service health states", () => {
|
||||
expect(deriveSystemHealthStatus({ configured: true, reachable: true })).toBe("ok");
|
||||
expect(deriveSystemHealthStatus({ configured: false, reachable: null })).toBe("warning");
|
||||
expect(deriveSystemHealthStatus({ configured: true, reachable: false })).toBe("critical");
|
||||
expect(deriveSystemHealthStatus({ configured: null, reachable: null })).toBe("unknown");
|
||||
});
|
||||
|
||||
it("builds summary counts and worst overall status", () => {
|
||||
const vm = buildSystemHealthVM({
|
||||
deploy: { environment: "staging", release: "abc123", nodeEnv: "production" },
|
||||
services: [
|
||||
{ id: "web", labelKey: "admin.system.services.web.label", category: "runtime", configured: true, reachable: true },
|
||||
{ id: "meili", labelKey: "admin.system.services.meili.label", category: "integration", configured: false, reachable: null },
|
||||
{ id: "postgres", labelKey: "admin.system.services.postgres.label", category: "database", configured: true, reachable: false },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.summary).toEqual({ total: 3, ok: 1, warning: 1, critical: 1, unknown: 0 });
|
||||
expect(vm.data.overallStatus).toBe("critical");
|
||||
expect(vm.data.services[0].categoryLabelKey).toBe("admin.system.categories.runtime");
|
||||
});
|
||||
});
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type SystemHealthStatus = "ok" | "warning" | "critical" | "unknown";
|
||||
export type SystemHealthTone = "success" | "warning" | "danger" | "neutral";
|
||||
export type SystemHealthCategory = "runtime" | "database" | "queue" | "integration" | "observability" | "storage";
|
||||
|
||||
export type SystemHealthServiceInput = {
|
||||
readonly id: string;
|
||||
readonly labelKey: string;
|
||||
readonly category: SystemHealthCategory;
|
||||
readonly configured: boolean | null;
|
||||
readonly reachable?: boolean | null;
|
||||
readonly detailKey?: string;
|
||||
readonly detailValue?: string;
|
||||
readonly href?: string;
|
||||
};
|
||||
|
||||
export type SystemHealthService = SystemHealthServiceInput & {
|
||||
readonly status: SystemHealthStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly tone: SystemHealthTone;
|
||||
readonly categoryLabelKey: string;
|
||||
};
|
||||
|
||||
export type SystemHealthDeploy = {
|
||||
readonly environment: string;
|
||||
readonly release: string;
|
||||
readonly nodeEnv: string;
|
||||
};
|
||||
|
||||
export type SystemHealthData = {
|
||||
readonly services: readonly SystemHealthService[];
|
||||
readonly summary: {
|
||||
readonly total: number;
|
||||
readonly ok: number;
|
||||
readonly warning: number;
|
||||
readonly critical: number;
|
||||
readonly unknown: number;
|
||||
};
|
||||
readonly overallStatus: SystemHealthStatus;
|
||||
readonly overallLabelKey: string;
|
||||
readonly deploy: SystemHealthDeploy;
|
||||
};
|
||||
|
||||
export type SystemHealthVM = VMState<SystemHealthData>;
|
||||
|
||||
export function deriveSystemHealthStatus(input: Pick<SystemHealthServiceInput, "configured" | "reachable">): SystemHealthStatus {
|
||||
if (input.reachable === false) return "critical";
|
||||
if (input.configured === false) return "warning";
|
||||
if (input.reachable === true || input.configured === true) return "ok";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function systemHealthTone(status: SystemHealthStatus): SystemHealthTone {
|
||||
if (status === "ok") return "success";
|
||||
if (status === "warning") return "warning";
|
||||
if (status === "critical") return "danger";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
const STATUS_SEVERITY: Record<SystemHealthStatus, number> = {
|
||||
ok: 0,
|
||||
unknown: 1,
|
||||
warning: 2,
|
||||
critical: 3,
|
||||
};
|
||||
|
||||
export function buildSystemHealthVM(input: {
|
||||
readonly services: readonly SystemHealthServiceInput[];
|
||||
readonly deploy: SystemHealthDeploy;
|
||||
}): SystemHealthVM {
|
||||
if (input.services.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
const services = input.services.map<SystemHealthService>((service) => {
|
||||
const status = deriveSystemHealthStatus(service);
|
||||
return {
|
||||
...service,
|
||||
status,
|
||||
tone: systemHealthTone(status),
|
||||
statusLabelKey: `admin.system.status.${status}`,
|
||||
categoryLabelKey: `admin.system.categories.${service.category}`,
|
||||
};
|
||||
});
|
||||
|
||||
const summary = services.reduce(
|
||||
(counts, service) => ({
|
||||
...counts,
|
||||
[service.status]: counts[service.status] + 1,
|
||||
}),
|
||||
{ total: services.length, ok: 0, warning: 0, critical: 0, unknown: 0 }
|
||||
);
|
||||
|
||||
const overallStatus = services.reduce<SystemHealthStatus>(
|
||||
(worst, service) => (STATUS_SEVERITY[service.status] > STATUS_SEVERITY[worst] ? service.status : worst),
|
||||
"ok"
|
||||
);
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
services,
|
||||
summary,
|
||||
overallStatus,
|
||||
overallLabelKey: `admin.system.status.${overallStatus}`,
|
||||
deploy: input.deploy,
|
||||
},
|
||||
};
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildTenantSecurityVM, deriveTenantSecurityRisk, type TenantSecurityInput } from "./tenant-security.vm.js";
|
||||
|
||||
const baseInput: TenantSecurityInput = {
|
||||
now: "2026-07-09T10:00:00.000Z",
|
||||
tenant: { id: "tenant_1", name: "Acme", slug: "acme", active: true },
|
||||
users: [
|
||||
{
|
||||
id: "user_1",
|
||||
email: "owner@example.test",
|
||||
name: "Owner Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: true,
|
||||
mfaPending: false,
|
||||
recoveryCodesConfigured: true,
|
||||
},
|
||||
{
|
||||
id: "user_2",
|
||||
email: "member@example.test",
|
||||
name: "Member Example",
|
||||
active: true,
|
||||
membershipStatus: "active",
|
||||
mfaEnabled: false,
|
||||
mfaPending: true,
|
||||
recoveryCodesConfigured: false,
|
||||
},
|
||||
],
|
||||
sessions: [
|
||||
{
|
||||
id: "session_1",
|
||||
userId: "user_1",
|
||||
userEmail: "owner@example.test",
|
||||
deviceLabel: "MacBook",
|
||||
userAgent: "Safari",
|
||||
approxLocation: "DE",
|
||||
createdAt: "2026-07-09T08:00:00.000Z",
|
||||
lastSeenAt: "2026-07-09T09:00:00.000Z",
|
||||
expiresAt: "2026-07-10T09:00:00.000Z",
|
||||
revokedAt: null,
|
||||
trustedAt: "2026-07-09T08:05:00.000Z",
|
||||
},
|
||||
],
|
||||
trustedDevices: [
|
||||
{
|
||||
id: "device_1",
|
||||
userId: "user_1",
|
||||
userEmail: "owner@example.test",
|
||||
deviceLabel: "Safari",
|
||||
approxLocation: "DE",
|
||||
lastUsedAt: "2026-07-09T08:05:00.000Z",
|
||||
expiresAt: "2026-08-09T08:05:00.000Z",
|
||||
revokedAt: null,
|
||||
},
|
||||
],
|
||||
magicLinks: [
|
||||
{
|
||||
id: "magic_1",
|
||||
userId: "user_2",
|
||||
userEmail: "member@example.test",
|
||||
createdAt: "2026-07-09T09:55:00.000Z",
|
||||
expiresAt: "2026-07-09T10:10:00.000Z",
|
||||
consumedAt: null,
|
||||
},
|
||||
],
|
||||
ipLogs: [
|
||||
{
|
||||
id: "ip_1",
|
||||
ip: "192.168.10.25",
|
||||
fromUrl: "/login",
|
||||
createdAt: "2026-07-09T09:50:00.000Z",
|
||||
userEmail: "member@example.test",
|
||||
apiKeyAlias: null,
|
||||
},
|
||||
],
|
||||
auditEvents: [
|
||||
{
|
||||
id: "audit_1",
|
||||
createdAt: "2026-07-09T09:49:00.000Z",
|
||||
action: "auth.login.failed",
|
||||
outcome: "failure",
|
||||
actorEmail: "member@example.test",
|
||||
actorId: "user_2",
|
||||
summaryText: "Login fehlgeschlagen",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("buildTenantSecurityVM", () => {
|
||||
it("builds tenant security metrics and masks IP addresses", () => {
|
||||
const vm = buildTenantSecurityVM(baseInput);
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.metrics.find((metric) => metric.id === "mfa")?.value).toBe("1/2");
|
||||
expect(vm.data.sessions[0]).toMatchObject({ status: "trusted", tone: "success" });
|
||||
expect(vm.data.magicLinks[0]).toMatchObject({ status: "pending", tone: "warning" });
|
||||
expect(vm.data.ipLogs[0]).toMatchObject({ maskedIp: "192.168.10.***", actorLabel: "member@example.test" });
|
||||
expect(vm.data.issues).toContain("admin.tenantSecurity.issues.mfaMissing");
|
||||
});
|
||||
|
||||
it("returns empty when there is nothing to diagnose", () => {
|
||||
const vm = buildTenantSecurityVM({ ...baseInput, users: [], sessions: [], trustedDevices: [], magicLinks: [], ipLogs: [], auditEvents: [] });
|
||||
|
||||
expect(vm.status).toBe("empty");
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveTenantSecurityRisk", () => {
|
||||
it("raises risk for login failure spikes", () => {
|
||||
expect(deriveTenantSecurityRisk({ mfaCoverage: 1, loginFailures: 3, pendingMagicLinks: 0, activeSessions: 2 })).toBe("high");
|
||||
});
|
||||
|
||||
it("keeps fully protected tenants low risk", () => {
|
||||
expect(deriveTenantSecurityRisk({ mfaCoverage: 1, loginFailures: 0, pendingMagicLinks: 0, activeSessions: 2 })).toBe("low");
|
||||
});
|
||||
});
|
||||
+312
@@ -0,0 +1,312 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type TenantSecurityRisk = "low" | "medium" | "high";
|
||||
export type TenantSecurityTone = "success" | "warning" | "danger" | "neutral";
|
||||
|
||||
export type TenantSecurityUserInput = {
|
||||
readonly id: string;
|
||||
readonly email: string;
|
||||
readonly name: string;
|
||||
readonly active: boolean;
|
||||
readonly membershipStatus: string;
|
||||
readonly mfaEnabled: boolean;
|
||||
readonly mfaPending: boolean;
|
||||
readonly recoveryCodesConfigured: boolean;
|
||||
};
|
||||
|
||||
export type TenantSecuritySessionInput = {
|
||||
readonly id: string;
|
||||
readonly userId: string;
|
||||
readonly userEmail: string;
|
||||
readonly deviceLabel: string | null;
|
||||
readonly userAgent: string | null;
|
||||
readonly approxLocation: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly lastSeenAt: string;
|
||||
readonly expiresAt: string;
|
||||
readonly revokedAt: string | null;
|
||||
readonly trustedAt: string | null;
|
||||
};
|
||||
|
||||
export type TenantSecurityTrustedDeviceInput = {
|
||||
readonly id: string;
|
||||
readonly userId: string;
|
||||
readonly userEmail: string;
|
||||
readonly deviceLabel: string | null;
|
||||
readonly approxLocation: string | null;
|
||||
readonly lastUsedAt: string;
|
||||
readonly expiresAt: string;
|
||||
readonly revokedAt: string | null;
|
||||
};
|
||||
|
||||
export type TenantSecurityMagicLinkInput = {
|
||||
readonly id: string;
|
||||
readonly userId: string;
|
||||
readonly userEmail: string;
|
||||
readonly createdAt: string;
|
||||
readonly expiresAt: string;
|
||||
readonly consumedAt: string | null;
|
||||
};
|
||||
|
||||
export type TenantSecurityIpLogInput = {
|
||||
readonly id: string;
|
||||
readonly ip: string;
|
||||
readonly fromUrl: string;
|
||||
readonly createdAt: string;
|
||||
readonly userEmail: string | null;
|
||||
readonly apiKeyAlias: string | null;
|
||||
};
|
||||
|
||||
export type TenantSecurityAuditInput = {
|
||||
readonly id: string;
|
||||
readonly createdAt: string;
|
||||
readonly action: string;
|
||||
readonly outcome: string;
|
||||
readonly actorEmail: string | null;
|
||||
readonly actorId: string | null;
|
||||
readonly summaryText: string | null;
|
||||
};
|
||||
|
||||
export type TenantSecurityInput = {
|
||||
readonly tenant: {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly active: boolean;
|
||||
};
|
||||
readonly now: string;
|
||||
readonly users: readonly TenantSecurityUserInput[];
|
||||
readonly sessions: readonly TenantSecuritySessionInput[];
|
||||
readonly trustedDevices: readonly TenantSecurityTrustedDeviceInput[];
|
||||
readonly magicLinks: readonly TenantSecurityMagicLinkInput[];
|
||||
readonly ipLogs: readonly TenantSecurityIpLogInput[];
|
||||
readonly auditEvents: readonly TenantSecurityAuditInput[];
|
||||
};
|
||||
|
||||
export type TenantSecurityMetric = {
|
||||
readonly id: string;
|
||||
readonly labelKey: string;
|
||||
readonly value: string;
|
||||
readonly detailKey: string;
|
||||
readonly tone: TenantSecurityTone;
|
||||
};
|
||||
|
||||
export type TenantSecurityUserRow = TenantSecurityUserInput & {
|
||||
readonly statusLabelKey: string;
|
||||
readonly mfaLabelKey: string;
|
||||
readonly risk: TenantSecurityRisk;
|
||||
readonly riskLabelKey: string;
|
||||
};
|
||||
|
||||
export type TenantSecuritySessionRow = TenantSecuritySessionInput & {
|
||||
readonly status: "active" | "trusted" | "expired" | "revoked";
|
||||
readonly statusLabelKey: string;
|
||||
readonly tone: TenantSecurityTone;
|
||||
readonly displayDevice: string;
|
||||
};
|
||||
|
||||
export type TenantSecurityTrustedDeviceRow = TenantSecurityTrustedDeviceInput & {
|
||||
readonly status: "active" | "expired" | "revoked";
|
||||
readonly statusLabelKey: string;
|
||||
readonly tone: TenantSecurityTone;
|
||||
readonly displayDevice: string;
|
||||
};
|
||||
|
||||
export type TenantSecurityMagicLinkRow = TenantSecurityMagicLinkInput & {
|
||||
readonly status: "pending" | "used" | "expired";
|
||||
readonly statusLabelKey: string;
|
||||
readonly tone: TenantSecurityTone;
|
||||
};
|
||||
|
||||
export type TenantSecurityIpRow = TenantSecurityIpLogInput & {
|
||||
readonly maskedIp: string;
|
||||
readonly actorLabel: string;
|
||||
};
|
||||
|
||||
export type TenantSecurityAuditRow = TenantSecurityAuditInput & {
|
||||
readonly tone: TenantSecurityTone;
|
||||
readonly displaySummary: string;
|
||||
};
|
||||
|
||||
export type TenantSecurityData = {
|
||||
readonly tenant: TenantSecurityInput["tenant"];
|
||||
readonly risk: TenantSecurityRisk;
|
||||
readonly riskLabelKey: string;
|
||||
readonly riskDetailKey: string;
|
||||
readonly metrics: readonly TenantSecurityMetric[];
|
||||
readonly users: readonly TenantSecurityUserRow[];
|
||||
readonly sessions: readonly TenantSecuritySessionRow[];
|
||||
readonly trustedDevices: readonly TenantSecurityTrustedDeviceRow[];
|
||||
readonly magicLinks: readonly TenantSecurityMagicLinkRow[];
|
||||
readonly ipLogs: readonly TenantSecurityIpRow[];
|
||||
readonly auditEvents: readonly TenantSecurityAuditRow[];
|
||||
readonly issues: readonly string[];
|
||||
};
|
||||
|
||||
export type TenantSecurityVM = VMState<TenantSecurityData>;
|
||||
|
||||
export function buildTenantSecurityVM(input: TenantSecurityInput): TenantSecurityVM {
|
||||
const activeUsers = input.users.filter((user) => user.active && user.membershipStatus === "active");
|
||||
const mfaEnabled = input.users.filter((user) => user.mfaEnabled);
|
||||
const sessions = input.sessions.map((session) => buildSessionRow(session, input.now));
|
||||
const trustedDevices = input.trustedDevices.map((device) => buildTrustedDeviceRow(device, input.now));
|
||||
const magicLinks = input.magicLinks.map((link) => buildMagicLinkRow(link, input.now));
|
||||
const loginFailures = input.auditEvents.filter((event) => isLoginEvent(event.action) && event.outcome !== "success").length;
|
||||
const pendingMagicLinks = magicLinks.filter((link) => link.status === "pending").length;
|
||||
const activeSessions = sessions.filter((session) => session.status === "active" || session.status === "trusted").length;
|
||||
const activeTrustedDevices = trustedDevices.filter((device) => device.status === "active").length;
|
||||
const mfaCoverage = activeUsers.length === 0 ? 1 : mfaEnabled.length / activeUsers.length;
|
||||
const issues = buildSecurityIssues({ activeUsers: activeUsers.length, mfaCoverage, loginFailures, pendingMagicLinks, activeSessions });
|
||||
const risk = deriveTenantSecurityRisk({ mfaCoverage, loginFailures, pendingMagicLinks, activeSessions });
|
||||
|
||||
if (input.users.length === 0 && input.sessions.length === 0 && input.auditEvents.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
tenant: input.tenant,
|
||||
risk,
|
||||
riskLabelKey: `admin.tenantSecurity.risk.${risk}`,
|
||||
riskDetailKey: `admin.tenantSecurity.riskDetail.${risk}`,
|
||||
metrics: [
|
||||
{
|
||||
id: "mfa",
|
||||
labelKey: "admin.tenantSecurity.metrics.mfa.label",
|
||||
value: `${mfaEnabled.length}/${activeUsers.length}`,
|
||||
detailKey: "admin.tenantSecurity.metrics.mfa.detail",
|
||||
tone: mfaCoverage >= 1 ? "success" : mfaCoverage >= 0.5 ? "warning" : "danger",
|
||||
},
|
||||
{
|
||||
id: "sessions",
|
||||
labelKey: "admin.tenantSecurity.metrics.sessions.label",
|
||||
value: String(activeSessions),
|
||||
detailKey: "admin.tenantSecurity.metrics.sessions.detail",
|
||||
tone: activeSessions > 0 ? "neutral" : "warning",
|
||||
},
|
||||
{
|
||||
id: "devices",
|
||||
labelKey: "admin.tenantSecurity.metrics.devices.label",
|
||||
value: String(activeTrustedDevices),
|
||||
detailKey: "admin.tenantSecurity.metrics.devices.detail",
|
||||
tone: activeTrustedDevices > 0 ? "neutral" : "success",
|
||||
},
|
||||
{
|
||||
id: "magicLinks",
|
||||
labelKey: "admin.tenantSecurity.metrics.magicLinks.label",
|
||||
value: String(pendingMagicLinks),
|
||||
detailKey: "admin.tenantSecurity.metrics.magicLinks.detail",
|
||||
tone: pendingMagicLinks > 0 ? "warning" : "success",
|
||||
},
|
||||
{
|
||||
id: "loginFailures",
|
||||
labelKey: "admin.tenantSecurity.metrics.loginFailures.label",
|
||||
value: String(loginFailures),
|
||||
detailKey: "admin.tenantSecurity.metrics.loginFailures.detail",
|
||||
tone: loginFailures >= 3 ? "danger" : loginFailures > 0 ? "warning" : "success",
|
||||
},
|
||||
],
|
||||
users: input.users.map((user) => ({
|
||||
...user,
|
||||
statusLabelKey: user.active ? "admin.tenantSecurity.users.status.active" : "admin.tenantSecurity.users.status.inactive",
|
||||
mfaLabelKey: user.mfaEnabled
|
||||
? "admin.tenantSecurity.users.mfa.enabled"
|
||||
: user.mfaPending
|
||||
? "admin.tenantSecurity.users.mfa.pending"
|
||||
: "admin.tenantSecurity.users.mfa.disabled",
|
||||
risk: user.active && !user.mfaEnabled ? "medium" : "low",
|
||||
riskLabelKey: user.active && !user.mfaEnabled ? "admin.tenantSecurity.risk.medium" : "admin.tenantSecurity.risk.low",
|
||||
})),
|
||||
sessions,
|
||||
trustedDevices,
|
||||
magicLinks,
|
||||
ipLogs: input.ipLogs.map((row) => ({
|
||||
...row,
|
||||
maskedIp: maskIp(row.ip),
|
||||
actorLabel: row.userEmail ?? row.apiKeyAlias ?? "system",
|
||||
})),
|
||||
auditEvents: input.auditEvents.map((event) => ({
|
||||
...event,
|
||||
tone: event.outcome === "success" ? "success" : event.outcome === "blocked" ? "danger" : "warning",
|
||||
displaySummary: event.summaryText ?? `${event.action} (${event.outcome})`,
|
||||
})),
|
||||
issues,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveTenantSecurityRisk(input: {
|
||||
readonly mfaCoverage: number;
|
||||
readonly loginFailures: number;
|
||||
readonly pendingMagicLinks: number;
|
||||
readonly activeSessions: number;
|
||||
}): TenantSecurityRisk {
|
||||
if (input.loginFailures >= 3 || input.mfaCoverage < 0.5) return "high";
|
||||
if (input.loginFailures > 0 || input.pendingMagicLinks > 0 || input.mfaCoverage < 1 || input.activeSessions === 0) return "medium";
|
||||
return "low";
|
||||
}
|
||||
|
||||
function buildSessionRow(session: TenantSecuritySessionInput, now: string): TenantSecuritySessionRow {
|
||||
const status =
|
||||
session.revokedAt !== null ? "revoked" : Date.parse(session.expiresAt) <= Date.parse(now) ? "expired" : session.trustedAt !== null ? "trusted" : "active";
|
||||
return {
|
||||
...session,
|
||||
status,
|
||||
statusLabelKey: `admin.tenantSecurity.sessions.status.${status}`,
|
||||
tone: status === "active" || status === "trusted" ? "success" : status === "expired" ? "warning" : "danger",
|
||||
displayDevice: session.deviceLabel ?? session.userAgent ?? "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
function buildTrustedDeviceRow(device: TenantSecurityTrustedDeviceInput, now: string): TenantSecurityTrustedDeviceRow {
|
||||
const status = device.revokedAt !== null ? "revoked" : Date.parse(device.expiresAt) <= Date.parse(now) ? "expired" : "active";
|
||||
return {
|
||||
...device,
|
||||
status,
|
||||
statusLabelKey: `admin.tenantSecurity.devices.status.${status}`,
|
||||
tone: status === "active" ? "success" : status === "expired" ? "warning" : "danger",
|
||||
displayDevice: device.deviceLabel ?? device.approxLocation ?? "unknown",
|
||||
};
|
||||
}
|
||||
|
||||
function buildMagicLinkRow(link: TenantSecurityMagicLinkInput, now: string): TenantSecurityMagicLinkRow {
|
||||
const status = link.consumedAt !== null ? "used" : Date.parse(link.expiresAt) <= Date.parse(now) ? "expired" : "pending";
|
||||
return {
|
||||
...link,
|
||||
status,
|
||||
statusLabelKey: `admin.tenantSecurity.magicLinks.status.${status}`,
|
||||
tone: status === "pending" ? "warning" : status === "used" ? "success" : "neutral",
|
||||
};
|
||||
}
|
||||
|
||||
function buildSecurityIssues(input: {
|
||||
readonly activeUsers: number;
|
||||
readonly mfaCoverage: number;
|
||||
readonly loginFailures: number;
|
||||
readonly pendingMagicLinks: number;
|
||||
readonly activeSessions: number;
|
||||
}): string[] {
|
||||
const issues: string[] = [];
|
||||
if (input.activeUsers > 0 && input.mfaCoverage < 1) issues.push("admin.tenantSecurity.issues.mfaMissing");
|
||||
if (input.loginFailures > 0) issues.push("admin.tenantSecurity.issues.loginFailures");
|
||||
if (input.loginFailures >= 3) issues.push("admin.tenantSecurity.issues.loginSpike");
|
||||
if (input.pendingMagicLinks > 0) issues.push("admin.tenantSecurity.issues.pendingMagicLinks");
|
||||
if (input.activeUsers > 0 && input.activeSessions === 0) issues.push("admin.tenantSecurity.issues.noActiveSessions");
|
||||
return issues;
|
||||
}
|
||||
|
||||
function isLoginEvent(action: string): boolean {
|
||||
const value = action.toLowerCase();
|
||||
return value.includes("login") || value.includes("mfa") || value.includes("magic") || value.includes("session");
|
||||
}
|
||||
|
||||
function maskIp(ip: string): string {
|
||||
if (ip.includes(":")) {
|
||||
const parts = ip.split(":").filter(Boolean);
|
||||
return parts.length <= 2 ? `${parts[0] ?? "****"}:****` : `${parts.slice(0, 2).join(":")}:****`;
|
||||
}
|
||||
const parts = ip.split(".");
|
||||
if (parts.length !== 4) return "****";
|
||||
return `${parts[0]}.${parts[1]}.${parts[2]}.***`;
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildWebhookInboxVM, resolveWebhookProvider, resolveWebhookStatus, type WebhookInboxInputRow } from "./webhook-inbox.vm.js";
|
||||
|
||||
function row(overrides: Partial<WebhookInboxInputRow>): WebhookInboxInputRow {
|
||||
return {
|
||||
id: "attempt_1",
|
||||
eventId: "event_1",
|
||||
eventName: "billing.mollie.webhook",
|
||||
eventResource: "billing",
|
||||
tenantId: "tenant_1",
|
||||
userId: null,
|
||||
endpoint: "https://api.hivegrid.de/webhooks/mollie",
|
||||
success: null,
|
||||
status: null,
|
||||
message: null,
|
||||
body: null,
|
||||
createdAt: "2026-07-09T10:00:00.000Z",
|
||||
startedAt: null,
|
||||
finishedAt: null,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("webhook inbox view-model", () => {
|
||||
it("classifies providers from event name and endpoint", () => {
|
||||
expect(resolveWebhookProvider(row({ endpoint: "https://example.test/lago", eventName: "billing.invoice" }))).toBe("lago");
|
||||
expect(resolveWebhookProvider(row({ endpoint: "https://example.test/webhook", eventName: "mailjet.event" }))).toBe("mailjet");
|
||||
expect(resolveWebhookProvider(row({ endpoint: "https://api.hivegrid.de/v1/events", eventName: "public.api.webhook" }))).toBe("api");
|
||||
});
|
||||
|
||||
it("classifies delivery states from provider attempt fields", () => {
|
||||
expect(resolveWebhookStatus(row({ success: true, status: 200 }))).toBe("delivered");
|
||||
expect(resolveWebhookStatus(row({ success: false, status: 500 }))).toBe("failed");
|
||||
expect(resolveWebhookStatus(row({ startedAt: "2026-07-09T10:00:00.000Z", finishedAt: null }))).toBe("pending");
|
||||
expect(resolveWebhookStatus(row({}))).toBe("unknown");
|
||||
});
|
||||
|
||||
it("builds summary counts and sorts failed attempts first", () => {
|
||||
const vm = buildWebhookInboxVM({
|
||||
rows: [
|
||||
row({ id: "delivered", success: true, status: 204, createdAt: "2026-07-09T10:03:00.000Z" }),
|
||||
row({ id: "pending", startedAt: "2026-07-09T10:02:00.000Z", createdAt: "2026-07-09T10:02:00.000Z" }),
|
||||
row({ id: "failed", success: false, status: 500, message: "Timeout", createdAt: "2026-07-09T10:01:00.000Z" }),
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.summary).toMatchObject({ totalCount: 3, failedCount: 1, pendingCount: 1, deliveredCount: 1 });
|
||||
expect(vm.data.rows.map((item) => item.id)).toEqual(["failed", "pending", "delivered"]);
|
||||
});
|
||||
});
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type WebhookInboxStatus = "delivered" | "failed" | "pending" | "unknown";
|
||||
export type WebhookInboxProvider = "mollie" | "lago" | "mailjet" | "api" | "unknown";
|
||||
|
||||
export type WebhookInboxInputRow = {
|
||||
readonly id: string;
|
||||
readonly eventId: string;
|
||||
readonly eventName: string;
|
||||
readonly eventResource: string | null;
|
||||
readonly tenantId: string | null;
|
||||
readonly userId: string | null;
|
||||
readonly endpoint: string;
|
||||
readonly success: boolean | null;
|
||||
readonly status: number | null;
|
||||
readonly message: string | null;
|
||||
readonly body: string | null;
|
||||
readonly createdAt: string;
|
||||
readonly startedAt: string | null;
|
||||
readonly finishedAt: string | null;
|
||||
};
|
||||
|
||||
export type WebhookInboxRow = WebhookInboxInputRow & {
|
||||
readonly provider: WebhookInboxProvider;
|
||||
readonly providerLabelKey: string;
|
||||
readonly deliveryStatus: WebhookInboxStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly statusTone: "success" | "danger" | "warning" | "neutral";
|
||||
readonly payloadPreview: string;
|
||||
readonly durationMs: number | null;
|
||||
};
|
||||
|
||||
export type WebhookInboxSummary = {
|
||||
readonly totalCount: number;
|
||||
readonly failedCount: number;
|
||||
readonly pendingCount: number;
|
||||
readonly deliveredCount: number;
|
||||
readonly unknownCount: number;
|
||||
};
|
||||
|
||||
export type WebhookInboxData = {
|
||||
readonly rows: readonly WebhookInboxRow[];
|
||||
readonly summary: WebhookInboxSummary;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
};
|
||||
|
||||
export type WebhookInboxVM = VMState<WebhookInboxData>;
|
||||
|
||||
export function buildWebhookInboxVM(input: { readonly rows: readonly WebhookInboxInputRow[] }): WebhookInboxVM {
|
||||
if (input.rows.length === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
const rows = input.rows.map((row): WebhookInboxRow => {
|
||||
const provider = resolveWebhookProvider(row);
|
||||
const deliveryStatus = resolveWebhookStatus(row);
|
||||
return {
|
||||
...row,
|
||||
provider,
|
||||
providerLabelKey: `admin.webhooks.providers.${provider}`,
|
||||
deliveryStatus,
|
||||
statusLabelKey: `admin.webhooks.status.${deliveryStatus}`,
|
||||
statusTone: webhookStatusTone(deliveryStatus),
|
||||
payloadPreview: buildPayloadPreview(row.body),
|
||||
durationMs: calculateDurationMs(row.startedAt, row.finishedAt),
|
||||
};
|
||||
});
|
||||
|
||||
const sortedRows = [...rows].sort((a, b) => webhookAttentionRank(b) - webhookAttentionRank(a) || b.createdAt.localeCompare(a.createdAt));
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: sortedRows,
|
||||
summary: {
|
||||
totalCount: rows.length,
|
||||
failedCount: rows.filter((row) => row.deliveryStatus === "failed").length,
|
||||
pendingCount: rows.filter((row) => row.deliveryStatus === "pending").length,
|
||||
deliveredCount: rows.filter((row) => row.deliveryStatus === "delivered").length,
|
||||
unknownCount: rows.filter((row) => row.deliveryStatus === "unknown").length,
|
||||
},
|
||||
emptyHeadlineKey: "admin.webhooks.empty.headline",
|
||||
emptyBodyKey: "admin.webhooks.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveWebhookProvider(row: Pick<WebhookInboxInputRow, "endpoint" | "eventName">): WebhookInboxProvider {
|
||||
const haystack = `${row.endpoint} ${row.eventName}`.toLowerCase();
|
||||
if (haystack.includes("mollie")) return "mollie";
|
||||
if (haystack.includes("lago")) return "lago";
|
||||
if (haystack.includes("mailjet")) return "mailjet";
|
||||
if (haystack.includes("/api/") || haystack.includes("api.")) return "api";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function resolveWebhookStatus(row: Pick<WebhookInboxInputRow, "success" | "status" | "startedAt" | "finishedAt">): WebhookInboxStatus {
|
||||
if (row.success === true || (row.status !== null && row.status >= 200 && row.status < 300)) return "delivered";
|
||||
if (row.success === false || (row.status !== null && row.status >= 400)) return "failed";
|
||||
if (row.startedAt !== null && row.finishedAt === null) return "pending";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function webhookStatusTone(status: WebhookInboxStatus): WebhookInboxRow["statusTone"] {
|
||||
if (status === "delivered") return "success";
|
||||
if (status === "failed") return "danger";
|
||||
if (status === "pending") return "warning";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
function buildPayloadPreview(body: string | null): string {
|
||||
const value = (body ?? "").trim();
|
||||
if (!value) return "";
|
||||
return value.length > 180 ? `${value.slice(0, 180)}...` : value;
|
||||
}
|
||||
|
||||
function calculateDurationMs(startedAt: string | null, finishedAt: string | null): number | null {
|
||||
if (!startedAt || !finishedAt) return null;
|
||||
const started = Date.parse(startedAt);
|
||||
const finished = Date.parse(finishedAt);
|
||||
if (!Number.isFinite(started) || !Number.isFinite(finished) || finished < started) return null;
|
||||
return finished - started;
|
||||
}
|
||||
|
||||
function webhookAttentionRank(row: WebhookInboxRow): number {
|
||||
if (row.deliveryStatus === "failed") return 30;
|
||||
if (row.deliveryStatus === "pending") return 20;
|
||||
if (row.deliveryStatus === "unknown") return 10;
|
||||
return 0;
|
||||
}
|
||||
+2
-2
@@ -15,7 +15,7 @@ describe("buildIntegrationCatalogVM", () => {
|
||||
categoryKey: integrationCategoryKey("erp"),
|
||||
connectionType: "rest_api",
|
||||
connectionCount: 2,
|
||||
detailHref: "/acme/integrations/sample-data-sync",
|
||||
detailHref: "/acme/settings/integrations/sample-data-sync",
|
||||
};
|
||||
|
||||
it("exposes connection count + category key, never credentials", () => {
|
||||
@@ -42,7 +42,7 @@ describe("buildConnectionDetailVM", () => {
|
||||
healthMessageKey: "integrations.health.active",
|
||||
lastHealthCheckIso: new Date("2026-06-01").toISOString(),
|
||||
tokenExpiresIso: null,
|
||||
syncsHref: "/acme/integrations/sample-data-sync/dc1/syncs",
|
||||
syncsHref: "/acme/settings/integrations/sample-data-sync/dc1/syncs",
|
||||
};
|
||||
|
||||
it("carries status + health metadata but never credential values", () => {
|
||||
|
||||
+5
-2
@@ -17,8 +17,8 @@ export interface ConnectionRow {
|
||||
readonly healthMessageKey: string | null;
|
||||
readonly lastHealthCheckIso: string | null;
|
||||
readonly tokenExpiresIso: string | null;
|
||||
/** Internal route to this connection's sync history. */
|
||||
readonly syncsHref: string;
|
||||
/** Internal route to this connection's sync history, or null when unsupported. */
|
||||
readonly syncsHref: string | null;
|
||||
}
|
||||
|
||||
export interface ConnectionDetailData {
|
||||
@@ -29,6 +29,7 @@ export interface ConnectionDetailData {
|
||||
readonly canDisconnect: boolean;
|
||||
readonly canManualSync: boolean;
|
||||
readonly connectHref: string;
|
||||
readonly projectImportHref: string | null;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
@@ -47,6 +48,7 @@ export interface BuildConnectionDetailVMInput {
|
||||
readonly canDisconnect: boolean;
|
||||
readonly canManualSync: boolean;
|
||||
readonly connectHref: string;
|
||||
readonly projectImportHref?: string | null;
|
||||
}
|
||||
|
||||
export function buildConnectionDetailVM(input: BuildConnectionDetailVMInput): ConnectionDetailVM {
|
||||
@@ -60,6 +62,7 @@ export function buildConnectionDetailVM(input: BuildConnectionDetailVMInput): Co
|
||||
canDisconnect: input.canDisconnect,
|
||||
canManualSync: input.canManualSync,
|
||||
connectHref: input.connectHref,
|
||||
projectImportHref: input.projectImportHref ?? null,
|
||||
emptyHeadlineKey: "integrations.connections.empty.headline",
|
||||
emptyBodyKey: "integrations.connections.empty.body",
|
||||
},
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildKwpProjectImportVM, type KwpProjectImportData } from "./kwp-project-import.vm.js";
|
||||
|
||||
const fixture: KwpProjectImportData = {
|
||||
tenantSlug: "acme",
|
||||
backHref: "/acme/settings/integrations/kwp",
|
||||
connectionId: "connection_1",
|
||||
connections: [{ id: "connection_1", label: "KWP Geerkens" }],
|
||||
query: " 4711 ",
|
||||
results: [{ externalProjectNumber: "4711", name: "Umbau", status: 2, statusLabel: "Auftrag" }],
|
||||
preview: null,
|
||||
pipelines: [],
|
||||
localProjects: [],
|
||||
boundProjects: [],
|
||||
capability: {
|
||||
status: "active",
|
||||
reasonCode: null,
|
||||
revision: 1,
|
||||
observedFingerprint: null,
|
||||
diff: null,
|
||||
},
|
||||
catalog: {
|
||||
status: "syncing",
|
||||
discoveredCount: 50_000,
|
||||
hydratedCount: 120,
|
||||
lastDiscoveryAt: "2026-07-24T12:00:00.000Z",
|
||||
lastCompletedAt: null,
|
||||
},
|
||||
canWrite: true,
|
||||
feedbackKey: null,
|
||||
};
|
||||
|
||||
describe("buildKwpProjectImportVM", () => {
|
||||
it("normalizes the targeted query without inventing a full import", () => {
|
||||
expect(buildKwpProjectImportVM(fixture)).toMatchObject({
|
||||
status: "ready",
|
||||
data: {
|
||||
query: "4711",
|
||||
connectionId: "connection_1",
|
||||
results: [{ externalProjectNumber: "4711" }],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("renders the connection empty state without provider data", () => {
|
||||
expect(buildKwpProjectImportVM({ ...fixture, connections: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
});
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type KwpProjectImportConnectionVM = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
};
|
||||
|
||||
export type KwpProjectSearchRowVM = {
|
||||
readonly externalProjectNumber: string;
|
||||
readonly name: string;
|
||||
readonly status: number;
|
||||
readonly statusLabel: string;
|
||||
};
|
||||
|
||||
export type KwpProjectImportCandidateVM = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly email: string | null;
|
||||
readonly addressLabel: string | null;
|
||||
readonly reason: "external_binding" | "exact_email" | "exact_name_and_address";
|
||||
};
|
||||
|
||||
export type KwpAddressPersonVM = {
|
||||
readonly externalContactId: string;
|
||||
readonly label: string;
|
||||
readonly email: string | null;
|
||||
readonly phone: string | null;
|
||||
};
|
||||
|
||||
export type KwpAddressRoleVM = {
|
||||
readonly role: "project" | "invoice" | "client";
|
||||
readonly addressCode: string;
|
||||
readonly label: string;
|
||||
readonly addressLabel: string;
|
||||
readonly email: string | null;
|
||||
readonly candidates: readonly KwpProjectImportCandidateVM[];
|
||||
readonly people: readonly KwpAddressPersonVM[];
|
||||
};
|
||||
|
||||
export type KwpPipelineOptionVM = {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly stages: readonly { readonly id: string; readonly label: string }[];
|
||||
};
|
||||
|
||||
export type KwpLocalProjectOptionVM = {
|
||||
readonly id: string;
|
||||
readonly projectNumber: string;
|
||||
readonly name: string;
|
||||
readonly pipelineId: string;
|
||||
readonly stageId: string;
|
||||
readonly startDate: string | null;
|
||||
readonly orderValue: string | null;
|
||||
readonly updatedAt: string;
|
||||
};
|
||||
|
||||
export type KwpBoundProjectVM = {
|
||||
readonly bindingId: string;
|
||||
readonly projectId: string;
|
||||
readonly externalProjectNumber: string;
|
||||
readonly projectNumber: string;
|
||||
readonly name: string;
|
||||
readonly state: "active" | "quarantined" | "missing";
|
||||
readonly revision: number;
|
||||
readonly projectUpdatedAt: string;
|
||||
readonly canRestore: boolean;
|
||||
};
|
||||
|
||||
export type KwpProjectImportPreviewVM = {
|
||||
readonly externalProjectNumber: string;
|
||||
readonly name: string;
|
||||
readonly status: number;
|
||||
readonly statusLabel: string;
|
||||
readonly startDate: string | null;
|
||||
readonly orderValue: number | null;
|
||||
readonly routing: { readonly pipelineId: string; readonly stageId: string; readonly revision: number } | null;
|
||||
readonly addresses: readonly KwpAddressRoleVM[];
|
||||
};
|
||||
|
||||
export type KwpCapabilityVM = {
|
||||
readonly status: "active" | "paused";
|
||||
readonly reasonCode: string | null;
|
||||
readonly revision: number;
|
||||
readonly observedFingerprint: string | null;
|
||||
readonly diff: {
|
||||
readonly added: readonly string[];
|
||||
readonly removed: readonly string[];
|
||||
readonly changed: readonly string[];
|
||||
readonly truncated: boolean;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type KwpProjectCatalogVM = {
|
||||
readonly status: "pending" | "syncing" | "ready" | "partial" | "paused";
|
||||
readonly discoveredCount: number;
|
||||
readonly hydratedCount: number;
|
||||
readonly lastDiscoveryAt: string | null;
|
||||
readonly lastCompletedAt: string | null;
|
||||
};
|
||||
|
||||
export type KwpProjectImportData = {
|
||||
readonly tenantSlug: string;
|
||||
readonly backHref: string;
|
||||
readonly connectionId: string;
|
||||
readonly connections: readonly KwpProjectImportConnectionVM[];
|
||||
readonly query: string;
|
||||
readonly results: readonly KwpProjectSearchRowVM[];
|
||||
readonly preview: KwpProjectImportPreviewVM | null;
|
||||
readonly pipelines: readonly KwpPipelineOptionVM[];
|
||||
readonly localProjects: readonly KwpLocalProjectOptionVM[];
|
||||
readonly boundProjects: readonly KwpBoundProjectVM[];
|
||||
readonly capability: KwpCapabilityVM;
|
||||
readonly catalog: KwpProjectCatalogVM;
|
||||
readonly canWrite: boolean;
|
||||
readonly feedbackKey: string | null;
|
||||
};
|
||||
|
||||
export type KwpProjectImportVM = VMState<KwpProjectImportData>;
|
||||
|
||||
export function buildKwpProjectImportVM(input: KwpProjectImportData): KwpProjectImportVM {
|
||||
const connections = input.connections
|
||||
.filter((row) => row.id.trim() && row.label.trim())
|
||||
.map((row) => ({ id: row.id.trim(), label: row.label.trim() }));
|
||||
if (connections.length === 0) return { status: "empty" };
|
||||
const selectedConnection = connections.some((row) => row.id === input.connectionId)
|
||||
? input.connectionId
|
||||
: connections[0]!.id;
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...input,
|
||||
connectionId: selectedConnection,
|
||||
connections,
|
||||
query: input.query.trim(),
|
||||
results: input.results.slice(0, 500),
|
||||
},
|
||||
};
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildKwpSetupVM } from "./kwp-setup.vm.js";
|
||||
|
||||
describe("buildKwpSetupVM", () => {
|
||||
it("builds a credential-free mandant selection model", () => {
|
||||
const vm = buildKwpSetupVM({
|
||||
mode: "mandant",
|
||||
tenantSlug: "acme",
|
||||
settingsHref: "/acme/settings/integrations/kwp",
|
||||
connectionId: "connection-1",
|
||||
connectionVersion: "2026-07-21T12:00:00.000Z",
|
||||
customerCode: "customer-1",
|
||||
discoveryMode: "available",
|
||||
mandants: [{ id: 1, code: "001", label: "Acme GmbH" }],
|
||||
feedback: null,
|
||||
});
|
||||
|
||||
expect(vm).toEqual({
|
||||
status: "ready",
|
||||
data: expect.objectContaining({
|
||||
mode: "mandant",
|
||||
customerCode: "customer-1",
|
||||
mandants: [{ id: 1, code: "001", label: "Acme GmbH" }],
|
||||
}),
|
||||
});
|
||||
expect(JSON.stringify(vm)).not.toMatch(/accessToken|refreshToken|clientSecret/u);
|
||||
});
|
||||
|
||||
it("copies option arrays so callers cannot mutate the source collection", () => {
|
||||
const tenants = [{ id: "tenant-1", name: "Acme", slug: "acme", setupHref: "/integrations/kwp/setup?tenant=acme" }];
|
||||
const vm = buildKwpSetupVM({
|
||||
mode: "entry",
|
||||
authenticated: true,
|
||||
loginHref: "/login",
|
||||
tenants,
|
||||
feedback: null,
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || vm.data.mode !== "entry") throw new Error("unexpected VM state");
|
||||
expect(vm.data.tenants).not.toBe(tenants);
|
||||
});
|
||||
});
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type KwpSetupFeedback = "oauth-error" | "configuration-error" | "selection-error" | "selection-expired" | null;
|
||||
|
||||
export type KwpSetupTenantOption = {
|
||||
readonly id: string;
|
||||
readonly name: string;
|
||||
readonly slug: string;
|
||||
readonly setupHref: string;
|
||||
};
|
||||
|
||||
export type KwpMandantOption = {
|
||||
readonly id: number;
|
||||
readonly code: string;
|
||||
readonly label: string;
|
||||
};
|
||||
|
||||
export type KwpSetupData =
|
||||
| {
|
||||
readonly mode: "entry";
|
||||
readonly authenticated: boolean;
|
||||
readonly loginHref: string;
|
||||
readonly tenants: readonly KwpSetupTenantOption[];
|
||||
readonly feedback: KwpSetupFeedback;
|
||||
}
|
||||
| {
|
||||
readonly mode: "oauth";
|
||||
readonly tenantSlug: string;
|
||||
readonly settingsHref: string;
|
||||
readonly feedback: KwpSetupFeedback;
|
||||
}
|
||||
| {
|
||||
readonly mode: "mandant";
|
||||
readonly tenantSlug: string;
|
||||
readonly settingsHref: string;
|
||||
readonly connectionId: string;
|
||||
readonly connectionVersion: string;
|
||||
readonly customerCode: string;
|
||||
readonly discoveryMode: "available" | "manual";
|
||||
readonly mandants: readonly KwpMandantOption[];
|
||||
readonly feedback: KwpSetupFeedback;
|
||||
};
|
||||
|
||||
export type KwpSetupVM = VMState<KwpSetupData>;
|
||||
|
||||
export function buildKwpSetupVM(data: KwpSetupData): KwpSetupVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...data,
|
||||
...(data.mode === "entry" ? { tenants: [...data.tenants] } : {}),
|
||||
...(data.mode === "mandant" ? { mandants: [...data.mandants] } : {}),
|
||||
} as KwpSetupData,
|
||||
};
|
||||
}
|
||||
+8
-11
@@ -1,19 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAuditListVM,
|
||||
deriveAuditActorKind,
|
||||
type AuditListFilterState,
|
||||
type AuditListInputRow,
|
||||
type AuditListPagination,
|
||||
} from "../index.js";
|
||||
import { buildAuditListVM, deriveAuditActorKind, type AuditListFilterState, type AuditListInputRow, type AuditListPagination } from "../index.js";
|
||||
|
||||
const filter: AuditListFilterState = {
|
||||
from: null,
|
||||
to: null,
|
||||
tenantId: null,
|
||||
actorType: null,
|
||||
actorId: null,
|
||||
action: null,
|
||||
outcome: null,
|
||||
targetType: null,
|
||||
targetId: null,
|
||||
};
|
||||
|
||||
const pagination: AuditListPagination = { page: 1, pageSize: 25, total: 1, totalPages: 1 };
|
||||
@@ -55,8 +52,8 @@ describe("actorKindKeySuffix camelCase mapping (audit-list.ts:107)", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("actorLabelFor id fallback (audit-list.ts:133)", () => {
|
||||
it("uses the actor id when no email is present and surfaces it in summaryParams", () => {
|
||||
describe("actorLabelFor readable fallback (audit-list.ts:133)", () => {
|
||||
it("uses the actor kind instead of exposing a technical id when no human label is present", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row({ actorEmail: null, actorId: " u9 " })],
|
||||
filter,
|
||||
@@ -64,8 +61,8 @@ describe("actorLabelFor id fallback (audit-list.ts:133)", () => {
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.actorLabel).toBe("u9");
|
||||
expect(vm.data.rows[0]?.summaryParams.actor).toBe("u9");
|
||||
expect(vm.data.rows[0]?.actorLabel).toBe("audit.actorKind.user");
|
||||
expect(vm.data.rows[0]?.summaryParams.actor).toBe("audit.actorKind.user");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+53
-7
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildAuditListVM,
|
||||
deriveAuditActorKind,
|
||||
deriveAuditActionLabelKey,
|
||||
deriveAuditSummaryKey,
|
||||
buildAuditFieldDiffs,
|
||||
toAuditListModel,
|
||||
@@ -16,10 +17,13 @@ const I18N_KEY = /^[a-zA-Z][a-zA-Z0-9]*(?:[.-][a-zA-Z0-9]+)*$/;
|
||||
const filter: AuditListFilterState = {
|
||||
from: null,
|
||||
to: null,
|
||||
tenantId: null,
|
||||
actorType: null,
|
||||
actorId: null,
|
||||
action: null,
|
||||
outcome: null,
|
||||
targetType: null,
|
||||
targetId: null,
|
||||
};
|
||||
|
||||
const pagination: AuditListPagination = { page: 1, pageSize: 25, total: 0, totalPages: 1 };
|
||||
@@ -59,11 +63,30 @@ describe("deriveAuditSummaryKey", () => {
|
||||
expect(deriveAuditSummaryKey("weird.thing.happened")).toBe("audit.summary.generic");
|
||||
});
|
||||
|
||||
it("describes login results without exposing the event code", () => {
|
||||
expect(deriveAuditSummaryKey("admin.login.fallback.success")).toBe("audit.summary.login");
|
||||
expect(deriveAuditSummaryKey("admin.login.fallback.failure")).toBe("audit.summary.loginFailed");
|
||||
expect(deriveAuditSummaryKey("admin.login.fallback.blocked")).toBe("audit.summary.loginBlocked");
|
||||
});
|
||||
|
||||
it("always returns a valid i18n key", () => {
|
||||
expect(deriveAuditSummaryKey("anything")).toMatch(I18N_KEY);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveAuditActionLabelKey", () => {
|
||||
it("maps known admin events and common action verbs to readable labels", () => {
|
||||
expect(deriveAuditActionLabelKey("admin.login.fallback.success")).toBe("audit.action.adminFallbackLoginSuccess");
|
||||
expect(deriveAuditActionLabelKey("admin.login.sso.failure")).toBe("audit.action.adminSsoLoginFailed");
|
||||
expect(deriveAuditActionLabelKey("kontakt.updated")).toBe("audit.action.updated");
|
||||
expect(deriveAuditActionLabelKey("weird.thing.happened")).toBe("audit.action.performed");
|
||||
});
|
||||
|
||||
it("always returns a valid i18n key", () => {
|
||||
expect(deriveAuditActionLabelKey("anything")).toMatch(I18N_KEY);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildAuditListVM", () => {
|
||||
it("returns a ready empty-state with i18n keys when there are no rows", () => {
|
||||
const vm = buildAuditListVM({ rows: [], filter, pagination, canExport: true });
|
||||
@@ -77,18 +100,20 @@ describe("buildAuditListVM", () => {
|
||||
|
||||
it("maps actor-kind marker, summary key and detail flag per row", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [row(), row({ id: "a2", actorType: "system", actorEmail: null, actorId: null, action: "x.y", hasMetadata: false })],
|
||||
rows: [row({ actorName: "Akeshan Example" }), row({ id: "a2", actorType: "system", actorEmail: null, actorId: null, action: "x.y", hasMetadata: false })],
|
||||
filter,
|
||||
pagination: { ...pagination, total: 2 },
|
||||
canExport: false,
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
const [first, second] = vm.data.rows;
|
||||
expect(first?.tenantId).toBeNull();
|
||||
expect(first?.actorKind).toBe("user");
|
||||
expect(first?.actorKindLabelKey).toBe("audit.actorKind.user");
|
||||
expect(first?.actorLabel).toBe("akeshan@example.com");
|
||||
expect(first?.actorLabel).toBe("Akeshan Example");
|
||||
expect(first?.actionLabelKey).toBe("audit.action.created");
|
||||
expect(first?.summaryKey).toBe("audit.summary.created");
|
||||
expect(first?.summaryParams.target).toBe("Kontakt#k1");
|
||||
expect(first?.summaryParams.target).toBe("Kontakt");
|
||||
expect(first?.hasDetail).toBe(true);
|
||||
// system actor without email/id falls back to the marker i18n key
|
||||
expect(second?.actorKind).toBe("system");
|
||||
@@ -110,11 +135,31 @@ describe("buildAuditFieldDiffs / persisted summary (AK-P3 DoD 2)", () => {
|
||||
expect(vm.data?.rows[1]?.summaryKey).toMatch(I18N_KEY);
|
||||
});
|
||||
|
||||
it("drops persisted summaries that repeat technical ids or action codes", () => {
|
||||
const vm = buildAuditListVM({
|
||||
rows: [
|
||||
row({
|
||||
actorName: "Raffael Sheikh",
|
||||
actorId: "cms2q01t70000zz4ymxuk5hba",
|
||||
action: "admin.login.fallback.success",
|
||||
summaryText: "cms2q01t70000zz4ymxuk5hba: admin.login.fallback.success",
|
||||
}),
|
||||
],
|
||||
filter,
|
||||
pagination,
|
||||
canExport: true,
|
||||
});
|
||||
|
||||
expect(vm.data?.rows[0]).toMatchObject({
|
||||
actorLabel: "Raffael Sheikh",
|
||||
actionLabelKey: "audit.action.adminFallbackLoginSuccess",
|
||||
summaryText: null,
|
||||
summaryKey: "audit.summary.login",
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a sorted field-by-field diff with masking for redacted values", () => {
|
||||
const diffs = buildAuditFieldDiffs(
|
||||
{ name: "Alt GmbH", apiKey: "[REDACTED]", status: "kontakt" },
|
||||
{ name: "Neu GmbH", apiKey: "[REDACTED]", plz: "10115" }
|
||||
);
|
||||
const diffs = buildAuditFieldDiffs({ name: "Alt GmbH", apiKey: "[REDACTED]", status: "kontakt" }, { name: "Neu GmbH", apiKey: "[REDACTED]", plz: "10115" });
|
||||
expect(diffs.map((entry) => entry.field)).toEqual(["apiKey", "name", "plz", "status"]);
|
||||
const masked = diffs.find((entry) => entry.field === "apiKey");
|
||||
expect(masked).toEqual({ field: "apiKey", before: null, after: null, masked: true });
|
||||
@@ -154,6 +199,7 @@ describe("buildAuditFieldDiffs / persisted summary (AK-P3 DoD 2)", () => {
|
||||
expect(first?.hasDetail).toBe(true);
|
||||
expect(vm.data?.rows[1]?.diff).toEqual([]);
|
||||
expect(vm.data?.rows[1]?.hasDetail).toBe(false);
|
||||
expect(vm.data?.summary).toMatchObject({ total: 0, pageRows: 2, failedRows: 0, detailRows: 1 });
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready VM");
|
||||
const model = toAuditListModel(vm.data);
|
||||
|
||||
+140
-15
@@ -31,12 +31,15 @@ export type AuditFieldDiff = {
|
||||
export type AuditListRow = {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly tenantId: string | null;
|
||||
readonly actorKind: AuditActorKind;
|
||||
/** i18n key for the actor-kind marker label, e.g. `audit.actorKind.user`. */
|
||||
readonly actorKindLabelKey: string;
|
||||
/** Best human label for the actor (email > id > marker fallback key). */
|
||||
/** Best human label for the actor (resolved name > email > actor-kind marker). */
|
||||
readonly actorLabel: string;
|
||||
readonly action: string;
|
||||
/** Localized, human-readable action label shown instead of the event code. */
|
||||
readonly actionLabelKey: string;
|
||||
/** Persisted German summary line — preferred over the derived template. */
|
||||
readonly summaryText: string | null;
|
||||
/** i18n key of the German summary template, resolved with {@link summaryParams}. */
|
||||
@@ -56,10 +59,13 @@ export type AuditListRow = {
|
||||
export type AuditListFilterState = {
|
||||
readonly from: string | null;
|
||||
readonly to: string | null;
|
||||
readonly tenantId: string | null;
|
||||
readonly actorType: string | null;
|
||||
readonly actorId: string | null;
|
||||
readonly action: string | null;
|
||||
readonly outcome: string | null;
|
||||
readonly targetType: string | null;
|
||||
readonly targetId: string | null;
|
||||
};
|
||||
|
||||
export type AuditListPagination = {
|
||||
@@ -73,6 +79,13 @@ export interface AuditListData {
|
||||
readonly rows: readonly AuditListRow[];
|
||||
readonly filter: AuditListFilterState;
|
||||
readonly pagination: AuditListPagination;
|
||||
readonly summary: {
|
||||
readonly total: number;
|
||||
readonly pageRows: number;
|
||||
readonly failedRows: number;
|
||||
readonly detailRows: number;
|
||||
readonly adminRows: number;
|
||||
};
|
||||
readonly canExport: boolean;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
@@ -84,7 +97,10 @@ export type AuditListVM = VMState<AuditListData>;
|
||||
export interface AuditListInputRow {
|
||||
readonly id: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly tenantId?: string | null;
|
||||
readonly actorType: string | null;
|
||||
/** Name resolved from User/AdminUser by the server read path. */
|
||||
readonly actorName?: string | null;
|
||||
readonly actorEmail: string | null;
|
||||
readonly actorId: string | null;
|
||||
readonly action: string;
|
||||
@@ -108,15 +124,7 @@ export interface BuildAuditListVMInput {
|
||||
readonly canExport: boolean;
|
||||
}
|
||||
|
||||
const KNOWN_ACTOR_KINDS: ReadonlySet<AuditActorKind> = new Set([
|
||||
"user",
|
||||
"admin",
|
||||
"system",
|
||||
"api_key",
|
||||
"plugin",
|
||||
"automation",
|
||||
"ki_agent",
|
||||
]);
|
||||
const KNOWN_ACTOR_KINDS: ReadonlySet<AuditActorKind> = new Set(["user", "admin", "system", "api_key", "plugin", "automation", "ki_agent"]);
|
||||
|
||||
/** Maps the raw `actorType` onto a normalized {@link AuditActorKind}. */
|
||||
export function deriveAuditActorKind(actorType: string | null | undefined): AuditActorKind {
|
||||
@@ -147,6 +155,15 @@ const SUMMARY_ACTION_VERBS: ReadonlyArray<readonly [RegExp, string]> = [
|
||||
* generic line so unmapped actions still render a readable sentence.
|
||||
*/
|
||||
export function deriveAuditSummaryKey(action: string): string {
|
||||
const tokens = actionTokens(action);
|
||||
if (tokens.includes("login") || (tokens.includes("signed") && tokens.includes("in"))) {
|
||||
if (tokens.some((token) => token === "failure" || token === "failed")) return "audit.summary.loginFailed";
|
||||
if (tokens.some((token) => token === "blocked" || token === "denied")) return "audit.summary.loginBlocked";
|
||||
return "audit.summary.login";
|
||||
}
|
||||
if (tokens.includes("logout") || (tokens.includes("signed") && tokens.includes("out"))) {
|
||||
return "audit.summary.logout";
|
||||
}
|
||||
for (const [pattern, verb] of SUMMARY_ACTION_VERBS) {
|
||||
if (pattern.test(action)) return `audit.summary.${verb}`;
|
||||
}
|
||||
@@ -154,11 +171,107 @@ export function deriveAuditSummaryKey(action: string): string {
|
||||
}
|
||||
|
||||
function actorLabelFor(row: AuditListInputRow, kind: AuditActorKind): string {
|
||||
if (row.actorName && row.actorName.trim().length > 0) return row.actorName.trim();
|
||||
if (row.actorEmail && row.actorEmail.trim().length > 0) return row.actorEmail.trim();
|
||||
if (row.actorId && row.actorId.trim().length > 0) return row.actorId.trim();
|
||||
return `audit.actorKind.${actorKindKeySuffix(kind)}`;
|
||||
}
|
||||
|
||||
const EXACT_ACTION_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
"admin.login.fallback.success": "audit.action.adminFallbackLoginSuccess",
|
||||
"admin.login.fallback.failure": "audit.action.adminFallbackLoginFailed",
|
||||
"admin.login.sso.success": "audit.action.adminSsoLoginSuccess",
|
||||
"admin.login.sso.failure": "audit.action.adminSsoLoginFailed",
|
||||
"auth.login.success": "audit.action.loginSuccess",
|
||||
"audit.exported": "audit.action.auditExported",
|
||||
};
|
||||
|
||||
const ACTION_TOKEN_LABEL_KEYS: Readonly<Record<string, string>> = {
|
||||
created: "audit.action.created",
|
||||
create: "audit.action.created",
|
||||
updated: "audit.action.updated",
|
||||
update: "audit.action.updated",
|
||||
saved: "audit.action.updated",
|
||||
changed: "audit.action.updated",
|
||||
deleted: "audit.action.deleted",
|
||||
delete: "audit.action.deleted",
|
||||
removed: "audit.action.deleted",
|
||||
archived: "audit.action.archived",
|
||||
archive: "audit.action.archived",
|
||||
restored: "audit.action.restored",
|
||||
restore: "audit.action.restored",
|
||||
reactivated: "audit.action.restored",
|
||||
exported: "audit.action.exported",
|
||||
export: "audit.action.exported",
|
||||
assigned: "audit.action.assigned",
|
||||
unassigned: "audit.action.unassigned",
|
||||
connected: "audit.action.connected",
|
||||
disconnected: "audit.action.disconnected",
|
||||
completed: "audit.action.completed",
|
||||
approved: "audit.action.approved",
|
||||
rejected: "audit.action.rejected",
|
||||
uploaded: "audit.action.uploaded",
|
||||
downloaded: "audit.action.downloaded",
|
||||
dispatched: "audit.action.sent",
|
||||
sent: "audit.action.sent",
|
||||
queued: "audit.action.queued",
|
||||
received: "audit.action.received",
|
||||
requested: "audit.action.requested",
|
||||
paused: "audit.action.paused",
|
||||
resumed: "audit.action.resumed",
|
||||
retried: "audit.action.retried",
|
||||
activated: "audit.action.activated",
|
||||
deactivated: "audit.action.deactivated",
|
||||
cancelled: "audit.action.cancelled",
|
||||
canceled: "audit.action.cancelled",
|
||||
blocked: "audit.action.blocked",
|
||||
denied: "audit.action.blocked",
|
||||
failure: "audit.action.failed",
|
||||
failed: "audit.action.failed",
|
||||
read: "audit.action.viewed",
|
||||
viewed: "audit.action.viewed",
|
||||
reveal: "audit.action.viewed",
|
||||
};
|
||||
|
||||
function actionTokens(action: string): string[] {
|
||||
return action
|
||||
.replace(/([a-z0-9])([A-Z])/g, "$1 $2")
|
||||
.toLowerCase()
|
||||
.split(/[^a-z0-9]+/)
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/** Maps stable machine event codes to a small, understandable action vocabulary. */
|
||||
export function deriveAuditActionLabelKey(action: string): string {
|
||||
const normalizedAction = action.trim().toLowerCase();
|
||||
const exactKey = EXACT_ACTION_LABEL_KEYS[normalizedAction];
|
||||
if (exactKey) return exactKey;
|
||||
|
||||
const tokens = actionTokens(action);
|
||||
if (tokens.includes("login") || (tokens.includes("signed") && tokens.includes("in"))) {
|
||||
if (tokens.some((token) => token === "failure" || token === "failed")) return "audit.action.loginFailed";
|
||||
if (tokens.some((token) => token === "blocked" || token === "denied")) return "audit.action.loginBlocked";
|
||||
return "audit.action.loginSuccess";
|
||||
}
|
||||
if (tokens.includes("logout") || (tokens.includes("signed") && tokens.includes("out"))) {
|
||||
return "audit.action.logout";
|
||||
}
|
||||
|
||||
for (let index = tokens.length - 1; index >= 0; index -= 1) {
|
||||
const key = ACTION_TOKEN_LABEL_KEYS[tokens[index] ?? ""];
|
||||
if (key) return key;
|
||||
}
|
||||
return "audit.action.performed";
|
||||
}
|
||||
|
||||
function persistedSummaryFor(row: AuditListInputRow): string | null {
|
||||
const summary = row.summaryText?.trim();
|
||||
if (!summary) return null;
|
||||
const normalizedSummary = summary.toLowerCase();
|
||||
if (normalizedSummary.includes(row.action.trim().toLowerCase())) return null;
|
||||
if (row.actorId && normalizedSummary.includes(row.actorId.trim().toLowerCase())) return null;
|
||||
return summary;
|
||||
}
|
||||
|
||||
const MASKED_SENTINEL = "[REDACTED]";
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
@@ -211,22 +324,25 @@ function toMetadataJson(metadata: unknown): string | null {
|
||||
export function buildAuditListVM(input: BuildAuditListVMInput): AuditListVM {
|
||||
const rows: AuditListRow[] = input.rows.map((row) => {
|
||||
const actorKind = deriveAuditActorKind(row.actorType);
|
||||
const actorLabel = actorLabelFor(row, actorKind);
|
||||
const diff = buildAuditFieldDiffs(row.beforeDiff, row.afterDiff);
|
||||
const metadataJson = toMetadataJson(row.metadata);
|
||||
const summaryText = row.summaryText && row.summaryText.trim().length > 0 ? row.summaryText.trim() : null;
|
||||
const summaryText = persistedSummaryFor(row);
|
||||
return {
|
||||
id: row.id,
|
||||
createdAtIso: row.createdAtIso,
|
||||
tenantId: row.tenantId ?? null,
|
||||
actorKind,
|
||||
actorKindLabelKey: `audit.actorKind.${actorKindKeySuffix(actorKind)}`,
|
||||
actorLabel: actorLabelFor(row, actorKind),
|
||||
actorLabel,
|
||||
action: row.action,
|
||||
actionLabelKey: deriveAuditActionLabelKey(row.action),
|
||||
summaryText,
|
||||
summaryKey: deriveAuditSummaryKey(row.action),
|
||||
summaryParams: {
|
||||
actor: actorLabelFor(row, actorKind),
|
||||
actor: actorLabel,
|
||||
action: row.action,
|
||||
target: row.targetType ? `${row.targetType}${row.targetId ? `#${row.targetId}` : ""}` : "",
|
||||
target: row.targetType ?? "",
|
||||
},
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId,
|
||||
@@ -243,6 +359,13 @@ export function buildAuditListVM(input: BuildAuditListVMInput): AuditListVM {
|
||||
rows,
|
||||
filter: input.filter,
|
||||
pagination: input.pagination,
|
||||
summary: {
|
||||
total: input.pagination.total,
|
||||
pageRows: rows.length,
|
||||
failedRows: rows.filter((row) => row.outcome === "failure" || row.outcome === "blocked").length,
|
||||
detailRows: rows.filter((row) => row.hasDetail).length,
|
||||
adminRows: rows.filter((row) => row.actorKind === "admin").length,
|
||||
},
|
||||
canExport: input.canExport,
|
||||
emptyHeadlineKey: "audit.viewer.empty.headline",
|
||||
emptyBodyKey: "audit.viewer.empty.body",
|
||||
@@ -259,6 +382,7 @@ export interface AuditListModelRow {
|
||||
readonly actorKindLabelKey: string;
|
||||
readonly actorLabel: string;
|
||||
readonly action: string;
|
||||
readonly actionLabelKey: string;
|
||||
readonly outcome: string;
|
||||
/** Persisted summary text, or null when the renderer should show the key. */
|
||||
readonly summaryText: string | null;
|
||||
@@ -292,6 +416,7 @@ export function toAuditListModel(data: AuditListData): AuditListModel {
|
||||
actorKindLabelKey: row.actorKindLabelKey,
|
||||
actorLabel: row.actorLabel,
|
||||
action: row.action,
|
||||
actionLabelKey: row.actionLabelKey,
|
||||
outcome: row.outcome,
|
||||
summaryText: row.summaryText,
|
||||
summaryKey: row.summaryKey,
|
||||
|
||||
+42
-1
@@ -75,9 +75,50 @@ function relativeLastSeen(lastSeenMs: number, nowMs: number): { bucket: LastSeen
|
||||
return { bucket: "days", count: Math.floor(diff / DAY_MS) };
|
||||
}
|
||||
|
||||
const BROWSER_PATTERNS: readonly (readonly [RegExp, string])[] = [
|
||||
[/edg[ea]?\//i, "Edge"],
|
||||
[/opr\/|opera/i, "Opera"],
|
||||
[/chrome\/|crios\//i, "Chrome"],
|
||||
[/firefox\/|fxios\//i, "Firefox"],
|
||||
[/safari\//i, "Safari"],
|
||||
];
|
||||
|
||||
const PLATFORM_PATTERNS: readonly (readonly [RegExp, string])[] = [
|
||||
[/iphone|ipad|ipod/i, "iOS"],
|
||||
[/android/i, "Android"],
|
||||
[/mac os x|macintosh/i, "macOS"],
|
||||
[/windows/i, "Windows"],
|
||||
[/cros/i, "ChromeOS"],
|
||||
[/linux/i, "Linux"],
|
||||
];
|
||||
|
||||
function matchFirst(value: string, patterns: readonly (readonly [RegExp, string])[]): string | undefined {
|
||||
for (const [pattern, label] of patterns) {
|
||||
if (pattern.test(value)) return label;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turns a raw user-agent into something a person can tell apart. Four sessions
|
||||
* from the same machine used to render as four identical 120-character UA
|
||||
* strings. Unrecognised agents keep their raw value rather than vanishing.
|
||||
*/
|
||||
export function summarizeUserAgent(userAgent: string): string {
|
||||
const value = userAgent.trim();
|
||||
if (value.length === 0) return value;
|
||||
// Safari ships "Version/x Safari/y"; Chrome/Edge also carry a Safari token, so
|
||||
// browser detection runs most-specific-first above.
|
||||
const browser = matchFirst(value, BROWSER_PATTERNS);
|
||||
const platform = matchFirst(value, PLATFORM_PATTERNS);
|
||||
if (browser && platform) return `${browser} · ${platform}`;
|
||||
return browser ?? platform ?? value;
|
||||
}
|
||||
|
||||
function toDevice(session: SessionDeviceInput, currentSessionId: string | null, nowMs: number): SessionDeviceData {
|
||||
const isCurrent = session.id === currentSessionId;
|
||||
const rawLabel = session.deviceLabel?.trim() || session.userAgent?.trim() || undefined;
|
||||
const agentLabel = session.userAgent?.trim() ? summarizeUserAgent(session.userAgent) : undefined;
|
||||
const rawLabel = session.deviceLabel?.trim() || agentLabel || undefined;
|
||||
const lastSeenMs = toMs(session.lastSeenAt);
|
||||
const relative = relativeLastSeen(lastSeenMs, nowMs);
|
||||
return {
|
||||
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBillingPaymentVM, type BillingPaymentInvoiceInput } from "./billing-payment.vm.js";
|
||||
|
||||
function invoice(overrides: Partial<BillingPaymentInvoiceInput> = {}): BillingPaymentInvoiceInput {
|
||||
return {
|
||||
id: "invoice_1",
|
||||
number: "LAG-001",
|
||||
issuingDate: "2026-07-10",
|
||||
amountCents: 4_900,
|
||||
currency: "eur",
|
||||
status: "finalized",
|
||||
paymentStatus: "succeeded",
|
||||
invoiceType: "subscription",
|
||||
downloadHref: "/acme/settings/subscription/invoices/invoice_1/download",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildBillingPaymentVM", () => {
|
||||
it("maps upstream failures to a localized error state", () => {
|
||||
expect(buildBillingPaymentVM({ invoices: [], errorKey: "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE" })).toEqual({
|
||||
status: "error",
|
||||
error: { messageKey: "settings.subscription.errors.INVOICE_LIST_UNAVAILABLE", code: "INVOICE_LIST_UNAVAILABLE" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns an empty state when Lago has no invoices", () => {
|
||||
expect(buildBillingPaymentVM({ invoices: [] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("sorts Lago invoices and exposes the Mollie payment state", () => {
|
||||
const vm = buildBillingPaymentVM({
|
||||
invoices: [invoice({ id: "older", issuingDate: "2026-06-01", paymentStatus: "failed" }), invoice()],
|
||||
lastPaymentExternalId: "tr_123",
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.invoices.map((item) => item.id)).toEqual(["invoice_1", "older"]);
|
||||
expect(vm.data?.invoices[0]).toMatchObject({ currency: "EUR", tone: "positive", paymentStatusLabelKey: "billing:billingPayment.paymentStatus.succeeded" });
|
||||
expect(vm.data?.latestPaymentStatus).toBe("succeeded");
|
||||
expect(vm.data?.hasMollieReference).toBe(true);
|
||||
});
|
||||
|
||||
it("points the in-app preview at the inline variant of the download route", () => {
|
||||
const vm = buildBillingPaymentVM({ invoices: [invoice(), invoice({ id: "voided", downloadHref: null })] });
|
||||
|
||||
expect(vm.data?.invoices.find((item) => item.id === "invoice_1")?.previewHref).toBe(
|
||||
"/acme/settings/subscription/invoices/invoice_1/download?disposition=inline"
|
||||
);
|
||||
expect(vm.data?.invoices.find((item) => item.id === "voided")?.previewHref).toBeNull();
|
||||
});
|
||||
});
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type BillingPaymentInvoiceInput = {
|
||||
readonly id: string;
|
||||
readonly number: string | null;
|
||||
readonly issuingDate: string | null;
|
||||
readonly amountCents: number | null;
|
||||
readonly currency: string | null;
|
||||
readonly status: string;
|
||||
readonly paymentStatus: string;
|
||||
readonly invoiceType: string | null;
|
||||
readonly downloadHref: string | null;
|
||||
};
|
||||
|
||||
export type BillingPaymentInvoiceVM = BillingPaymentInvoiceInput & {
|
||||
readonly statusLabelKey: string;
|
||||
readonly paymentStatusLabelKey: string;
|
||||
readonly tone: "neutral" | "positive" | "warning" | "negative";
|
||||
/** Same file as `downloadHref`, but served for the in-app preview frame. */
|
||||
readonly previewHref: string | null;
|
||||
};
|
||||
|
||||
export type BillingPaymentData = {
|
||||
readonly invoices: readonly BillingPaymentInvoiceVM[];
|
||||
readonly latestPaymentStatus: string | null;
|
||||
readonly latestPaymentStatusLabelKey: string;
|
||||
readonly hasMollieReference: boolean;
|
||||
readonly helpTitleKey: string;
|
||||
readonly helpDescriptionKey: string;
|
||||
};
|
||||
|
||||
export type BillingPaymentVM = VMState<BillingPaymentData>;
|
||||
|
||||
export type BuildBillingPaymentVMInput = {
|
||||
readonly invoices: readonly BillingPaymentInvoiceInput[];
|
||||
readonly lastPaymentExternalId?: string | null;
|
||||
readonly errorKey?: string | null;
|
||||
};
|
||||
|
||||
function statusSegment(value: string): string {
|
||||
return value.trim().replace(/[^a-zA-Z0-9]+(.)?/gu, (_match, next: string | undefined) => next?.toUpperCase() ?? "") || "unknown";
|
||||
}
|
||||
|
||||
function invoiceTone(invoice: BillingPaymentInvoiceInput): BillingPaymentInvoiceVM["tone"] {
|
||||
if (invoice.paymentStatus === "succeeded" || invoice.paymentStatus === "paid") return "positive";
|
||||
if (invoice.paymentStatus === "failed" || invoice.status === "failed" || invoice.status === "voided") return "negative";
|
||||
if (invoice.paymentStatus === "pending") return "warning";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
/** The download route serves the same file inline when asked to. */
|
||||
function previewHrefFor(downloadHref: string | null): string | null {
|
||||
if (!downloadHref) return null;
|
||||
return `${downloadHref}${downloadHref.includes("?") ? "&" : "?"}disposition=inline`;
|
||||
}
|
||||
|
||||
export function buildBillingPaymentVM(input: BuildBillingPaymentVMInput): BillingPaymentVM {
|
||||
if (input.errorKey) return { status: "error", error: { messageKey: input.errorKey, code: "INVOICE_LIST_UNAVAILABLE" } };
|
||||
if (input.invoices.length === 0) return { status: "empty" };
|
||||
|
||||
const invoices = [...input.invoices]
|
||||
.sort((left, right) => (right.issuingDate ?? "").localeCompare(left.issuingDate ?? ""))
|
||||
.map((invoice): BillingPaymentInvoiceVM => ({
|
||||
...invoice,
|
||||
currency: invoice.currency?.toUpperCase() ?? null,
|
||||
statusLabelKey: `billing:billingPayment.invoiceStatus.${statusSegment(invoice.status)}`,
|
||||
paymentStatusLabelKey: `billing:billingPayment.paymentStatus.${statusSegment(invoice.paymentStatus)}`,
|
||||
tone: invoiceTone(invoice),
|
||||
previewHref: previewHrefFor(invoice.downloadHref),
|
||||
}));
|
||||
const latestPaymentStatus = invoices[0]?.paymentStatus ?? null;
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
invoices,
|
||||
latestPaymentStatus,
|
||||
latestPaymentStatusLabelKey: `billing:billingPayment.paymentStatus.${statusSegment(latestPaymentStatus ?? "unknown")}`,
|
||||
hasMollieReference: Boolean(input.lastPaymentExternalId),
|
||||
helpTitleKey: "billing:billingPayment.help.title",
|
||||
helpDescriptionKey: "billing:billingPayment.help.description",
|
||||
},
|
||||
};
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBillingUsageVM } from "./billing-usage.vm.js";
|
||||
|
||||
describe("buildBillingUsageVM", () => {
|
||||
it("returns empty when no supported v1 metrics exist", () => {
|
||||
expect(buildBillingUsageVM({ periodStart: "2026-07-01", periodEnd: "2026-08-01", metrics: [{ metricCode: "ai_tokens", quantity: 12, quota: 100, remaining: 88, exceeded: false, percentUsed: 12 }] })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("builds automation and storage counters without usage-billing data", () => {
|
||||
const vm = buildBillingUsageVM({
|
||||
periodStart: "2026-07-01T00:00:00.000Z",
|
||||
periodEnd: "2026-08-01T00:00:00.000Z",
|
||||
metrics: [
|
||||
{ metricCode: "automation_runs", quantity: 82, quota: 100, remaining: 18, exceeded: false, percentUsed: 82 },
|
||||
{ metricCode: "storage_bytes", quantity: 2_000, quota: null, remaining: null, exceeded: false, percentUsed: null },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data?.hasWarning).toBe(true);
|
||||
expect(vm.data?.hasExceeded).toBe(false);
|
||||
expect(vm.data?.metrics).toEqual([
|
||||
expect.objectContaining({ metricCode: "automation_runs", warning: true, tone: "warning", valueFormat: "number" }),
|
||||
expect.objectContaining({ metricCode: "storage_bytes", warning: false, tone: "neutral", valueFormat: "bytes" }),
|
||||
]);
|
||||
expect(vm.data?.unavailableMetrics).toEqual([]);
|
||||
expect(vm.data).not.toHaveProperty("overage");
|
||||
expect(vm.data).not.toHaveProperty("amount");
|
||||
});
|
||||
|
||||
it("keeps healthy counters visible while marking storage as unavailable", () => {
|
||||
const vm = buildBillingUsageVM({
|
||||
periodStart: "2026-07-01",
|
||||
periodEnd: "2026-08-01",
|
||||
unavailableMetricCodes: ["storage_bytes"],
|
||||
metrics: [
|
||||
{ metricCode: "automation_runs", quantity: 12, quota: 100, remaining: 88, exceeded: false, percentUsed: 12 },
|
||||
{ metricCode: "storage_bytes", quantity: 0, quota: null, remaining: null, exceeded: false, percentUsed: null },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: {
|
||||
unavailableMetrics: ["storage_bytes"],
|
||||
metrics: [expect.objectContaining({ metricCode: "automation_runs", quantity: 12 })],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes exhausted metrics to the danger state", () => {
|
||||
const vm = buildBillingUsageVM({
|
||||
periodStart: "2026-07-01",
|
||||
periodEnd: "2026-08-01",
|
||||
metrics: [{ metricCode: "automation_runs", quantity: 120, quota: 100, remaining: 0, exceeded: false, percentUsed: 120 }],
|
||||
});
|
||||
|
||||
expect(vm.data?.metrics[0]).toMatchObject({ exceeded: true, warning: false, tone: "danger", percentUsed: 100 });
|
||||
expect(vm.data?.hasExceeded).toBe(true);
|
||||
});
|
||||
});
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
export type BillingUsageMetricCode = "automation_runs" | "storage_bytes";
|
||||
export type BillingUsageTone = "neutral" | "warning" | "danger";
|
||||
export type BillingUsageValueFormat = "number" | "bytes";
|
||||
|
||||
export type BillingUsageMetricInput = {
|
||||
readonly metricCode: string;
|
||||
readonly quantity: number;
|
||||
readonly quota: number | null;
|
||||
readonly remaining: number | null;
|
||||
readonly exceeded: boolean;
|
||||
readonly percentUsed: number | null;
|
||||
};
|
||||
|
||||
export type BillingUsageMetricVM = {
|
||||
readonly metricCode: BillingUsageMetricCode;
|
||||
readonly labelKey: string;
|
||||
readonly valueFormat: BillingUsageValueFormat;
|
||||
readonly quantity: number;
|
||||
readonly quota: number | null;
|
||||
readonly remaining: number | null;
|
||||
readonly percentUsed: number | null;
|
||||
readonly exceeded: boolean;
|
||||
readonly warning: boolean;
|
||||
readonly tone: BillingUsageTone;
|
||||
};
|
||||
|
||||
export type BillingUsageData = {
|
||||
readonly periodStart: string;
|
||||
readonly periodEnd: string;
|
||||
readonly metrics: readonly BillingUsageMetricVM[];
|
||||
readonly unavailableMetrics: readonly BillingUsageMetricCode[];
|
||||
readonly hasWarning: boolean;
|
||||
readonly hasExceeded: boolean;
|
||||
};
|
||||
|
||||
export type BillingUsageVM = VMState<BillingUsageData>;
|
||||
|
||||
export type BuildBillingUsageVMInput = {
|
||||
readonly periodStart: string;
|
||||
readonly periodEnd: string;
|
||||
readonly metrics: readonly BillingUsageMetricInput[];
|
||||
readonly unavailableMetricCodes?: readonly string[];
|
||||
};
|
||||
|
||||
const METRIC_META: Readonly<Record<BillingUsageMetricCode, { labelKey: string; valueFormat: BillingUsageValueFormat }>> = {
|
||||
automation_runs: { labelKey: "billing:usage.metrics.automation_runs", valueFormat: "number" },
|
||||
storage_bytes: { labelKey: "billing:usage.metrics.storage_bytes", valueFormat: "bytes" },
|
||||
};
|
||||
|
||||
function isBillingUsageMetricCode(value: string): value is BillingUsageMetricCode {
|
||||
return value === "automation_runs" || value === "storage_bytes";
|
||||
}
|
||||
|
||||
export function buildBillingUsageVM(input: BuildBillingUsageVMInput): BillingUsageVM {
|
||||
const unavailableMetrics = [...new Set((input.unavailableMetricCodes ?? []).filter(isBillingUsageMetricCode))];
|
||||
const unavailableSet = new Set(unavailableMetrics);
|
||||
const metrics = input.metrics.filter((metric) => isBillingUsageMetricCode(metric.metricCode) && !unavailableSet.has(metric.metricCode)).map((metric): BillingUsageMetricVM => {
|
||||
const meta = METRIC_META[metric.metricCode as BillingUsageMetricCode];
|
||||
const percentUsed = metric.percentUsed === null ? null : Math.max(0, Math.min(100, metric.percentUsed));
|
||||
const exceeded = metric.exceeded || (metric.quota !== null && metric.quantity >= metric.quota);
|
||||
const warning = !exceeded && percentUsed !== null && percentUsed >= 80;
|
||||
return {
|
||||
metricCode: metric.metricCode as BillingUsageMetricCode,
|
||||
labelKey: meta.labelKey,
|
||||
valueFormat: meta.valueFormat,
|
||||
quantity: Math.max(0, metric.quantity),
|
||||
quota: metric.quota,
|
||||
remaining: metric.remaining,
|
||||
percentUsed,
|
||||
exceeded,
|
||||
warning,
|
||||
tone: exceeded ? "danger" : warning ? "warning" : "neutral",
|
||||
};
|
||||
});
|
||||
|
||||
if (metrics.length === 0 && unavailableMetrics.length === 0) return { status: "empty" };
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
periodStart: input.periodStart,
|
||||
periodEnd: input.periodEnd,
|
||||
metrics,
|
||||
unavailableMetrics,
|
||||
hasWarning: metrics.some((metric) => metric.warning),
|
||||
hasExceeded: metrics.some((metric) => metric.exceeded),
|
||||
},
|
||||
};
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeSeatUsage, getSeatPackage, seatPackageIds } from "@hivegrid/entitlements";
|
||||
|
||||
import { buildSeatUsageVM } from "./seat-usage.vm.js";
|
||||
|
||||
const starter = getSeatPackage(seatPackageIds.starter);
|
||||
|
||||
describe("buildSeatUsageVM", () => {
|
||||
it("is empty when there is no package and no active seats", () => {
|
||||
const vm = buildSeatUsageVM({ packageId: null, usage: null, counts: { office: 0, field: 0 } });
|
||||
expect(vm.status).toBe("empty");
|
||||
});
|
||||
|
||||
it("renders occupancy against package limits with no overage", () => {
|
||||
const usage = computeSeatUsage({ package: starter, officeUsed: 1, fieldUsed: 4 });
|
||||
const vm = buildSeatUsageVM({ packageId: "starter", usage, counts: { office: 1, field: 4 } });
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.hasPackage).toBe(true);
|
||||
expect(vm.data.packageId).toBe("starter");
|
||||
expect(vm.data.packageNameKey).toBe("settings.subscription.seats.package.starter");
|
||||
expect(vm.data.hasOverage).toBe(false);
|
||||
expect(vm.data.totalExtraCostEur).toBe(0);
|
||||
expect(vm.data.currency).toBe("EUR");
|
||||
|
||||
const [office, field] = vm.data.categories;
|
||||
expect(office).toMatchObject({ seatType: "office", labelKey: "settings.subscription.seats.office", used: 1, included: 2, extra: 0, overLimit: false });
|
||||
expect(field).toMatchObject({ seatType: "field", labelKey: "settings.subscription.seats.field", used: 4, included: 5, extra: 0, overLimit: false });
|
||||
});
|
||||
|
||||
it("surfaces per-category extra seats and total cost on overage", () => {
|
||||
// starter: office 5 used => 3 extra × 59 = 177; field 8 used => 3 extra × 25 = 75.
|
||||
const usage = computeSeatUsage({ package: starter, officeUsed: 5, fieldUsed: 8 });
|
||||
const vm = buildSeatUsageVM({ packageId: "starter", usage, counts: { office: 5, field: 8 } });
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.hasOverage).toBe(true);
|
||||
expect(vm.data.totalExtraCostEur).toBe(252);
|
||||
|
||||
const [office, field] = vm.data.categories;
|
||||
expect(office).toMatchObject({ extra: 3, extraPriceEur: 59, extraCostEur: 177, overLimit: true });
|
||||
expect(field).toMatchObject({ extra: 3, extraPriceEur: 25, extraCostEur: 75, overLimit: true });
|
||||
});
|
||||
|
||||
it("falls back to counts-only (no limits) when no package is resolved", () => {
|
||||
const vm = buildSeatUsageVM({ packageId: null, usage: null, counts: { office: 3, field: 7 } });
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.hasPackage).toBe(false);
|
||||
expect(vm.data.packageId).toBeNull();
|
||||
expect(vm.data.packageNameKey).toBeNull();
|
||||
expect(vm.data.hasOverage).toBe(false);
|
||||
|
||||
const [office, field] = vm.data.categories;
|
||||
expect(office).toMatchObject({ used: 3, included: null, extra: 0, extraPriceEur: null, extraCostEur: 0, overLimit: false });
|
||||
expect(field).toMatchObject({ used: 7, included: null, extraPriceEur: null });
|
||||
});
|
||||
});
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import type { SeatPackageId, SeatType, SeatUsageResult } from "@hivegrid/entitlements";
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Tenant seat-usage view-model (Fundament E).
|
||||
*
|
||||
* Pure presentation: the loader counts the tenant's active seats
|
||||
* (`getTenantSeatCounts`), resolves the seat package (`resolveSeatPackageId`),
|
||||
* runs the pure `computeSeatUsage`, and hands the result here. This builder maps
|
||||
* that into an i18n-keyed, currency-agnostic model the billing UI renders. No
|
||||
* React, no Prisma, no app imports (DoD A.3). Euro amounts stay numeric — the
|
||||
* screen formats them with the active locale.
|
||||
*/
|
||||
|
||||
const CURRENCY = "EUR";
|
||||
|
||||
export type SeatUsageCategoryVM = {
|
||||
readonly seatType: SeatType;
|
||||
/** i18n key for the category name (Büro / Baustelle). */
|
||||
readonly labelKey: string;
|
||||
readonly used: number;
|
||||
/** Included seats, or null when no package is resolved. */
|
||||
readonly included: number | null;
|
||||
/** Extra seats above the included amount (0 without a package). */
|
||||
readonly extra: number;
|
||||
/** Per-seat extra price in euros, or null without a package. */
|
||||
readonly extraPriceEur: number | null;
|
||||
/** extra × extraPriceEur, in euros. */
|
||||
readonly extraCostEur: number;
|
||||
readonly overLimit: boolean;
|
||||
};
|
||||
|
||||
export type SeatUsageData = {
|
||||
readonly hasPackage: boolean;
|
||||
readonly packageId: SeatPackageId | null;
|
||||
/** i18n key for the resolved package name, or null when unresolved. */
|
||||
readonly packageNameKey: string | null;
|
||||
/** Both categories in a stable order: office first, then field. */
|
||||
readonly categories: readonly SeatUsageCategoryVM[];
|
||||
readonly totalExtraCostEur: number;
|
||||
readonly hasOverage: boolean;
|
||||
readonly currency: string;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
/** Klartext notice key shown when there is at least one overage. */
|
||||
readonly overageNoticeKey: string;
|
||||
/** Hint key shown when no package could be resolved (counts only). */
|
||||
readonly noPackageHintKey: string;
|
||||
};
|
||||
|
||||
export type SeatUsageVM = VMState<SeatUsageData>;
|
||||
|
||||
const CATEGORY_LABEL_KEYS: Readonly<Record<SeatType, string>> = {
|
||||
office: "settings.subscription.seats.office",
|
||||
field: "settings.subscription.seats.field",
|
||||
};
|
||||
|
||||
const PACKAGE_NAME_KEYS: Readonly<Record<SeatPackageId, string>> = {
|
||||
starter: "settings.subscription.seats.package.starter",
|
||||
team: "settings.subscription.seats.package.team",
|
||||
business: "settings.subscription.seats.package.business",
|
||||
};
|
||||
|
||||
export interface BuildSeatUsageVMInput {
|
||||
readonly packageId: SeatPackageId | null;
|
||||
/** Result of `computeSeatUsage`, or null when no package was resolved. */
|
||||
readonly usage: SeatUsageResult | null;
|
||||
/** Raw active-seat counts (always available, drives the no-package path). */
|
||||
readonly counts: { readonly office: number; readonly field: number };
|
||||
}
|
||||
|
||||
function categoryFromUsage(seatType: SeatType, usage: SeatUsageResult): SeatUsageCategoryVM {
|
||||
const category = usage[seatType];
|
||||
return {
|
||||
seatType,
|
||||
labelKey: CATEGORY_LABEL_KEYS[seatType],
|
||||
used: category.used,
|
||||
included: category.included,
|
||||
extra: category.extra,
|
||||
extraPriceEur: category.extraPriceEur,
|
||||
extraCostEur: category.extraCostEur,
|
||||
overLimit: category.overLimit,
|
||||
};
|
||||
}
|
||||
|
||||
function categoryFromCount(seatType: SeatType, used: number): SeatUsageCategoryVM {
|
||||
return {
|
||||
seatType,
|
||||
labelKey: CATEGORY_LABEL_KEYS[seatType],
|
||||
used,
|
||||
included: null,
|
||||
extra: 0,
|
||||
extraPriceEur: null,
|
||||
extraCostEur: 0,
|
||||
overLimit: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSeatUsageVM(input: BuildSeatUsageVMInput): SeatUsageVM {
|
||||
const { packageId, usage, counts } = input;
|
||||
|
||||
// No package resolved and no active seats at all → nothing to show.
|
||||
if (!packageId && counts.office === 0 && counts.field === 0) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
|
||||
const base = {
|
||||
totalExtraCostEur: usage?.totalExtraCostEur ?? 0,
|
||||
hasOverage: usage?.hasOverage ?? false,
|
||||
currency: CURRENCY,
|
||||
titleKey: "settings.subscription.seats.title",
|
||||
descriptionKey: "settings.subscription.seats.description",
|
||||
overageNoticeKey: "settings.subscription.seats.overageNotice",
|
||||
noPackageHintKey: "settings.subscription.seats.noPackageHint",
|
||||
} as const;
|
||||
|
||||
if (packageId && usage) {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...base,
|
||||
hasPackage: true,
|
||||
packageId,
|
||||
packageNameKey: PACKAGE_NAME_KEYS[packageId],
|
||||
categories: [categoryFromUsage("office", usage), categoryFromUsage("field", usage)],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Counts without package limits (best-effort fallback per Fundament E).
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
...base,
|
||||
hasPackage: false,
|
||||
packageId: null,
|
||||
packageNameKey: null,
|
||||
categories: [categoryFromCount("office", counts.office), categoryFromCount("field", counts.field)],
|
||||
},
|
||||
};
|
||||
}
|
||||
+481
@@ -0,0 +1,481 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
buildSelfServiceCheckoutPaymentMethodsVM,
|
||||
buildSelfServiceSubscriptionCatalogVM,
|
||||
buildSelfServiceSubscriptionManagementPolicyVM,
|
||||
buildSelfServiceSubscriptionPageVM,
|
||||
buildSelfServiceSubscriptionPricePreviewVM,
|
||||
type BuildSelfServiceSubscriptionPricePreviewVMInput,
|
||||
type SelfServiceSubscriptionPlanVM,
|
||||
type SelfServiceSubscriptionPriceVM,
|
||||
} from "./self-service-subscription.vm.js";
|
||||
|
||||
function price(overrides: Partial<SelfServiceSubscriptionPriceVM> = {}): SelfServiceSubscriptionPriceVM {
|
||||
return {
|
||||
id: "price_starter_monthly",
|
||||
billingPeriod: 3,
|
||||
currency: "eur",
|
||||
unitAmountCents: 2900,
|
||||
trialDays: 14,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function plan(code: string, overrides: Partial<SelfServiceSubscriptionPlanVM> = {}): SelfServiceSubscriptionPlanVM {
|
||||
return {
|
||||
id: `plan_${code}`,
|
||||
code,
|
||||
titleKey: `billing:selfService.plan.${code}.title`,
|
||||
descriptionKey: `billing:selfService.plan.${code}.description`,
|
||||
badge: null,
|
||||
quantityMode: "per_seat",
|
||||
features: [{ code: "crm", titleKey: "billing:selfService.feature.crm" }],
|
||||
prices: [price({ id: `price_${code}_monthly` })],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const starter = plan("starter");
|
||||
const business = plan("business", {
|
||||
badge: " billing:selfService.plan.business.badge ",
|
||||
prices: [price({ id: "price_business_monthly", unitAmountCents: 4900, trialDays: 30 })],
|
||||
});
|
||||
const effectiveAtByChangeKind = {
|
||||
new: "immediate",
|
||||
upgrade: "immediate",
|
||||
downgrade: "period_end",
|
||||
billing_period_change: "period_end",
|
||||
seat_increase: "immediate",
|
||||
seat_decrease: "period_end",
|
||||
configuration_increase: "immediate",
|
||||
configuration_decrease: "period_end",
|
||||
configuration_change: "period_end",
|
||||
unchanged: "immediate",
|
||||
} as const;
|
||||
const policy = buildSelfServiceSubscriptionManagementPolicyVM({ planOrder: [starter.code, business.code], effectiveAtByChangeKind });
|
||||
const periodEnd = "2026-08-15T00:00:00.000Z";
|
||||
|
||||
function previewInput(overrides: Partial<BuildSelfServiceSubscriptionPricePreviewVMInput> = {}): BuildSelfServiceSubscriptionPricePreviewVMInput {
|
||||
return {
|
||||
currentPlan: starter,
|
||||
currentPrice: starter.prices[0]!,
|
||||
currentSeatQuantity: 2,
|
||||
currentPeriodEnd: periodEnd,
|
||||
selectedPlan: starter,
|
||||
selectedPrice: starter.prices[0]!,
|
||||
selectedSeatQuantity: 2,
|
||||
policy,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildSelfServiceSubscriptionCatalogVM", () => {
|
||||
it("builds a serializable public catalog and keeps all money in integer cents", () => {
|
||||
const vm = buildSelfServiceSubscriptionCatalogVM({ plans: [starter, business] });
|
||||
|
||||
expect(vm).toEqual({
|
||||
plans: [
|
||||
{
|
||||
...starter,
|
||||
prices: [{ ...starter.prices[0], currency: "EUR" }],
|
||||
},
|
||||
{
|
||||
...business,
|
||||
badge: "billing:selfService.plan.business.badge",
|
||||
prices: [{ ...business.prices[0], currency: "EUR" }],
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.parse(JSON.stringify(vm))).toEqual(vm);
|
||||
expect(vm.plans[1]?.prices[0]?.unitAmountCents).toBe(4900);
|
||||
});
|
||||
|
||||
it("rejects ambiguous catalog identifiers", () => {
|
||||
expect(() => buildSelfServiceSubscriptionCatalogVM({ plans: [starter, plan("starter", { id: "another_id" })] })).toThrow(/duplicate value starter/);
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionCatalogVM({
|
||||
plans: [plan("starter", { prices: [price({ id: "duplicate" }), price({ id: "duplicate", billingPeriod: 4 })] })],
|
||||
})
|
||||
).toThrow(/duplicate value duplicate/);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["fractional cents", { unitAmountCents: 29.5 }],
|
||||
["negative cents", { unitAmountCents: -1 }],
|
||||
["fractional trial days", { trialDays: 1.5 }],
|
||||
["negative billing period", { billingPeriod: -1 }],
|
||||
])("rejects %s", (_label, invalidPrice) => {
|
||||
expect(() => buildSelfServiceSubscriptionCatalogVM({ plans: [plan("starter", { prices: [price(invalidPrice)] })] })).toThrow(/safe integer/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSelfServiceSubscriptionManagementPolicyVM", () => {
|
||||
it("keeps the server-supplied timing policy explicit", () => {
|
||||
expect(policy).toEqual({
|
||||
planOrder: ["starter", "business"],
|
||||
effectiveAtByChangeKind: {
|
||||
new: "immediate",
|
||||
upgrade: "immediate",
|
||||
downgrade: "period_end",
|
||||
billing_period_change: "period_end",
|
||||
seat_increase: "immediate",
|
||||
seat_decrease: "period_end",
|
||||
configuration_increase: "immediate",
|
||||
configuration_decrease: "period_end",
|
||||
configuration_change: "period_end",
|
||||
unchanged: "immediate",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("allows a server-owned policy override without changing unrelated rules", () => {
|
||||
const customPolicy = buildSelfServiceSubscriptionManagementPolicyVM({
|
||||
planOrder: ["starter", "business"],
|
||||
effectiveAtByChangeKind: { ...effectiveAtByChangeKind, seat_increase: "period_end" },
|
||||
});
|
||||
|
||||
expect(customPolicy.effectiveAtByChangeKind.seat_increase).toBe("period_end");
|
||||
expect(customPolicy.effectiveAtByChangeKind.upgrade).toBe("immediate");
|
||||
});
|
||||
|
||||
it("rejects duplicate plan codes in the hierarchy", () => {
|
||||
expect(() => buildSelfServiceSubscriptionManagementPolicyVM({ planOrder: ["starter", "starter"], effectiveAtByChangeKind })).toThrow(
|
||||
/duplicate value starter/
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSelfServiceSubscriptionPageVM", () => {
|
||||
it("normalizes unique checkout payment methods and exposes a hosted fallback", () => {
|
||||
expect(
|
||||
buildSelfServiceCheckoutPaymentMethodsVM([
|
||||
{ id: " IDEAL ", label: " iDEAL " },
|
||||
{ id: "creditcard", label: "Credit card" },
|
||||
])
|
||||
).toEqual({
|
||||
status: "ready",
|
||||
methods: [
|
||||
{ id: "ideal", label: "iDEAL" },
|
||||
{ id: "creditcard", label: "Credit card" },
|
||||
],
|
||||
});
|
||||
expect(buildSelfServiceCheckoutPaymentMethodsVM([])).toEqual({ status: "fallback", methods: [] });
|
||||
expect(buildSelfServiceCheckoutPaymentMethodsVM([], "card")).toEqual({ status: "required_card_unavailable", methods: [] });
|
||||
expect(() =>
|
||||
buildSelfServiceCheckoutPaymentMethodsVM([
|
||||
{ id: "ideal", label: "iDEAL" },
|
||||
{ id: "IDEAL", label: "Duplicate" },
|
||||
])
|
||||
).toThrow("unique provider ids");
|
||||
});
|
||||
|
||||
it("nests the existing overview, catalog, management and fixed trial policy", () => {
|
||||
const overview = { status: "empty" } as const;
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview,
|
||||
catalog: { plans: [starter, business] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 3,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
currentSelection: { planId: starter.id, planCode: starter.code, priceId: starter.prices[0]!.id, seatQuantity: 3 },
|
||||
preferredSelection: { planId: business.id, priceId: business.prices[0]!.id },
|
||||
});
|
||||
|
||||
expect(vm.overview).toBe(overview);
|
||||
expect(vm.catalog.plans.map(({ code }) => code)).toEqual(["starter", "business"]);
|
||||
expect(vm.managementPolicy.planOrder).toEqual(["starter", "business"]);
|
||||
expect(vm).toMatchObject({
|
||||
minimumSeatQuantity: 3,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
trialPolicy: { requiresManualActivation: false, requiresPaymentMethod: true },
|
||||
currentSelection: { planId: "plan_starter", planCode: "starter", priceId: "price_starter_monthly", seatQuantity: 3 },
|
||||
preferredSelection: { planId: "plan_business", priceId: "price_business_monthly" },
|
||||
});
|
||||
expect(JSON.parse(JSON.stringify(vm))).toEqual(vm);
|
||||
});
|
||||
|
||||
it("rejects a non-positive minimum seat quantity", () => {
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans: [] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 0,
|
||||
canManage: false,
|
||||
billingHref: "/acme/settings/billing",
|
||||
})
|
||||
).toThrow(/minimumSeatQuantity/);
|
||||
});
|
||||
|
||||
it("keeps the displayed email add-on gross amount bound to net plus VAT", () => {
|
||||
const input = {
|
||||
overview: { status: "empty" } as const,
|
||||
catalog: { plans: [starter] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 1,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
emailMarketingAddOns: [
|
||||
{
|
||||
productId: "product_email_s",
|
||||
priceId: "price_email_s",
|
||||
code: "email_marketing_s",
|
||||
title: "E-Mail-Marketing S",
|
||||
monthlyEmailLimit: 10_000,
|
||||
amountCents: 5_900,
|
||||
vatRateBasisPoints: 1_900,
|
||||
vatAmountCents: 1_121,
|
||||
grossAmountCents: 7_021,
|
||||
currency: "eur",
|
||||
active: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(buildSelfServiceSubscriptionPageVM(input).emailMarketingAddOns[0]).toMatchObject({
|
||||
amountCents: 5_900,
|
||||
vatAmountCents: 1_121,
|
||||
grossAmountCents: 7_021,
|
||||
currency: "EUR",
|
||||
});
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPageVM({
|
||||
...input,
|
||||
emailMarketingAddOns: [{ ...input.emailMarketingAddOns[0]!, grossAmountCents: 5_900 }],
|
||||
})
|
||||
).toThrow(/must equal net amount plus VAT/);
|
||||
});
|
||||
|
||||
it("normalizes read-only storage and email usage into bounded percentages", () => {
|
||||
const vm = buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans: [starter] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 1,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
usage: {
|
||||
storage: {
|
||||
status: "ready",
|
||||
capacityBytes: 1_000,
|
||||
storedBytes: 800,
|
||||
reservedBytes: 300,
|
||||
remainingBytes: 0,
|
||||
percentUsed: 0,
|
||||
},
|
||||
emailMarketing: {
|
||||
status: "ready",
|
||||
periodStart: "2026-07-15T00:00:00.000Z",
|
||||
periodEnd: "2026-08-15T00:00:00.000Z",
|
||||
limit: 10_000,
|
||||
used: 2_500,
|
||||
remaining: 7_500,
|
||||
percentUsed: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(vm.usage).toEqual({
|
||||
storage: expect.objectContaining({ percentUsed: 100 }),
|
||||
emailMarketing: expect.objectContaining({ percentUsed: 25 }),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a preferred registration price outside the public catalog", () => {
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans: [starter] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 1,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
preferredSelection: { planId: starter.id, priceId: "forged_price" },
|
||||
})
|
||||
).toThrow(/preferredSelection/);
|
||||
});
|
||||
|
||||
it("rejects incomplete preferred registration seat quantities", () => {
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPageVM({
|
||||
overview: { status: "empty" },
|
||||
catalog: { plans: [starter] },
|
||||
managementPolicy: policy,
|
||||
minimumSeatQuantity: 1,
|
||||
canManage: true,
|
||||
billingHref: "/acme/settings/billing",
|
||||
preferredSelection: { planId: starter.id, priceId: starter.prices[0]!.id, officeSeatQuantity: 5 },
|
||||
})
|
||||
).toThrow(/provided together/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildSelfServiceSubscriptionPricePreviewVM", () => {
|
||||
it("classifies a new subscription and calculates the recurring total server-side", () => {
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentPlan: null,
|
||||
currentSeatQuantity: 0,
|
||||
currentPeriodEnd: null,
|
||||
selectedPlan: business,
|
||||
selectedPrice: business.prices[0]!,
|
||||
selectedSeatQuantity: 3,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
changeKind: "new",
|
||||
effectiveAt: "immediate",
|
||||
effectiveAtDate: null,
|
||||
recurringTotalCents: 14700,
|
||||
trialDays: 30,
|
||||
selectedSeatQuantity: 3,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["upgrade", starter, business, 2, 2, "upgrade", "immediate", null],
|
||||
["downgrade", business, starter, 2, 2, "downgrade", "period_end", periodEnd],
|
||||
["seat increase", starter, starter, 2, 4, "seat_increase", "immediate", null],
|
||||
["seat decrease", starter, starter, 4, 2, "seat_decrease", "period_end", periodEnd],
|
||||
["unchanged", starter, starter, 2, 2, "unchanged", "immediate", null],
|
||||
] as const)("classifies %s", (_label, currentPlan, selectedPlan, currentSeats, selectedSeats, changeKind, effectiveAt, effectiveAtDate) => {
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentPlan,
|
||||
currentSeatQuantity: currentSeats,
|
||||
selectedPlan,
|
||||
selectedPrice: selectedPlan.prices[0]!,
|
||||
selectedSeatQuantity: selectedSeats,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm).toMatchObject({ changeKind, effectiveAt, effectiveAtDate });
|
||||
expect(vm.recurringTotalCents).toBe(selectedPlan.prices[0]!.unitAmountCents * selectedSeats);
|
||||
expect(vm.trialDays).toBe(selectedPlan.prices[0]!.trialDays);
|
||||
});
|
||||
|
||||
it("lets a plan change take precedence when plan and seat quantity change together", () => {
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({ selectedPlan: business, selectedPrice: business.prices[0]!, selectedSeatQuantity: 1 })
|
||||
);
|
||||
|
||||
expect(vm.changeKind).toBe("upgrade");
|
||||
expect(vm.effectiveAt).toBe("immediate");
|
||||
});
|
||||
|
||||
it("classifies a billing-period change and defers it to period end", () => {
|
||||
const yearly = price({ id: "price_starter_yearly", billingPeriod: 4, unitAmountCents: 29_000 });
|
||||
const planWithPeriods = plan("starter", { prices: [starter.prices[0]!, yearly] });
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentPlan: planWithPeriods,
|
||||
currentPrice: planWithPeriods.prices[0]!,
|
||||
selectedPlan: planWithPeriods,
|
||||
selectedPrice: yearly,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm).toMatchObject({ changeKind: "billing_period_change", effectiveAt: "period_end", effectiveAtDate: periodEnd });
|
||||
});
|
||||
|
||||
it("treats a storage-only top-up as an immediate configuration increase", () => {
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentStorageAddOnCodes: [],
|
||||
selectedStorageAddOnCodes: ["storage_100gb"],
|
||||
currentRecurringNetTotalCents: 19_900,
|
||||
baseAmountCents: 19_900,
|
||||
storageAmountCents: 900,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm).toMatchObject({ changeKind: "configuration_increase", effectiveAt: "immediate", effectiveAtDate: null });
|
||||
});
|
||||
|
||||
it("defers a storage-only reduction to the current period end", () => {
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentStorageAddOnCodes: ["storage_100gb"],
|
||||
selectedStorageAddOnCodes: [],
|
||||
currentRecurringNetTotalCents: 20_800,
|
||||
baseAmountCents: 19_900,
|
||||
storageAmountCents: 0,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm).toMatchObject({ changeKind: "configuration_decrease", effectiveAt: "period_end", effectiveAtDate: periodEnd });
|
||||
});
|
||||
|
||||
it("does not multiply flat package prices by the selected seat quantity", () => {
|
||||
const flatPlan = plan("starter", { quantityMode: "flat" });
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({
|
||||
currentPlan: null,
|
||||
currentPrice: null,
|
||||
currentSeatQuantity: 0,
|
||||
currentPeriodEnd: null,
|
||||
selectedPlan: flatPlan,
|
||||
selectedPrice: flatPlan.prices[0]!,
|
||||
selectedSeatQuantity: 7,
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm.recurringTotalCents).toBe(flatPlan.prices[0]!.unitAmountCents);
|
||||
});
|
||||
|
||||
it("uses the supplied server management policy", () => {
|
||||
const customPolicy = buildSelfServiceSubscriptionManagementPolicyVM({
|
||||
planOrder: ["starter", "business"],
|
||||
effectiveAtByChangeKind: { ...effectiveAtByChangeKind, seat_increase: "period_end" },
|
||||
});
|
||||
const vm = buildSelfServiceSubscriptionPricePreviewVM(previewInput({ selectedSeatQuantity: 3, policy: customPolicy }));
|
||||
|
||||
expect(vm).toMatchObject({ changeKind: "seat_increase", effectiveAt: "period_end", effectiveAtDate: periodEnd });
|
||||
});
|
||||
|
||||
it("rejects a price that is absent from or differs from the selected plan catalog", () => {
|
||||
expect(() => buildSelfServiceSubscriptionPricePreviewVM(previewInput({ selectedPrice: price({ id: "unknown" }) }))).toThrow(/does not belong/);
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({ selectedPrice: { ...starter.prices[0]!, unitAmountCents: starter.prices[0]!.unitAmountCents + 1 } })
|
||||
)
|
||||
).toThrow(/does not match/);
|
||||
});
|
||||
|
||||
it("rejects plan changes outside the server-owned hierarchy", () => {
|
||||
const unknown = plan("unknown");
|
||||
expect(() => buildSelfServiceSubscriptionPricePreviewVM(previewInput({ selectedPlan: unknown, selectedPrice: unknown.prices[0]! }))).toThrow(
|
||||
/missing from policy planOrder/
|
||||
);
|
||||
});
|
||||
|
||||
it("requires a period end for deferred changes", () => {
|
||||
expect(() => buildSelfServiceSubscriptionPricePreviewVM(previewInput({ currentSeatQuantity: 2, selectedSeatQuantity: 1, currentPeriodEnd: null }))).toThrow(
|
||||
/currentPeriodEnd is required/
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["zero selected seats", { selectedSeatQuantity: 0 }],
|
||||
["fractional selected seats", { selectedSeatQuantity: 1.5 }],
|
||||
["zero current seats with a subscription", { currentSeatQuantity: 0 }],
|
||||
])("rejects %s", (_label, overrides) => {
|
||||
expect(() => buildSelfServiceSubscriptionPricePreviewVM(previewInput(overrides))).toThrow(/SeatQuantity/);
|
||||
});
|
||||
|
||||
it("rejects totals outside the safe integer range", () => {
|
||||
const expensive = plan("expensive", {
|
||||
prices: [price({ id: "price_expensive", unitAmountCents: Number.MAX_SAFE_INTEGER })],
|
||||
});
|
||||
const expensivePolicy = buildSelfServiceSubscriptionManagementPolicyVM({ planOrder: ["starter", "expensive"], effectiveAtByChangeKind });
|
||||
|
||||
expect(() =>
|
||||
buildSelfServiceSubscriptionPricePreviewVM(
|
||||
previewInput({ selectedPlan: expensive, selectedPrice: expensive.prices[0]!, selectedSeatQuantity: 2, policy: expensivePolicy })
|
||||
)
|
||||
).toThrow(/safe integer range/);
|
||||
});
|
||||
});
|
||||
+740
@@ -0,0 +1,740 @@
|
||||
import type { SubscriptionOverviewVM } from "./subscription-overview.vm.js";
|
||||
|
||||
export type SelfServiceSubscriptionPlanFeatureVM = {
|
||||
readonly code: string;
|
||||
readonly titleKey: string;
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionPriceVM = {
|
||||
readonly id: string;
|
||||
readonly billingPeriod: number;
|
||||
readonly currency: string;
|
||||
readonly unitAmountCents: number;
|
||||
readonly trialDays: number;
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionPackageTermsVM = {
|
||||
readonly packageId: "starter" | "team" | "business";
|
||||
readonly monthlyCents: number;
|
||||
readonly annualSepaMonthlyEquivalentCents: number;
|
||||
readonly officeSeatsIncluded: number;
|
||||
readonly fieldSeatsIncluded: number;
|
||||
readonly storageIncludedGb: number;
|
||||
readonly storagePerAdditionalSeatGb: number;
|
||||
readonly officeExtraMonthlyCents: number;
|
||||
readonly fieldExtraMonthlyCents: number;
|
||||
readonly officeExtraAnnualSepaCents: number;
|
||||
readonly fieldExtraAnnualSepaCents: number;
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionPlanVM = {
|
||||
readonly id: string;
|
||||
readonly code: string;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
readonly badge: string | null;
|
||||
readonly quantityMode: "flat" | "per_seat";
|
||||
readonly packageTerms?: SelfServiceSubscriptionPackageTermsVM | null;
|
||||
readonly features: readonly SelfServiceSubscriptionPlanFeatureVM[];
|
||||
readonly prices: readonly SelfServiceSubscriptionPriceVM[];
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionCatalogVM = {
|
||||
/**
|
||||
* The server supplies only public, active plans and prices in ascending plan
|
||||
* order. Keeping that order makes the upgrade hierarchy explicit without
|
||||
* exposing persistence-specific fields in the public plan contract.
|
||||
*/
|
||||
readonly plans: readonly SelfServiceSubscriptionPlanVM[];
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionChangeKind =
|
||||
| "new"
|
||||
| "upgrade"
|
||||
| "downgrade"
|
||||
| "billing_period_change"
|
||||
| "seat_increase"
|
||||
| "seat_decrease"
|
||||
| "configuration_increase"
|
||||
| "configuration_decrease"
|
||||
| "configuration_change"
|
||||
| "unchanged";
|
||||
|
||||
export type SelfServiceSubscriptionEffectiveAt = "immediate" | "period_end";
|
||||
|
||||
export type SelfServiceSubscriptionManagementPolicyVM = {
|
||||
/** Plan codes in ascending entitlement/tier order. */
|
||||
readonly planOrder: readonly string[];
|
||||
readonly effectiveAtByChangeKind: Readonly<Record<SelfServiceSubscriptionChangeKind, SelfServiceSubscriptionEffectiveAt>>;
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionTrialPolicyVM = {
|
||||
readonly requiresManualActivation: false;
|
||||
readonly requiresPaymentMethod: true;
|
||||
};
|
||||
|
||||
export type SelfServiceCheckoutPaymentMethodsVM =
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly methods: readonly {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
}[];
|
||||
}
|
||||
| {
|
||||
readonly status: "fallback";
|
||||
readonly methods: readonly [];
|
||||
}
|
||||
| {
|
||||
readonly status: "required_card_unavailable";
|
||||
readonly methods: readonly [];
|
||||
};
|
||||
|
||||
export function buildSelfServiceCheckoutPaymentMethodsVM(
|
||||
methods: readonly { readonly id: string; readonly label: string }[] | null,
|
||||
unavailableRequirement?: "card"
|
||||
): SelfServiceCheckoutPaymentMethodsVM {
|
||||
if (!methods?.length) {
|
||||
return unavailableRequirement === "card" ? { status: "required_card_unavailable", methods: [] } : { status: "fallback", methods: [] };
|
||||
}
|
||||
const normalized = methods.map((method) => ({
|
||||
id: assertNonEmpty(method.id, "paymentMethod.id").toLowerCase(),
|
||||
label: assertNonEmpty(method.label, `paymentMethod.label for ${method.id}`),
|
||||
}));
|
||||
if (normalized.some((method) => !/^[a-z][a-z0-9_-]{1,63}$/u.test(method.id)) || new Set(normalized.map((method) => method.id)).size !== normalized.length) {
|
||||
throw new Error("payment methods must have unique provider ids");
|
||||
}
|
||||
return { status: "ready", methods: normalized };
|
||||
}
|
||||
|
||||
export type SelfServiceSubscriptionUsageVM = {
|
||||
readonly storage:
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly capacityBytes: number;
|
||||
readonly storedBytes: number;
|
||||
readonly reservedBytes: number;
|
||||
readonly remainingBytes: number;
|
||||
readonly percentUsed: number;
|
||||
}
|
||||
| {
|
||||
readonly status: "unavailable";
|
||||
readonly reason: "subscription_missing" | "billing_read_only" | "plan_unknown";
|
||||
};
|
||||
readonly emailMarketing:
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly periodStart: string;
|
||||
readonly periodEnd: string;
|
||||
readonly limit: number | null;
|
||||
readonly used: number;
|
||||
readonly remaining: number | null;
|
||||
readonly percentUsed: number | null;
|
||||
}
|
||||
| {
|
||||
readonly status: "unavailable";
|
||||
readonly reason: "billing_read_only" | "plan_required" | "limit_invalid";
|
||||
};
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionPageVM = {
|
||||
readonly overview: SubscriptionOverviewVM;
|
||||
readonly catalog: SelfServiceSubscriptionCatalogVM;
|
||||
readonly managementPolicy: SelfServiceSubscriptionManagementPolicyVM;
|
||||
readonly minimumSeatQuantity: number;
|
||||
readonly minimumSeatQuantities: {
|
||||
readonly office: number;
|
||||
readonly field: number;
|
||||
};
|
||||
readonly storageAddOns: readonly {
|
||||
readonly code: string;
|
||||
readonly title: string;
|
||||
readonly storageGb: number;
|
||||
readonly amountCents: number;
|
||||
readonly currency: string;
|
||||
}[];
|
||||
readonly emailMarketingAddOns: readonly {
|
||||
readonly productId: string;
|
||||
readonly priceId: string;
|
||||
readonly code: string;
|
||||
readonly title: string;
|
||||
readonly monthlyEmailLimit: number;
|
||||
readonly amountCents: number;
|
||||
readonly vatRateBasisPoints: number;
|
||||
readonly vatAmountCents: number;
|
||||
readonly grossAmountCents: number;
|
||||
readonly currency: string;
|
||||
readonly active: boolean;
|
||||
}[];
|
||||
readonly usage: SelfServiceSubscriptionUsageVM | null;
|
||||
readonly canManage: boolean;
|
||||
readonly billingHref: string;
|
||||
readonly trialPolicy: SelfServiceSubscriptionTrialPolicyVM;
|
||||
readonly currentSelection: SelfServiceSubscriptionCurrentSelectionVM | null;
|
||||
readonly preferredSelection: {
|
||||
readonly planId: string;
|
||||
readonly priceId: string;
|
||||
readonly officeSeatQuantity?: number;
|
||||
readonly fieldSeatQuantity?: number;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionCurrentSelectionVM = {
|
||||
readonly planId: string;
|
||||
readonly planCode: string;
|
||||
readonly priceId: string | null;
|
||||
readonly seatQuantity: number;
|
||||
readonly officeSeatQuantity?: number;
|
||||
readonly fieldSeatQuantity?: number;
|
||||
readonly storageAddOnCodes?: readonly string[];
|
||||
};
|
||||
|
||||
export type SelfServiceSubscriptionPricePreviewVM = {
|
||||
readonly currentPlan: SelfServiceSubscriptionPlanVM | null;
|
||||
readonly currentPrice: SelfServiceSubscriptionPriceVM | null;
|
||||
readonly currentSeatQuantity: number;
|
||||
readonly currentPeriodEnd: string | null;
|
||||
readonly selectedPlan: SelfServiceSubscriptionPlanVM;
|
||||
readonly selectedPrice: SelfServiceSubscriptionPriceVM;
|
||||
readonly selectedSeatQuantity: number;
|
||||
readonly selectedOfficeSeatQuantity: number;
|
||||
readonly selectedFieldSeatQuantity: number;
|
||||
readonly selectedStorageAddOnCodes: readonly string[];
|
||||
readonly includedStorageGb: number;
|
||||
readonly additionalSeatStorageGb: number;
|
||||
readonly addOnStorageGb: number;
|
||||
readonly totalStorageGb: number;
|
||||
readonly baseAmountCents: number;
|
||||
readonly officeSeatAmountCents: number;
|
||||
readonly fieldSeatAmountCents: number;
|
||||
readonly storageAmountCents: number;
|
||||
readonly recurringNetTotalCents: number;
|
||||
readonly vatRateBasisPoints: number;
|
||||
readonly vatAmountCents: number;
|
||||
readonly recurringGrossTotalCents: number;
|
||||
readonly changeKind: SelfServiceSubscriptionChangeKind;
|
||||
readonly effectiveAt: SelfServiceSubscriptionEffectiveAt;
|
||||
readonly effectiveAtDate: string | null;
|
||||
/** Backward-compatible net total. New payment code must use recurringGrossTotalCents. */
|
||||
readonly recurringTotalCents: number;
|
||||
readonly trialDays: number;
|
||||
};
|
||||
|
||||
export type BuildSelfServiceSubscriptionCatalogVMInput = {
|
||||
/** Must already be tenant-safe and filtered to public, active catalog rows. */
|
||||
readonly plans: readonly SelfServiceSubscriptionPlanVM[];
|
||||
};
|
||||
|
||||
export type BuildSelfServiceSubscriptionManagementPolicyVMInput = {
|
||||
readonly planOrder: readonly string[];
|
||||
readonly effectiveAtByChangeKind: Readonly<Record<SelfServiceSubscriptionChangeKind, SelfServiceSubscriptionEffectiveAt>>;
|
||||
};
|
||||
|
||||
export type BuildSelfServiceSubscriptionPageVMInput = {
|
||||
readonly overview: SubscriptionOverviewVM;
|
||||
readonly catalog: SelfServiceSubscriptionCatalogVM;
|
||||
readonly managementPolicy: SelfServiceSubscriptionManagementPolicyVM;
|
||||
readonly minimumSeatQuantity: number;
|
||||
readonly minimumSeatQuantities?: {
|
||||
readonly office: number;
|
||||
readonly field: number;
|
||||
};
|
||||
readonly storageAddOns?: SelfServiceSubscriptionPageVM["storageAddOns"];
|
||||
readonly emailMarketingAddOns?: SelfServiceSubscriptionPageVM["emailMarketingAddOns"];
|
||||
readonly usage?: SelfServiceSubscriptionUsageVM | null;
|
||||
readonly canManage: boolean;
|
||||
readonly billingHref: string;
|
||||
readonly currentSelection?: SelfServiceSubscriptionCurrentSelectionVM | null;
|
||||
readonly preferredSelection?: {
|
||||
readonly planId: string;
|
||||
readonly priceId: string;
|
||||
readonly officeSeatQuantity?: number;
|
||||
readonly fieldSeatQuantity?: number;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export type BuildSelfServiceSubscriptionPricePreviewVMInput = {
|
||||
readonly currentPlan: SelfServiceSubscriptionPlanVM | null;
|
||||
readonly currentPrice?: SelfServiceSubscriptionPriceVM | null;
|
||||
readonly currentSeatQuantity: number;
|
||||
readonly currentOfficeSeatQuantity?: number;
|
||||
readonly currentFieldSeatQuantity?: number;
|
||||
readonly currentStorageAddOnCodes?: readonly string[];
|
||||
readonly currentRecurringNetTotalCents?: number;
|
||||
readonly currentPeriodEnd: string | null;
|
||||
readonly selectedPlan: SelfServiceSubscriptionPlanVM;
|
||||
readonly selectedPrice: SelfServiceSubscriptionPriceVM;
|
||||
readonly selectedSeatQuantity: number;
|
||||
readonly selectedOfficeSeatQuantity?: number;
|
||||
readonly selectedFieldSeatQuantity?: number;
|
||||
readonly selectedStorageAddOnCodes?: readonly string[];
|
||||
readonly includedStorageGb?: number;
|
||||
readonly additionalSeatStorageGb?: number;
|
||||
readonly addOnStorageGb?: number;
|
||||
readonly totalStorageGb?: number;
|
||||
readonly baseAmountCents?: number;
|
||||
readonly officeSeatAmountCents?: number;
|
||||
readonly fieldSeatAmountCents?: number;
|
||||
readonly storageAmountCents?: number;
|
||||
readonly vatRateBasisPoints?: number;
|
||||
readonly vatAmountCents?: number;
|
||||
readonly recurringGrossTotalCents?: number;
|
||||
readonly policy: SelfServiceSubscriptionManagementPolicyVM;
|
||||
};
|
||||
|
||||
const TRIAL_POLICY: SelfServiceSubscriptionTrialPolicyVM = {
|
||||
requiresManualActivation: false,
|
||||
requiresPaymentMethod: true,
|
||||
};
|
||||
|
||||
function assertNonEmpty(value: string, field: string): string {
|
||||
const normalized = value.trim();
|
||||
if (!normalized) throw new Error(`${field} must not be empty`);
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function assertNonNegativeInteger(value: number, field: string): number {
|
||||
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`${field} must be a non-negative safe integer`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertPositiveInteger(value: number, field: string): number {
|
||||
if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${field} must be a positive safe integer`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertIsoTimestamp(value: string, field: string): string {
|
||||
const normalized = value.trim();
|
||||
const parsed = new Date(normalized);
|
||||
if (!normalized || !Number.isFinite(parsed.getTime()) || parsed.toISOString() !== normalized) {
|
||||
throw new Error(`${field} must be a canonical ISO timestamp`);
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
function assertBasisPoints(value: number, field: string): number {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 10_000) {
|
||||
throw new Error(`${field} must be an integer between 0 and 10000`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function assertEffectiveAt(value: SelfServiceSubscriptionEffectiveAt, changeKind: SelfServiceSubscriptionChangeKind): SelfServiceSubscriptionEffectiveAt {
|
||||
if (value !== "immediate" && value !== "period_end") throw new Error(`Invalid effectiveAt policy for ${changeKind}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function cloneFeature(feature: SelfServiceSubscriptionPlanFeatureVM, planCode: string): SelfServiceSubscriptionPlanFeatureVM {
|
||||
return {
|
||||
code: assertNonEmpty(feature.code, `Feature code for plan ${planCode}`),
|
||||
titleKey: assertNonEmpty(feature.titleKey, `Feature titleKey for plan ${planCode}`),
|
||||
};
|
||||
}
|
||||
|
||||
function clonePrice(price: SelfServiceSubscriptionPriceVM, planCode: string): SelfServiceSubscriptionPriceVM {
|
||||
return {
|
||||
id: assertNonEmpty(price.id, `Price id for plan ${planCode}`),
|
||||
billingPeriod: assertNonNegativeInteger(price.billingPeriod, `Price billingPeriod for plan ${planCode}`),
|
||||
currency: assertNonEmpty(price.currency, `Price currency for plan ${planCode}`).toUpperCase(),
|
||||
unitAmountCents: assertNonNegativeInteger(price.unitAmountCents, `Price unitAmountCents for plan ${planCode}`),
|
||||
trialDays: assertNonNegativeInteger(price.trialDays, `Price trialDays for plan ${planCode}`),
|
||||
};
|
||||
}
|
||||
|
||||
function assertUnique(values: readonly string[], field: string): void {
|
||||
const seen = new Set<string>();
|
||||
for (const value of values) {
|
||||
if (seen.has(value)) throw new Error(`${field} contains duplicate value ${value}`);
|
||||
seen.add(value);
|
||||
}
|
||||
}
|
||||
|
||||
function clonePlan(plan: SelfServiceSubscriptionPlanVM): SelfServiceSubscriptionPlanVM {
|
||||
const id = assertNonEmpty(plan.id, "Plan id");
|
||||
const code = assertNonEmpty(plan.code, `Plan code for ${id}`);
|
||||
const features = plan.features.map((feature) => cloneFeature(feature, code));
|
||||
const prices = plan.prices.map((price) => clonePrice(price, code));
|
||||
|
||||
assertUnique(
|
||||
features.map((feature) => feature.code),
|
||||
`Features for plan ${code}`
|
||||
);
|
||||
assertUnique(
|
||||
prices.map((price) => price.id),
|
||||
`Prices for plan ${code}`
|
||||
);
|
||||
|
||||
return {
|
||||
id,
|
||||
code,
|
||||
titleKey: assertNonEmpty(plan.titleKey, `Plan titleKey for ${code}`),
|
||||
descriptionKey: assertNonEmpty(plan.descriptionKey, `Plan descriptionKey for ${code}`),
|
||||
badge: plan.badge?.trim() || null,
|
||||
quantityMode: plan.quantityMode === "per_seat" ? "per_seat" : "flat",
|
||||
...(plan.packageTerms
|
||||
? {
|
||||
packageTerms: {
|
||||
packageId: plan.packageTerms.packageId,
|
||||
monthlyCents: assertNonNegativeInteger(plan.packageTerms.monthlyCents, `Package monthly price for ${code}`),
|
||||
annualSepaMonthlyEquivalentCents: assertNonNegativeInteger(
|
||||
plan.packageTerms.annualSepaMonthlyEquivalentCents,
|
||||
`Package annual SEPA price for ${code}`
|
||||
),
|
||||
officeSeatsIncluded: assertNonNegativeInteger(plan.packageTerms.officeSeatsIncluded, `Office seats for ${code}`),
|
||||
fieldSeatsIncluded: assertNonNegativeInteger(plan.packageTerms.fieldSeatsIncluded, `Field seats for ${code}`),
|
||||
storageIncludedGb: assertNonNegativeInteger(plan.packageTerms.storageIncludedGb, `Storage for ${code}`),
|
||||
storagePerAdditionalSeatGb: assertPositiveInteger(
|
||||
plan.packageTerms.storagePerAdditionalSeatGb,
|
||||
`Storage per additional seat for ${code}`
|
||||
),
|
||||
officeExtraMonthlyCents: assertNonNegativeInteger(plan.packageTerms.officeExtraMonthlyCents, `Office extra-seat price for ${code}`),
|
||||
fieldExtraMonthlyCents: assertNonNegativeInteger(plan.packageTerms.fieldExtraMonthlyCents, `Field extra-seat price for ${code}`),
|
||||
officeExtraAnnualSepaCents: assertNonNegativeInteger(plan.packageTerms.officeExtraAnnualSepaCents, `Office annual extra-seat price for ${code}`),
|
||||
fieldExtraAnnualSepaCents: assertNonNegativeInteger(plan.packageTerms.fieldExtraAnnualSepaCents, `Field annual extra-seat price for ${code}`),
|
||||
},
|
||||
}
|
||||
: plan.packageTerms === null
|
||||
? { packageTerms: null }
|
||||
: {}),
|
||||
features,
|
||||
prices,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSelfServiceSubscriptionCatalogVM(input: BuildSelfServiceSubscriptionCatalogVMInput): SelfServiceSubscriptionCatalogVM {
|
||||
const plans = input.plans.map(clonePlan);
|
||||
assertUnique(
|
||||
plans.map((plan) => plan.id),
|
||||
"Catalog plan ids"
|
||||
);
|
||||
assertUnique(
|
||||
plans.map((plan) => plan.code),
|
||||
"Catalog plan codes"
|
||||
);
|
||||
return { plans };
|
||||
}
|
||||
|
||||
export function buildSelfServiceSubscriptionManagementPolicyVM(
|
||||
input: BuildSelfServiceSubscriptionManagementPolicyVMInput
|
||||
): SelfServiceSubscriptionManagementPolicyVM {
|
||||
const planOrder = input.planOrder.map((code) => assertNonEmpty(code, "Policy plan code"));
|
||||
assertUnique(planOrder, "Policy planOrder");
|
||||
|
||||
return {
|
||||
planOrder,
|
||||
effectiveAtByChangeKind: {
|
||||
new: assertEffectiveAt(input.effectiveAtByChangeKind.new, "new"),
|
||||
upgrade: assertEffectiveAt(input.effectiveAtByChangeKind.upgrade, "upgrade"),
|
||||
downgrade: assertEffectiveAt(input.effectiveAtByChangeKind.downgrade, "downgrade"),
|
||||
billing_period_change: assertEffectiveAt(input.effectiveAtByChangeKind.billing_period_change, "billing_period_change"),
|
||||
seat_increase: assertEffectiveAt(input.effectiveAtByChangeKind.seat_increase, "seat_increase"),
|
||||
seat_decrease: assertEffectiveAt(input.effectiveAtByChangeKind.seat_decrease, "seat_decrease"),
|
||||
configuration_increase: assertEffectiveAt(input.effectiveAtByChangeKind.configuration_increase, "configuration_increase"),
|
||||
configuration_decrease: assertEffectiveAt(input.effectiveAtByChangeKind.configuration_decrease, "configuration_decrease"),
|
||||
configuration_change: assertEffectiveAt(input.effectiveAtByChangeKind.configuration_change, "configuration_change"),
|
||||
unchanged: assertEffectiveAt(input.effectiveAtByChangeKind.unchanged, "unchanged"),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildSelfServiceSubscriptionPageVM(input: BuildSelfServiceSubscriptionPageVMInput): SelfServiceSubscriptionPageVM {
|
||||
const catalog = buildSelfServiceSubscriptionCatalogVM(input.catalog);
|
||||
const minimumSeatQuantity = assertPositiveInteger(input.minimumSeatQuantity, "minimumSeatQuantity");
|
||||
const minimumSeatQuantities = input.minimumSeatQuantities
|
||||
? {
|
||||
office: assertNonNegativeInteger(input.minimumSeatQuantities.office, "minimumSeatQuantities.office"),
|
||||
field: assertNonNegativeInteger(input.minimumSeatQuantities.field, "minimumSeatQuantities.field"),
|
||||
}
|
||||
: { office: minimumSeatQuantity, field: 0 };
|
||||
const managementPolicy = buildSelfServiceSubscriptionManagementPolicyVM(input.managementPolicy);
|
||||
const preferredSelection = input.preferredSelection
|
||||
? {
|
||||
planId: assertNonEmpty(input.preferredSelection.planId, "preferredSelection.planId"),
|
||||
priceId: assertNonEmpty(input.preferredSelection.priceId, "preferredSelection.priceId"),
|
||||
...(input.preferredSelection.officeSeatQuantity === undefined
|
||||
? {}
|
||||
: {
|
||||
officeSeatQuantity: assertPositiveInteger(input.preferredSelection.officeSeatQuantity, "preferredSelection.officeSeatQuantity"),
|
||||
}),
|
||||
...(input.preferredSelection.fieldSeatQuantity === undefined
|
||||
? {}
|
||||
: {
|
||||
fieldSeatQuantity: assertNonNegativeInteger(input.preferredSelection.fieldSeatQuantity, "preferredSelection.fieldSeatQuantity"),
|
||||
}),
|
||||
}
|
||||
: null;
|
||||
if (preferredSelection && (preferredSelection.officeSeatQuantity === undefined) !== (preferredSelection.fieldSeatQuantity === undefined)) {
|
||||
throw new Error("preferredSelection seat quantities must be provided together");
|
||||
}
|
||||
if (
|
||||
preferredSelection &&
|
||||
!catalog.plans.some((plan) => plan.id === preferredSelection.planId && plan.prices.some((price) => price.id === preferredSelection.priceId))
|
||||
) {
|
||||
throw new Error("preferredSelection must reference an available catalog price");
|
||||
}
|
||||
|
||||
const storageUsage =
|
||||
input.usage?.storage.status === "ready"
|
||||
? {
|
||||
status: "ready" as const,
|
||||
capacityBytes: assertPositiveInteger(input.usage.storage.capacityBytes, "usage.storage.capacityBytes"),
|
||||
storedBytes: assertNonNegativeInteger(input.usage.storage.storedBytes, "usage.storage.storedBytes"),
|
||||
reservedBytes: assertNonNegativeInteger(input.usage.storage.reservedBytes, "usage.storage.reservedBytes"),
|
||||
remainingBytes: assertNonNegativeInteger(input.usage.storage.remainingBytes, "usage.storage.remainingBytes"),
|
||||
percentUsed: Math.min(100, ((input.usage.storage.storedBytes + input.usage.storage.reservedBytes) / input.usage.storage.capacityBytes) * 100),
|
||||
}
|
||||
: input.usage?.storage;
|
||||
if (
|
||||
storageUsage?.status === "ready" &&
|
||||
storageUsage.remainingBytes !== Math.max(0, storageUsage.capacityBytes - storageUsage.storedBytes - storageUsage.reservedBytes)
|
||||
) {
|
||||
throw new Error("usage.storage.remainingBytes must match capacity minus used and reserved bytes");
|
||||
}
|
||||
|
||||
const emailMarketingUsage =
|
||||
input.usage?.emailMarketing.status === "ready"
|
||||
? {
|
||||
status: "ready" as const,
|
||||
periodStart: assertIsoTimestamp(input.usage.emailMarketing.periodStart, "usage.emailMarketing.periodStart"),
|
||||
periodEnd: assertIsoTimestamp(input.usage.emailMarketing.periodEnd, "usage.emailMarketing.periodEnd"),
|
||||
limit: input.usage.emailMarketing.limit === null ? null : assertPositiveInteger(input.usage.emailMarketing.limit, "usage.emailMarketing.limit"),
|
||||
used: assertNonNegativeInteger(input.usage.emailMarketing.used, "usage.emailMarketing.used"),
|
||||
remaining:
|
||||
input.usage.emailMarketing.remaining === null
|
||||
? null
|
||||
: assertNonNegativeInteger(input.usage.emailMarketing.remaining, "usage.emailMarketing.remaining"),
|
||||
percentUsed:
|
||||
input.usage.emailMarketing.limit === null ? null : Math.min(100, (input.usage.emailMarketing.used / input.usage.emailMarketing.limit) * 100),
|
||||
}
|
||||
: input.usage?.emailMarketing;
|
||||
if (
|
||||
emailMarketingUsage?.status === "ready" &&
|
||||
emailMarketingUsage.remaining !== (emailMarketingUsage.limit === null ? null : Math.max(0, emailMarketingUsage.limit - emailMarketingUsage.used))
|
||||
) {
|
||||
throw new Error("usage.emailMarketing.remaining must match limit minus used");
|
||||
}
|
||||
const usage = input.usage && storageUsage && emailMarketingUsage ? { storage: storageUsage, emailMarketing: emailMarketingUsage } : null;
|
||||
|
||||
return {
|
||||
overview: input.overview,
|
||||
catalog,
|
||||
managementPolicy,
|
||||
minimumSeatQuantity,
|
||||
minimumSeatQuantities,
|
||||
storageAddOns: (input.storageAddOns ?? []).map((addOn) => ({
|
||||
code: assertNonEmpty(addOn.code, "storageAddOn.code"),
|
||||
title: assertNonEmpty(addOn.title, `storageAddOn.title for ${addOn.code}`),
|
||||
storageGb: assertPositiveInteger(addOn.storageGb, `storageAddOn.storageGb for ${addOn.code}`),
|
||||
amountCents: assertPositiveInteger(addOn.amountCents, `storageAddOn.amountCents for ${addOn.code}`),
|
||||
currency: assertNonEmpty(addOn.currency, `storageAddOn.currency for ${addOn.code}`).toUpperCase(),
|
||||
})),
|
||||
emailMarketingAddOns: (input.emailMarketingAddOns ?? []).map((addOn) => {
|
||||
const amountCents = assertPositiveInteger(addOn.amountCents, `emailMarketingAddOn.amountCents for ${addOn.code}`);
|
||||
const vatAmountCents = assertPositiveInteger(addOn.vatAmountCents, `emailMarketingAddOn.vatAmountCents for ${addOn.code}`);
|
||||
const grossAmountCents = assertPositiveInteger(addOn.grossAmountCents, `emailMarketingAddOn.grossAmountCents for ${addOn.code}`);
|
||||
if (amountCents + vatAmountCents !== grossAmountCents) {
|
||||
throw new RangeError(`emailMarketingAddOn gross amount for ${addOn.code} must equal net amount plus VAT`);
|
||||
}
|
||||
return {
|
||||
productId: assertNonEmpty(addOn.productId, `emailMarketingAddOn.productId for ${addOn.code}`),
|
||||
priceId: assertNonEmpty(addOn.priceId, `emailMarketingAddOn.priceId for ${addOn.code}`),
|
||||
code: assertNonEmpty(addOn.code, "emailMarketingAddOn.code"),
|
||||
title: assertNonEmpty(addOn.title, `emailMarketingAddOn.title for ${addOn.code}`),
|
||||
monthlyEmailLimit: assertPositiveInteger(addOn.monthlyEmailLimit, `emailMarketingAddOn.monthlyEmailLimit for ${addOn.code}`),
|
||||
amountCents,
|
||||
vatRateBasisPoints: assertPositiveInteger(addOn.vatRateBasisPoints, `emailMarketingAddOn.vatRateBasisPoints for ${addOn.code}`),
|
||||
vatAmountCents,
|
||||
grossAmountCents,
|
||||
currency: assertNonEmpty(addOn.currency, `emailMarketingAddOn.currency for ${addOn.code}`).toUpperCase(),
|
||||
active: addOn.active,
|
||||
};
|
||||
}),
|
||||
usage,
|
||||
canManage: input.canManage,
|
||||
billingHref: assertNonEmpty(input.billingHref, "billingHref"),
|
||||
trialPolicy: { ...TRIAL_POLICY },
|
||||
preferredSelection,
|
||||
currentSelection: input.currentSelection
|
||||
? {
|
||||
planId: assertNonEmpty(input.currentSelection.planId, "currentSelection.planId"),
|
||||
planCode: assertNonEmpty(input.currentSelection.planCode, "currentSelection.planCode"),
|
||||
priceId: input.currentSelection.priceId?.trim() || null,
|
||||
seatQuantity: assertPositiveInteger(input.currentSelection.seatQuantity, "currentSelection.seatQuantity"),
|
||||
...(input.currentSelection.officeSeatQuantity === undefined
|
||||
? {}
|
||||
: {
|
||||
officeSeatQuantity: assertNonNegativeInteger(input.currentSelection.officeSeatQuantity, "currentSelection.officeSeatQuantity"),
|
||||
}),
|
||||
...(input.currentSelection.fieldSeatQuantity === undefined
|
||||
? {}
|
||||
: {
|
||||
fieldSeatQuantity: assertNonNegativeInteger(input.currentSelection.fieldSeatQuantity, "currentSelection.fieldSeatQuantity"),
|
||||
}),
|
||||
...(input.currentSelection.storageAddOnCodes === undefined
|
||||
? {}
|
||||
: {
|
||||
storageAddOnCodes: input.currentSelection.storageAddOnCodes.map((code) => assertNonEmpty(code, "currentSelection.storageAddOnCode")),
|
||||
}),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
function resolvePlanChangeKind(
|
||||
currentPlan: SelfServiceSubscriptionPlanVM,
|
||||
selectedPlan: SelfServiceSubscriptionPlanVM,
|
||||
policy: SelfServiceSubscriptionManagementPolicyVM
|
||||
): "upgrade" | "downgrade" | null {
|
||||
if (currentPlan.code === selectedPlan.code) return null;
|
||||
|
||||
const currentRank = policy.planOrder.indexOf(currentPlan.code);
|
||||
const selectedRank = policy.planOrder.indexOf(selectedPlan.code);
|
||||
if (currentRank < 0) throw new Error(`Current plan ${currentPlan.code} is missing from policy planOrder`);
|
||||
if (selectedRank < 0) throw new Error(`Selected plan ${selectedPlan.code} is missing from policy planOrder`);
|
||||
return selectedRank > currentRank ? "upgrade" : "downgrade";
|
||||
}
|
||||
|
||||
function resolveChangeKind(input: BuildSelfServiceSubscriptionPricePreviewVMInput): SelfServiceSubscriptionChangeKind {
|
||||
if (!input.currentPlan) return "new";
|
||||
|
||||
const planChangeKind = resolvePlanChangeKind(input.currentPlan, input.selectedPlan, input.policy);
|
||||
if (planChangeKind) return planChangeKind;
|
||||
if (input.currentPrice && input.currentPrice.id !== input.selectedPrice.id) return "billing_period_change";
|
||||
if (input.selectedSeatQuantity > input.currentSeatQuantity) return "seat_increase";
|
||||
if (input.selectedSeatQuantity < input.currentSeatQuantity) return "seat_decrease";
|
||||
|
||||
const currentStorageCodes = [...new Set(input.currentStorageAddOnCodes ?? [])].sort();
|
||||
const selectedStorageCodes = [...new Set(input.selectedStorageAddOnCodes ?? [])].sort();
|
||||
const roleMixChanged =
|
||||
(input.currentOfficeSeatQuantity !== undefined && input.currentOfficeSeatQuantity !== input.selectedOfficeSeatQuantity) ||
|
||||
(input.currentFieldSeatQuantity !== undefined && input.currentFieldSeatQuantity !== input.selectedFieldSeatQuantity);
|
||||
const storageChanged =
|
||||
currentStorageCodes.length !== selectedStorageCodes.length || currentStorageCodes.some((code, index) => code !== selectedStorageCodes[index]);
|
||||
if (roleMixChanged || storageChanged) {
|
||||
const selectedRecurringNetTotalCents =
|
||||
(input.baseAmountCents ?? 0) + (input.officeSeatAmountCents ?? 0) + (input.fieldSeatAmountCents ?? 0) + (input.storageAmountCents ?? 0);
|
||||
const currentRecurringNetTotalCents = input.currentRecurringNetTotalCents;
|
||||
if (currentRecurringNetTotalCents !== undefined) {
|
||||
if (selectedRecurringNetTotalCents > currentRecurringNetTotalCents) return "configuration_increase";
|
||||
if (selectedRecurringNetTotalCents < currentRecurringNetTotalCents) return "configuration_decrease";
|
||||
}
|
||||
return "configuration_change";
|
||||
}
|
||||
return "unchanged";
|
||||
}
|
||||
|
||||
function samePrice(left: SelfServiceSubscriptionPriceVM, right: SelfServiceSubscriptionPriceVM): boolean {
|
||||
return (
|
||||
left.id === right.id &&
|
||||
left.billingPeriod === right.billingPeriod &&
|
||||
left.currency.toUpperCase() === right.currency.toUpperCase() &&
|
||||
left.unitAmountCents === right.unitAmountCents &&
|
||||
left.trialDays === right.trialDays
|
||||
);
|
||||
}
|
||||
|
||||
export function buildSelfServiceSubscriptionPricePreviewVM(input: BuildSelfServiceSubscriptionPricePreviewVMInput): SelfServiceSubscriptionPricePreviewVM {
|
||||
const selectedPlan = clonePlan(input.selectedPlan);
|
||||
const requestedPrice = clonePrice(input.selectedPrice, selectedPlan.code);
|
||||
const selectedPrice = selectedPlan.prices.find((price) => price.id === requestedPrice.id);
|
||||
if (!selectedPrice) throw new Error(`Price ${requestedPrice.id} does not belong to selected plan ${selectedPlan.code}`);
|
||||
if (!samePrice(selectedPrice, requestedPrice)) throw new Error(`Price ${requestedPrice.id} does not match selected plan catalog data`);
|
||||
|
||||
const currentPlan = input.currentPlan ? clonePlan(input.currentPlan) : null;
|
||||
const currentPrice = currentPlan && input.currentPrice ? (currentPlan.prices.find((price) => price.id === input.currentPrice?.id) ?? null) : null;
|
||||
const currentSeatQuantity = currentPlan
|
||||
? assertPositiveInteger(input.currentSeatQuantity, "currentSeatQuantity")
|
||||
: assertNonNegativeInteger(input.currentSeatQuantity, "currentSeatQuantity");
|
||||
const selectedSeatQuantity = assertPositiveInteger(input.selectedSeatQuantity, "selectedSeatQuantity");
|
||||
const policy = buildSelfServiceSubscriptionManagementPolicyVM(input.policy);
|
||||
const changeKind = resolveChangeKind({
|
||||
...input,
|
||||
currentPlan,
|
||||
currentPrice,
|
||||
currentSeatQuantity,
|
||||
selectedPlan,
|
||||
selectedPrice,
|
||||
selectedSeatQuantity,
|
||||
policy,
|
||||
});
|
||||
const effectiveAt = policy.effectiveAtByChangeKind[changeKind];
|
||||
if (effectiveAt === "period_end" && !input.currentPeriodEnd) throw new Error(`currentPeriodEnd is required for ${changeKind}`);
|
||||
|
||||
const recurringTotalCents = selectedPlan.quantityMode === "per_seat" ? selectedPrice.unitAmountCents * selectedSeatQuantity : selectedPrice.unitAmountCents;
|
||||
if (!Number.isSafeInteger(recurringTotalCents)) {
|
||||
throw new Error("recurringTotalCents exceeds the safe integer range");
|
||||
}
|
||||
const selectedOfficeSeatQuantity = assertNonNegativeInteger(input.selectedOfficeSeatQuantity ?? selectedSeatQuantity, "selectedOfficeSeatQuantity");
|
||||
const selectedFieldSeatQuantity = assertNonNegativeInteger(input.selectedFieldSeatQuantity ?? 0, "selectedFieldSeatQuantity");
|
||||
if (selectedOfficeSeatQuantity + selectedFieldSeatQuantity !== selectedSeatQuantity) {
|
||||
throw new Error("Selected role seat quantities must equal selectedSeatQuantity");
|
||||
}
|
||||
const baseAmountCents = assertNonNegativeInteger(input.baseAmountCents ?? recurringTotalCents, "baseAmountCents");
|
||||
const officeSeatAmountCents = assertNonNegativeInteger(input.officeSeatAmountCents ?? 0, "officeSeatAmountCents");
|
||||
const fieldSeatAmountCents = assertNonNegativeInteger(input.fieldSeatAmountCents ?? 0, "fieldSeatAmountCents");
|
||||
const storageAmountCents = assertNonNegativeInteger(input.storageAmountCents ?? 0, "storageAmountCents");
|
||||
const calculatedRecurringTotalCents =
|
||||
input.baseAmountCents === undefined &&
|
||||
input.officeSeatAmountCents === undefined &&
|
||||
input.fieldSeatAmountCents === undefined &&
|
||||
input.storageAmountCents === undefined
|
||||
? recurringTotalCents
|
||||
: baseAmountCents + officeSeatAmountCents + fieldSeatAmountCents + storageAmountCents;
|
||||
if (!Number.isSafeInteger(calculatedRecurringTotalCents)) throw new Error("recurringTotalCents exceeds the safe integer range");
|
||||
const vatRateBasisPoints = assertBasisPoints(input.vatRateBasisPoints ?? 0, "vatRateBasisPoints");
|
||||
const expectedVatAmountCents = Math.round((calculatedRecurringTotalCents * vatRateBasisPoints) / 10_000);
|
||||
const vatAmountCents = assertNonNegativeInteger(input.vatAmountCents ?? expectedVatAmountCents, "vatAmountCents");
|
||||
if (vatAmountCents !== expectedVatAmountCents) {
|
||||
throw new Error("vatAmountCents does not match recurring net total and VAT rate");
|
||||
}
|
||||
const expectedGrossTotalCents = calculatedRecurringTotalCents + vatAmountCents;
|
||||
if (!Number.isSafeInteger(expectedGrossTotalCents)) {
|
||||
throw new Error("recurringGrossTotalCents exceeds the safe integer range");
|
||||
}
|
||||
const recurringGrossTotalCents = assertNonNegativeInteger(input.recurringGrossTotalCents ?? expectedGrossTotalCents, "recurringGrossTotalCents");
|
||||
if (recurringGrossTotalCents !== expectedGrossTotalCents) {
|
||||
throw new Error("recurringGrossTotalCents does not match net total plus VAT");
|
||||
}
|
||||
const selectedStorageAddOnCodes = (input.selectedStorageAddOnCodes ?? []).map((code) => assertNonEmpty(code, "selectedStorageAddOnCode"));
|
||||
assertUnique(selectedStorageAddOnCodes, "selectedStorageAddOnCodes");
|
||||
const includedStorageGb = assertPositiveInteger(input.includedStorageGb ?? selectedPlan.packageTerms?.storageIncludedGb ?? 1, "includedStorageGb");
|
||||
const additionalSeatStorageGb = assertNonNegativeInteger(input.additionalSeatStorageGb ?? 0, "additionalSeatStorageGb");
|
||||
const addOnStorageGb = assertNonNegativeInteger(input.addOnStorageGb ?? 0, "addOnStorageGb");
|
||||
const totalStorageGb = assertPositiveInteger(
|
||||
input.totalStorageGb ?? includedStorageGb + additionalSeatStorageGb + addOnStorageGb,
|
||||
"totalStorageGb"
|
||||
);
|
||||
if (totalStorageGb !== includedStorageGb + additionalSeatStorageGb + addOnStorageGb) {
|
||||
throw new Error("totalStorageGb must equal included, additional-seat, and add-on storage");
|
||||
}
|
||||
|
||||
return {
|
||||
currentPlan,
|
||||
currentPrice,
|
||||
currentSeatQuantity,
|
||||
currentPeriodEnd: input.currentPeriodEnd,
|
||||
selectedPlan,
|
||||
selectedPrice,
|
||||
selectedSeatQuantity,
|
||||
selectedOfficeSeatQuantity,
|
||||
selectedFieldSeatQuantity,
|
||||
selectedStorageAddOnCodes,
|
||||
includedStorageGb,
|
||||
additionalSeatStorageGb,
|
||||
addOnStorageGb,
|
||||
totalStorageGb,
|
||||
baseAmountCents,
|
||||
officeSeatAmountCents,
|
||||
fieldSeatAmountCents,
|
||||
storageAmountCents,
|
||||
recurringNetTotalCents: calculatedRecurringTotalCents,
|
||||
vatRateBasisPoints,
|
||||
vatAmountCents,
|
||||
recurringGrossTotalCents,
|
||||
changeKind,
|
||||
effectiveAt,
|
||||
effectiveAtDate: effectiveAt === "period_end" ? input.currentPeriodEnd : null,
|
||||
recurringTotalCents: calculatedRecurringTotalCents,
|
||||
trialDays: selectedPrice.trialDays,
|
||||
};
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSubscriptionBannerVM, isSubscriptionBannerStatus } from "./subscription-banner.vm.js";
|
||||
|
||||
describe("subscription banner view-model", () => {
|
||||
it("returns empty when there is no subscription", () => {
|
||||
expect(buildSubscriptionBannerVM({ status: "active", hasSubscription: false })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("hides trial banners when the end is unknown, invalid, expired, or more than three days away", () => {
|
||||
const now = "2026-07-12T12:00:00.000Z";
|
||||
expect(buildSubscriptionBannerVM({ status: "trial", hasSubscription: true, now })).toEqual({ status: "empty" });
|
||||
expect(buildSubscriptionBannerVM({ status: "trial", hasSubscription: true, trialEndsAt: "not-a-date", now })).toEqual({ status: "empty" });
|
||||
expect(buildSubscriptionBannerVM({ status: "trial", hasSubscription: true, trialEndsAt: "2026-07-12T11:59:59.999Z", now })).toEqual({ status: "empty" });
|
||||
expect(buildSubscriptionBannerVM({ status: "trial", hasSubscription: true, trialEndsAt: "2026-07-15T12:00:00.001Z", now })).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("shows trial banners only inside the final three days", () => {
|
||||
const vm = buildSubscriptionBannerVM({
|
||||
status: "trial",
|
||||
hasSubscription: true,
|
||||
trialEndsAt: "2026-07-15T12:00:00.000Z",
|
||||
now: "2026-07-12T12:00:00.000Z",
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.status).toBe("trial");
|
||||
expect(vm.data.tone).toBe("success");
|
||||
expect(vm.data.trialDaysRemaining).toBe(3);
|
||||
expect(vm.data.readOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps active available for surfaces that choose to render it", () => {
|
||||
const vm = buildSubscriptionBannerVM({ status: "active", hasSubscription: true });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.status).toBe("active");
|
||||
expect(vm.data.tone).toBe("success");
|
||||
expect(vm.data.trialDaysRemaining).toBeNull();
|
||||
expect(vm.data.readOnly).toBe(false);
|
||||
});
|
||||
|
||||
it("falls back to trial for unknown status only when a final-window end date is known", () => {
|
||||
const vm = buildSubscriptionBannerVM({
|
||||
status: "gibberish",
|
||||
hasSubscription: true,
|
||||
trialEndsAt: "2026-07-14T00:00:00.000Z",
|
||||
now: "2026-07-12T00:00:00.000Z",
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.status).toBe("trial");
|
||||
expect(vm.data.trialDaysRemaining).toBe(2);
|
||||
});
|
||||
|
||||
it("marks past_due and cancelled as warnings and read-only", () => {
|
||||
const pastDue = buildSubscriptionBannerVM({ status: "past_due", hasSubscription: true });
|
||||
const cancelled = buildSubscriptionBannerVM({ status: "cancelled", hasSubscription: true });
|
||||
if (pastDue.status !== "ready" || cancelled.status !== "ready") throw new Error("expected ready");
|
||||
expect(pastDue.data.tone).toBe("warning");
|
||||
expect(pastDue.data.readOnly).toBe(true);
|
||||
expect(pastDue.data.titleKey).toBe("settings.subscription.banner.pastDue.title");
|
||||
expect(pastDue.data.descriptionKey).toBe("settings.subscription.banner.pastDue.description");
|
||||
expect(cancelled.data.tone).toBe("warning");
|
||||
expect(cancelled.data.readOnly).toBe(true);
|
||||
expect(cancelled.data.titleKey).toBe("settings.subscription.banner.cancelled.title");
|
||||
});
|
||||
|
||||
it("escalates a frozen account to the danger tone", () => {
|
||||
const vm = buildSubscriptionBannerVM({ status: "frozen", hasSubscription: true });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.tone).toBe("danger");
|
||||
expect(vm.data.readOnly).toBe(true);
|
||||
expect(vm.data.titleKey).toBe("settings.subscription.banner.frozen.title");
|
||||
});
|
||||
|
||||
it("guards the status union", () => {
|
||||
expect(isSubscriptionBannerStatus("frozen")).toBe(true);
|
||||
expect(isSubscriptionBannerStatus("past_due")).toBe(true);
|
||||
expect(isSubscriptionBannerStatus("nope")).toBe(false);
|
||||
expect(isSubscriptionBannerStatus(null)).toBe(false);
|
||||
});
|
||||
});
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* Tenant-facing subscription/billing status banner (Welle 4, Deliverable 1).
|
||||
*
|
||||
* Pure presentation: the loader normalizes the raw {@link TenantSubscription}
|
||||
* status (reusing `normalizeBillingSubscriptionStatus` from `@hivegrid/db`) and
|
||||
* hands the resolved status here. This function maps the five billing states to
|
||||
* a prominent account-level banner (tone + i18n keys). No new states are
|
||||
* invented — the status set mirrors `TenantSubscription.status`.
|
||||
*/
|
||||
|
||||
export type SubscriptionBannerStatus = "trial" | "active" | "past_due" | "cancelled" | "frozen";
|
||||
export type SubscriptionBannerTone = "success" | "warning" | "danger";
|
||||
|
||||
export type SubscriptionBannerData = {
|
||||
readonly status: SubscriptionBannerStatus;
|
||||
readonly tone: SubscriptionBannerTone;
|
||||
readonly titleKey: string;
|
||||
readonly descriptionKey: string;
|
||||
/** Whole days until the trial ends; populated only inside the final three-day window. */
|
||||
readonly trialDaysRemaining: number | null;
|
||||
/** Read-only states (past_due|cancelled|frozen) limit write access. */
|
||||
readonly readOnly: boolean;
|
||||
};
|
||||
|
||||
export type SubscriptionBannerVM = VMState<SubscriptionBannerData>;
|
||||
|
||||
// i18n key segment per status (camelCase, aligned with the `billing:status.*`
|
||||
// namespace naming already used across the app).
|
||||
const STATUS_KEY_SEGMENT: Record<SubscriptionBannerStatus, string> = {
|
||||
trial: "trial",
|
||||
active: "active",
|
||||
past_due: "pastDue",
|
||||
cancelled: "cancelled",
|
||||
frozen: "frozen",
|
||||
};
|
||||
|
||||
// Tone per status. Constrained to success/warning/danger (no info tone):
|
||||
// active/trial read as positive, past_due/cancelled as a soft warning, and a
|
||||
// frozen (read-only, service interrupted) account as the hard danger signal.
|
||||
const STATUS_TONE: Record<SubscriptionBannerStatus, SubscriptionBannerTone> = {
|
||||
trial: "success",
|
||||
active: "success",
|
||||
past_due: "warning",
|
||||
cancelled: "warning",
|
||||
frozen: "danger",
|
||||
};
|
||||
|
||||
const READ_ONLY_STATUSES: ReadonlySet<SubscriptionBannerStatus> = new Set(["past_due", "cancelled", "frozen"]);
|
||||
const DAY_IN_MS = 24 * 60 * 60 * 1000;
|
||||
const TRIAL_BANNER_WINDOW_IN_MS = 3 * DAY_IN_MS;
|
||||
|
||||
export type SubscriptionBannerInput = {
|
||||
readonly status: string | null | undefined;
|
||||
readonly hasSubscription: boolean;
|
||||
readonly trialEndsAt?: Date | string | null;
|
||||
/** Injectable clock for deterministic server-side rendering and tests. */
|
||||
readonly now?: Date | string;
|
||||
};
|
||||
|
||||
export function isSubscriptionBannerStatus(value: string | null | undefined): value is SubscriptionBannerStatus {
|
||||
return value === "trial" || value === "active" || value === "past_due" || value === "cancelled" || value === "frozen";
|
||||
}
|
||||
|
||||
function timestamp(value: Date | string | null | undefined): number | null {
|
||||
if (!value) return null;
|
||||
const parsed = value instanceof Date ? value.getTime() : Date.parse(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
function trialDaysRemaining(input: Pick<SubscriptionBannerInput, "trialEndsAt" | "now">): number | null {
|
||||
const trialEnd = timestamp(input.trialEndsAt);
|
||||
const now = timestamp(input.now ?? new Date());
|
||||
if (trialEnd === null || now === null) return null;
|
||||
|
||||
const remaining = trialEnd - now;
|
||||
if (remaining < 0 || remaining > TRIAL_BANNER_WINDOW_IN_MS) return null;
|
||||
return Math.ceil(remaining / DAY_IN_MS);
|
||||
}
|
||||
|
||||
export function buildSubscriptionBannerVM(input: SubscriptionBannerInput): SubscriptionBannerVM {
|
||||
if (!input.hasSubscription) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
const status = isSubscriptionBannerStatus(input.status) ? input.status : "trial";
|
||||
const remainingTrialDays = status === "trial" ? trialDaysRemaining(input) : null;
|
||||
if (status === "trial" && remainingTrialDays === null) {
|
||||
return { status: "empty" };
|
||||
}
|
||||
const segment = STATUS_KEY_SEGMENT[status];
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
status,
|
||||
tone: STATUS_TONE[status],
|
||||
titleKey: `settings.subscription.banner.${segment}.title`,
|
||||
descriptionKey: `settings.subscription.banner.${segment}.description`,
|
||||
trialDaysRemaining: remainingTrialDays,
|
||||
readOnly: READ_ONLY_STATUSES.has(status),
|
||||
},
|
||||
};
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSubscriptionOverviewVM, type BuildSubscriptionOverviewVMInput } from "./subscription-overview.vm.js";
|
||||
|
||||
function input(overrides: Partial<BuildSubscriptionOverviewVMInput> = {}): BuildSubscriptionOverviewVMInput {
|
||||
return {
|
||||
hasSubscription: true,
|
||||
status: "active",
|
||||
planCode: "business",
|
||||
seatUsage: { status: "empty" },
|
||||
products: [
|
||||
{
|
||||
id: "product_1",
|
||||
titleKey: "plans.business",
|
||||
code: "business",
|
||||
kind: "recurring_add_on",
|
||||
acquisition: {
|
||||
productKind: "recurring_add_on",
|
||||
status: "active",
|
||||
lagoSubscriptionId: "lago_subscription_1",
|
||||
},
|
||||
quantity: 2,
|
||||
currentPeriodEnd: "2026-08-01T00:00:00.000Z",
|
||||
prices: [{ amount: 49, currency: "eur", billingPeriod: 3 }],
|
||||
},
|
||||
],
|
||||
entitlements: [{ code: "automation", titleKey: "features.automation", enabled: true, value: 100, used: 12, remaining: 88 }],
|
||||
canCancel: true,
|
||||
contactHref: "https://example.test/contact",
|
||||
now: "2026-07-12T00:00:00.000Z",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildSubscriptionOverviewVM", () => {
|
||||
it("returns an empty state when no subscription exists", () => {
|
||||
expect(buildSubscriptionOverviewVM(input({ hasSubscription: false }))).toEqual({ status: "empty" });
|
||||
});
|
||||
|
||||
it("builds a read-only plan overview without catalog or checkout data", () => {
|
||||
const vm = buildSubscriptionOverviewVM(input());
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
expect(vm.data).toMatchObject({ status: "active", planCode: "business", planLabel: "plans.business" });
|
||||
expect(vm.data?.products[0]).toMatchObject({ state: "active", canCancel: true, quantity: 2 });
|
||||
expect(vm.data?.products[0]?.prices[0]).toEqual({
|
||||
amount: 49,
|
||||
currency: "EUR",
|
||||
period: "monthly",
|
||||
periodLabelKey: "billing:subscriptionOverview.period.monthly",
|
||||
quantity: 1,
|
||||
});
|
||||
expect(vm.data?.entitlements[0]?.code).toBe("automation");
|
||||
expect(vm.data).not.toHaveProperty("availablePlans");
|
||||
expect(vm.data).not.toHaveProperty("checkout");
|
||||
});
|
||||
|
||||
it("marks cancelled and ended products as non-cancellable", () => {
|
||||
const vm = buildSubscriptionOverviewVM(
|
||||
input({
|
||||
products: [
|
||||
{ id: "cancelled", titleKey: "plans.cancelled", cancelledAt: "2026-07-01T00:00:00.000Z", endsAt: "2026-08-01T00:00:00.000Z", prices: [] },
|
||||
{ id: "ended", titleKey: "plans.ended", endsAt: "2026-07-01T00:00:00.000Z", prices: [] },
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm.data?.products.map(({ state, canCancel }) => ({ state, canCancel }))).toEqual([
|
||||
{ state: "cancelled", canCancel: false },
|
||||
{ state: "ended", canCancel: false },
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks a future product as scheduled and keeps it non-cancellable", () => {
|
||||
const vm = buildSubscriptionOverviewVM(
|
||||
input({
|
||||
products: [
|
||||
{
|
||||
id: "scheduled",
|
||||
titleKey: "plans.business",
|
||||
currentPeriodStart: "2026-08-01T00:00:00.000Z",
|
||||
prices: [],
|
||||
},
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm.data?.products[0]).toMatchObject({ state: "scheduled", canCancel: false });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
label: "base plan",
|
||||
product: { kind: "base_plan" as const, acquisition: null },
|
||||
},
|
||||
{
|
||||
label: "one-time setup",
|
||||
product: { kind: "one_time_setup" as const, acquisition: null },
|
||||
},
|
||||
{
|
||||
label: "recurring add-on without an acquisition",
|
||||
product: { kind: "recurring_add_on" as const, acquisition: null },
|
||||
},
|
||||
{
|
||||
label: "recurring add-on without a provider reference",
|
||||
product: {
|
||||
kind: "recurring_add_on" as const,
|
||||
acquisition: { productKind: "recurring_add_on" as const, status: "active", lagoSubscriptionId: null },
|
||||
},
|
||||
},
|
||||
{
|
||||
label: "inactive recurring acquisition",
|
||||
product: {
|
||||
kind: "recurring_add_on" as const,
|
||||
acquisition: { productKind: "recurring_add_on" as const, status: "cancelled", lagoSubscriptionId: "lago_subscription_1" },
|
||||
},
|
||||
},
|
||||
])("keeps an active $label non-cancellable", ({ product }) => {
|
||||
const vm = buildSubscriptionOverviewVM(
|
||||
input({
|
||||
products: [{ id: "protected", titleKey: "plans.protected", prices: [], ...product }],
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm.data?.products[0]).toMatchObject({ state: "active", canCancel: false });
|
||||
});
|
||||
|
||||
it("exposes a deterministic trial countdown and the final-three-days banner", () => {
|
||||
const vm = buildSubscriptionOverviewVM(
|
||||
input({
|
||||
status: "trial",
|
||||
trialEndsAt: "2026-07-15T00:00:00.000Z",
|
||||
})
|
||||
);
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") return;
|
||||
expect(vm.data.trialEndsAt).toBe("2026-07-15T00:00:00.000Z");
|
||||
expect(vm.data.trialDaysRemaining).toBe(3);
|
||||
expect(vm.data.banner).toMatchObject({ status: "ready", data: { status: "trial", trialDaysRemaining: 3 } });
|
||||
});
|
||||
});
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import { buildSubscriptionBannerVM, type SubscriptionBannerVM, type SubscriptionBannerStatus } from "./subscription-banner.vm.js";
|
||||
import type { SeatUsageVM } from "./seat-usage.vm.js";
|
||||
|
||||
export type SubscriptionOverviewPricePeriod = "once" | "daily" | "weekly" | "monthly" | "yearly" | "quarterly" | "semiAnnual" | "unknown";
|
||||
export type SubscriptionOverviewProductState = "active" | "cancelled" | "ended" | "scheduled";
|
||||
|
||||
export type SubscriptionOverviewPriceInput = {
|
||||
readonly amount: number | null;
|
||||
readonly currency: string | null;
|
||||
readonly billingPeriod: number | null;
|
||||
readonly quantity?: number | null;
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewProductInput = {
|
||||
readonly id: string;
|
||||
readonly titleKey: string;
|
||||
readonly code?: string | null;
|
||||
readonly kind?: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override" | null;
|
||||
readonly acquisition?: {
|
||||
readonly productKind: "base_plan" | "recurring_add_on" | "one_time_setup" | "contract_override";
|
||||
readonly status: string;
|
||||
readonly lagoSubscriptionId: string | null;
|
||||
} | null;
|
||||
readonly quantity?: number | null;
|
||||
readonly cancelledAt?: string | null;
|
||||
readonly endsAt?: string | null;
|
||||
readonly currentPeriodStart?: string | null;
|
||||
readonly currentPeriodEnd?: string | null;
|
||||
readonly prices: readonly SubscriptionOverviewPriceInput[];
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewEntitlementInput = {
|
||||
readonly code: string;
|
||||
readonly titleKey: string;
|
||||
readonly enabled: boolean;
|
||||
readonly value: number;
|
||||
readonly used: number;
|
||||
readonly remaining: number | "unlimited";
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewPriceVM = {
|
||||
readonly amount: number | null;
|
||||
readonly currency: string | null;
|
||||
readonly period: SubscriptionOverviewPricePeriod;
|
||||
readonly periodLabelKey: string;
|
||||
readonly quantity: number;
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewProductVM = {
|
||||
readonly id: string;
|
||||
readonly titleKey: string;
|
||||
readonly code: string | null;
|
||||
readonly quantity: number;
|
||||
readonly state: SubscriptionOverviewProductState;
|
||||
readonly stateLabelKey: string;
|
||||
readonly currentPeriodEnd: string | null;
|
||||
readonly canCancel: boolean;
|
||||
readonly prices: readonly SubscriptionOverviewPriceVM[];
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewEntitlementVM = SubscriptionOverviewEntitlementInput & {
|
||||
readonly labelKey: string;
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewData = {
|
||||
readonly status: SubscriptionBannerStatus;
|
||||
readonly statusLabelKey: string;
|
||||
readonly trialEndsAt: string | null;
|
||||
readonly trialDaysRemaining: number | null;
|
||||
readonly planCode: string | null;
|
||||
readonly planLabel: string | null;
|
||||
readonly banner: SubscriptionBannerVM;
|
||||
readonly seatUsage: SeatUsageVM;
|
||||
readonly products: readonly SubscriptionOverviewProductVM[];
|
||||
readonly entitlements: readonly SubscriptionOverviewEntitlementVM[];
|
||||
readonly contactHref: string;
|
||||
readonly emptyTitleKey: string;
|
||||
readonly emptyDescriptionKey: string;
|
||||
};
|
||||
|
||||
export type SubscriptionOverviewVM = VMState<SubscriptionOverviewData>;
|
||||
|
||||
export type BuildSubscriptionOverviewVMInput = {
|
||||
readonly hasSubscription: boolean;
|
||||
readonly status: string | null | undefined;
|
||||
readonly trialEndsAt?: string | null;
|
||||
readonly planCode?: string | null;
|
||||
readonly seatUsage: SeatUsageVM;
|
||||
readonly products: readonly SubscriptionOverviewProductInput[];
|
||||
readonly entitlements: readonly SubscriptionOverviewEntitlementInput[];
|
||||
readonly canCancel: boolean;
|
||||
readonly contactHref: string;
|
||||
readonly now?: string;
|
||||
};
|
||||
|
||||
const PERIODS: Readonly<Record<number, SubscriptionOverviewPricePeriod>> = {
|
||||
0: "once",
|
||||
1: "daily",
|
||||
2: "weekly",
|
||||
3: "monthly",
|
||||
4: "yearly",
|
||||
5: "quarterly",
|
||||
6: "semiAnnual",
|
||||
};
|
||||
|
||||
function normalizeStatus(status: string | null | undefined): SubscriptionBannerStatus {
|
||||
if (status === "active" || status === "past_due" || status === "cancelled" || status === "frozen") return status;
|
||||
return "trial";
|
||||
}
|
||||
|
||||
function productState(product: SubscriptionOverviewProductInput, now: number): SubscriptionOverviewProductState {
|
||||
if (product.endsAt && Date.parse(product.endsAt) <= now) return "ended";
|
||||
if (product.cancelledAt) return "cancelled";
|
||||
if (product.currentPeriodStart && Date.parse(product.currentPeriodStart) > now) return "scheduled";
|
||||
return "active";
|
||||
}
|
||||
|
||||
function priceVM(price: SubscriptionOverviewPriceInput): SubscriptionOverviewPriceVM {
|
||||
const period = price.billingPeriod === null ? "unknown" : (PERIODS[price.billingPeriod] ?? "unknown");
|
||||
return {
|
||||
amount: price.amount,
|
||||
currency: price.currency?.toUpperCase() ?? null,
|
||||
period,
|
||||
periodLabelKey: `billing:subscriptionOverview.period.${period}`,
|
||||
quantity: Math.max(1, price.quantity ?? 1),
|
||||
};
|
||||
}
|
||||
|
||||
function remainingTrialDays(trialEndsAt: string | null | undefined, now: number): number | null {
|
||||
if (!trialEndsAt) return null;
|
||||
const end = Date.parse(trialEndsAt);
|
||||
if (!Number.isFinite(end)) return null;
|
||||
return Math.max(0, Math.ceil((end - now) / (24 * 60 * 60 * 1000)));
|
||||
}
|
||||
|
||||
function isCancellableRecurringAddOn(product: SubscriptionOverviewProductInput, state: SubscriptionOverviewProductState): boolean {
|
||||
const acquisition = product.acquisition;
|
||||
return (
|
||||
state === "active" &&
|
||||
product.kind === "recurring_add_on" &&
|
||||
acquisition?.productKind === "recurring_add_on" &&
|
||||
acquisition.status === "active" &&
|
||||
Boolean(acquisition.lagoSubscriptionId?.trim())
|
||||
);
|
||||
}
|
||||
|
||||
export function buildSubscriptionOverviewVM(input: BuildSubscriptionOverviewVMInput): SubscriptionOverviewVM {
|
||||
if (!input.hasSubscription) return { status: "empty" };
|
||||
|
||||
const status = normalizeStatus(input.status);
|
||||
const now = Date.parse(input.now ?? new Date().toISOString());
|
||||
const products = input.products.map((product): SubscriptionOverviewProductVM => {
|
||||
const state = productState(product, now);
|
||||
return {
|
||||
id: product.id,
|
||||
titleKey: product.titleKey,
|
||||
code: product.code?.trim() || null,
|
||||
quantity: Math.max(1, product.quantity ?? 1),
|
||||
state,
|
||||
stateLabelKey: `billing:subscriptionOverview.productState.${state}`,
|
||||
currentPeriodEnd: product.currentPeriodEnd ?? product.endsAt ?? null,
|
||||
canCancel: input.canCancel && isCancellableRecurringAddOn(product, state),
|
||||
prices: product.prices.map(priceVM),
|
||||
};
|
||||
});
|
||||
const planCode = input.planCode?.trim() || null;
|
||||
const trialEndsAt = input.trialEndsAt ?? null;
|
||||
const trialDaysRemaining = status === "trial" ? remainingTrialDays(trialEndsAt, now) : null;
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
status,
|
||||
statusLabelKey: `billing:subscriptionOverview.status.${status}`,
|
||||
trialEndsAt,
|
||||
trialDaysRemaining,
|
||||
planCode,
|
||||
planLabel: products.find((product) => product.state !== "ended")?.titleKey ?? planCode,
|
||||
banner: buildSubscriptionBannerVM({ status, hasSubscription: true, trialEndsAt, now: input.now }),
|
||||
seatUsage: input.seatUsage,
|
||||
products,
|
||||
entitlements: [...input.entitlements]
|
||||
.sort((left, right) => left.titleKey.localeCompare(right.titleKey))
|
||||
.map((entitlement) => ({ ...entitlement, labelKey: entitlement.titleKey })),
|
||||
contactHref: input.contactHref,
|
||||
emptyTitleKey: "billing:subscriptionOverview.empty.title",
|
||||
emptyDescriptionKey: "billing:subscriptionOverview.empty.description",
|
||||
},
|
||||
};
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
AVAILABILITY_WEEKDAYS,
|
||||
buildAvailabilityVM,
|
||||
parseAvailabilityPayload,
|
||||
serializeAvailabilityPayload,
|
||||
type AvailabilityPayload,
|
||||
type AvailabilityRuleVM,
|
||||
} from "./availability.vm.js";
|
||||
|
||||
const rule = (over: Partial<AvailabilityRuleVM> = {}): AvailabilityRuleVM => ({
|
||||
id: "r1",
|
||||
dayOfWeek: "monday",
|
||||
startTime: "09:00",
|
||||
endTime: "12:00",
|
||||
timezone: "Europe/Berlin",
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("buildAvailabilityVM (M06 Block F, interim AD-28)", () => {
|
||||
it("groups rules by weekday in Monday-first order with sorted windows", () => {
|
||||
const vm = buildAvailabilityVM({
|
||||
rules: [rule({ id: "r2", startTime: "14:00", endTime: "17:00" }), rule(), rule({ id: "r3", dayOfWeek: "friday" })],
|
||||
exceptions: [],
|
||||
fallbackTimezone: "Europe/Berlin",
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(vm.data.rulesByWeekday.map((group) => group.day)).toEqual([...AVAILABILITY_WEEKDAYS]);
|
||||
const monday = vm.data.rulesByWeekday[0];
|
||||
expect(monday?.dayKey).toBe("bookings.availability.weekday.monday");
|
||||
expect(monday?.windows.map((w) => w.startTime)).toEqual(["09:00", "14:00"]);
|
||||
expect(vm.data.rulesByWeekday[4]?.windows).toHaveLength(1);
|
||||
expect(vm.data.rulesByWeekday[1]?.windows).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("prefers the persisted timezone over the fallback", () => {
|
||||
const withRule = buildAvailabilityVM({ rules: [rule({ timezone: "Europe/Vienna" })], exceptions: [], fallbackTimezone: "Europe/Berlin" });
|
||||
const withoutRule = buildAvailabilityVM({ rules: [], exceptions: [], fallbackTimezone: "Europe/Berlin" });
|
||||
if (withRule.status !== "ready" || !withRule.data || withoutRule.status !== "ready" || !withoutRule.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(withRule.data.defaultTimezone).toBe("Europe/Vienna");
|
||||
expect(withoutRule.data.defaultTimezone).toBe("Europe/Berlin");
|
||||
});
|
||||
});
|
||||
|
||||
describe("availability payload codecs", () => {
|
||||
const payload: AvailabilityPayload = {
|
||||
rules: [{ dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" }],
|
||||
exceptions: [
|
||||
{ date: "2026-07-20", kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
|
||||
{ date: "2026-07-21", kind: "custom_window", startTime: "10:00", endTime: "14:00", reason: null, timezone: "Europe/Berlin" },
|
||||
],
|
||||
};
|
||||
|
||||
it("round-trips serialize → parse", () => {
|
||||
const parsed = parseAvailabilityPayload(serializeAvailabilityPayload(payload));
|
||||
expect(parsed.ok).toBe(true);
|
||||
if (!parsed.ok) {
|
||||
throw new Error("expected ok");
|
||||
}
|
||||
expect(parsed.payload).toEqual(payload);
|
||||
});
|
||||
|
||||
it("rejects malformed JSON with a stable error key", () => {
|
||||
const parsed = parseAvailabilityPayload("{nope");
|
||||
expect(parsed).toEqual({ ok: false, errorKey: "bookings.availability.error.invalidPayload" });
|
||||
});
|
||||
|
||||
it("rejects wrong shapes (missing arrays, bad weekday, bad kind)", () => {
|
||||
expect(parseAvailabilityPayload(JSON.stringify({ rules: [] })).ok).toBe(false);
|
||||
expect(parseAvailabilityPayload(JSON.stringify({ rules: [{ dayOfWeek: "funday", startTime: "09:00", endTime: "10:00", timezone: "Europe/Berlin" }], exceptions: [] })).ok).toBe(false);
|
||||
expect(parseAvailabilityPayload(JSON.stringify({ rules: [], exceptions: [{ date: "2026-07-20", kind: "party", timezone: "Europe/Berlin" }] })).ok).toBe(false);
|
||||
});
|
||||
|
||||
it("normalizes omitted optional exception fields to null", () => {
|
||||
const parsed = parseAvailabilityPayload(JSON.stringify({ rules: [], exceptions: [{ date: "2026-07-20", kind: "unavailable", timezone: "Europe/Berlin" }] }));
|
||||
if (!parsed.ok) {
|
||||
throw new Error("expected ok");
|
||||
}
|
||||
expect(parsed.payload.exceptions[0]).toEqual({ date: "2026-07-20", kind: "unavailable", startTime: null, endTime: null, reason: null, timezone: "Europe/Berlin" });
|
||||
});
|
||||
});
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P16b · provider availability view-model + form payload codecs (M06 Block F,
|
||||
* interim UI AD-28). Pure (DoD A.3): the loader resolves the provider's persisted
|
||||
* rules/exceptions (AvailabilityService), this groups them for the weekly editor.
|
||||
* The editor submits one serialized JSON payload (atomic full replace); the codecs
|
||||
* here only validate the SHAPE — deep validation (times, timezone, windows) stays
|
||||
* in AvailabilityService on the server.
|
||||
*/
|
||||
|
||||
export type AvailabilityWeekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
|
||||
|
||||
export const AVAILABILITY_WEEKDAYS: readonly AvailabilityWeekday[] = [
|
||||
"monday",
|
||||
"tuesday",
|
||||
"wednesday",
|
||||
"thursday",
|
||||
"friday",
|
||||
"saturday",
|
||||
"sunday",
|
||||
];
|
||||
|
||||
export type AvailabilityExceptionKindVM = "unavailable" | "custom_window";
|
||||
|
||||
export interface AvailabilityRuleVM {
|
||||
readonly id: string | null;
|
||||
readonly dayOfWeek: AvailabilityWeekday;
|
||||
/** `HH:mm` wall-clock times. */
|
||||
readonly startTime: string;
|
||||
readonly endTime: string;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityExceptionVM {
|
||||
readonly id: string | null;
|
||||
/** ISO calendar date `YYYY-MM-DD`. */
|
||||
readonly date: string;
|
||||
readonly kind: AvailabilityExceptionKindVM;
|
||||
readonly startTime: string | null;
|
||||
readonly endTime: string | null;
|
||||
readonly reason: string | null;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityWeekdayGroup {
|
||||
readonly day: AvailabilityWeekday;
|
||||
/** i18n key for the weekday label (e.g. `bookings.availability.weekday.monday`). */
|
||||
readonly dayKey: string;
|
||||
readonly windows: readonly AvailabilityRuleVM[];
|
||||
}
|
||||
|
||||
export interface AvailabilityData {
|
||||
readonly rulesByWeekday: readonly AvailabilityWeekdayGroup[];
|
||||
readonly exceptions: readonly AvailabilityExceptionVM[];
|
||||
/** Timezone the editor pre-selects: first persisted rule/exception, else fallback. */
|
||||
readonly defaultTimezone: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type AvailabilityVM = VMState<AvailabilityData>;
|
||||
|
||||
export interface BuildAvailabilityInput {
|
||||
readonly rules: readonly AvailabilityRuleVM[];
|
||||
readonly exceptions: readonly AvailabilityExceptionVM[];
|
||||
readonly fallbackTimezone: string;
|
||||
}
|
||||
|
||||
export function availabilityWeekdayKey(day: AvailabilityWeekday): string {
|
||||
return `bookings.availability.weekday.${day}`;
|
||||
}
|
||||
|
||||
export function buildAvailabilityVM(input: BuildAvailabilityInput): AvailabilityVM {
|
||||
const rulesByWeekday = AVAILABILITY_WEEKDAYS.map((day) => ({
|
||||
day,
|
||||
dayKey: availabilityWeekdayKey(day),
|
||||
windows: input.rules
|
||||
.filter((rule) => rule.dayOfWeek === day)
|
||||
.slice()
|
||||
.sort((a, b) => a.startTime.localeCompare(b.startTime)),
|
||||
}));
|
||||
const defaultTimezone = input.rules[0]?.timezone ?? input.exceptions[0]?.timezone ?? input.fallbackTimezone;
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rulesByWeekday,
|
||||
exceptions: input.exceptions,
|
||||
defaultTimezone,
|
||||
emptyHeadlineKey: "bookings.availability.empty.headline",
|
||||
emptyBodyKey: "bookings.availability.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// --- form payload codecs (editor <-> action) ---
|
||||
|
||||
export interface AvailabilityRulePayload {
|
||||
readonly dayOfWeek: AvailabilityWeekday;
|
||||
readonly startTime: string;
|
||||
readonly endTime: string;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityExceptionPayload {
|
||||
readonly date: string;
|
||||
readonly kind: AvailabilityExceptionKindVM;
|
||||
readonly startTime: string | null;
|
||||
readonly endTime: string | null;
|
||||
readonly reason: string | null;
|
||||
readonly timezone: string;
|
||||
}
|
||||
|
||||
export interface AvailabilityPayload {
|
||||
readonly rules: readonly AvailabilityRulePayload[];
|
||||
readonly exceptions: readonly AvailabilityExceptionPayload[];
|
||||
}
|
||||
|
||||
export type ParsedAvailabilityPayload = { readonly ok: true; readonly payload: AvailabilityPayload } | { readonly ok: false; readonly errorKey: string };
|
||||
|
||||
export function serializeAvailabilityPayload(payload: AvailabilityPayload): string {
|
||||
return JSON.stringify(payload);
|
||||
}
|
||||
|
||||
const WEEKDAY_SET: ReadonlySet<string> = new Set(AVAILABILITY_WEEKDAYS);
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === "string" && value.length > 0;
|
||||
}
|
||||
|
||||
function parseRule(value: unknown): AvailabilityRulePayload | null {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
const rule = value as Record<string, unknown>;
|
||||
if (!isNonEmptyString(rule.dayOfWeek) || !WEEKDAY_SET.has(rule.dayOfWeek)) {
|
||||
return null;
|
||||
}
|
||||
if (!isNonEmptyString(rule.startTime) || !isNonEmptyString(rule.endTime) || !isNonEmptyString(rule.timezone)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
dayOfWeek: rule.dayOfWeek as AvailabilityWeekday,
|
||||
startTime: rule.startTime,
|
||||
endTime: rule.endTime,
|
||||
timezone: rule.timezone,
|
||||
};
|
||||
}
|
||||
|
||||
function parseException(value: unknown): AvailabilityExceptionPayload | null {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
const exception = value as Record<string, unknown>;
|
||||
if (!isNonEmptyString(exception.date) || !isNonEmptyString(exception.timezone)) {
|
||||
return null;
|
||||
}
|
||||
if (exception.kind !== "unavailable" && exception.kind !== "custom_window") {
|
||||
return null;
|
||||
}
|
||||
const startTime = exception.startTime;
|
||||
const endTime = exception.endTime;
|
||||
const reason = exception.reason;
|
||||
if (startTime !== null && startTime !== undefined && typeof startTime !== "string") {
|
||||
return null;
|
||||
}
|
||||
if (endTime !== null && endTime !== undefined && typeof endTime !== "string") {
|
||||
return null;
|
||||
}
|
||||
if (reason !== null && reason !== undefined && typeof reason !== "string") {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
date: exception.date,
|
||||
kind: exception.kind,
|
||||
startTime: (startTime as string | undefined) ?? null,
|
||||
endTime: (endTime as string | undefined) ?? null,
|
||||
reason: (reason as string | undefined) ?? null,
|
||||
timezone: exception.timezone,
|
||||
};
|
||||
}
|
||||
|
||||
/** Shape-validate the submitted editor payload; deep validation stays server-side. */
|
||||
export function parseAvailabilityPayload(json: string): ParsedAvailabilityPayload {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(json);
|
||||
} catch {
|
||||
return { ok: false, errorKey: "bookings.availability.error.invalidPayload" };
|
||||
}
|
||||
if (typeof raw !== "object" || raw === null) {
|
||||
return { ok: false, errorKey: "bookings.availability.error.invalidPayload" };
|
||||
}
|
||||
const { rules, exceptions } = raw as Record<string, unknown>;
|
||||
if (!Array.isArray(rules) || !Array.isArray(exceptions)) {
|
||||
return { ok: false, errorKey: "bookings.availability.error.invalidPayload" };
|
||||
}
|
||||
const parsedRules: AvailabilityRulePayload[] = [];
|
||||
for (const rule of rules) {
|
||||
const parsed = parseRule(rule);
|
||||
if (!parsed) {
|
||||
return { ok: false, errorKey: "bookings.availability.error.invalidPayload" };
|
||||
}
|
||||
parsedRules.push(parsed);
|
||||
}
|
||||
const parsedExceptions: AvailabilityExceptionPayload[] = [];
|
||||
for (const exception of exceptions) {
|
||||
const parsed = parseException(exception);
|
||||
if (!parsed) {
|
||||
return { ok: false, errorKey: "bookings.availability.error.invalidPayload" };
|
||||
}
|
||||
parsedExceptions.push(parsed);
|
||||
}
|
||||
return { ok: true, payload: { rules: parsedRules, exceptions: parsedExceptions } };
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
import type { VMState } from "../index.js";
|
||||
import type { AppointmentStatus } from "./booking-list.vm.js";
|
||||
|
||||
/**
|
||||
* AK-P16b · booking detail view-model (M06 Block D, interim UI AD-28). Pure
|
||||
* (DoD A.3): the loader resolves the appointment (owner-checked) plus the data
|
||||
* the lifecycle dialogs need — provider options for re-assign (admin only) and
|
||||
* the date bounds the reschedule picker may offer. Candidate slots themselves
|
||||
* are fetched per date via the route loader (`?slotsDate=`), not stored here.
|
||||
*/
|
||||
|
||||
export interface BookingIntakeEntry {
|
||||
readonly key: string;
|
||||
readonly value: string;
|
||||
}
|
||||
|
||||
export interface BookingProviderOption {
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
/** One selectable reschedule slot returned by the route loader for a date. */
|
||||
export interface RescheduleSlotOption {
|
||||
readonly startAtIso: string;
|
||||
/** Pre-formatted time label in the appointment's timezone (e.g. `09:30`). */
|
||||
readonly label: string;
|
||||
}
|
||||
|
||||
export interface BookingDetailData {
|
||||
readonly id: string;
|
||||
readonly status: AppointmentStatus;
|
||||
/** i18n key for the status pill (e.g. `bookings.status.scheduled`). */
|
||||
readonly statusKey: string;
|
||||
readonly whenLabel: string;
|
||||
readonly pageTitle: string;
|
||||
readonly customerName: string;
|
||||
readonly customerEmail: string;
|
||||
readonly intake: readonly BookingIntakeEntry[];
|
||||
readonly cancellationReason: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
/** Re-assign candidates; empty unless the viewer has `bookings.admin`. */
|
||||
readonly providerOptions: readonly BookingProviderOption[];
|
||||
/** Inclusive ISO date bounds the reschedule date picker may offer. */
|
||||
readonly minRescheduleDateIso: string;
|
||||
readonly maxRescheduleDateIso: string;
|
||||
}
|
||||
|
||||
export type BookingDetailVM = VMState<BookingDetailData>;
|
||||
|
||||
export interface BuildBookingDetailInput {
|
||||
readonly id: string;
|
||||
readonly status: AppointmentStatus;
|
||||
readonly whenLabel: string;
|
||||
readonly pageTitle: string;
|
||||
readonly customerName: string;
|
||||
readonly customerEmail: string;
|
||||
readonly intake: readonly BookingIntakeEntry[];
|
||||
readonly cancellationReason: string | null;
|
||||
readonly canWrite: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
readonly providerOptions: readonly BookingProviderOption[];
|
||||
readonly minRescheduleDateIso: string;
|
||||
readonly maxRescheduleDateIso: string;
|
||||
}
|
||||
|
||||
export function buildBookingDetailVM(input: BuildBookingDetailInput): BookingDetailVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
id: input.id,
|
||||
status: input.status,
|
||||
statusKey: `bookings.status.${input.status}`,
|
||||
whenLabel: input.whenLabel,
|
||||
pageTitle: input.pageTitle,
|
||||
customerName: input.customerName,
|
||||
customerEmail: input.customerEmail,
|
||||
intake: input.intake,
|
||||
cancellationReason: input.cancellationReason,
|
||||
canWrite: input.canWrite,
|
||||
canAdmin: input.canAdmin,
|
||||
providerOptions: input.providerOptions,
|
||||
minRescheduleDateIso: input.minRescheduleDateIso,
|
||||
maxRescheduleDateIso: input.maxRescheduleDateIso,
|
||||
},
|
||||
};
|
||||
}
|
||||
+13
@@ -36,6 +36,19 @@ export function bookingStatusKey(status: AppointmentStatus): string {
|
||||
return `bookings.status.${status}`;
|
||||
}
|
||||
|
||||
/** Interim list tabs (AD-28): brief's Anstehend/Vergangen/Storniert buckets. */
|
||||
export type BookingListTab = "upcoming" | "past" | "cancelled";
|
||||
|
||||
export function bookingListTab(row: Pick<BookingListRow, "status" | "startAtIso">, nowIso: string): BookingListTab {
|
||||
if (row.status === "cancelled") {
|
||||
return "cancelled";
|
||||
}
|
||||
if ((row.status === "scheduled" || row.status === "held") && row.startAtIso >= nowIso) {
|
||||
return "upcoming";
|
||||
}
|
||||
return "past";
|
||||
}
|
||||
|
||||
export interface BuildBookingListInput {
|
||||
readonly rows: readonly BookingListRow[];
|
||||
}
|
||||
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
/**
|
||||
* AK-P16b · booking-pages list view-model (M06 Block E.1, interim UI AD-28).
|
||||
* Pure (DoD A.3): the loader resolves the tenant's booking pages and the
|
||||
* absolute public URL per row (no `window.location` access in the screen).
|
||||
*/
|
||||
|
||||
export interface BookingPageListRow {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly slug: string;
|
||||
readonly durationMinutes: number;
|
||||
readonly isPublished: boolean;
|
||||
readonly providerCount: number;
|
||||
readonly editHref: string;
|
||||
readonly publicPath: string;
|
||||
/** Absolute public URL resolved by the loader (origin + publicPath). */
|
||||
readonly publicUrl: string;
|
||||
}
|
||||
|
||||
export interface BookingPagesListData {
|
||||
readonly rows: readonly BookingPageListRow[];
|
||||
readonly canCreate: boolean;
|
||||
readonly newHref: string;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
}
|
||||
|
||||
export type BookingPagesListVM = VMState<BookingPagesListData>;
|
||||
|
||||
export interface BuildBookingPagesListInput {
|
||||
readonly rows: readonly BookingPageListRow[];
|
||||
readonly canCreate: boolean;
|
||||
readonly newHref: string;
|
||||
}
|
||||
|
||||
export function buildBookingPagesListVM(input: BuildBookingPagesListInput): BookingPagesListVM {
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
rows: input.rows,
|
||||
canCreate: input.canCreate,
|
||||
newHref: input.newHref,
|
||||
emptyHeadlineKey: "bookings.pages.empty.headline",
|
||||
emptyBodyKey: "bookings.pages.empty.body",
|
||||
},
|
||||
};
|
||||
}
|
||||
+79
-1
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildBookingListVM, bookingStatusKey, type BookingListRow } from "./booking-list.vm.js";
|
||||
import { buildBookingListVM, bookingListTab, bookingStatusKey, type BookingListRow } from "./booking-list.vm.js";
|
||||
import { buildBookingDetailVM } from "./booking-detail.vm.js";
|
||||
import { buildBookingPagesListVM, type BookingPageListRow } from "./booking-pages.vm.js";
|
||||
|
||||
const row = (over: Partial<BookingListRow> = {}): BookingListRow => ({
|
||||
id: "a1",
|
||||
@@ -44,3 +46,79 @@ describe("buildBookingListVM (M06 Block C)", () => {
|
||||
expect(bookingStatusKey("rescheduled")).toBe("bookings.status.rescheduled");
|
||||
});
|
||||
});
|
||||
|
||||
describe("bookingListTab (interim tabs, AD-28)", () => {
|
||||
const now = "2026-07-10T12:00:00.000Z";
|
||||
|
||||
it("scheduled/held in the future are upcoming", () => {
|
||||
expect(bookingListTab({ status: "scheduled", startAtIso: "2026-07-11T09:00:00.000Z" }, now)).toBe("upcoming");
|
||||
expect(bookingListTab({ status: "held", startAtIso: "2026-07-11T09:00:00.000Z" }, now)).toBe("upcoming");
|
||||
});
|
||||
|
||||
it("cancelled always lands in the cancelled tab regardless of time", () => {
|
||||
expect(bookingListTab({ status: "cancelled", startAtIso: "2026-07-11T09:00:00.000Z" }, now)).toBe("cancelled");
|
||||
expect(bookingListTab({ status: "cancelled", startAtIso: "2026-07-01T09:00:00.000Z" }, now)).toBe("cancelled");
|
||||
});
|
||||
|
||||
it("past appointments and terminal statuses are past", () => {
|
||||
expect(bookingListTab({ status: "scheduled", startAtIso: "2026-07-01T09:00:00.000Z" }, now)).toBe("past");
|
||||
expect(bookingListTab({ status: "no_show", startAtIso: "2026-07-11T09:00:00.000Z" }, now)).toBe("past");
|
||||
expect(bookingListTab({ status: "rescheduled", startAtIso: "2026-07-11T09:00:00.000Z" }, now)).toBe("past");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBookingDetailVM (M06 Block D, interim AD-28)", () => {
|
||||
it("derives the status key and carries capability flags + picker bounds", () => {
|
||||
const vm = buildBookingDetailVM({
|
||||
id: "a1",
|
||||
status: "scheduled",
|
||||
whenLabel: "10.07.2026, 09:00",
|
||||
pageTitle: "Wartungstermin",
|
||||
customerName: "Max Muster",
|
||||
customerEmail: "max@example.com",
|
||||
intake: [{ key: "telefon", value: "0151" }],
|
||||
cancellationReason: null,
|
||||
canWrite: true,
|
||||
canAdmin: false,
|
||||
providerOptions: [],
|
||||
minRescheduleDateIso: "2026-07-10",
|
||||
maxRescheduleDateIso: "2026-08-09",
|
||||
});
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(vm.data.statusKey).toBe("bookings.status.scheduled");
|
||||
expect(vm.data.canWrite).toBe(true);
|
||||
expect(vm.data.canAdmin).toBe(false);
|
||||
expect(vm.data.minRescheduleDateIso).toBe("2026-07-10");
|
||||
expect(vm.data.intake).toEqual([{ key: "telefon", value: "0151" }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildBookingPagesListVM (M06 Block E.1, interim AD-28)", () => {
|
||||
const pageRow = (over: Partial<BookingPageListRow> = {}): BookingPageListRow => ({
|
||||
id: "p1",
|
||||
title: "Beratung",
|
||||
slug: "beratung",
|
||||
durationMinutes: 30,
|
||||
isPublished: true,
|
||||
providerCount: 2,
|
||||
editHref: "/t/bookings/pages/p1",
|
||||
publicPath: "/b/t/beratung",
|
||||
publicUrl: "https://app.example.com/b/t/beratung",
|
||||
...over,
|
||||
});
|
||||
|
||||
it("carries rows, create capability and empty keys", () => {
|
||||
const vm = buildBookingPagesListVM({ rows: [pageRow()], canCreate: true, newHref: "/t/bookings/pages/new" });
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready" || !vm.data) {
|
||||
throw new Error("expected ready");
|
||||
}
|
||||
expect(vm.data.rows[0]?.publicUrl).toBe("https://app.example.com/b/t/beratung");
|
||||
expect(vm.data.canCreate).toBe(true);
|
||||
expect(vm.data.newHref).toBe("/t/bookings/pages/new");
|
||||
expect(vm.data.emptyHeadlineKey).toBe("bookings.pages.empty.headline");
|
||||
});
|
||||
});
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { addDaysIso, addMonthsIso, buildCalendarMonthGrid, buildCalendarWeekDays, startOfWeekIso } from "./calendar-grid.js";
|
||||
import type { CalendarViewEventRow } from "./calendar-view.vm.js";
|
||||
|
||||
const event = (over: Partial<CalendarViewEventRow> = {}): CalendarViewEventRow => ({
|
||||
id: "e1",
|
||||
source: "hivegrid_internal",
|
||||
sourceKey: "calendar.source.hivegrid_internal",
|
||||
title: "Termin",
|
||||
startsAt: "2026-07-10T07:00:00.000Z",
|
||||
endsAt: "2026-07-10T07:30:00.000Z",
|
||||
isAllDay: false,
|
||||
linkType: null,
|
||||
...over,
|
||||
});
|
||||
|
||||
describe("calendar grid date helpers", () => {
|
||||
it("addDaysIso / addMonthsIso / startOfWeekIso are pure UTC math", () => {
|
||||
expect(addDaysIso("2026-07-31", 1)).toBe("2026-08-01");
|
||||
expect(addDaysIso("2026-03-01", -1)).toBe("2026-02-28");
|
||||
expect(addMonthsIso("2026-12-15", 1)).toBe("2027-01-01");
|
||||
expect(addMonthsIso("2026-01-15", -1)).toBe("2025-12-01");
|
||||
// 2026-07-10 is a Friday → Monday is 2026-07-06.
|
||||
expect(startOfWeekIso("2026-07-10")).toBe("2026-07-06");
|
||||
// Sunday belongs to the week starting the previous Monday.
|
||||
expect(startOfWeekIso("2026-07-12")).toBe("2026-07-06");
|
||||
expect(startOfWeekIso("2026-07-06")).toBe("2026-07-06");
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCalendarMonthGrid (AK-P16a interim grid)", () => {
|
||||
it("pads the month to full Monday-first weeks and flags the anchor month", () => {
|
||||
// July 2026: 1st is a Wednesday, 31st is a Friday.
|
||||
const weeks = buildCalendarMonthGrid({ events: [], anchorIso: "2026-07-10", todayIso: "2026-07-10" });
|
||||
expect(weeks[0]).toHaveLength(7);
|
||||
expect(weeks[0]?.[0]?.dateIso).toBe("2026-06-29");
|
||||
expect(weeks[0]?.[0]?.inAnchorMonth).toBe(false);
|
||||
expect(weeks[0]?.[2]?.dateIso).toBe("2026-07-01");
|
||||
expect(weeks[0]?.[2]?.inAnchorMonth).toBe(true);
|
||||
const last = weeks[weeks.length - 1];
|
||||
expect(last?.[6]?.dateIso).toBe("2026-08-02");
|
||||
expect(weeks.flat().some((cell) => cell.dateIso === "2026-07-31")).toBe(true);
|
||||
});
|
||||
|
||||
it("marks today and buckets events into their Berlin-local day", () => {
|
||||
// 22:30 UTC on the 10th is 00:30 Berlin time on the 11th (CEST).
|
||||
const weeks = buildCalendarMonthGrid({
|
||||
events: [event(), event({ id: "e2", startsAt: "2026-07-10T22:30:00.000Z", endsAt: "2026-07-10T23:00:00.000Z" })],
|
||||
anchorIso: "2026-07-10",
|
||||
todayIso: "2026-07-10",
|
||||
});
|
||||
const cells = weeks.flat();
|
||||
const day10 = cells.find((cell) => cell.dateIso === "2026-07-10");
|
||||
const day11 = cells.find((cell) => cell.dateIso === "2026-07-11");
|
||||
expect(day10?.isToday).toBe(true);
|
||||
expect(day10?.events.map((e) => e.id)).toEqual(["e1"]);
|
||||
expect(day11?.events.map((e) => e.id)).toEqual(["e2"]);
|
||||
});
|
||||
|
||||
it("expands multi-day events across cells without spilling past an exclusive midnight end", () => {
|
||||
const weeks = buildCalendarMonthGrid({
|
||||
events: [
|
||||
event({ id: "multi", startsAt: "2026-07-13T09:00:00.000Z", endsAt: "2026-07-15T10:00:00.000Z" }),
|
||||
// All-day event stored as [00:00, next-day 00:00) Berlin time (22:00 UTC in July).
|
||||
event({ id: "allday", isAllDay: true, startsAt: "2026-07-19T22:00:00.000Z", endsAt: "2026-07-20T22:00:00.000Z" }),
|
||||
],
|
||||
anchorIso: "2026-07-10",
|
||||
todayIso: "2026-07-10",
|
||||
});
|
||||
const byDate = new Map(weeks.flat().map((cell) => [cell.dateIso, cell.events.map((e) => e.id)]));
|
||||
expect(byDate.get("2026-07-13")).toEqual(["multi"]);
|
||||
expect(byDate.get("2026-07-14")).toEqual(["multi"]);
|
||||
expect(byDate.get("2026-07-15")).toEqual(["multi"]);
|
||||
expect(byDate.get("2026-07-16")).toEqual([]);
|
||||
expect(byDate.get("2026-07-20")).toEqual(["allday"]);
|
||||
expect(byDate.get("2026-07-21")).toEqual([]);
|
||||
});
|
||||
|
||||
it("sorts a day's events by start time", () => {
|
||||
const weeks = buildCalendarMonthGrid({
|
||||
events: [
|
||||
event({ id: "later", startsAt: "2026-07-10T10:00:00.000Z", endsAt: "2026-07-10T11:00:00.000Z" }),
|
||||
event({ id: "earlier", startsAt: "2026-07-10T06:00:00.000Z", endsAt: "2026-07-10T06:30:00.000Z" }),
|
||||
],
|
||||
anchorIso: "2026-07-10",
|
||||
todayIso: "2026-07-10",
|
||||
});
|
||||
const day10 = weeks.flat().find((cell) => cell.dateIso === "2026-07-10");
|
||||
expect(day10?.events.map((e) => e.id)).toEqual(["earlier", "later"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildCalendarWeekDays (AK-P16a interim grid)", () => {
|
||||
it("returns the Monday-first week containing the anchor", () => {
|
||||
const days = buildCalendarWeekDays({ events: [event()], anchorIso: "2026-07-10", todayIso: "2026-07-09" });
|
||||
expect(days).toHaveLength(7);
|
||||
expect(days[0]?.dateIso).toBe("2026-07-06");
|
||||
expect(days[6]?.dateIso).toBe("2026-07-12");
|
||||
expect(days[4]?.events.map((e) => e.id)).toEqual(["e1"]);
|
||||
expect(days[3]?.isToday).toBe(true);
|
||||
});
|
||||
|
||||
it("throws on non-ISO anchors instead of guessing", () => {
|
||||
expect(() => buildCalendarWeekDays({ events: [], anchorIso: "10.07.2026", todayIso: "2026-07-10" })).toThrow(/ISO calendar date/);
|
||||
});
|
||||
});
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
import type { CalendarViewEventRow } from "./calendar-view.vm.js";
|
||||
|
||||
/**
|
||||
* AK-P16a · pure month/week grid derivation for the interim calendar view
|
||||
* (AD-28). Buckets the loader's events into day cells for a CSS-grid month
|
||||
* (Monday-first weeks) or a single week. Day assignment uses a fixed IANA
|
||||
* timezone (app default Europe/Berlin) so server and client render the same
|
||||
* cells (hydration rule).
|
||||
*/
|
||||
|
||||
export interface CalendarDayCell {
|
||||
/** ISO calendar date `YYYY-MM-DD`. */
|
||||
readonly dateIso: string;
|
||||
readonly dayOfMonth: number;
|
||||
/** False for leading/trailing days that pad the month grid to full weeks. */
|
||||
readonly inAnchorMonth: boolean;
|
||||
readonly isToday: boolean;
|
||||
readonly events: readonly CalendarViewEventRow[];
|
||||
}
|
||||
|
||||
export interface BuildCalendarGridInput {
|
||||
readonly events: readonly CalendarViewEventRow[];
|
||||
/** ISO calendar date `YYYY-MM-DD` inside the month/week to render. */
|
||||
readonly anchorIso: string;
|
||||
readonly todayIso: string;
|
||||
/** IANA timezone used to bucket event timestamps into days. */
|
||||
readonly timeZone?: string;
|
||||
}
|
||||
|
||||
export const CALENDAR_GRID_DEFAULT_TIME_ZONE = "Europe/Berlin";
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
function assertDateIso(dateIso: string): void {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/u.test(dateIso)) {
|
||||
throw new Error(`Expected ISO calendar date (YYYY-MM-DD), got: ${dateIso}`);
|
||||
}
|
||||
}
|
||||
|
||||
function utcDate(dateIso: string): Date {
|
||||
assertDateIso(dateIso);
|
||||
return new Date(`${dateIso}T00:00:00Z`);
|
||||
}
|
||||
|
||||
function toIso(date: Date): string {
|
||||
return date.toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
/** Add whole days to an ISO calendar date (pure UTC math). */
|
||||
export function addDaysIso(dateIso: string, days: number): string {
|
||||
return toIso(new Date(utcDate(dateIso).getTime() + days * DAY_MS));
|
||||
}
|
||||
|
||||
/** Add whole months to an ISO calendar date, clamping to the 1st for grid anchors. */
|
||||
export function addMonthsIso(dateIso: string, months: number): string {
|
||||
const date = utcDate(dateIso);
|
||||
const shifted = new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + months, 1));
|
||||
return toIso(shifted);
|
||||
}
|
||||
|
||||
/** Monday of the ISO week containing the date. */
|
||||
export function startOfWeekIso(dateIso: string): string {
|
||||
const date = utcDate(dateIso);
|
||||
const weekday = date.getUTCDay(); // 0 = Sunday
|
||||
const offset = weekday === 0 ? 6 : weekday - 1;
|
||||
return addDaysIso(dateIso, -offset);
|
||||
}
|
||||
|
||||
function dayKeyFormatter(timeZone: string): Intl.DateTimeFormat {
|
||||
// en-CA yields YYYY-MM-DD directly.
|
||||
return new Intl.DateTimeFormat("en-CA", { timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
||||
}
|
||||
|
||||
/** Bucket events by the calendar dates they overlap in the given timezone. */
|
||||
function bucketEventsByDay(events: readonly CalendarViewEventRow[], timeZone: string): Map<string, CalendarViewEventRow[]> {
|
||||
const formatter = dayKeyFormatter(timeZone);
|
||||
const byDay = new Map<string, CalendarViewEventRow[]>();
|
||||
const sorted = events.slice().sort((a, b) => a.startsAt.localeCompare(b.startsAt) || a.id.localeCompare(b.id));
|
||||
for (const event of sorted) {
|
||||
const startsAt = new Date(event.startsAt);
|
||||
const endsAt = new Date(event.endsAt);
|
||||
if (Number.isNaN(startsAt.getTime())) {
|
||||
continue;
|
||||
}
|
||||
const startKey = formatter.format(startsAt);
|
||||
// Treat the end as exclusive when the event has an extent, so an all-day
|
||||
// event ending at midnight does not spill into the next day cell.
|
||||
const effectiveEnd = !Number.isNaN(endsAt.getTime()) && endsAt.getTime() > startsAt.getTime() ? new Date(endsAt.getTime() - 1) : startsAt;
|
||||
const endKey = formatter.format(effectiveEnd);
|
||||
for (let key = startKey, guard = 0; guard < 62; key = addDaysIso(key, 1), guard += 1) {
|
||||
const bucket = byDay.get(key);
|
||||
if (bucket) {
|
||||
bucket.push(event);
|
||||
} else {
|
||||
byDay.set(key, [event]);
|
||||
}
|
||||
if (key === endKey) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return byDay;
|
||||
}
|
||||
|
||||
function buildCell(dateIso: string, anchorMonth: string, todayIso: string, byDay: ReadonlyMap<string, CalendarViewEventRow[]>): CalendarDayCell {
|
||||
return {
|
||||
dateIso,
|
||||
dayOfMonth: Number(dateIso.slice(8, 10)),
|
||||
inAnchorMonth: dateIso.slice(0, 7) === anchorMonth,
|
||||
isToday: dateIso === todayIso,
|
||||
events: byDay.get(dateIso) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
/** Monday-first month grid (full weeks) around the anchor's month. */
|
||||
export function buildCalendarMonthGrid(input: BuildCalendarGridInput): CalendarDayCell[][] {
|
||||
assertDateIso(input.anchorIso);
|
||||
assertDateIso(input.todayIso);
|
||||
const timeZone = input.timeZone ?? CALENDAR_GRID_DEFAULT_TIME_ZONE;
|
||||
const anchorMonth = input.anchorIso.slice(0, 7);
|
||||
const firstOfMonth = `${anchorMonth}-01`;
|
||||
const gridStart = startOfWeekIso(firstOfMonth);
|
||||
const firstOfNextMonth = addMonthsIso(firstOfMonth, 1);
|
||||
const byDay = bucketEventsByDay(input.events, timeZone);
|
||||
|
||||
const weeks: CalendarDayCell[][] = [];
|
||||
let cursor = gridStart;
|
||||
do {
|
||||
const week: CalendarDayCell[] = [];
|
||||
for (let i = 0; i < 7; i += 1) {
|
||||
week.push(buildCell(cursor, anchorMonth, input.todayIso, byDay));
|
||||
cursor = addDaysIso(cursor, 1);
|
||||
}
|
||||
weeks.push(week);
|
||||
} while (cursor < firstOfNextMonth);
|
||||
return weeks;
|
||||
}
|
||||
|
||||
/** Monday-first single week containing the anchor. */
|
||||
export function buildCalendarWeekDays(input: BuildCalendarGridInput): CalendarDayCell[] {
|
||||
assertDateIso(input.anchorIso);
|
||||
assertDateIso(input.todayIso);
|
||||
const timeZone = input.timeZone ?? CALENDAR_GRID_DEFAULT_TIME_ZONE;
|
||||
const anchorMonth = input.anchorIso.slice(0, 7);
|
||||
const byDay = bucketEventsByDay(input.events, timeZone);
|
||||
const start = startOfWeekIso(input.anchorIso);
|
||||
const days: CalendarDayCell[] = [];
|
||||
for (let i = 0; i < 7; i += 1) {
|
||||
days.push(buildCell(addDaysIso(start, i), anchorMonth, input.todayIso, byDay));
|
||||
}
|
||||
return days;
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatAuditAdministrationVM, buildChatAuditOverviewVM, ChatAuditOverviewVMSchema } from "./audit.vm.js";
|
||||
|
||||
describe("AK-P15b chat audit overview view model", () => {
|
||||
it("requires a reason session before exposing tenant channels", () => {
|
||||
const vm = buildChatAuditOverviewVM({
|
||||
session: null,
|
||||
channels: [channel()],
|
||||
canAdminister: true,
|
||||
});
|
||||
|
||||
expect(vm).toEqual(expect.objectContaining({ status: "ready" }));
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.requiresReason).toBe(true);
|
||||
expect(vm.data.channels).toEqual([]);
|
||||
expect(ChatAuditOverviewVMSchema.safeParse(vm).success).toBe(true);
|
||||
});
|
||||
|
||||
it("builds a read-only channel list for an active short-lived session", () => {
|
||||
const vm = buildChatAuditOverviewVM({
|
||||
session: {
|
||||
id: "audit-session-1",
|
||||
reason: "Prüfung einer konkreten Kundenreklamation",
|
||||
expiresAtIso: "2026-07-16T12:15:00.000Z",
|
||||
},
|
||||
channels: [channel()],
|
||||
canAdminister: true,
|
||||
});
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.isReadOnly).toBe(true);
|
||||
expect(vm.data.requiresReason).toBe(false);
|
||||
expect(vm.data.channels[0]).toMatchObject({
|
||||
id: "chat-1",
|
||||
kindLabelKey: "chat.channel.kind.dm",
|
||||
isArchived: false,
|
||||
canArchive: true,
|
||||
participantLabels: ["Anna", "Ben"],
|
||||
});
|
||||
});
|
||||
|
||||
it("exposes member and cleanup controls only with chat admin permission", () => {
|
||||
const adminVm = buildChatAuditAdministrationVM({
|
||||
channel: { id: "chat-1", kind: "dm", title: "Anna · Ben", archivedAtIso: null },
|
||||
canAdminister: true,
|
||||
members: [
|
||||
{ userId: "anna", displayName: "Anna", avatarUrl: null, roleInChat: "admin" },
|
||||
{ userId: "ben", displayName: "Ben", avatarUrl: null, roleInChat: "member" },
|
||||
],
|
||||
});
|
||||
if (adminVm.status !== "ready") throw new Error("expected ready");
|
||||
expect(adminVm.data.canArchive).toBe(true);
|
||||
expect(adminVm.data.members).toEqual([
|
||||
expect.objectContaining({ userId: "anna", canDemote: true, canRemove: true }),
|
||||
expect.objectContaining({ userId: "ben", canPromote: true, canRemove: true }),
|
||||
]);
|
||||
|
||||
const readOnlyVm = buildChatAuditAdministrationVM({
|
||||
channel: { id: "chat-1", kind: "dm", title: "Anna · Ben", archivedAtIso: null },
|
||||
canAdminister: false,
|
||||
members: [{ userId: "anna", displayName: "Anna", avatarUrl: null, roleInChat: "admin" }],
|
||||
});
|
||||
if (readOnlyVm.status !== "ready") throw new Error("expected ready");
|
||||
expect(readOnlyVm.data.canArchive).toBe(false);
|
||||
expect(readOnlyVm.data.members[0]).toMatchObject({ canDemote: false, canRemove: false });
|
||||
});
|
||||
});
|
||||
|
||||
function channel() {
|
||||
return {
|
||||
id: "chat-1",
|
||||
kind: "dm" as const,
|
||||
title: "Anna · Ben",
|
||||
description: null,
|
||||
participantLabels: ["Anna", "Ben", "Anna"],
|
||||
memberCount: 2,
|
||||
isPrivate: true,
|
||||
archivedAtIso: null,
|
||||
lastMessageAtIso: "2026-07-16T12:00:00.000Z",
|
||||
detailHref: "/demo/settings/chat/audit/chat-1",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
import type { ChatChannelKind } from "./channel-list.vm.js";
|
||||
|
||||
export interface ChatAuditSessionVM {
|
||||
readonly id: string;
|
||||
readonly reason: string;
|
||||
readonly expiresAtIso: string;
|
||||
}
|
||||
|
||||
export interface ChatAuditChannelRowInput {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly participantLabels: readonly string[];
|
||||
readonly memberCount: number;
|
||||
readonly isPrivate: boolean;
|
||||
readonly archivedAtIso: string | null;
|
||||
readonly lastMessageAtIso: string | null;
|
||||
readonly detailHref: string;
|
||||
}
|
||||
|
||||
export interface ChatAuditChannelRowVM extends ChatAuditChannelRowInput {
|
||||
readonly kindLabelKey: "chat.channel.kind.project" | "chat.channel.kind.group" | "chat.channel.kind.dm";
|
||||
readonly isArchived: boolean;
|
||||
readonly canArchive: boolean;
|
||||
}
|
||||
|
||||
export interface ChatAuditOverviewData {
|
||||
readonly session: ChatAuditSessionVM | null;
|
||||
readonly channels: readonly ChatAuditChannelRowVM[];
|
||||
readonly requiresReason: boolean;
|
||||
readonly isReadOnly: true;
|
||||
readonly canAdminister: boolean;
|
||||
readonly keys: {
|
||||
readonly title: "chat.audit.title";
|
||||
readonly description: "chat.audit.description";
|
||||
readonly reasonLabel: "chat.audit.reason.label";
|
||||
readonly reasonHelp: "chat.audit.reason.help";
|
||||
readonly emptyTitle: "chat.audit.empty.title";
|
||||
readonly emptyBody: "chat.audit.empty.body";
|
||||
};
|
||||
}
|
||||
|
||||
export type ChatAuditOverviewVM = VMState<ChatAuditOverviewData>;
|
||||
|
||||
const chatAuditSessionSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).max(500),
|
||||
reason: z.string().trim().min(1).max(500),
|
||||
expiresAtIso: z.string().datetime({ offset: true }),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatAuditChannelRowSchema = z
|
||||
.object({
|
||||
id: z.string().min(1).max(500),
|
||||
kind: z.enum(["project", "group", "dm"]),
|
||||
title: z.string().min(1),
|
||||
description: z.string().nullable(),
|
||||
participantLabels: z.array(z.string().min(1)),
|
||||
memberCount: z.number().int().nonnegative(),
|
||||
isPrivate: z.boolean(),
|
||||
archivedAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
lastMessageAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
detailHref: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatAuditOverviewDataSchema = z
|
||||
.object({
|
||||
session: chatAuditSessionSchema.nullable(),
|
||||
channels: z.array(
|
||||
chatAuditChannelRowSchema.extend({
|
||||
kindLabelKey: z.enum(["chat.channel.kind.project", "chat.channel.kind.group", "chat.channel.kind.dm"]),
|
||||
isArchived: z.boolean(),
|
||||
canArchive: z.boolean(),
|
||||
})
|
||||
),
|
||||
requiresReason: z.boolean(),
|
||||
isReadOnly: z.literal(true),
|
||||
canAdminister: z.boolean(),
|
||||
keys: z
|
||||
.object({
|
||||
title: z.literal("chat.audit.title"),
|
||||
description: z.literal("chat.audit.description"),
|
||||
reasonLabel: z.literal("chat.audit.reason.label"),
|
||||
reasonHelp: z.literal("chat.audit.reason.help"),
|
||||
emptyTitle: z.literal("chat.audit.empty.title"),
|
||||
emptyBody: z.literal("chat.audit.empty.body"),
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, context) => {
|
||||
if (data.requiresReason !== (data.session === null) || (data.session === null && data.channels.length > 0)) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.audit.invalid_session_state" });
|
||||
}
|
||||
});
|
||||
|
||||
export const ChatAuditOverviewVMSchema = z
|
||||
.object({ status: z.literal("ready"), data: chatAuditOverviewDataSchema })
|
||||
.strict();
|
||||
|
||||
export function buildChatAuditOverviewVM(input: {
|
||||
readonly session: ChatAuditSessionVM | null;
|
||||
readonly channels: readonly ChatAuditChannelRowInput[];
|
||||
readonly canAdminister?: boolean;
|
||||
}): ChatAuditOverviewVM {
|
||||
const canAdminister = input.canAdminister === true;
|
||||
const channels = input.session
|
||||
? input.channels.map((channel) => ({
|
||||
...channel,
|
||||
participantLabels: [...new Set(channel.participantLabels.map((label) => label.trim()).filter(Boolean))],
|
||||
memberCount: Math.max(0, Math.trunc(channel.memberCount)),
|
||||
kindLabelKey: `chat.channel.kind.${channel.kind}` as const,
|
||||
isArchived: channel.archivedAtIso !== null,
|
||||
canArchive: canAdminister && channel.archivedAtIso === null,
|
||||
}))
|
||||
: [];
|
||||
const data: ChatAuditOverviewData = {
|
||||
session: input.session,
|
||||
channels,
|
||||
requiresReason: input.session === null,
|
||||
isReadOnly: true,
|
||||
canAdminister,
|
||||
keys: {
|
||||
title: "chat.audit.title",
|
||||
description: "chat.audit.description",
|
||||
reasonLabel: "chat.audit.reason.label",
|
||||
reasonHelp: "chat.audit.reason.help",
|
||||
emptyTitle: "chat.audit.empty.title",
|
||||
emptyBody: "chat.audit.empty.body",
|
||||
},
|
||||
};
|
||||
chatAuditOverviewDataSchema.parse(data);
|
||||
return ready(data);
|
||||
}
|
||||
|
||||
export interface ChatAuditAdminMemberInput {
|
||||
readonly userId: string;
|
||||
readonly displayName: string;
|
||||
readonly avatarUrl: string | null;
|
||||
readonly roleInChat: "admin" | "member";
|
||||
}
|
||||
|
||||
export interface ChatAuditAdminMemberVM extends ChatAuditAdminMemberInput {
|
||||
readonly roleLabelKey: "chat.audit.members.role.admin" | "chat.audit.members.role.member";
|
||||
readonly canPromote: boolean;
|
||||
readonly canDemote: boolean;
|
||||
readonly canRemove: boolean;
|
||||
}
|
||||
|
||||
export interface ChatAuditAdministrationData {
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
readonly title: string;
|
||||
readonly isArchived: boolean;
|
||||
};
|
||||
readonly canAdminister: boolean;
|
||||
readonly canArchive: boolean;
|
||||
readonly members: readonly ChatAuditAdminMemberVM[];
|
||||
}
|
||||
|
||||
export type ChatAuditAdministrationVM = VMState<ChatAuditAdministrationData>;
|
||||
|
||||
const chatAuditAdminMemberSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1).max(500),
|
||||
displayName: z.string().min(1),
|
||||
avatarUrl: z.string().nullable(),
|
||||
roleInChat: z.enum(["admin", "member"]),
|
||||
roleLabelKey: z.enum(["chat.audit.members.role.admin", "chat.audit.members.role.member"]),
|
||||
canPromote: z.boolean(),
|
||||
canDemote: z.boolean(),
|
||||
canRemove: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatAuditAdministrationDataSchema = z
|
||||
.object({
|
||||
channel: z
|
||||
.object({
|
||||
id: z.string().min(1).max(500),
|
||||
kind: z.enum(["project", "group", "dm"]),
|
||||
title: z.string().min(1),
|
||||
isArchived: z.boolean(),
|
||||
})
|
||||
.strict(),
|
||||
canAdminister: z.boolean(),
|
||||
canArchive: z.boolean(),
|
||||
members: z.array(chatAuditAdminMemberSchema),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, context) => {
|
||||
if (!data.canAdminister && (data.canArchive || data.members.some((member) => member.canPromote || member.canDemote || member.canRemove))) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.audit.admin_permission_required" });
|
||||
}
|
||||
});
|
||||
|
||||
export function buildChatAuditAdministrationVM(input: {
|
||||
readonly channel: { readonly id: string; readonly kind: ChatChannelKind; readonly title: string; readonly archivedAtIso: string | null };
|
||||
readonly canAdminister: boolean;
|
||||
readonly members: readonly ChatAuditAdminMemberInput[];
|
||||
}): ChatAuditAdministrationVM {
|
||||
const canMutate = input.canAdminister && input.channel.archivedAtIso === null;
|
||||
const data: ChatAuditAdministrationData = {
|
||||
channel: {
|
||||
id: input.channel.id,
|
||||
kind: input.channel.kind,
|
||||
title: input.channel.title.trim() || input.channel.id,
|
||||
isArchived: input.channel.archivedAtIso !== null,
|
||||
},
|
||||
canAdminister: input.canAdminister,
|
||||
canArchive: canMutate,
|
||||
members: input.members.map((member) => ({
|
||||
...member,
|
||||
displayName: member.displayName.trim() || member.userId,
|
||||
roleLabelKey: `chat.audit.members.role.${member.roleInChat}` as const,
|
||||
canPromote: canMutate && member.roleInChat === "member",
|
||||
canDemote: canMutate && member.roleInChat === "admin",
|
||||
canRemove: canMutate,
|
||||
})),
|
||||
};
|
||||
chatAuditAdministrationDataSchema.parse(data);
|
||||
return ready(data);
|
||||
}
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildChatChannelCreateVM,
|
||||
ChatChannelCreateVMSchema,
|
||||
chatChannelCreateSubmissionSchema,
|
||||
type ChatTenantUserOptionInput,
|
||||
} from "./channel-create.vm.js";
|
||||
|
||||
function user(userId: string, displayName: string): ChatTenantUserOptionInput {
|
||||
return {
|
||||
userId,
|
||||
displayName,
|
||||
email: `${userId}@example.test`,
|
||||
avatar: { imageUrl: null, fallbackLabel: displayName.slice(0, 2).toUpperCase() },
|
||||
};
|
||||
}
|
||||
|
||||
const USERS = [user("viewer", "Raffael"), user("peer-1", "Akeshan"), user("peer-2", "Luna")];
|
||||
|
||||
describe("buildChatChannelCreateVM", () => {
|
||||
it("derives allowed modes from permissions and excludes the current user", () => {
|
||||
const vm = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: [...USERS, user("peer-1", "Duplicate")],
|
||||
permissions: { canCreateGroup: false, canCreateDm: true },
|
||||
requestedMode: "group",
|
||||
dmDraft: { peerUserId: "peer-1" },
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.allowedModes).toEqual(["dm"]);
|
||||
expect(vm.data.selectedMode).toBe("dm");
|
||||
expect(vm.data.userOptions.map(({ userId }) => userId)).toEqual(["peer-1", "peer-2"]);
|
||||
expect(vm.data.form).toMatchObject({ mode: "dm", peerUserId: "peer-1", canSubmit: true });
|
||||
expect(vm.data.keys.usersLoadingKey).toBe("chat.channelCreate.users.loading");
|
||||
});
|
||||
|
||||
it("builds a public/private group draft and reports required or stale values by key", () => {
|
||||
const vm = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: USERS,
|
||||
permissions: { canCreateGroup: true, canCreateDm: false },
|
||||
tenantGroups: [
|
||||
{ groupId: "group-1", name: "Team Süd", description: "Montage", memberCount: 4 },
|
||||
{ groupId: "group-2", name: "Lehrlinge", description: "", memberCount: 2 },
|
||||
],
|
||||
groupDraft: {
|
||||
name: " ",
|
||||
description: "Montage-Team",
|
||||
privacy: "private",
|
||||
initialUserIds: ["peer-1", "peer-1", "missing", "viewer"],
|
||||
initialGroupIds: ["group-1", "group-1", "missing-group"],
|
||||
syncGroupMembership: true,
|
||||
},
|
||||
});
|
||||
if (vm.status !== "ready" || vm.data.form?.mode !== "group") throw new Error("expected group form");
|
||||
|
||||
expect(vm.data.form).toMatchObject({
|
||||
privacy: "private",
|
||||
initialUserIds: ["peer-1"],
|
||||
initialGroupIds: ["group-1"],
|
||||
syncGroupMembership: true,
|
||||
canSubmit: false,
|
||||
});
|
||||
expect(vm.data.form.validationErrorKeys).toEqual([
|
||||
"chat.channelCreate.validation.groupNameRequired",
|
||||
"chat.channelCreate.validation.duplicateInitialUsers",
|
||||
"chat.channelCreate.validation.userUnavailable",
|
||||
"chat.channelCreate.validation.duplicateInitialGroups",
|
||||
"chat.channelCreate.validation.groupUnavailable",
|
||||
]);
|
||||
expect(vm.data.groupOptions).toEqual([
|
||||
{ groupId: "group-1", name: "Team Süd", description: "Montage", memberCount: 4 },
|
||||
{ groupId: "group-2", name: "Lehrlinge", description: "", memberCount: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps DM structurally limited to one peer and exposes missing/unavailable validation", () => {
|
||||
const missing = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: USERS,
|
||||
permissions: { canCreateGroup: false, canCreateDm: true },
|
||||
requestedMode: "dm",
|
||||
});
|
||||
const self = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: USERS,
|
||||
permissions: { canCreateGroup: false, canCreateDm: true },
|
||||
requestedMode: "dm",
|
||||
dmDraft: { peerUserId: "viewer" },
|
||||
});
|
||||
if (missing.status !== "ready" || self.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(missing.data.form).toMatchObject({ peerUserId: null, validationErrorKeys: ["chat.channelCreate.validation.dmPeerRequired"] });
|
||||
expect(self.data.form).toMatchObject({ peerUserId: "viewer", validationErrorKeys: ["chat.channelCreate.validation.dmPeerUnavailable"] });
|
||||
});
|
||||
|
||||
it("returns an explicit permission-empty state when neither mode is allowed", () => {
|
||||
const vm = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: USERS,
|
||||
permissions: { canCreateGroup: false, canCreateDm: false },
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data).toMatchObject({ allowedModes: [], selectedMode: null, form: null });
|
||||
expect(vm.data.keys.noAllowedModesKey).toBe("chat.channelCreate.permissions.none");
|
||||
});
|
||||
|
||||
it("validates strict action and render contracts", () => {
|
||||
expect(
|
||||
chatChannelCreateSubmissionSchema.safeParse({ mode: "dm", peerUserId: "peer-1", peerUserIds: ["peer-2"] }).success,
|
||||
).toBe(false);
|
||||
const duplicateGroup = chatChannelCreateSubmissionSchema.safeParse({
|
||||
mode: "group",
|
||||
name: "Montage",
|
||||
description: null,
|
||||
privacy: "public",
|
||||
initialUserIds: ["peer-1", "peer-1"],
|
||||
initialGroupIds: [],
|
||||
syncGroupMembership: false,
|
||||
});
|
||||
expect(duplicateGroup.success).toBe(false);
|
||||
if (!duplicateGroup.success) expect(duplicateGroup.error.issues[0]?.message).toBe("chat.channelCreate.validation.duplicateInitialUsers");
|
||||
|
||||
const vm = buildChatChannelCreateVM({
|
||||
currentUserId: "viewer",
|
||||
tenantUsers: USERS,
|
||||
permissions: { canCreateGroup: true, canCreateDm: true },
|
||||
groupDraft: { name: "Montage", initialUserIds: ["peer-1"] },
|
||||
});
|
||||
expect(ChatChannelCreateVMSchema.parse(JSON.parse(JSON.stringify(vm)) as unknown)).toEqual(vm);
|
||||
expect(ChatChannelCreateVMSchema.safeParse({ ...vm, unexpected: true }).success).toBe(false);
|
||||
});
|
||||
|
||||
it("requires a selected permission group when automatic group sync is enabled", () => {
|
||||
const parsed = chatChannelCreateSubmissionSchema.safeParse({
|
||||
mode: "group",
|
||||
name: "Team Süd",
|
||||
description: null,
|
||||
privacy: "private",
|
||||
initialUserIds: [],
|
||||
initialGroupIds: [],
|
||||
syncGroupMembership: true,
|
||||
});
|
||||
|
||||
expect(parsed.success).toBe(false);
|
||||
if (!parsed.success) expect(parsed.error.issues[0]?.message).toBe("chat.channelCreate.validation.groupUnavailable");
|
||||
});
|
||||
});
|
||||
+434
@@ -0,0 +1,434 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
import type { ChatAvatarVM } from "./channel-list.vm.js";
|
||||
|
||||
export type ChatChannelCreateMode = "group" | "dm";
|
||||
export type ChatGroupPrivacy = "public" | "private";
|
||||
|
||||
export const CHAT_CHANNEL_CREATE_VALIDATION_KEYS = {
|
||||
groupNameRequired: "chat.channelCreate.validation.groupNameRequired",
|
||||
userUnavailable: "chat.channelCreate.validation.userUnavailable",
|
||||
duplicateInitialUsers: "chat.channelCreate.validation.duplicateInitialUsers",
|
||||
groupUnavailable: "chat.channelCreate.validation.groupUnavailable",
|
||||
duplicateInitialGroups: "chat.channelCreate.validation.duplicateInitialGroups",
|
||||
dmPeerRequired: "chat.channelCreate.validation.dmPeerRequired",
|
||||
dmPeerUnavailable: "chat.channelCreate.validation.dmPeerUnavailable",
|
||||
} as const;
|
||||
|
||||
export type ChatChannelCreateValidationKey = (typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS)[keyof typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS];
|
||||
|
||||
export interface ChatTenantUserOptionInput {
|
||||
readonly userId: string;
|
||||
readonly displayName: string;
|
||||
readonly email: string;
|
||||
readonly avatar: ChatAvatarVM;
|
||||
}
|
||||
|
||||
export interface ChatTenantUserOptionVM extends ChatTenantUserOptionInput {
|
||||
readonly isCurrentUser: boolean;
|
||||
}
|
||||
|
||||
export interface ChatPermissionGroupOptionInput {
|
||||
readonly groupId: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly memberCount: number;
|
||||
}
|
||||
|
||||
export type ChatPermissionGroupOptionVM = ChatPermissionGroupOptionInput;
|
||||
|
||||
export interface ChatChannelCreatePermissionsVM {
|
||||
readonly canCreateGroup: boolean;
|
||||
readonly canCreateDm: boolean;
|
||||
}
|
||||
|
||||
export interface ChatGroupCreateDraftInput {
|
||||
readonly name?: string;
|
||||
readonly description?: string;
|
||||
readonly privacy?: ChatGroupPrivacy;
|
||||
readonly initialUserIds?: readonly string[];
|
||||
readonly initialGroupIds?: readonly string[];
|
||||
readonly syncGroupMembership?: boolean;
|
||||
}
|
||||
|
||||
export interface ChatDmCreateDraftInput {
|
||||
readonly peerUserId?: string | null;
|
||||
}
|
||||
|
||||
export interface ChatGroupCreateFormVM {
|
||||
readonly mode: "group";
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
readonly privacy: ChatGroupPrivacy;
|
||||
readonly initialUserIds: readonly string[];
|
||||
readonly initialGroupIds: readonly string[];
|
||||
readonly syncGroupMembership: boolean;
|
||||
readonly validationErrorKeys: readonly ChatChannelCreateValidationKey[];
|
||||
readonly canSubmit: boolean;
|
||||
}
|
||||
|
||||
export interface ChatDmCreateFormVM {
|
||||
readonly mode: "dm";
|
||||
readonly peerUserId: string | null;
|
||||
readonly validationErrorKeys: readonly ChatChannelCreateValidationKey[];
|
||||
readonly canSubmit: boolean;
|
||||
}
|
||||
|
||||
export type ChatChannelCreateFormVM = ChatGroupCreateFormVM | ChatDmCreateFormVM;
|
||||
|
||||
export interface ChatChannelCreateKeysVM {
|
||||
readonly titleKey: "chat.channelCreate.title";
|
||||
readonly groupModeKey: "chat.channelCreate.mode.group";
|
||||
readonly dmModeKey: "chat.channelCreate.mode.dm";
|
||||
readonly usersEmptyKey: "chat.channelCreate.users.empty";
|
||||
readonly usersLoadingKey: "chat.channelCreate.users.loading";
|
||||
readonly groupsEmptyKey: "chat.channelCreate.groups.empty";
|
||||
readonly noAllowedModesKey: "chat.channelCreate.permissions.none";
|
||||
readonly validation: {
|
||||
readonly groupNameRequired: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupNameRequired;
|
||||
readonly userUnavailable: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.userUnavailable;
|
||||
readonly duplicateInitialUsers: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialUsers;
|
||||
readonly groupUnavailable: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable;
|
||||
readonly duplicateInitialGroups: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialGroups;
|
||||
readonly dmPeerRequired: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerRequired;
|
||||
readonly dmPeerUnavailable: typeof CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerUnavailable;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ChatChannelCreateData {
|
||||
readonly permissions: ChatChannelCreatePermissionsVM;
|
||||
readonly allowedModes: readonly ChatChannelCreateMode[];
|
||||
readonly selectedMode: ChatChannelCreateMode | null;
|
||||
readonly form: ChatChannelCreateFormVM | null;
|
||||
/** Active tenant users, excluding the current user. */
|
||||
readonly userOptions: readonly ChatTenantUserOptionVM[];
|
||||
readonly groupOptions: readonly ChatPermissionGroupOptionVM[];
|
||||
readonly keys: ChatChannelCreateKeysVM;
|
||||
}
|
||||
|
||||
export type ChatChannelCreateVM = VMState<ChatChannelCreateData>;
|
||||
|
||||
export interface BuildChatChannelCreateVMInput {
|
||||
readonly currentUserId: string;
|
||||
readonly tenantUsers: readonly ChatTenantUserOptionInput[];
|
||||
readonly tenantGroups?: readonly ChatPermissionGroupOptionInput[];
|
||||
readonly permissions: ChatChannelCreatePermissionsVM;
|
||||
readonly requestedMode?: ChatChannelCreateMode;
|
||||
readonly groupDraft?: ChatGroupCreateDraftInput;
|
||||
readonly dmDraft?: ChatDmCreateDraftInput;
|
||||
}
|
||||
|
||||
export const chatChannelCreateModeSchema = z.enum(["group", "dm"]);
|
||||
export const chatGroupPrivacySchema = z.enum(["public", "private"]);
|
||||
|
||||
const chatAvatarSchema = z
|
||||
.object({
|
||||
imageUrl: z.string().min(1).nullable(),
|
||||
fallbackLabel: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatTenantUserOptionInputSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
displayName: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
avatar: chatAvatarSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatTenantUserOptionVMSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
displayName: z.string().min(1),
|
||||
email: z.string().email(),
|
||||
avatar: chatAvatarSchema,
|
||||
isCurrentUser: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatPermissionGroupOptionInputSchema = z
|
||||
.object({
|
||||
groupId: z.string().min(1),
|
||||
name: z.string().min(1),
|
||||
description: z.string(),
|
||||
memberCount: z.number().int().nonnegative(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatPermissionGroupOptionVMSchema = chatPermissionGroupOptionInputSchema;
|
||||
|
||||
const userIdSchema = z.string().trim().min(1, { message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.userUnavailable });
|
||||
|
||||
const chatGroupCreateSubmissionObjectSchema = z
|
||||
.object({
|
||||
mode: z.literal("group"),
|
||||
name: z.string().trim().min(1, { message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupNameRequired }),
|
||||
description: z.string().trim().nullable(),
|
||||
privacy: chatGroupPrivacySchema,
|
||||
initialUserIds: z
|
||||
.array(userIdSchema)
|
||||
.refine((ids) => new Set(ids).size === ids.length, { message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialUsers }),
|
||||
initialGroupIds: z
|
||||
.array(userIdSchema)
|
||||
.refine((ids) => new Set(ids).size === ids.length, { message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialGroups }),
|
||||
syncGroupMembership: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatGroupCreateSubmissionSchema = chatGroupCreateSubmissionObjectSchema.refine(
|
||||
(submission) => !submission.syncGroupMembership || submission.initialGroupIds.length > 0,
|
||||
{
|
||||
message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable,
|
||||
path: ["syncGroupMembership"],
|
||||
}
|
||||
);
|
||||
|
||||
export const chatDmCreateSubmissionSchema = z
|
||||
.object({
|
||||
mode: z.literal("dm"),
|
||||
peerUserId: z.string().trim().min(1, { message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerRequired }),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Strict action payload. A DM structurally carries exactly one peer id; group
|
||||
* initial members remain a unique list because the creator is added server-side. */
|
||||
export const chatChannelCreateSubmissionSchema = z
|
||||
.discriminatedUnion("mode", [chatGroupCreateSubmissionObjectSchema, chatDmCreateSubmissionSchema])
|
||||
.superRefine((submission, context) => {
|
||||
if (submission.mode === "group" && submission.syncGroupMembership && submission.initialGroupIds.length === 0) {
|
||||
context.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable,
|
||||
path: ["syncGroupMembership"],
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
export type ChatGroupCreateSubmission = z.infer<typeof chatGroupCreateSubmissionSchema>;
|
||||
export type ChatDmCreateSubmission = z.infer<typeof chatDmCreateSubmissionSchema>;
|
||||
export type ChatChannelCreateSubmission = z.infer<typeof chatChannelCreateSubmissionSchema>;
|
||||
|
||||
const chatChannelCreateValidationKeySchema = z.enum([
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupNameRequired,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.userUnavailable,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialUsers,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialGroups,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerRequired,
|
||||
CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerUnavailable,
|
||||
]);
|
||||
|
||||
const chatGroupCreateFormVMSchema = z
|
||||
.object({
|
||||
mode: z.literal("group"),
|
||||
name: z.string(),
|
||||
description: z.string(),
|
||||
privacy: chatGroupPrivacySchema,
|
||||
initialUserIds: z.array(z.string().min(1)),
|
||||
initialGroupIds: z.array(z.string().min(1)),
|
||||
syncGroupMembership: z.boolean(),
|
||||
validationErrorKeys: z.array(chatChannelCreateValidationKeySchema),
|
||||
canSubmit: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatDmCreateFormVMSchema = z
|
||||
.object({
|
||||
mode: z.literal("dm"),
|
||||
peerUserId: z.string().min(1).nullable(),
|
||||
validationErrorKeys: z.array(chatChannelCreateValidationKeySchema),
|
||||
canSubmit: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelCreateFormVMSchema = z.discriminatedUnion("mode", [chatGroupCreateFormVMSchema, chatDmCreateFormVMSchema]);
|
||||
|
||||
const chatChannelCreatePermissionsVMSchema = z
|
||||
.object({
|
||||
canCreateGroup: z.boolean(),
|
||||
canCreateDm: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelCreateKeysVMSchema = z
|
||||
.object({
|
||||
titleKey: z.literal("chat.channelCreate.title"),
|
||||
groupModeKey: z.literal("chat.channelCreate.mode.group"),
|
||||
dmModeKey: z.literal("chat.channelCreate.mode.dm"),
|
||||
usersEmptyKey: z.literal("chat.channelCreate.users.empty"),
|
||||
usersLoadingKey: z.literal("chat.channelCreate.users.loading"),
|
||||
groupsEmptyKey: z.literal("chat.channelCreate.groups.empty"),
|
||||
noAllowedModesKey: z.literal("chat.channelCreate.permissions.none"),
|
||||
validation: z
|
||||
.object({
|
||||
groupNameRequired: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupNameRequired),
|
||||
userUnavailable: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.userUnavailable),
|
||||
duplicateInitialUsers: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialUsers),
|
||||
groupUnavailable: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable),
|
||||
duplicateInitialGroups: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialGroups),
|
||||
dmPeerRequired: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerRequired),
|
||||
dmPeerUnavailable: z.literal(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerUnavailable),
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelCreateDataSchema = z
|
||||
.object({
|
||||
permissions: chatChannelCreatePermissionsVMSchema,
|
||||
allowedModes: z.array(chatChannelCreateModeSchema),
|
||||
selectedMode: chatChannelCreateModeSchema.nullable(),
|
||||
form: chatChannelCreateFormVMSchema.nullable(),
|
||||
userOptions: z.array(chatTenantUserOptionVMSchema),
|
||||
groupOptions: z.array(chatPermissionGroupOptionVMSchema),
|
||||
keys: chatChannelCreateKeysVMSchema,
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, context) => {
|
||||
if (new Set(data.allowedModes).size !== data.allowedModes.length) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
if ((data.selectedMode === null) !== (data.form === null)) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
if (data.selectedMode !== null && (!data.allowedModes.includes(data.selectedMode) || data.form?.mode !== data.selectedMode)) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
});
|
||||
|
||||
export const ChatChannelCreateVMSchema = z
|
||||
.object({
|
||||
status: z.literal("ready"),
|
||||
data: chatChannelCreateDataSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function buildChatTenantUserOptions(users: readonly ChatTenantUserOptionInput[], currentUserId: string): ChatTenantUserOptionVM[] {
|
||||
const seen = new Set<string>();
|
||||
|
||||
return users.flatMap((user) => {
|
||||
const userId = user.userId.trim();
|
||||
if (!userId || seen.has(userId)) return [];
|
||||
seen.add(userId);
|
||||
|
||||
return [
|
||||
{
|
||||
...user,
|
||||
userId,
|
||||
displayName: user.displayName.trim() || user.email,
|
||||
isCurrentUser: userId === currentUserId,
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildChatPermissionGroupOptions(groups: readonly ChatPermissionGroupOptionInput[]): ChatPermissionGroupOptionVM[] {
|
||||
const seen = new Set<string>();
|
||||
return groups.flatMap((group) => {
|
||||
const groupId = group.groupId.trim();
|
||||
const name = group.name.trim();
|
||||
if (!groupId || !name || seen.has(groupId) || !Number.isInteger(group.memberCount) || group.memberCount < 0) return [];
|
||||
seen.add(groupId);
|
||||
return [{ ...group, groupId, name, description: group.description.trim() }];
|
||||
});
|
||||
}
|
||||
|
||||
export function buildChatChannelCreateVM(input: BuildChatChannelCreateVMInput): ChatChannelCreateVM {
|
||||
const allUserOptions = buildChatTenantUserOptions(input.tenantUsers, input.currentUserId);
|
||||
const userOptions = allUserOptions.filter((user) => !user.isCurrentUser);
|
||||
const groupOptions = buildChatPermissionGroupOptions(input.tenantGroups ?? []);
|
||||
const selectableUserIds = new Set(userOptions.map((user) => user.userId));
|
||||
const selectableGroupIds = new Set(groupOptions.map((group) => group.groupId));
|
||||
const allowedModes: ChatChannelCreateMode[] = [];
|
||||
if (input.permissions.canCreateGroup) allowedModes.push("group");
|
||||
if (input.permissions.canCreateDm) allowedModes.push("dm");
|
||||
|
||||
const selectedMode = allowedModes.includes(input.requestedMode ?? "group") ? (input.requestedMode ?? "group") : (allowedModes[0] ?? null);
|
||||
const form =
|
||||
selectedMode === "group"
|
||||
? buildGroupForm(input.groupDraft, selectableUserIds, selectableGroupIds, input.currentUserId)
|
||||
: selectedMode === "dm"
|
||||
? buildDmForm(input.dmDraft, selectableUserIds, input.currentUserId)
|
||||
: null;
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
permissions: input.permissions,
|
||||
allowedModes,
|
||||
selectedMode,
|
||||
form,
|
||||
userOptions,
|
||||
groupOptions,
|
||||
keys: {
|
||||
titleKey: "chat.channelCreate.title",
|
||||
groupModeKey: "chat.channelCreate.mode.group",
|
||||
dmModeKey: "chat.channelCreate.mode.dm",
|
||||
usersEmptyKey: "chat.channelCreate.users.empty",
|
||||
usersLoadingKey: "chat.channelCreate.users.loading",
|
||||
groupsEmptyKey: "chat.channelCreate.groups.empty",
|
||||
noAllowedModesKey: "chat.channelCreate.permissions.none",
|
||||
validation: CHAT_CHANNEL_CREATE_VALIDATION_KEYS,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buildGroupForm(
|
||||
draft: ChatGroupCreateDraftInput | undefined,
|
||||
selectableUserIds: ReadonlySet<string>,
|
||||
selectableGroupIds: ReadonlySet<string>,
|
||||
currentUserId: string
|
||||
): ChatGroupCreateFormVM {
|
||||
const requestedUserIds = (draft?.initialUserIds ?? []).map((userId) => userId.trim()).filter(Boolean);
|
||||
const uniqueUserIds = [...new Set(requestedUserIds)];
|
||||
const hasDuplicateUsers = uniqueUserIds.length !== requestedUserIds.length;
|
||||
const hasUnavailableUser = uniqueUserIds.some((userId) => userId === currentUserId || !selectableUserIds.has(userId));
|
||||
const initialUserIds = uniqueUserIds.filter((userId) => userId !== currentUserId && selectableUserIds.has(userId));
|
||||
const requestedGroupIds = (draft?.initialGroupIds ?? []).map((groupId) => groupId.trim()).filter(Boolean);
|
||||
const uniqueGroupIds = [...new Set(requestedGroupIds)];
|
||||
const hasDuplicateGroups = uniqueGroupIds.length !== requestedGroupIds.length;
|
||||
const hasUnavailableGroup = uniqueGroupIds.some((groupId) => !selectableGroupIds.has(groupId));
|
||||
const initialGroupIds = uniqueGroupIds.filter((groupId) => selectableGroupIds.has(groupId));
|
||||
const syncGroupMembership = draft?.syncGroupMembership === true && initialGroupIds.length > 0;
|
||||
const validationErrorKeys: ChatChannelCreateValidationKey[] = [];
|
||||
if (!(draft?.name ?? "").trim()) validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupNameRequired);
|
||||
if (hasDuplicateUsers) validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialUsers);
|
||||
if (hasUnavailableUser) validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.userUnavailable);
|
||||
if (hasDuplicateGroups) validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.duplicateInitialGroups);
|
||||
if (hasUnavailableGroup || (draft?.syncGroupMembership === true && initialGroupIds.length === 0)) {
|
||||
validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.groupUnavailable);
|
||||
}
|
||||
|
||||
return {
|
||||
mode: "group",
|
||||
name: draft?.name ?? "",
|
||||
description: draft?.description ?? "",
|
||||
privacy: draft?.privacy ?? "public",
|
||||
initialUserIds,
|
||||
initialGroupIds,
|
||||
syncGroupMembership,
|
||||
validationErrorKeys,
|
||||
canSubmit: validationErrorKeys.length === 0,
|
||||
};
|
||||
}
|
||||
|
||||
function buildDmForm(draft: ChatDmCreateDraftInput | undefined, selectableUserIds: ReadonlySet<string>, currentUserId: string): ChatDmCreateFormVM {
|
||||
const requestedPeerUserId = draft?.peerUserId?.trim() || null;
|
||||
const validationErrorKeys: ChatChannelCreateValidationKey[] = [];
|
||||
if (!requestedPeerUserId) {
|
||||
validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerRequired);
|
||||
} else if (requestedPeerUserId === currentUserId || !selectableUserIds.has(requestedPeerUserId)) {
|
||||
validationErrorKeys.push(CHAT_CHANNEL_CREATE_VALIDATION_KEYS.dmPeerUnavailable);
|
||||
}
|
||||
|
||||
return {
|
||||
mode: "dm",
|
||||
peerUserId: requestedPeerUserId,
|
||||
validationErrorKeys,
|
||||
canSubmit: validationErrorKeys.length === 0,
|
||||
};
|
||||
}
|
||||
+428
@@ -0,0 +1,428 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildChatChannelDetailVM,
|
||||
ChatChannelDetailVMSchema,
|
||||
groupChatMessagesByDay,
|
||||
reconcileChatMessages,
|
||||
type BuildChatChannelDetailVMInput,
|
||||
type ChatMessageCandidate,
|
||||
} from "./channel-detail.vm.js";
|
||||
|
||||
const BASE_TIME = "2026-07-15T10:00:00.000Z";
|
||||
|
||||
function message(overrides: Partial<ChatMessageCandidate> = {}): ChatMessageCandidate {
|
||||
return {
|
||||
id: "local:client-1",
|
||||
clientMessageId: "client-1",
|
||||
source: "local_echo",
|
||||
deliveryState: "sending",
|
||||
failureReasonKey: null,
|
||||
author: {
|
||||
userId: "user-1",
|
||||
displayName: "Raffael",
|
||||
avatar: { imageUrl: null, fallbackLabel: "RS" },
|
||||
isCurrentUser: true,
|
||||
},
|
||||
bodyMarkdown: "Status ist unterwegs",
|
||||
bodyFormat: "markdown",
|
||||
systemEvent: null,
|
||||
createdAtIso: BASE_TIME,
|
||||
updatedAtIso: BASE_TIME,
|
||||
editedAtIso: null,
|
||||
deletedAtIso: null,
|
||||
parentMessageId: null,
|
||||
mentions: [],
|
||||
reactions: [],
|
||||
thread: null,
|
||||
attachments: [],
|
||||
linkPreviews: [],
|
||||
readAggregate: { readCount: 0, recipientCount: 2, readerUserIds: [], readerLabels: [], labelKey: "chat.message.read.aggregate" },
|
||||
pin: null,
|
||||
actions: { canReact: true, canReply: true, canEdit: true, canDelete: true, canPin: true, canMarkAsTask: true },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function detailInput(messages: readonly ChatMessageCandidate[]): BuildChatChannelDetailVMInput {
|
||||
return {
|
||||
header: {
|
||||
id: "chat-1",
|
||||
kind: "group",
|
||||
title: "Montage",
|
||||
subtitle: null,
|
||||
avatar: { imageUrl: null, fallbackLabel: "MO" },
|
||||
project: null,
|
||||
memberCount: 4,
|
||||
isPrivate: true,
|
||||
isArchived: false,
|
||||
isAuditMode: false,
|
||||
canManage: true,
|
||||
settingsHref: "/chat/chat-1/settings",
|
||||
pinnedHref: "/chat/chat-1/pinned",
|
||||
searchHref: "/chat/search?channel=chat-1",
|
||||
},
|
||||
messages,
|
||||
typingLabels: [],
|
||||
pinnedMessages: [
|
||||
{ messageId: "m-old", authorLabel: "A", snippet: "Alt", pinnedAtIso: "2026-07-15T08:00:00.000Z", pinnedByLabel: "P", href: "#m-old" },
|
||||
{ messageId: "m-new-a", authorLabel: "B", snippet: "Neu A", pinnedAtIso: "2026-07-15T09:00:00.000Z", pinnedByLabel: "P", href: "#m-new-a" },
|
||||
{ messageId: "m-new-b", authorLabel: "C", snippet: "Neu B", pinnedAtIso: "2026-07-15T09:00:00.000Z", pinnedByLabel: "P", href: "#m-new-b" },
|
||||
],
|
||||
history: { olderCursor: "older", hasOlder: true },
|
||||
composer: {
|
||||
disabledReasonKey: null,
|
||||
canSend: true,
|
||||
canAttachFiles: true,
|
||||
canRecordVoice: true,
|
||||
canMention: true,
|
||||
canMarkAsTask: true,
|
||||
draftStorageKey: "tenant-1:user-1:chat-1",
|
||||
maxBodyLength: 8_000,
|
||||
},
|
||||
connection: { state: "online", reconnectAttempt: 0, retryAtIso: null },
|
||||
};
|
||||
}
|
||||
|
||||
describe("reconcileChatMessages", () => {
|
||||
it("replaces a local echo with the latest canonical ACK/WS/persisted form", () => {
|
||||
const local = message();
|
||||
const websocket = message({
|
||||
id: "message-1",
|
||||
source: "websocket",
|
||||
deliveryState: "sending",
|
||||
updatedAtIso: "2026-07-15T10:00:01.000Z",
|
||||
});
|
||||
const ack = message({
|
||||
id: "message-1",
|
||||
source: "http_ack",
|
||||
deliveryState: "sending",
|
||||
updatedAtIso: "2026-07-15T10:00:02.000Z",
|
||||
reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }],
|
||||
});
|
||||
const persisted = message({
|
||||
id: "message-1",
|
||||
source: "persisted",
|
||||
deliveryState: "sent",
|
||||
updatedAtIso: "2026-07-15T10:00:01.500Z",
|
||||
});
|
||||
|
||||
const result = reconcileChatMessages([local, websocket, ack, persisted]);
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
id: "message-1",
|
||||
clientMessageId: "client-1",
|
||||
source: "http_ack",
|
||||
deliveryState: "sent",
|
||||
deliveryStateKey: "chat.message.delivery.sent",
|
||||
failureReasonKey: null,
|
||||
});
|
||||
expect(result[0]?.reactions[0]?.emoji).toBe("👍");
|
||||
});
|
||||
|
||||
it("retains a failed local echo and scopes deduplication by author", () => {
|
||||
const failed = message({ deliveryState: "failed", failureReasonKey: "chat.message.sendFailed" });
|
||||
const otherAuthor = message({
|
||||
id: "message-other",
|
||||
source: "persisted",
|
||||
author: {
|
||||
userId: "user-2",
|
||||
displayName: "Akeshan",
|
||||
avatar: { imageUrl: null, fallbackLabel: "AK" },
|
||||
isCurrentUser: false,
|
||||
},
|
||||
});
|
||||
|
||||
const result = reconcileChatMessages([failed, otherAuthor]);
|
||||
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result[0]).toMatchObject({ deliveryState: "failed", failureReasonKey: "chat.message.sendFailed" });
|
||||
expect(result[1]).toMatchObject({ id: "message-other", deliveryState: "sent" });
|
||||
});
|
||||
|
||||
it("scrubs deleted message content and exposes only a tombstone", () => {
|
||||
const result = reconcileChatMessages([
|
||||
message({
|
||||
id: "message-deleted",
|
||||
source: "persisted",
|
||||
deletedAtIso: "2026-07-15T10:01:00.000Z",
|
||||
mentions: [{ kind: "user", id: "user-2", label: "Akeshan", href: "/users/user-2" }],
|
||||
reactions: [{ emoji: "👍", count: 1, reactedByViewer: true, reactorLabels: ["Raffael"] }],
|
||||
attachments: [
|
||||
{
|
||||
id: "attachment-1",
|
||||
fileId: "file-1",
|
||||
kind: "file",
|
||||
fileName: "intern.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 42,
|
||||
downloadHref: "/files/file-1",
|
||||
previewHref: null,
|
||||
altText: null,
|
||||
durationSeconds: null,
|
||||
scanStatus: "clean",
|
||||
},
|
||||
],
|
||||
linkPreviews: [{ url: "https://example.test/private", title: "Intern", description: "Vertraulich", imageUrl: null, siteName: "example.test" }],
|
||||
pin: { pinnedAtIso: BASE_TIME, pinnedByLabel: "Raffael", note: "Intern" },
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
bodyMarkdown: null,
|
||||
mentions: [],
|
||||
reactions: [],
|
||||
attachments: [],
|
||||
linkPreviews: [],
|
||||
pin: null,
|
||||
tombstoneKey: "chat.message.deleted",
|
||||
actions: {
|
||||
canReact: false,
|
||||
canReply: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
canPin: false,
|
||||
canMarkAsTask: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps actorless system events immutable and free of user-message affordances", () => {
|
||||
const result = reconcileChatMessages([
|
||||
message({
|
||||
id: "system-message-1",
|
||||
clientMessageId: "system:project-created:project-1",
|
||||
source: "persisted",
|
||||
deliveryState: "failed",
|
||||
failureReasonKey: "chat.message.sendFailed",
|
||||
retryable: true,
|
||||
author: null,
|
||||
bodyMarkdown: "stored fallback must not be rendered",
|
||||
bodyFormat: "system",
|
||||
systemEvent: {
|
||||
kind: "project_created",
|
||||
labelKey: "chat.systemEvent.projectCreated",
|
||||
values: { project: "Wärmepumpe Müller" },
|
||||
},
|
||||
readAggregate: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
author: null,
|
||||
bodyMarkdown: null,
|
||||
bodyFormat: "system",
|
||||
deliveryState: "sent",
|
||||
failureReasonKey: null,
|
||||
retryable: false,
|
||||
readAggregate: null,
|
||||
systemEvent: {
|
||||
kind: "project_created",
|
||||
labelKey: "chat.systemEvent.projectCreated",
|
||||
values: { project: "Wärmepumpe Müller" },
|
||||
},
|
||||
actions: {
|
||||
canReact: false,
|
||||
canReply: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
canPin: false,
|
||||
canMarkAsTask: false,
|
||||
},
|
||||
});
|
||||
expect(ChatChannelDetailVMSchema.safeParse(buildChatChannelDetailVM(detailInput(result))).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildChatChannelDetailVM", () => {
|
||||
it("builds the complete detail contract and sorts pinned summaries stably", () => {
|
||||
const vm = buildChatChannelDetailVM(detailInput([message()]));
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.pinnedMessages.map(({ messageId }) => messageId)).toEqual(["m-new-a", "m-new-b", "m-old"]);
|
||||
expect(vm.data.composer).toMatchObject({ enabled: true, placeholderKey: "chat.composer.placeholder" });
|
||||
expect(vm.data.connection).toMatchObject({ state: "online", stateLabelKey: "chat.connection.online", canRetry: false });
|
||||
expect(vm.data.history).toEqual({ olderCursor: "older", hasOlder: true });
|
||||
expect(vm.data.messageGroups).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("adds the mandatory DM audit banner and disables a blocked composer", () => {
|
||||
const base = detailInput([]);
|
||||
const vm = buildChatChannelDetailVM({
|
||||
...base,
|
||||
header: { ...base.header, kind: "dm", isAuditMode: true },
|
||||
messages: [message()],
|
||||
composer: { ...base.composer, canSend: true, disabledReasonKey: null },
|
||||
connection: { state: "blocked", reconnectAttempt: -1, retryAtIso: null },
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.header.dmAuditBannerKey).toBe("chat.audit.dmBanner");
|
||||
expect(vm.data.header).toMatchObject({ canManage: false, settingsHref: null });
|
||||
expect(vm.data.header.pinnedHref).toBeNull();
|
||||
expect(vm.data.pinnedMessages).toEqual([]);
|
||||
expect(vm.data.composer).toMatchObject({
|
||||
enabled: false,
|
||||
disabledReasonKey: "chat.composer.auditReadOnly",
|
||||
canSend: false,
|
||||
canAttachFiles: false,
|
||||
canRecordVoice: false,
|
||||
canMention: false,
|
||||
canMarkAsTask: false,
|
||||
});
|
||||
expect(vm.data.connection).toMatchObject({ stateLabelKey: "chat.connection.blocked", reconnectAttempt: 0, canRetry: false });
|
||||
expect(vm.data.messages[0]?.actions).toEqual({
|
||||
canReact: false,
|
||||
canReply: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
canPin: false,
|
||||
canMarkAsTask: false,
|
||||
});
|
||||
expect(vm.data.emptyBodyKey).toBe("chat.channel.empty.body");
|
||||
});
|
||||
|
||||
it("normalizes archived composer, impossible history cursors, typing, and day groups", () => {
|
||||
const base = detailInput([
|
||||
message(),
|
||||
message({
|
||||
id: "message-2",
|
||||
clientMessageId: "client-2",
|
||||
source: "persisted",
|
||||
createdAtIso: "2026-07-16T08:00:00.000Z",
|
||||
updatedAtIso: "2026-07-16T08:00:00.000Z",
|
||||
linkPreviews: [{ url: "https://example.test", title: "Beispiel", description: null, imageUrl: null, siteName: "example.test" }],
|
||||
}),
|
||||
]);
|
||||
const vm = buildChatChannelDetailVM({
|
||||
...base,
|
||||
header: { ...base.header, isArchived: true },
|
||||
typingLabels: ["Akeshan"],
|
||||
history: { olderCursor: null, hasOlder: true },
|
||||
});
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.composer).toMatchObject({
|
||||
enabled: false,
|
||||
disabledReasonKey: "chat.composer.archived",
|
||||
canSend: false,
|
||||
canAttachFiles: false,
|
||||
canRecordVoice: false,
|
||||
canMention: false,
|
||||
canMarkAsTask: false,
|
||||
});
|
||||
expect(vm.data.header).toMatchObject({ canManage: false, settingsHref: null });
|
||||
expect(vm.data.messages.every(({ actions }) => Object.values(actions).every((allowed) => !allowed))).toBe(true);
|
||||
expect(vm.data.history).toEqual({ olderCursor: null, hasOlder: false });
|
||||
expect(vm.data.typingLabels).toEqual(["Akeshan"]);
|
||||
expect(vm.data.messageGroups.map(({ dateIso }) => dateIso)).toEqual(["2026-07-15", "2026-07-16"]);
|
||||
expect(vm.data.messages[1]?.linkPreviews[0]?.title).toBe("Beispiel");
|
||||
});
|
||||
|
||||
it("removes all pin affordances from direct messages", () => {
|
||||
const pinnedMessage = message({
|
||||
pin: { pinnedAtIso: BASE_TIME, pinnedByLabel: "Raffael", note: null },
|
||||
});
|
||||
const base = detailInput([pinnedMessage]);
|
||||
const vm = buildChatChannelDetailVM({ ...base, header: { ...base.header, kind: "dm" } });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.messages[0]?.pin).toBeNull();
|
||||
expect(vm.data.messages[0]?.actions.canPin).toBe(false);
|
||||
expect(vm.data.header.pinnedHref).toBeNull();
|
||||
expect(vm.data.pinnedMessages).toEqual([]);
|
||||
});
|
||||
|
||||
it("validates the strict serializable channel-detail contract", () => {
|
||||
const vm = buildChatChannelDetailVM(
|
||||
detailInput([
|
||||
message({
|
||||
id: "message-1",
|
||||
source: "persisted",
|
||||
linkPreviews: [{ url: "https://example.test", title: "Beispiel", description: null, imageUrl: null, siteName: "example.test" }],
|
||||
}),
|
||||
])
|
||||
);
|
||||
const serialized = JSON.parse(JSON.stringify(vm)) as unknown;
|
||||
|
||||
expect(ChatChannelDetailVMSchema.parse(serialized)).toEqual(vm);
|
||||
|
||||
const invalid = JSON.parse(JSON.stringify(vm)) as {
|
||||
data: { messages: Array<Record<string, unknown>> };
|
||||
};
|
||||
invalid.data.messages[0] = { ...invalid.data.messages[0], unexpected: true };
|
||||
expect(ChatChannelDetailVMSchema.safeParse(invalid).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects non-HTTP link-preview and image URLs", () => {
|
||||
const unsafeLink = buildChatChannelDetailVM(
|
||||
detailInput([
|
||||
message({
|
||||
source: "persisted",
|
||||
linkPreviews: [{ url: "javascript:alert(1)", title: null, description: null, imageUrl: "data:image/png;base64,AA==", siteName: null }],
|
||||
}),
|
||||
])
|
||||
);
|
||||
|
||||
expect(ChatChannelDetailVMSchema.safeParse(unsafeLink).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("groupChatMessagesByDay", () => {
|
||||
it("uses the app timezone instead of UTC around local midnight", () => {
|
||||
const messages = reconcileChatMessages([
|
||||
message({
|
||||
id: "message-before-midnight",
|
||||
clientMessageId: "client-before-midnight",
|
||||
source: "persisted",
|
||||
createdAtIso: "2026-01-15T22:59:00.000Z",
|
||||
updatedAtIso: "2026-01-15T22:59:00.000Z",
|
||||
}),
|
||||
message({
|
||||
id: "message-after-midnight",
|
||||
clientMessageId: "client-after-midnight",
|
||||
source: "persisted",
|
||||
createdAtIso: "2026-01-15T23:01:00.000Z",
|
||||
updatedAtIso: "2026-01-15T23:01:00.000Z",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(groupChatMessagesByDay(messages).map(({ dateIso }) => dateIso)).toEqual(["2026-01-15", "2026-01-16"]);
|
||||
});
|
||||
|
||||
it("keeps grouping and strict schema parsing aligned across local midnight and both DST transitions", () => {
|
||||
const timestamps = [
|
||||
["winter-before-midnight", "2026-01-15T22:59:00.000Z"],
|
||||
["winter-after-midnight", "2026-01-15T23:01:00.000Z"],
|
||||
["spring-before-jump", "2026-03-29T00:30:00.000Z"],
|
||||
["spring-after-jump", "2026-03-29T01:30:00.000Z"],
|
||||
["summer-before-midnight", "2026-07-15T21:59:00.000Z"],
|
||||
["summer-after-midnight", "2026-07-15T22:01:00.000Z"],
|
||||
["autumn-first-0230", "2026-10-25T00:30:00.000Z"],
|
||||
["autumn-second-0230", "2026-10-25T01:30:00.000Z"],
|
||||
] as const;
|
||||
const candidates = timestamps.map(([id, timestamp]) =>
|
||||
message({
|
||||
id: `message-${id}`,
|
||||
clientMessageId: `client-${id}`,
|
||||
source: "persisted",
|
||||
createdAtIso: timestamp,
|
||||
updatedAtIso: timestamp,
|
||||
})
|
||||
);
|
||||
const vm = buildChatChannelDetailVM(detailInput(candidates));
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.messageGroups.map(({ dateIso, messages }) => [dateIso, messages.length])).toEqual([
|
||||
["2026-01-15", 1],
|
||||
["2026-01-16", 1],
|
||||
["2026-03-29", 2],
|
||||
["2026-07-15", 1],
|
||||
["2026-07-16", 1],
|
||||
["2026-10-25", 2],
|
||||
]);
|
||||
const serialized = JSON.parse(JSON.stringify(vm)) as unknown;
|
||||
expect(ChatChannelDetailVMSchema.parse(serialized)).toEqual(vm);
|
||||
});
|
||||
});
|
||||
+783
@@ -0,0 +1,783 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
import type { ChatAvatarVM, ChatChannelKind, ChatChannelProjectVM } from "./channel-list.vm.js";
|
||||
import { chatSystemEventVMSchema, type ChatSystemEventVM } from "./system-event.vm.js";
|
||||
|
||||
export type ChatConnectionState = "connecting" | "online" | "reconnecting" | "offline" | "blocked";
|
||||
export type ChatMessageTransportSource = "persisted" | "websocket" | "http_ack" | "local_echo";
|
||||
export type ChatMessageDeliveryState = "sending" | "sent" | "failed";
|
||||
export type ChatAttachmentKind = "file" | "image" | "voice";
|
||||
|
||||
const CHAT_VM_INVARIANT_ERROR = "chat.errors.integrityFailure";
|
||||
export const CHAT_DEFAULT_TIME_ZONE = "Europe/Berlin";
|
||||
const chatDateKeyFormatters = new Map<string, Intl.DateTimeFormat>();
|
||||
|
||||
export interface ChatChannelHeaderVM {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
readonly title: string;
|
||||
readonly subtitle: string | null;
|
||||
readonly avatar: ChatAvatarVM;
|
||||
readonly project: ChatChannelProjectVM | null;
|
||||
readonly memberCount: number;
|
||||
readonly isPrivate: boolean;
|
||||
readonly isArchived: boolean;
|
||||
readonly isAuditMode: boolean;
|
||||
readonly dmAuditBannerKey: string | null;
|
||||
readonly canManage: boolean;
|
||||
readonly settingsHref: string | null;
|
||||
readonly pinnedHref: string | null;
|
||||
readonly searchHref: string;
|
||||
}
|
||||
|
||||
export interface ChatResolvedAuthorVM {
|
||||
readonly userId: string;
|
||||
readonly displayName: string;
|
||||
readonly avatar: ChatAvatarVM;
|
||||
readonly isCurrentUser: boolean;
|
||||
}
|
||||
|
||||
export interface ChatResolvedMentionVM {
|
||||
readonly kind: "user" | "project" | "contact" | "company";
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly href: string | null;
|
||||
}
|
||||
|
||||
export interface ChatReactionVM {
|
||||
readonly emoji: string;
|
||||
readonly count: number;
|
||||
readonly reactedByViewer: boolean;
|
||||
readonly reactorLabels: readonly string[];
|
||||
}
|
||||
|
||||
export interface ChatThreadAggregateVM {
|
||||
readonly id: string;
|
||||
readonly replyCount: number;
|
||||
readonly participantLabels: readonly string[];
|
||||
readonly lastReplyAtIso: string | null;
|
||||
readonly isFollowing: boolean;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface ChatAttachmentVM {
|
||||
readonly id: string;
|
||||
readonly fileId: string;
|
||||
readonly kind: ChatAttachmentKind;
|
||||
readonly fileName: string;
|
||||
readonly mimeType: string;
|
||||
readonly sizeBytes: number;
|
||||
readonly downloadHref: string;
|
||||
readonly previewHref: string | null;
|
||||
readonly altText: string | null;
|
||||
readonly durationSeconds: number | null;
|
||||
readonly scanStatus: "pending" | "clean" | "blocked";
|
||||
}
|
||||
|
||||
export interface ChatLinkPreviewVM {
|
||||
readonly url: string;
|
||||
readonly title: string | null;
|
||||
readonly description: string | null;
|
||||
readonly imageUrl: string | null;
|
||||
readonly siteName: string | null;
|
||||
}
|
||||
|
||||
export interface ChatReadAggregateVM {
|
||||
readonly readCount: number;
|
||||
readonly recipientCount: number;
|
||||
readonly readerUserIds: readonly string[];
|
||||
readonly readerLabels: readonly string[];
|
||||
readonly labelKey: string;
|
||||
}
|
||||
|
||||
export interface ChatMessagePinVM {
|
||||
readonly pinnedAtIso: string;
|
||||
readonly pinnedByLabel: string;
|
||||
readonly note: string | null;
|
||||
}
|
||||
|
||||
export interface ChatMessageActionsVM {
|
||||
readonly canReact: boolean;
|
||||
readonly canReply: boolean;
|
||||
readonly canEdit: boolean;
|
||||
readonly canDelete: boolean;
|
||||
readonly canPin: boolean;
|
||||
readonly canMarkAsTask: boolean;
|
||||
}
|
||||
|
||||
/** One transport candidate. A local echo and its persisted/WS/HTTP variants
|
||||
* intentionally share authorUserId + clientMessageId. */
|
||||
export interface ChatMessageCandidate {
|
||||
readonly id: string;
|
||||
readonly clientMessageId: string;
|
||||
readonly source: ChatMessageTransportSource;
|
||||
readonly deliveryState: ChatMessageDeliveryState;
|
||||
readonly failureReasonKey: string | null;
|
||||
readonly retryable?: boolean;
|
||||
readonly author: ChatResolvedAuthorVM | null;
|
||||
readonly bodyMarkdown: string | null;
|
||||
readonly bodyFormat: "markdown" | "system";
|
||||
readonly systemEvent: ChatSystemEventVM | null;
|
||||
readonly createdAtIso: string;
|
||||
readonly updatedAtIso: string;
|
||||
readonly editedAtIso: string | null;
|
||||
readonly deletedAtIso: string | null;
|
||||
readonly parentMessageId: string | null;
|
||||
readonly mentions: readonly ChatResolvedMentionVM[];
|
||||
readonly reactions: readonly ChatReactionVM[];
|
||||
readonly thread: ChatThreadAggregateVM | null;
|
||||
readonly attachments: readonly ChatAttachmentVM[];
|
||||
readonly linkPreviews: readonly ChatLinkPreviewVM[];
|
||||
readonly readAggregate: ChatReadAggregateVM | null;
|
||||
readonly pin: ChatMessagePinVM | null;
|
||||
readonly actions: ChatMessageActionsVM;
|
||||
}
|
||||
|
||||
export interface ChatMessageVM extends Omit<ChatMessageCandidate, "deliveryState" | "failureReasonKey" | "retryable"> {
|
||||
readonly deliveryState: ChatMessageDeliveryState;
|
||||
readonly deliveryStateKey: string;
|
||||
readonly failureReasonKey: string | null;
|
||||
readonly retryable: boolean;
|
||||
readonly tombstoneKey: string | null;
|
||||
}
|
||||
|
||||
export interface ChatPinnedMessageSummaryVM {
|
||||
readonly messageId: string;
|
||||
readonly authorLabel: string;
|
||||
readonly snippet: string;
|
||||
readonly pinnedAtIso: string;
|
||||
readonly pinnedByLabel: string;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface ChatHistoryVM {
|
||||
/** Opaque keyset cursor for the next older page. */
|
||||
readonly olderCursor: string | null;
|
||||
readonly hasOlder: boolean;
|
||||
}
|
||||
|
||||
export interface ChatMessageDayGroupVM {
|
||||
readonly dateIso: string;
|
||||
readonly messages: readonly ChatMessageVM[];
|
||||
}
|
||||
|
||||
export interface ChatPresenceVM {
|
||||
readonly userId: string;
|
||||
readonly status: "online" | "away";
|
||||
}
|
||||
|
||||
export interface ChatComposerVM {
|
||||
readonly enabled: boolean;
|
||||
readonly disabledReasonKey: string | null;
|
||||
readonly canSend: boolean;
|
||||
readonly canAttachFiles: boolean;
|
||||
readonly canRecordVoice: boolean;
|
||||
readonly canMention: boolean;
|
||||
readonly canMarkAsTask: boolean;
|
||||
readonly draftStorageKey: string;
|
||||
readonly maxBodyLength: number;
|
||||
readonly placeholderKey: string;
|
||||
}
|
||||
|
||||
export interface ChatConnectionVM {
|
||||
readonly state: ChatConnectionState;
|
||||
readonly stateLabelKey: string;
|
||||
readonly reconnectAttempt: number;
|
||||
readonly retryAtIso: string | null;
|
||||
readonly canRetry: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelDetailData {
|
||||
readonly header: ChatChannelHeaderVM;
|
||||
readonly messages: readonly ChatMessageVM[];
|
||||
readonly messageGroups: readonly ChatMessageDayGroupVM[];
|
||||
readonly presence: readonly ChatPresenceVM[];
|
||||
readonly typingLabels: readonly string[];
|
||||
readonly pinnedMessages: readonly ChatPinnedMessageSummaryVM[];
|
||||
readonly history: ChatHistoryVM;
|
||||
readonly composer: ChatComposerVM;
|
||||
readonly connection: ChatConnectionVM;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly loadOlderLabelKey: string;
|
||||
readonly newMessagesLabelKey: string;
|
||||
}
|
||||
|
||||
export type ChatChannelDetailVM = VMState<ChatChannelDetailData>;
|
||||
|
||||
export interface BuildChatChannelDetailVMInput {
|
||||
readonly header: Omit<ChatChannelHeaderVM, "dmAuditBannerKey">;
|
||||
readonly messages: readonly ChatMessageCandidate[];
|
||||
readonly pinnedMessages: readonly ChatPinnedMessageSummaryVM[];
|
||||
readonly typingLabels: readonly string[];
|
||||
readonly history: ChatHistoryVM;
|
||||
readonly composer: Omit<ChatComposerVM, "enabled" | "placeholderKey">;
|
||||
readonly connection: Omit<ChatConnectionVM, "stateLabelKey" | "canRetry">;
|
||||
}
|
||||
|
||||
export const chatConnectionStateSchema = z.enum(["connecting", "online", "reconnecting", "offline", "blocked"]);
|
||||
export const chatMessageTransportSourceSchema = z.enum(["persisted", "websocket", "http_ack", "local_echo"]);
|
||||
export const chatMessageDeliveryStateSchema = z.enum(["sending", "sent", "failed"]);
|
||||
export const chatAttachmentKindSchema = z.enum(["file", "image", "voice"]);
|
||||
|
||||
const chatChannelKindSchema = z.enum(["project", "group", "dm"]);
|
||||
const chatAvatarVMSchema = z
|
||||
.object({
|
||||
imageUrl: z.string().min(1).nullable(),
|
||||
fallbackLabel: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
const chatChannelProjectVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
number: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
stageLabel: z.string().min(1),
|
||||
href: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelHeaderVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
kind: chatChannelKindSchema,
|
||||
title: z.string().min(1),
|
||||
subtitle: z.string().nullable(),
|
||||
avatar: chatAvatarVMSchema,
|
||||
project: chatChannelProjectVMSchema.nullable(),
|
||||
memberCount: z.number().int().nonnegative(),
|
||||
isPrivate: z.boolean(),
|
||||
isArchived: z.boolean(),
|
||||
isAuditMode: z.boolean(),
|
||||
dmAuditBannerKey: z.literal("chat.audit.dmBanner").nullable(),
|
||||
canManage: z.boolean(),
|
||||
settingsHref: z.string().min(1).nullable(),
|
||||
pinnedHref: z.string().min(1).nullable(),
|
||||
searchHref: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatResolvedAuthorVMSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
displayName: z.string().min(1),
|
||||
avatar: chatAvatarVMSchema,
|
||||
isCurrentUser: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatResolvedMentionVMSchema = z
|
||||
.object({
|
||||
kind: z.enum(["user", "project", "contact", "company"]),
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
href: z.string().min(1).nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatReactionVMSchema = z
|
||||
.object({
|
||||
emoji: z.string().min(1),
|
||||
count: z.number().int().nonnegative(),
|
||||
reactedByViewer: z.boolean(),
|
||||
reactorLabels: z.array(z.string().min(1)),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatThreadAggregateVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
replyCount: z.number().int().nonnegative(),
|
||||
participantLabels: z.array(z.string().min(1)),
|
||||
lastReplyAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
isFollowing: z.boolean(),
|
||||
href: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatAttachmentVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
fileId: z.string().min(1),
|
||||
kind: chatAttachmentKindSchema,
|
||||
fileName: z.string().min(1),
|
||||
mimeType: z.string().min(1),
|
||||
sizeBytes: z.number().int().nonnegative(),
|
||||
downloadHref: z.string().min(1),
|
||||
previewHref: z.string().min(1).nullable(),
|
||||
altText: z.string().nullable(),
|
||||
durationSeconds: z.number().nonnegative().nullable(),
|
||||
scanStatus: z.enum(["pending", "clean", "blocked"]),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const absoluteHttpUrlSchema = z
|
||||
.string()
|
||||
.url()
|
||||
.refine((value) => {
|
||||
const protocol = new URL(value).protocol;
|
||||
return protocol === "http:" || protocol === "https:";
|
||||
}, "Link previews require an absolute HTTP URL");
|
||||
|
||||
const chatLinkPreviewVMSchema = z
|
||||
.object({
|
||||
url: absoluteHttpUrlSchema,
|
||||
title: z.string().nullable(),
|
||||
description: z.string().nullable(),
|
||||
imageUrl: absoluteHttpUrlSchema.nullable(),
|
||||
siteName: z.string().nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatReadAggregateVMSchema = z
|
||||
.object({
|
||||
readCount: z.number().int().nonnegative(),
|
||||
recipientCount: z.number().int().nonnegative(),
|
||||
readerUserIds: z.array(z.string().min(1)),
|
||||
readerLabels: z.array(z.string().min(1)),
|
||||
labelKey: z.string().min(1),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((aggregate, context) => {
|
||||
if (
|
||||
aggregate.readerUserIds.length !== aggregate.readerLabels.length ||
|
||||
new Set(aggregate.readerUserIds).size !== aggregate.readerUserIds.length ||
|
||||
aggregate.readCount !== aggregate.readerUserIds.length ||
|
||||
aggregate.readCount > aggregate.recipientCount
|
||||
) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
});
|
||||
|
||||
const chatMessagePinVMSchema = z
|
||||
.object({
|
||||
pinnedAtIso: z.string().datetime({ offset: true }),
|
||||
pinnedByLabel: z.string().min(1),
|
||||
note: z.string().nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatMessageActionsVMSchema = z
|
||||
.object({
|
||||
canReact: z.boolean(),
|
||||
canReply: z.boolean(),
|
||||
canEdit: z.boolean(),
|
||||
canDelete: z.boolean(),
|
||||
canPin: z.boolean(),
|
||||
canMarkAsTask: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatMessageVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
clientMessageId: z.string().min(1),
|
||||
source: chatMessageTransportSourceSchema,
|
||||
deliveryState: chatMessageDeliveryStateSchema,
|
||||
deliveryStateKey: z.enum(["chat.message.delivery.sending", "chat.message.delivery.sent", "chat.message.delivery.failed"]),
|
||||
failureReasonKey: z.string().min(1).nullable(),
|
||||
retryable: z.boolean(),
|
||||
author: chatResolvedAuthorVMSchema.nullable(),
|
||||
bodyMarkdown: z.string().nullable(),
|
||||
bodyFormat: z.enum(["markdown", "system"]),
|
||||
systemEvent: chatSystemEventVMSchema.nullable(),
|
||||
createdAtIso: z.string().datetime({ offset: true }),
|
||||
updatedAtIso: z.string().datetime({ offset: true }),
|
||||
editedAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
deletedAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
parentMessageId: z.string().min(1).nullable(),
|
||||
mentions: z.array(chatResolvedMentionVMSchema),
|
||||
reactions: z.array(chatReactionVMSchema),
|
||||
thread: chatThreadAggregateVMSchema.nullable(),
|
||||
attachments: z.array(chatAttachmentVMSchema),
|
||||
linkPreviews: z.array(chatLinkPreviewVMSchema),
|
||||
readAggregate: chatReadAggregateVMSchema.nullable(),
|
||||
pin: chatMessagePinVMSchema.nullable(),
|
||||
actions: chatMessageActionsVMSchema,
|
||||
tombstoneKey: z.literal("chat.message.deleted").nullable(),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((message, context) => {
|
||||
const isDeleted = message.deletedAtIso !== null;
|
||||
const isSystem = message.bodyFormat === "system";
|
||||
|
||||
if (isSystem) {
|
||||
if (
|
||||
message.author !== null ||
|
||||
message.systemEvent === null ||
|
||||
message.bodyMarkdown !== null ||
|
||||
message.readAggregate !== null ||
|
||||
message.parentMessageId !== null ||
|
||||
message.mentions.length > 0 ||
|
||||
message.reactions.length > 0 ||
|
||||
message.thread !== null ||
|
||||
message.attachments.length > 0 ||
|
||||
message.linkPreviews.length > 0 ||
|
||||
message.pin !== null ||
|
||||
message.source === "local_echo" ||
|
||||
message.deliveryState !== "sent" ||
|
||||
Object.values(message.actions).some(Boolean)
|
||||
) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
} else if (message.author === null || message.systemEvent !== null || message.readAggregate === null) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
if (isDeleted && message.tombstoneKey !== "chat.message.deleted") {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR, path: ["tombstoneKey"] });
|
||||
}
|
||||
if (!isDeleted && message.tombstoneKey !== null) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR, path: ["tombstoneKey"] });
|
||||
}
|
||||
if (
|
||||
isDeleted &&
|
||||
(message.bodyMarkdown !== null ||
|
||||
message.mentions.length > 0 ||
|
||||
message.reactions.length > 0 ||
|
||||
message.attachments.length > 0 ||
|
||||
message.linkPreviews.length > 0 ||
|
||||
message.pin !== null ||
|
||||
Object.values(message.actions).some(Boolean))
|
||||
) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
});
|
||||
|
||||
const chatPinnedMessageSummaryVMSchema = z
|
||||
.object({
|
||||
messageId: z.string().min(1),
|
||||
authorLabel: z.string().min(1),
|
||||
snippet: z.string(),
|
||||
pinnedAtIso: z.string().datetime({ offset: true }),
|
||||
pinnedByLabel: z.string().min(1),
|
||||
href: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatHistoryVMSchema = z
|
||||
.object({
|
||||
olderCursor: z.string().min(1).nullable(),
|
||||
hasOlder: z.boolean(),
|
||||
})
|
||||
.strict()
|
||||
.refine((history) => history.hasOlder === (history.olderCursor !== null), {
|
||||
message: CHAT_VM_INVARIANT_ERROR,
|
||||
});
|
||||
|
||||
const chatMessageDayGroupVMSchema = z
|
||||
.object({
|
||||
dateIso: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
||||
messages: z.array(chatMessageVMSchema),
|
||||
})
|
||||
.strict()
|
||||
.refine((group) => group.messages.every((message) => chatDateKey(message.createdAtIso) === group.dateIso), {
|
||||
message: CHAT_VM_INVARIANT_ERROR,
|
||||
path: ["messages"],
|
||||
});
|
||||
|
||||
const chatComposerVMSchema = z
|
||||
.object({
|
||||
enabled: z.boolean(),
|
||||
disabledReasonKey: z.string().min(1).nullable(),
|
||||
canSend: z.boolean(),
|
||||
canAttachFiles: z.boolean(),
|
||||
canRecordVoice: z.boolean(),
|
||||
canMention: z.boolean(),
|
||||
canMarkAsTask: z.boolean(),
|
||||
draftStorageKey: z.string().min(1),
|
||||
maxBodyLength: z.number().int().nonnegative(),
|
||||
placeholderKey: z.literal("chat.composer.placeholder"),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((composer, context) => {
|
||||
const hasEnabledAction = composer.canSend || composer.canAttachFiles || composer.canRecordVoice || composer.canMention || composer.canMarkAsTask;
|
||||
if (composer.enabled !== composer.canSend) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR, path: ["enabled"] });
|
||||
}
|
||||
if (!composer.enabled && hasEnabledAction) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
});
|
||||
|
||||
const chatConnectionVMSchema = z
|
||||
.object({
|
||||
state: chatConnectionStateSchema,
|
||||
stateLabelKey: z.enum([
|
||||
"chat.connection.connecting",
|
||||
"chat.connection.online",
|
||||
"chat.connection.reconnecting",
|
||||
"chat.connection.offline",
|
||||
"chat.connection.blocked",
|
||||
]),
|
||||
reconnectAttempt: z.number().int().nonnegative(),
|
||||
retryAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
canRetry: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatPresenceVMSchema = z
|
||||
.object({
|
||||
userId: z.string().min(1),
|
||||
status: z.enum(["online", "away"]),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelDetailDataSchema = z
|
||||
.object({
|
||||
header: chatChannelHeaderVMSchema,
|
||||
messages: z.array(chatMessageVMSchema),
|
||||
messageGroups: z.array(chatMessageDayGroupVMSchema),
|
||||
presence: z.array(chatPresenceVMSchema),
|
||||
typingLabels: z.array(z.string().min(1)),
|
||||
pinnedMessages: z.array(chatPinnedMessageSummaryVMSchema),
|
||||
history: chatHistoryVMSchema,
|
||||
composer: chatComposerVMSchema,
|
||||
connection: chatConnectionVMSchema,
|
||||
emptyHeadlineKey: z.literal("chat.channel.empty.headline"),
|
||||
emptyBodyKey: z.literal("chat.channel.empty.body"),
|
||||
loadOlderLabelKey: z.literal("chat.channel.loadOlder"),
|
||||
newMessagesLabelKey: z.literal("chat.channel.newMessages"),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, context) => {
|
||||
if (data.header.kind === "dm") {
|
||||
const hasPinAffordance =
|
||||
data.header.pinnedHref !== null || data.pinnedMessages.length > 0 || data.messages.some((message) => message.pin !== null || message.actions.canPin);
|
||||
if (hasPinAffordance) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
}
|
||||
if (data.header.isAuditMode && data.composer.disabledReasonKey !== "chat.composer.auditReadOnly") {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR, path: ["composer"] });
|
||||
}
|
||||
if (!data.header.isAuditMode && data.header.isArchived && data.composer.disabledReasonKey !== "chat.composer.archived") {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR, path: ["composer"] });
|
||||
}
|
||||
if (data.header.isAuditMode || data.header.isArchived) {
|
||||
if (data.header.canManage || data.header.settingsHref !== null || data.messages.some((message) => Object.values(message.actions).some(Boolean))) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: CHAT_VM_INVARIANT_ERROR });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
/** Strict serializable render contract produced by buildChatChannelDetailVM. */
|
||||
export const ChatChannelDetailVMSchema = z
|
||||
.object({
|
||||
status: z.literal("ready"),
|
||||
data: chatChannelDetailDataSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function chatConnectionStateLabelKey(state: ChatConnectionState): string {
|
||||
return `chat.connection.${state}`;
|
||||
}
|
||||
|
||||
export function chatMessageDeliveryStateKey(state: ChatMessageDeliveryState): string {
|
||||
return `chat.message.delivery.${state}`;
|
||||
}
|
||||
|
||||
/** Stable identity shared by the loader, local echo, WebSocket, and HTTP ACK
|
||||
* paths. Durable system messages intentionally have no synthetic author. */
|
||||
export function chatMessageIdentityKey(
|
||||
candidate: Pick<ChatMessageCandidate, "author" | "clientMessageId">
|
||||
): string {
|
||||
return `${candidate.author?.userId ?? "system"}\u0000${candidate.clientMessageId}`;
|
||||
}
|
||||
|
||||
/** Reconcile local echo, WebSocket fan-out, and HTTP ACK/history without
|
||||
* duplicate rows. The client id is author-scoped because the database allows
|
||||
* different authors to generate the same clientMessageId. */
|
||||
export function reconcileChatMessages(candidates: readonly ChatMessageCandidate[], options: { readonly allowPins?: boolean } = {}): ChatMessageVM[] {
|
||||
const byClientMessage = new Map<string, { candidate: ChatMessageCandidate; firstIndex: number }>();
|
||||
|
||||
candidates.forEach((candidate, index) => {
|
||||
const key = chatMessageIdentityKey(candidate);
|
||||
const current = byClientMessage.get(key);
|
||||
if (!current) {
|
||||
byClientMessage.set(key, { candidate, firstIndex: index });
|
||||
return;
|
||||
}
|
||||
if (isPreferredCandidate(candidate, current.candidate)) {
|
||||
byClientMessage.set(key, { candidate, firstIndex: current.firstIndex });
|
||||
}
|
||||
});
|
||||
|
||||
return [...byClientMessage.values()]
|
||||
.sort((left, right) => compareIso(left.candidate.createdAtIso, right.candidate.createdAtIso) || left.firstIndex - right.firstIndex)
|
||||
.map(({ candidate }) => toMessageVM(candidate, options.allowPins !== false));
|
||||
}
|
||||
|
||||
/** Pinned overview is newest-first. Equal timestamps retain loader order. */
|
||||
export function stableSortPinnedMessages(rows: readonly ChatPinnedMessageSummaryVM[]): ChatPinnedMessageSummaryVM[] {
|
||||
return rows
|
||||
.map((row, index) => ({ row, index }))
|
||||
.sort((left, right) => compareIso(right.row.pinnedAtIso, left.row.pinnedAtIso) || left.index - right.index)
|
||||
.map(({ row }) => row);
|
||||
}
|
||||
|
||||
export function buildChatChannelDetailVM(input: BuildChatChannelDetailVMInput): ChatChannelDetailVM {
|
||||
const allowPins = input.header.kind !== "dm";
|
||||
const isReadOnly = input.header.isAuditMode || input.header.isArchived;
|
||||
const messages = reconcileChatMessages(input.messages, { allowPins }).map((message) =>
|
||||
isReadOnly ? { ...message, actions: DELETED_MESSAGE_ACTIONS } : message
|
||||
);
|
||||
const isDmAudit = input.header.kind === "dm" && input.header.isAuditMode;
|
||||
const canRetry = input.connection.state === "offline" || input.connection.state === "reconnecting";
|
||||
const disabledReasonKey = input.header.isAuditMode
|
||||
? "chat.composer.auditReadOnly"
|
||||
: input.header.isArchived
|
||||
? "chat.composer.archived"
|
||||
: input.composer.disabledReasonKey;
|
||||
const composerEnabled = input.composer.canSend && disabledReasonKey === null;
|
||||
const hasOlder = input.history.hasOlder && input.history.olderCursor !== null;
|
||||
|
||||
return ready<ChatChannelDetailData>({
|
||||
header: {
|
||||
...input.header,
|
||||
memberCount: normalizeCount(input.header.memberCount),
|
||||
dmAuditBannerKey: isDmAudit ? "chat.audit.dmBanner" : null,
|
||||
pinnedHref: allowPins ? input.header.pinnedHref : null,
|
||||
canManage: isReadOnly ? false : input.header.canManage,
|
||||
settingsHref: isReadOnly ? null : input.header.settingsHref,
|
||||
},
|
||||
messages,
|
||||
messageGroups: groupChatMessagesByDay(messages),
|
||||
presence: [],
|
||||
typingLabels: [...input.typingLabels],
|
||||
pinnedMessages: allowPins ? stableSortPinnedMessages(input.pinnedMessages) : [],
|
||||
history: {
|
||||
olderCursor: hasOlder ? input.history.olderCursor : null,
|
||||
hasOlder,
|
||||
},
|
||||
composer: {
|
||||
...input.composer,
|
||||
disabledReasonKey,
|
||||
enabled: composerEnabled,
|
||||
canSend: composerEnabled,
|
||||
canAttachFiles: composerEnabled && input.composer.canAttachFiles,
|
||||
canRecordVoice: composerEnabled && input.composer.canRecordVoice,
|
||||
canMention: composerEnabled && input.composer.canMention,
|
||||
canMarkAsTask: composerEnabled && input.composer.canMarkAsTask,
|
||||
maxBodyLength: normalizeCount(input.composer.maxBodyLength),
|
||||
placeholderKey: "chat.composer.placeholder",
|
||||
},
|
||||
connection: {
|
||||
...input.connection,
|
||||
reconnectAttempt: normalizeCount(input.connection.reconnectAttempt),
|
||||
stateLabelKey: chatConnectionStateLabelKey(input.connection.state),
|
||||
canRetry,
|
||||
},
|
||||
emptyHeadlineKey: "chat.channel.empty.headline",
|
||||
emptyBodyKey: "chat.channel.empty.body",
|
||||
loadOlderLabelKey: "chat.channel.loadOlder",
|
||||
newMessagesLabelKey: "chat.channel.newMessages",
|
||||
});
|
||||
}
|
||||
|
||||
export function groupChatMessagesByDay(messages: readonly ChatMessageVM[], timeZone: string = CHAT_DEFAULT_TIME_ZONE): ChatMessageDayGroupVM[] {
|
||||
const groups: ChatMessageDayGroupVM[] = [];
|
||||
for (const message of messages) {
|
||||
const dateIso = chatDateKey(message.createdAtIso, timeZone);
|
||||
const current = groups.at(-1);
|
||||
if (current?.dateIso === dateIso) {
|
||||
groups[groups.length - 1] = { dateIso, messages: [...current.messages, message] };
|
||||
} else {
|
||||
groups.push({ dateIso, messages: [message] });
|
||||
}
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function chatDateKey(timestamp: string, timeZone: string = CHAT_DEFAULT_TIME_ZONE): string {
|
||||
let formatter = chatDateKeyFormatters.get(timeZone);
|
||||
if (!formatter) {
|
||||
formatter = new Intl.DateTimeFormat("en-CA", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
});
|
||||
chatDateKeyFormatters.set(timeZone, formatter);
|
||||
}
|
||||
const parts = formatter.formatToParts(new Date(timestamp));
|
||||
const year = parts.find((part) => part.type === "year")?.value;
|
||||
const month = parts.find((part) => part.type === "month")?.value;
|
||||
const day = parts.find((part) => part.type === "day")?.value;
|
||||
if (!year || !month || !day) throw new Error(CHAT_VM_INVARIANT_ERROR);
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
function toMessageVM(candidate: ChatMessageCandidate, allowPins: boolean): ChatMessageVM {
|
||||
const isSystem = candidate.bodyFormat === "system";
|
||||
const deliveryState = !isSystem && candidate.source === "local_echo" ? candidate.deliveryState : "sent";
|
||||
const isDeleted = candidate.deletedAtIso !== null;
|
||||
return {
|
||||
...candidate,
|
||||
author: isSystem ? null : candidate.author,
|
||||
bodyMarkdown: isDeleted || isSystem ? null : candidate.bodyMarkdown,
|
||||
systemEvent: isSystem ? candidate.systemEvent : null,
|
||||
mentions: isDeleted || isSystem ? [] : candidate.mentions,
|
||||
reactions:
|
||||
isDeleted || isSystem ? [] : candidate.reactions.map((reaction) => ({ ...reaction, count: normalizeCount(reaction.count) })),
|
||||
attachments: isDeleted || isSystem ? [] : candidate.attachments,
|
||||
linkPreviews: isDeleted || isSystem ? [] : candidate.linkPreviews,
|
||||
readAggregate: candidate.readAggregate
|
||||
? {
|
||||
...candidate.readAggregate,
|
||||
readCount: normalizeCount(candidate.readAggregate.readCount),
|
||||
recipientCount: normalizeCount(candidate.readAggregate.recipientCount),
|
||||
readerUserIds: [...candidate.readAggregate.readerUserIds],
|
||||
readerLabels: [...candidate.readAggregate.readerLabels],
|
||||
}
|
||||
: null,
|
||||
thread: !isSystem && candidate.thread
|
||||
? {
|
||||
...candidate.thread,
|
||||
replyCount: normalizeCount(candidate.thread.replyCount),
|
||||
}
|
||||
: null,
|
||||
pin: isDeleted || isSystem || !allowPins ? null : candidate.pin,
|
||||
actions: isDeleted || isSystem ? DELETED_MESSAGE_ACTIONS : allowPins ? candidate.actions : { ...candidate.actions, canPin: false },
|
||||
deliveryState,
|
||||
deliveryStateKey: chatMessageDeliveryStateKey(deliveryState),
|
||||
failureReasonKey: deliveryState === "failed" ? candidate.failureReasonKey : null,
|
||||
retryable: deliveryState === "failed" && candidate.retryable === true,
|
||||
tombstoneKey: isDeleted ? "chat.message.deleted" : null,
|
||||
};
|
||||
}
|
||||
|
||||
const DELETED_MESSAGE_ACTIONS: ChatMessageActionsVM = Object.freeze({
|
||||
canReact: false,
|
||||
canReply: false,
|
||||
canEdit: false,
|
||||
canDelete: false,
|
||||
canPin: false,
|
||||
canMarkAsTask: false,
|
||||
});
|
||||
|
||||
function isPreferredCandidate(candidate: ChatMessageCandidate, current: ChatMessageCandidate): boolean {
|
||||
const candidateCanonical = candidate.source !== "local_echo";
|
||||
const currentCanonical = current.source !== "local_echo";
|
||||
if (candidateCanonical !== currentCanonical) return candidateCanonical;
|
||||
|
||||
const updatedComparison = compareIso(candidate.updatedAtIso, current.updatedAtIso);
|
||||
if (updatedComparison !== 0) return updatedComparison > 0;
|
||||
return SOURCE_PRIORITY[candidate.source] > SOURCE_PRIORITY[current.source];
|
||||
}
|
||||
|
||||
const SOURCE_PRIORITY: Readonly<Record<ChatMessageTransportSource, number>> = {
|
||||
local_echo: 0,
|
||||
persisted: 1,
|
||||
websocket: 2,
|
||||
http_ack: 3,
|
||||
};
|
||||
|
||||
function compareIso(left: string, right: string): number {
|
||||
return left.localeCompare(right);
|
||||
}
|
||||
|
||||
function normalizeCount(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatChannelListVM, ChatChannelListVMSchema, type BuildChatChannelListVMInput, type ChatChannelListRowInput } from "./channel-list.vm.js";
|
||||
|
||||
function row(id: string, overrides: Partial<ChatChannelListRowInput> = {}): ChatChannelListRowInput {
|
||||
return {
|
||||
id,
|
||||
kind: "group",
|
||||
title: `Channel ${id}`,
|
||||
subtitle: null,
|
||||
detailHref: `/chat/${id}`,
|
||||
avatar: { imageUrl: null, fallbackLabel: id },
|
||||
project: null,
|
||||
lastMessage: null,
|
||||
typingLabels: [],
|
||||
unreadCount: 0,
|
||||
hasMention: false,
|
||||
isPinned: false,
|
||||
isPrivate: false,
|
||||
notificationPreference: "all_messages",
|
||||
archivedAtIso: null,
|
||||
memberCount: 2,
|
||||
canManage: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function input(rows: readonly ChatChannelListRowInput[]): BuildChatChannelListVMInput {
|
||||
return {
|
||||
rows,
|
||||
discoverRows: [
|
||||
{
|
||||
id: "discover-1",
|
||||
title: "Baustellen-News",
|
||||
description: null,
|
||||
avatar: { imageUrl: null, fallbackLabel: "BN" },
|
||||
memberCount: 12,
|
||||
isJoined: false,
|
||||
canJoin: true,
|
||||
joinHref: "/chat/discover-1/join",
|
||||
detailHref: null,
|
||||
},
|
||||
],
|
||||
filter: { query: "", view: "all", showArchived: false },
|
||||
permissions: {
|
||||
canWrite: true,
|
||||
canCreateGroup: true,
|
||||
canCreateDm: true,
|
||||
canDiscover: true,
|
||||
canViewMentions: true,
|
||||
canSearch: true,
|
||||
canViewArchived: true,
|
||||
canAdmin: false,
|
||||
},
|
||||
hrefs: {
|
||||
newChannel: "/chat/new?kind=group",
|
||||
newDm: "/chat/new?kind=dm",
|
||||
search: "/chat/search",
|
||||
mentions: "/chat/mentions",
|
||||
archived: "/chat?archived=1",
|
||||
},
|
||||
totals: { unread: 4, mentions: 1 },
|
||||
nextCursor: "next",
|
||||
discoverNextCursor: "discover-next",
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildChatChannelListVM", () => {
|
||||
it("places pinned channels first without disturbing either stable partition", () => {
|
||||
const original = [row("u1"), row("p1", { isPinned: true }), row("u2"), row("p2", { isPinned: true })];
|
||||
const vm = buildChatChannelListVM(input(original));
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows.map(({ id }) => id)).toEqual(["p1", "p2", "u1", "u2"]);
|
||||
expect(original.map(({ id }) => id)).toEqual(["u1", "p1", "u2", "p2"]);
|
||||
});
|
||||
|
||||
it("derives unread, mention, mute, archive and kind display state", () => {
|
||||
const vm = buildChatChannelListVM(
|
||||
input([
|
||||
row("project", {
|
||||
kind: "project",
|
||||
unreadCount: 3,
|
||||
hasMention: true,
|
||||
notificationPreference: "muted",
|
||||
archivedAtIso: "2026-07-15T09:00:00.000Z",
|
||||
memberCount: -2,
|
||||
}),
|
||||
])
|
||||
);
|
||||
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]).toMatchObject({
|
||||
hasUnread: true,
|
||||
hasMention: true,
|
||||
isMuted: true,
|
||||
isArchived: true,
|
||||
memberCount: 0,
|
||||
kindLabelKey: "chat.channel.kind.project",
|
||||
});
|
||||
expect(vm.data.permissions.canCreateDm).toBe(true);
|
||||
expect(vm.data.discoverRows[0]?.canJoin).toBe(true);
|
||||
});
|
||||
|
||||
it("derives unread state from the normalized counter", () => {
|
||||
const vm = buildChatChannelListVM(input([row("invalid-unread", { unreadCount: Number.POSITIVE_INFINITY })]));
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.rows[0]).toMatchObject({ unreadCount: 0, hasUnread: false });
|
||||
});
|
||||
|
||||
it("keeps filter controls and i18n empty states available for an empty result", () => {
|
||||
const vm = buildChatChannelListVM({ ...input([]), discoverRows: [], nextCursor: "ignored", discoverNextCursor: "ignored" });
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.rows).toEqual([]);
|
||||
expect(vm.data.nextCursor).toBeNull();
|
||||
expect(vm.data.discoverNextCursor).toBeNull();
|
||||
expect(vm.data.emptyHeadlineKey).toBe("chat.channelList.empty.headline");
|
||||
expect(vm.data.noResultsBodyKey).toBe("chat.channelList.noResults.body");
|
||||
});
|
||||
|
||||
it("validates the strict serializable channel-list contract", () => {
|
||||
const vm = buildChatChannelListVM(
|
||||
input([
|
||||
row("project-1", {
|
||||
kind: "project",
|
||||
lastMessage: {
|
||||
authorLabel: "Akeshan",
|
||||
snippet: "Montage ist eingeplant",
|
||||
systemEvent: null,
|
||||
createdAtIso: "2026-07-15T10:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
])
|
||||
);
|
||||
const serialized = JSON.parse(JSON.stringify(vm)) as unknown;
|
||||
|
||||
expect(ChatChannelListVMSchema.parse(serialized)).toEqual(vm);
|
||||
|
||||
const invalid = JSON.parse(JSON.stringify(vm)) as {
|
||||
data: { rows: Array<Record<string, unknown>> };
|
||||
};
|
||||
invalid.data.rows[0] = { ...invalid.data.rows[0], unexpected: true };
|
||||
expect(ChatChannelListVMSchema.safeParse(invalid).success).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts a system-event preview without a synthetic author", () => {
|
||||
const vm = buildChatChannelListVM(
|
||||
input([
|
||||
row("project-1", {
|
||||
lastMessage: {
|
||||
authorLabel: null,
|
||||
snippet: "",
|
||||
systemEvent: {
|
||||
kind: "channel_archived",
|
||||
labelKey: "chat.systemEvent.channelArchived",
|
||||
values: {},
|
||||
},
|
||||
createdAtIso: "2026-07-15T10:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
])
|
||||
);
|
||||
|
||||
expect(ChatChannelListVMSchema.parse(vm)).toEqual(vm);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
expect(vm.data.rows[0]?.lastMessage).toMatchObject({ authorLabel: null, systemEvent: { kind: "channel_archived" } });
|
||||
});
|
||||
});
|
||||
+322
@@ -0,0 +1,322 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
import { chatSystemEventVMSchema, type ChatSystemEventVM } from "./system-event.vm.js";
|
||||
|
||||
/** Pure channel-index contract. Resolved labels and hrefs are supplied by the
|
||||
* loader; this package never imports routing, Prisma, React, or tenant state. */
|
||||
export type ChatChannelKind = "project" | "group" | "dm";
|
||||
export type ChatChannelNotificationPreference = "all_messages" | "mentions_only" | "muted";
|
||||
export type ChatChannelListView = "all" | "unread" | "mentions" | "pinned" | "projects" | "groups" | "direct";
|
||||
|
||||
export interface ChatAvatarVM {
|
||||
readonly imageUrl: string | null;
|
||||
readonly fallbackLabel: string;
|
||||
}
|
||||
|
||||
export interface ChatChannelProjectVM {
|
||||
readonly id: string;
|
||||
readonly number: string;
|
||||
readonly label: string;
|
||||
readonly stageLabel: string;
|
||||
readonly href: string;
|
||||
}
|
||||
|
||||
export interface ChatChannelLastMessageVM {
|
||||
readonly authorLabel: string | null;
|
||||
readonly snippet: string;
|
||||
readonly systemEvent: ChatSystemEventVM | null;
|
||||
readonly createdAtIso: string;
|
||||
}
|
||||
|
||||
export interface ChatChannelListRowInput {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
/** Resolved DM counterpart, group name, or project title. */
|
||||
readonly title: string;
|
||||
readonly subtitle: string | null;
|
||||
readonly detailHref: string;
|
||||
readonly avatar: ChatAvatarVM;
|
||||
readonly project: ChatChannelProjectVM | null;
|
||||
readonly lastMessage: ChatChannelLastMessageVM | null;
|
||||
/** Resolved names only; the UI decides how many to show. */
|
||||
readonly typingLabels: readonly string[];
|
||||
readonly unreadCount: number;
|
||||
readonly hasMention: boolean;
|
||||
readonly isPinned: boolean;
|
||||
readonly isPrivate: boolean;
|
||||
readonly notificationPreference: ChatChannelNotificationPreference;
|
||||
readonly archivedAtIso: string | null;
|
||||
readonly memberCount: number;
|
||||
readonly canManage: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelListRowVM extends ChatChannelListRowInput {
|
||||
readonly hasUnread: boolean;
|
||||
readonly isMuted: boolean;
|
||||
readonly isArchived: boolean;
|
||||
readonly kindLabelKey: string;
|
||||
}
|
||||
|
||||
export interface ChatDiscoverChannelRowVM {
|
||||
readonly id: string;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly avatar: ChatAvatarVM;
|
||||
readonly memberCount: number;
|
||||
readonly isJoined: boolean;
|
||||
readonly canJoin: boolean;
|
||||
readonly joinHref: string | null;
|
||||
readonly detailHref: string | null;
|
||||
}
|
||||
|
||||
export interface ChatChannelListFilterState {
|
||||
readonly query: string;
|
||||
readonly view: ChatChannelListView;
|
||||
readonly showArchived: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelListPermissionsVM {
|
||||
readonly canWrite: boolean;
|
||||
readonly canCreateGroup: boolean;
|
||||
readonly canCreateDm: boolean;
|
||||
readonly canDiscover: boolean;
|
||||
readonly canViewMentions: boolean;
|
||||
readonly canSearch: boolean;
|
||||
readonly canViewArchived: boolean;
|
||||
readonly canAdmin: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelListHrefsVM {
|
||||
readonly newChannel: string;
|
||||
readonly newDm: string;
|
||||
readonly search: string;
|
||||
readonly mentions: string;
|
||||
readonly archived: string;
|
||||
}
|
||||
|
||||
export interface ChatChannelListTotalsVM {
|
||||
readonly unread: number;
|
||||
readonly mentions: number;
|
||||
}
|
||||
|
||||
export interface ChatChannelListData {
|
||||
readonly rows: readonly ChatChannelListRowVM[];
|
||||
readonly discoverRows: readonly ChatDiscoverChannelRowVM[];
|
||||
readonly filter: ChatChannelListFilterState;
|
||||
readonly permissions: ChatChannelListPermissionsVM;
|
||||
readonly hrefs: ChatChannelListHrefsVM;
|
||||
readonly totals: ChatChannelListTotalsVM;
|
||||
readonly nextCursor: string | null;
|
||||
readonly discoverNextCursor: string | null;
|
||||
readonly emptyHeadlineKey: string;
|
||||
readonly emptyBodyKey: string;
|
||||
readonly noResultsHeadlineKey: string;
|
||||
readonly noResultsBodyKey: string;
|
||||
readonly discoverHeadlineKey: string;
|
||||
}
|
||||
|
||||
export type ChatChannelListVM = VMState<ChatChannelListData>;
|
||||
|
||||
export interface BuildChatChannelListVMInput {
|
||||
readonly rows: readonly ChatChannelListRowInput[];
|
||||
readonly discoverRows: readonly ChatDiscoverChannelRowVM[];
|
||||
readonly filter: ChatChannelListFilterState;
|
||||
readonly permissions: ChatChannelListPermissionsVM;
|
||||
readonly hrefs: ChatChannelListHrefsVM;
|
||||
readonly totals: ChatChannelListTotalsVM;
|
||||
readonly nextCursor?: string | null;
|
||||
readonly discoverNextCursor?: string | null;
|
||||
}
|
||||
|
||||
export const chatChannelKindSchema = z.enum(["project", "group", "dm"]);
|
||||
export const chatChannelNotificationPreferenceSchema = z.enum(["all_messages", "mentions_only", "muted"]);
|
||||
export const chatChannelListViewSchema = z.enum(["all", "unread", "mentions", "pinned", "projects", "groups", "direct"]);
|
||||
|
||||
export const chatAvatarVMSchema = z
|
||||
.object({
|
||||
imageUrl: z.string().min(1).nullable(),
|
||||
fallbackLabel: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelProjectVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
number: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
stageLabel: z.string().min(1),
|
||||
href: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelLastMessageVMSchema = z
|
||||
.object({
|
||||
authorLabel: z.string().min(1).nullable(),
|
||||
snippet: z.string(),
|
||||
systemEvent: chatSystemEventVMSchema.nullable(),
|
||||
createdAtIso: z.string().datetime({ offset: true }),
|
||||
})
|
||||
.strict()
|
||||
.superRefine((message, context) => {
|
||||
if ((message.systemEvent === null) === (message.authorLabel === null)) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
});
|
||||
|
||||
export const chatChannelListRowVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
kind: chatChannelKindSchema,
|
||||
title: z.string().min(1),
|
||||
subtitle: z.string().nullable(),
|
||||
detailHref: z.string().min(1),
|
||||
avatar: chatAvatarVMSchema,
|
||||
project: chatChannelProjectVMSchema.nullable(),
|
||||
lastMessage: chatChannelLastMessageVMSchema.nullable(),
|
||||
typingLabels: z.array(z.string().min(1)),
|
||||
unreadCount: z.number().int().nonnegative(),
|
||||
hasMention: z.boolean(),
|
||||
isPinned: z.boolean(),
|
||||
isPrivate: z.boolean(),
|
||||
notificationPreference: chatChannelNotificationPreferenceSchema,
|
||||
archivedAtIso: z.string().datetime({ offset: true }).nullable(),
|
||||
memberCount: z.number().int().nonnegative(),
|
||||
canManage: z.boolean(),
|
||||
hasUnread: z.boolean(),
|
||||
isMuted: z.boolean(),
|
||||
isArchived: z.boolean(),
|
||||
kindLabelKey: z.enum(["chat.channel.kind.project", "chat.channel.kind.group", "chat.channel.kind.dm"]),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatDiscoverChannelRowVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
title: z.string().min(1),
|
||||
description: z.string().nullable(),
|
||||
avatar: chatAvatarVMSchema,
|
||||
memberCount: z.number().int().nonnegative(),
|
||||
isJoined: z.boolean(),
|
||||
canJoin: z.boolean(),
|
||||
joinHref: z.string().min(1).nullable(),
|
||||
detailHref: z.string().min(1).nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelListFilterStateSchema = z
|
||||
.object({
|
||||
query: z.string(),
|
||||
view: chatChannelListViewSchema,
|
||||
showArchived: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelListPermissionsVMSchema = z
|
||||
.object({
|
||||
canWrite: z.boolean(),
|
||||
canCreateGroup: z.boolean(),
|
||||
canCreateDm: z.boolean(),
|
||||
canDiscover: z.boolean(),
|
||||
canViewMentions: z.boolean(),
|
||||
canSearch: z.boolean(),
|
||||
canViewArchived: z.boolean(),
|
||||
canAdmin: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelListHrefsVMSchema = z
|
||||
.object({
|
||||
newChannel: z.string().min(1),
|
||||
newDm: z.string().min(1),
|
||||
search: z.string().min(1),
|
||||
mentions: z.string().min(1),
|
||||
archived: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const chatChannelListTotalsVMSchema = z
|
||||
.object({
|
||||
unread: z.number().int().nonnegative(),
|
||||
mentions: z.number().int().nonnegative(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelListDataSchema = z
|
||||
.object({
|
||||
rows: z.array(chatChannelListRowVMSchema),
|
||||
discoverRows: z.array(chatDiscoverChannelRowVMSchema),
|
||||
filter: chatChannelListFilterStateSchema,
|
||||
permissions: chatChannelListPermissionsVMSchema,
|
||||
hrefs: chatChannelListHrefsVMSchema,
|
||||
totals: chatChannelListTotalsVMSchema,
|
||||
nextCursor: z.string().min(1).nullable(),
|
||||
discoverNextCursor: z.string().min(1).nullable(),
|
||||
emptyHeadlineKey: z.literal("chat.channelList.empty.headline"),
|
||||
emptyBodyKey: z.literal("chat.channelList.empty.body"),
|
||||
noResultsHeadlineKey: z.literal("chat.channelList.noResults.headline"),
|
||||
noResultsBodyKey: z.literal("chat.channelList.noResults.body"),
|
||||
discoverHeadlineKey: z.literal("chat.channelList.discover.headline"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Strict serializable render contract produced by buildChatChannelListVM. */
|
||||
export const ChatChannelListVMSchema = z
|
||||
.object({
|
||||
status: z.literal("ready"),
|
||||
data: chatChannelListDataSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function chatChannelKindLabelKey(kind: ChatChannelKind): string {
|
||||
return `chat.channel.kind.${kind}`;
|
||||
}
|
||||
|
||||
/** Personal pins lead the list while both the pinned and unpinned partitions
|
||||
* keep the server-provided order. The input array is never mutated. */
|
||||
export function stablePinnedChannelsFirst(rows: readonly ChatChannelListRowInput[]): ChatChannelListRowInput[] {
|
||||
return rows
|
||||
.map((row, index) => ({ row, index }))
|
||||
.sort((left, right) => Number(right.row.isPinned) - Number(left.row.isPinned) || left.index - right.index)
|
||||
.map(({ row }) => row);
|
||||
}
|
||||
|
||||
export function buildChatChannelListVM(input: BuildChatChannelListVMInput): ChatChannelListVM {
|
||||
const rows = stablePinnedChannelsFirst(input.rows).map<ChatChannelListRowVM>((row) => {
|
||||
const unreadCount = normalizeCount(row.unreadCount);
|
||||
|
||||
return {
|
||||
...row,
|
||||
unreadCount,
|
||||
memberCount: normalizeCount(row.memberCount),
|
||||
hasUnread: unreadCount > 0,
|
||||
isMuted: row.notificationPreference === "muted",
|
||||
isArchived: row.archivedAtIso !== null,
|
||||
kindLabelKey: chatChannelKindLabelKey(row.kind),
|
||||
};
|
||||
});
|
||||
|
||||
return ready<ChatChannelListData>({
|
||||
rows,
|
||||
discoverRows: input.discoverRows.map((row) => ({ ...row, memberCount: normalizeCount(row.memberCount) })),
|
||||
filter: input.filter,
|
||||
permissions: input.permissions,
|
||||
hrefs: input.hrefs,
|
||||
totals: {
|
||||
unread: normalizeCount(input.totals.unread),
|
||||
mentions: normalizeCount(input.totals.mentions),
|
||||
},
|
||||
nextCursor: rows.length === 0 ? null : (input.nextCursor ?? null),
|
||||
discoverNextCursor: input.discoverRows.length === 0 ? null : (input.discoverNextCursor ?? null),
|
||||
emptyHeadlineKey: "chat.channelList.empty.headline",
|
||||
emptyBodyKey: "chat.channelList.empty.body",
|
||||
noResultsHeadlineKey: "chat.channelList.noResults.headline",
|
||||
noResultsBodyKey: "chat.channelList.noResults.body",
|
||||
discoverHeadlineKey: "chat.channelList.discover.headline",
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeCount(value: number): number {
|
||||
return Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;
|
||||
}
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
buildChatChannelSettingsVM,
|
||||
ChatChannelSettingsVMSchema,
|
||||
chatChannelSettingsDataSchema,
|
||||
type BuildChatChannelSettingsVMInput,
|
||||
type ChatChannelSettingsMemberInput,
|
||||
} from "./channel-settings.vm.js";
|
||||
import type { ChatTenantUserOptionInput } from "./channel-create.vm.js";
|
||||
|
||||
function user(userId: string): ChatTenantUserOptionInput {
|
||||
return {
|
||||
userId,
|
||||
displayName: `User ${userId}`,
|
||||
email: `${userId}@example.test`,
|
||||
avatar: { imageUrl: null, fallbackLabel: userId.slice(0, 2).toUpperCase() },
|
||||
};
|
||||
}
|
||||
|
||||
function member(userId: string, overrides: Partial<ChatChannelSettingsMemberInput> = {}): ChatChannelSettingsMemberInput {
|
||||
return { user: user(userId), role: "member", ...overrides };
|
||||
}
|
||||
|
||||
const PROJECT = { id: "project-1", number: "P-001", label: "Heizung Müller", stageLabel: "Montage", href: "/projects/project-1" };
|
||||
|
||||
function baseInput(kind: "group" | "dm" | "project", members: readonly ChatChannelSettingsMemberInput[]): BuildChatChannelSettingsVMInput {
|
||||
return {
|
||||
currentUserId: "viewer",
|
||||
channel: {
|
||||
id: "chat-1",
|
||||
kind,
|
||||
title: "Montage",
|
||||
description: null,
|
||||
isPrivate: kind !== "group",
|
||||
isArchived: false,
|
||||
project: kind === "project" ? PROJECT : null,
|
||||
},
|
||||
members,
|
||||
tenantUsers: [user("viewer"), user("admin-2"), user("member-1"), user("candidate")],
|
||||
permissions: {
|
||||
canManageMembers: true,
|
||||
canManageAdmins: true,
|
||||
canChangePrivacy: true,
|
||||
canLeave: true,
|
||||
canManageManualGuests: true,
|
||||
canArchive: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildChatChannelSettingsVM", () => {
|
||||
it("exposes group member/admin/privacy actions and protects the last admin", () => {
|
||||
const input = baseInput("group", [member("viewer", { role: "admin" }), member("member-1")]);
|
||||
const vm = buildChatChannelSettingsVM(input);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.channel.privacy).toBe("public");
|
||||
expect(vm.data.leave).toEqual({ canLeave: false, blockedReasonKey: "chat.channelSettings.validation.lastAdminLeave" });
|
||||
expect(vm.data.members.find(({ userId }) => userId === "member-1")?.actions).toMatchObject({
|
||||
canPromoteToAdmin: true,
|
||||
canRemoveFromGroup: true,
|
||||
});
|
||||
expect(vm.data.candidateUsers.map(({ userId }) => userId)).toEqual(["admin-2", "candidate"]);
|
||||
expect(vm.data.keys.membersLoadingKey).toBe("chat.channelSettings.members.loading");
|
||||
});
|
||||
|
||||
it("allows an admin to leave once another admin exists", () => {
|
||||
const vm = buildChatChannelSettingsVM(
|
||||
baseInput("group", [member("viewer", { role: "admin" }), member("admin-2", { role: "admin" })]),
|
||||
);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.leave).toEqual({ canLeave: true, blockedReasonKey: null });
|
||||
expect(vm.data.members.every(({ source }) => source === "group")).toBe(true);
|
||||
});
|
||||
|
||||
it("makes a two-person DM fully read-only", () => {
|
||||
const vm = buildChatChannelSettingsVM(baseInput("dm", [member("viewer"), member("member-1")]));
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.infoKey).toBe("chat.channelSettings.dm.readOnly");
|
||||
expect(vm.data.members).toHaveLength(2);
|
||||
expect(vm.data.members.every(({ source, actions }) => source === "dm" && Object.values(actions).every((allowed) => !allowed))).toBe(true);
|
||||
expect(vm.data.candidateUsers).toEqual([]);
|
||||
expect(Object.values(vm.data.permissions).every((allowed) => !allowed)).toBe(true);
|
||||
expect(vm.data.leave.canLeave).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps project members read-only while allowing separate manual guests", () => {
|
||||
const vm = buildChatChannelSettingsVM(
|
||||
baseInput("project", [
|
||||
member("viewer", { isProjectManaged: true }),
|
||||
member("member-1", { isProjectManaged: true }),
|
||||
member("admin-2", { isManualGuest: true, manualRole: "member" }),
|
||||
]),
|
||||
);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(vm.data.channel.project).toEqual(PROJECT);
|
||||
expect(vm.data.infoKey).toBe("chat.channelSettings.project.managedExternally");
|
||||
expect(vm.data.members.find(({ userId }) => userId === "member-1")).toMatchObject({
|
||||
source: "project",
|
||||
actions: { canRemoveManualGuest: false },
|
||||
});
|
||||
expect(vm.data.members.find(({ userId }) => userId === "admin-2")).toMatchObject({
|
||||
source: "manual_guest",
|
||||
actions: { canPromoteToAdmin: true, canRemoveManualGuest: true },
|
||||
});
|
||||
expect(vm.data.candidateUsers.map(({ userId }) => userId)).toEqual(["candidate"]);
|
||||
expect(vm.data.permissions).toMatchObject({
|
||||
canManageGroupMembers: false,
|
||||
canManageGroupAdmins: false,
|
||||
canChangeGroupPrivacy: false,
|
||||
canManageManualGuests: true,
|
||||
canArchive: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("validates kind invariants and strict serializability", () => {
|
||||
const vm = buildChatChannelSettingsVM(baseInput("dm", [member("viewer"), member("member-1")]));
|
||||
expect(ChatChannelSettingsVMSchema.parse(JSON.parse(JSON.stringify(vm)) as unknown)).toEqual(vm);
|
||||
expect(ChatChannelSettingsVMSchema.safeParse({ ...vm, unexpected: true }).success).toBe(false);
|
||||
if (vm.status !== "ready") throw new Error("expected ready");
|
||||
|
||||
expect(chatChannelSettingsDataSchema.safeParse({ ...vm.data, members: vm.data.members.slice(0, 1) }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
+397
@@ -0,0 +1,397 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { VMState } from "../index.js";
|
||||
|
||||
import {
|
||||
buildChatTenantUserOptions,
|
||||
chatTenantUserOptionVMSchema,
|
||||
type ChatTenantUserOptionInput,
|
||||
type ChatTenantUserOptionVM,
|
||||
} from "./channel-create.vm.js";
|
||||
import type { ChatChannelKind, ChatChannelProjectVM } from "./channel-list.vm.js";
|
||||
|
||||
export type ChatChannelSettingsMemberRole = "admin" | "member";
|
||||
export type ChatChannelSettingsMemberSource = "group" | "dm" | "project" | "manual_guest" | "project_and_manual";
|
||||
|
||||
export const CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS = {
|
||||
memberRequired: "chat.channelSettings.validation.memberRequired",
|
||||
userUnavailable: "chat.channelSettings.validation.userUnavailable",
|
||||
lastAdminLeave: "chat.channelSettings.validation.lastAdminLeave",
|
||||
lastAdminDemote: "chat.channelSettings.validation.lastAdminDemote",
|
||||
projectMemberManagedExternally: "chat.channelSettings.validation.projectMemberManagedExternally",
|
||||
dmReadOnly: "chat.channelSettings.validation.dmReadOnly",
|
||||
} as const;
|
||||
|
||||
export interface ChatChannelSettingsMemberInput {
|
||||
readonly user: ChatTenantUserOptionInput;
|
||||
readonly role: ChatChannelSettingsMemberRole;
|
||||
/** Project-sync provenance. Ignored for group and DM rows. */
|
||||
readonly isProjectManaged?: boolean;
|
||||
/** Explicit extra access independent from project membership. */
|
||||
readonly isManualGuest?: boolean;
|
||||
/** Role carried by the manual source; the effective role may stay admin through project provenance. */
|
||||
readonly manualRole?: ChatChannelSettingsMemberRole | null;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsMemberActionsVM {
|
||||
readonly canPromoteToAdmin: boolean;
|
||||
readonly canDemoteFromAdmin: boolean;
|
||||
readonly canRemoveFromGroup: boolean;
|
||||
readonly canRemoveManualGuest: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsMemberVM extends ChatTenantUserOptionVM {
|
||||
readonly role: ChatChannelSettingsMemberRole;
|
||||
readonly roleLabelKey: "chat.channelSettings.role.admin" | "chat.channelSettings.role.member";
|
||||
readonly source: ChatChannelSettingsMemberSource;
|
||||
readonly sourceLabelKey:
|
||||
| "chat.channelSettings.source.group"
|
||||
| "chat.channelSettings.source.dm"
|
||||
| "chat.channelSettings.source.project"
|
||||
| "chat.channelSettings.source.manualGuest"
|
||||
| "chat.channelSettings.source.projectAndManual";
|
||||
readonly isProjectManaged: boolean;
|
||||
readonly isManualGuest: boolean;
|
||||
readonly actions: ChatChannelSettingsMemberActionsVM;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsChannelVM {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly isPrivate: boolean;
|
||||
readonly isArchived: boolean;
|
||||
readonly privacy: "public" | "private" | null;
|
||||
readonly project: ChatChannelProjectVM | null;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsPermissionsVM {
|
||||
readonly canManageGroupMembers: boolean;
|
||||
readonly canManageGroupAdmins: boolean;
|
||||
readonly canChangeGroupPrivacy: boolean;
|
||||
readonly canManageManualGuests: boolean;
|
||||
readonly canArchive: boolean;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsLeaveVM {
|
||||
readonly canLeave: boolean;
|
||||
readonly blockedReasonKey: typeof CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.lastAdminLeave | null;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsKeysVM {
|
||||
readonly titleKey: "chat.channelSettings.title";
|
||||
readonly membersEmptyKey: "chat.channelSettings.members.empty";
|
||||
readonly membersLoadingKey: "chat.channelSettings.members.loading";
|
||||
readonly candidatesEmptyKey: "chat.channelSettings.candidates.empty";
|
||||
readonly candidatesLoadingKey: "chat.channelSettings.candidates.loading";
|
||||
readonly dmReadOnlyKey: "chat.channelSettings.dm.readOnly";
|
||||
readonly projectManagedExternallyKey: "chat.channelSettings.project.managedExternally";
|
||||
readonly manualGuestsHeadlineKey: "chat.channelSettings.project.manualGuests";
|
||||
readonly validation: typeof CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS;
|
||||
}
|
||||
|
||||
export interface ChatChannelSettingsData {
|
||||
readonly channel: ChatChannelSettingsChannelVM;
|
||||
readonly members: readonly ChatChannelSettingsMemberVM[];
|
||||
readonly candidateUsers: readonly ChatTenantUserOptionVM[];
|
||||
readonly permissions: ChatChannelSettingsPermissionsVM;
|
||||
readonly leave: ChatChannelSettingsLeaveVM;
|
||||
readonly infoKey: "chat.channelSettings.dm.readOnly" | "chat.channelSettings.project.managedExternally" | null;
|
||||
readonly keys: ChatChannelSettingsKeysVM;
|
||||
}
|
||||
|
||||
export type ChatChannelSettingsVM = VMState<ChatChannelSettingsData>;
|
||||
|
||||
export interface BuildChatChannelSettingsVMInput {
|
||||
readonly currentUserId: string;
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly kind: ChatChannelKind;
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly isPrivate: boolean;
|
||||
readonly isArchived: boolean;
|
||||
readonly project: ChatChannelProjectVM | null;
|
||||
};
|
||||
readonly members: readonly ChatChannelSettingsMemberInput[];
|
||||
readonly tenantUsers: readonly ChatTenantUserOptionInput[];
|
||||
readonly permissions: {
|
||||
readonly canManageMembers: boolean;
|
||||
readonly canManageAdmins: boolean;
|
||||
readonly canChangePrivacy: boolean;
|
||||
readonly canLeave: boolean;
|
||||
readonly canManageManualGuests: boolean;
|
||||
readonly canArchive: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
const memberRoleSchema = z.enum(["admin", "member"]);
|
||||
const memberSourceSchema = z.enum(["group", "dm", "project", "manual_guest", "project_and_manual"]);
|
||||
const channelKindSchema = z.enum(["project", "group", "dm"]);
|
||||
const channelProjectSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
number: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
stageLabel: z.string().min(1),
|
||||
href: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const memberActionsSchema = z
|
||||
.object({
|
||||
canPromoteToAdmin: z.boolean(),
|
||||
canDemoteFromAdmin: z.boolean(),
|
||||
canRemoveFromGroup: z.boolean(),
|
||||
canRemoveManualGuest: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelSettingsMemberVMSchema = chatTenantUserOptionVMSchema
|
||||
.extend({
|
||||
role: memberRoleSchema,
|
||||
roleLabelKey: z.enum(["chat.channelSettings.role.admin", "chat.channelSettings.role.member"]),
|
||||
source: memberSourceSchema,
|
||||
sourceLabelKey: z.enum([
|
||||
"chat.channelSettings.source.group",
|
||||
"chat.channelSettings.source.dm",
|
||||
"chat.channelSettings.source.project",
|
||||
"chat.channelSettings.source.manualGuest",
|
||||
"chat.channelSettings.source.projectAndManual",
|
||||
]),
|
||||
isProjectManaged: z.boolean(),
|
||||
isManualGuest: z.boolean(),
|
||||
actions: memberActionsSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
const channelSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
kind: channelKindSchema,
|
||||
title: z.string().min(1),
|
||||
description: z.string().nullable(),
|
||||
isPrivate: z.boolean(),
|
||||
isArchived: z.boolean(),
|
||||
privacy: z.enum(["public", "private"]).nullable(),
|
||||
project: channelProjectSchema.nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const permissionsSchema = z
|
||||
.object({
|
||||
canManageGroupMembers: z.boolean(),
|
||||
canManageGroupAdmins: z.boolean(),
|
||||
canChangeGroupPrivacy: z.boolean(),
|
||||
canManageManualGuests: z.boolean(),
|
||||
canArchive: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const leaveSchema = z
|
||||
.object({
|
||||
canLeave: z.boolean(),
|
||||
blockedReasonKey: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.lastAdminLeave).nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const keysSchema = z
|
||||
.object({
|
||||
titleKey: z.literal("chat.channelSettings.title"),
|
||||
membersEmptyKey: z.literal("chat.channelSettings.members.empty"),
|
||||
membersLoadingKey: z.literal("chat.channelSettings.members.loading"),
|
||||
candidatesEmptyKey: z.literal("chat.channelSettings.candidates.empty"),
|
||||
candidatesLoadingKey: z.literal("chat.channelSettings.candidates.loading"),
|
||||
dmReadOnlyKey: z.literal("chat.channelSettings.dm.readOnly"),
|
||||
projectManagedExternallyKey: z.literal("chat.channelSettings.project.managedExternally"),
|
||||
manualGuestsHeadlineKey: z.literal("chat.channelSettings.project.manualGuests"),
|
||||
validation: z
|
||||
.object({
|
||||
memberRequired: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.memberRequired),
|
||||
userUnavailable: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.userUnavailable),
|
||||
lastAdminLeave: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.lastAdminLeave),
|
||||
lastAdminDemote: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.lastAdminDemote),
|
||||
projectMemberManagedExternally: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.projectMemberManagedExternally),
|
||||
dmReadOnly: z.literal(CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.dmReadOnly),
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatChannelSettingsDataSchema = z
|
||||
.object({
|
||||
channel: channelSchema,
|
||||
members: z.array(chatChannelSettingsMemberVMSchema),
|
||||
candidateUsers: z.array(chatTenantUserOptionVMSchema),
|
||||
permissions: permissionsSchema,
|
||||
leave: leaveSchema,
|
||||
infoKey: z.enum(["chat.channelSettings.dm.readOnly", "chat.channelSettings.project.managedExternally"]).nullable(),
|
||||
keys: keysSchema,
|
||||
})
|
||||
.strict()
|
||||
.superRefine((data, context) => {
|
||||
const memberIds = data.members.map((member) => member.userId);
|
||||
const candidateIds = data.candidateUsers.map((user) => user.userId);
|
||||
const invalidIdentitySet =
|
||||
new Set(memberIds).size !== memberIds.length ||
|
||||
new Set(candidateIds).size !== candidateIds.length ||
|
||||
candidateIds.some((userId) => memberIds.includes(userId));
|
||||
if (invalidIdentitySet) context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
|
||||
if (data.channel.kind === "group") {
|
||||
if (data.channel.project !== null || data.channel.privacy === null || data.infoKey !== null) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
if ((data.channel.privacy === "private") !== data.channel.isPrivate || data.members.some((member) => member.source !== "group")) {
|
||||
context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
}
|
||||
|
||||
if (data.channel.kind === "dm") {
|
||||
const hasWritableDmState =
|
||||
data.channel.project !== null ||
|
||||
data.channel.privacy !== null ||
|
||||
!data.channel.isPrivate ||
|
||||
data.members.length !== 2 ||
|
||||
data.members.some((member) => member.source !== "dm" || Object.values(member.actions).some(Boolean)) ||
|
||||
data.candidateUsers.length > 0 ||
|
||||
Object.values(data.permissions).some(Boolean) ||
|
||||
data.leave.canLeave ||
|
||||
data.infoKey !== "chat.channelSettings.dm.readOnly";
|
||||
if (hasWritableDmState) context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
|
||||
if (data.channel.kind === "project") {
|
||||
const invalidProjectState =
|
||||
data.channel.project === null ||
|
||||
data.channel.privacy !== null ||
|
||||
!data.channel.isPrivate ||
|
||||
data.members.some((member) => !["project", "manual_guest", "project_and_manual"].includes(member.source)) ||
|
||||
data.permissions.canManageGroupMembers ||
|
||||
data.permissions.canManageGroupAdmins ||
|
||||
data.permissions.canChangeGroupPrivacy ||
|
||||
data.leave.canLeave ||
|
||||
data.infoKey !== "chat.channelSettings.project.managedExternally";
|
||||
if (invalidProjectState) context.addIssue({ code: z.ZodIssueCode.custom, message: "chat.errors.integrityFailure" });
|
||||
}
|
||||
});
|
||||
|
||||
export const ChatChannelSettingsVMSchema = z
|
||||
.object({
|
||||
status: z.literal("ready"),
|
||||
data: chatChannelSettingsDataSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function buildChatChannelSettingsVM(input: BuildChatChannelSettingsVMInput): ChatChannelSettingsVM {
|
||||
assertUniqueMemberIds(input.members);
|
||||
const kind = input.channel.kind;
|
||||
const adminCount = kind === "group" ? input.members.filter((member) => member.role === "admin").length : 0;
|
||||
const canManageGroupMembers = kind === "group" && !input.channel.isArchived && input.permissions.canManageMembers;
|
||||
const canManageGroupAdmins = kind === "group" && !input.channel.isArchived && input.permissions.canManageAdmins;
|
||||
const canChangeGroupPrivacy = kind === "group" && !input.channel.isArchived && input.permissions.canChangePrivacy;
|
||||
const canManageManualGuests = kind === "project" && !input.channel.isArchived && input.permissions.canManageManualGuests;
|
||||
const canArchive = (kind === "group" || kind === "project") && input.permissions.canArchive && !input.channel.isArchived;
|
||||
|
||||
const members = input.members.map<ChatChannelSettingsMemberVM>((member) => {
|
||||
const user = buildChatTenantUserOptions([member.user], input.currentUserId)[0];
|
||||
if (!user) throw new Error("chat.errors.integrityFailure");
|
||||
const isOnlyAdmin = kind === "group" && member.role === "admin" && adminCount === 1;
|
||||
const isProjectManaged = kind === "project" && Boolean(member.isProjectManaged);
|
||||
const isManualGuest = kind === "project" && Boolean(member.isManualGuest);
|
||||
const manualRole = isManualGuest ? (member.manualRole ?? member.role) : null;
|
||||
const source = memberSource(kind, isProjectManaged, isManualGuest);
|
||||
|
||||
return {
|
||||
...user,
|
||||
role: member.role,
|
||||
roleLabelKey: `chat.channelSettings.role.${member.role}`,
|
||||
source,
|
||||
sourceLabelKey: memberSourceLabelKey(source),
|
||||
isProjectManaged,
|
||||
isManualGuest,
|
||||
actions: {
|
||||
canPromoteToAdmin:
|
||||
(canManageGroupAdmins && member.role === "member") ||
|
||||
(canManageManualGuests && isManualGuest && manualRole === "member"),
|
||||
canDemoteFromAdmin:
|
||||
(canManageGroupAdmins && member.role === "admin" && !isOnlyAdmin) ||
|
||||
(canManageManualGuests && isManualGuest && manualRole === "admin"),
|
||||
canRemoveFromGroup: canManageGroupMembers && !user.isCurrentUser && !isOnlyAdmin,
|
||||
canRemoveManualGuest: canManageManualGuests && isManualGuest && !user.isCurrentUser,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const currentMember = members.find((member) => member.isCurrentUser);
|
||||
const viewerIsOnlyAdmin = kind === "group" && currentMember?.role === "admin" && adminCount === 1;
|
||||
const canLeave =
|
||||
kind === "group" && !input.channel.isArchived && input.permissions.canLeave && currentMember !== undefined && !viewerIsOnlyAdmin;
|
||||
const memberIds = new Set(members.map((member) => member.userId));
|
||||
const canAddUsers = canManageGroupMembers || canManageManualGuests;
|
||||
const candidateUsers = canAddUsers
|
||||
? buildChatTenantUserOptions(input.tenantUsers, input.currentUserId).filter(
|
||||
(user) => !user.isCurrentUser && !memberIds.has(user.userId),
|
||||
)
|
||||
: [];
|
||||
|
||||
return {
|
||||
status: "ready",
|
||||
data: {
|
||||
channel: {
|
||||
...input.channel,
|
||||
isPrivate: kind === "group" ? input.channel.isPrivate : true,
|
||||
privacy: kind === "group" ? (input.channel.isPrivate ? "private" : "public") : null,
|
||||
project: kind === "project" ? input.channel.project : null,
|
||||
},
|
||||
members,
|
||||
candidateUsers,
|
||||
permissions: { canManageGroupMembers, canManageGroupAdmins, canChangeGroupPrivacy, canManageManualGuests, canArchive },
|
||||
leave: {
|
||||
canLeave,
|
||||
blockedReasonKey: viewerIsOnlyAdmin && input.permissions.canLeave ? CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS.lastAdminLeave : null,
|
||||
},
|
||||
infoKey:
|
||||
kind === "dm"
|
||||
? "chat.channelSettings.dm.readOnly"
|
||||
: kind === "project"
|
||||
? "chat.channelSettings.project.managedExternally"
|
||||
: null,
|
||||
keys: {
|
||||
titleKey: "chat.channelSettings.title",
|
||||
membersEmptyKey: "chat.channelSettings.members.empty",
|
||||
membersLoadingKey: "chat.channelSettings.members.loading",
|
||||
candidatesEmptyKey: "chat.channelSettings.candidates.empty",
|
||||
candidatesLoadingKey: "chat.channelSettings.candidates.loading",
|
||||
dmReadOnlyKey: "chat.channelSettings.dm.readOnly",
|
||||
projectManagedExternallyKey: "chat.channelSettings.project.managedExternally",
|
||||
manualGuestsHeadlineKey: "chat.channelSettings.project.manualGuests",
|
||||
validation: CHAT_CHANNEL_SETTINGS_VALIDATION_KEYS,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function memberSource(
|
||||
kind: ChatChannelKind,
|
||||
isProjectManaged: boolean,
|
||||
isManualGuest: boolean,
|
||||
): ChatChannelSettingsMemberSource {
|
||||
if (kind === "group") return "group";
|
||||
if (kind === "dm") return "dm";
|
||||
if (isProjectManaged && isManualGuest) return "project_and_manual";
|
||||
if (isProjectManaged) return "project";
|
||||
if (isManualGuest) return "manual_guest";
|
||||
throw new Error("chat.errors.integrityFailure");
|
||||
}
|
||||
|
||||
function memberSourceLabelKey(source: ChatChannelSettingsMemberSource): ChatChannelSettingsMemberVM["sourceLabelKey"] {
|
||||
const suffix = source === "manual_guest" ? "manualGuest" : source === "project_and_manual" ? "projectAndManual" : source;
|
||||
return `chat.channelSettings.source.${suffix}`;
|
||||
}
|
||||
|
||||
function assertUniqueMemberIds(members: readonly ChatChannelSettingsMemberInput[]): void {
|
||||
const ids = members.map((member) => member.user.userId);
|
||||
if (new Set(ids).size !== ids.length) throw new Error("chat.errors.integrityFailure");
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatMentionAutocompleteVM } from "./mention-autocomplete.vm.js";
|
||||
|
||||
describe("buildChatMentionAutocompleteVM", () => {
|
||||
it("groups in the stable user/project/contact/company order and builds safe entity links", () => {
|
||||
expect(
|
||||
buildChatMentionAutocompleteVM({
|
||||
tenantSlug: "demo tenant",
|
||||
suggestions: [
|
||||
{ kind: "company", id: "company/1", label: "Muster GmbH", detail: null },
|
||||
{ kind: "user", id: "user_1", label: "Raffael", detail: "raffael@example.test" },
|
||||
{ kind: "project", id: "project_1", label: "P-100 · Heizung", detail: "P-100" },
|
||||
{ kind: "contact", id: "contact_1", label: "Anna Becker", detail: null },
|
||||
],
|
||||
}).groups
|
||||
).toEqual([
|
||||
{
|
||||
kind: "user",
|
||||
labelKey: "chat.mention.groups.users",
|
||||
items: [{ kind: "user", id: "user_1", label: "Raffael", detail: "raffael@example.test", href: null }],
|
||||
},
|
||||
{
|
||||
kind: "project",
|
||||
labelKey: "chat.mention.groups.projects",
|
||||
items: [{ kind: "project", id: "project_1", label: "P-100 · Heizung", detail: "P-100", href: "/demo%20tenant/projects/project_1" }],
|
||||
},
|
||||
{
|
||||
kind: "contact",
|
||||
labelKey: "chat.mention.groups.contacts",
|
||||
items: [{ kind: "contact", id: "contact_1", label: "Anna Becker", detail: null, href: "/demo%20tenant/contacts/contact_1" }],
|
||||
},
|
||||
{
|
||||
kind: "company",
|
||||
labelKey: "chat.mention.groups.companies",
|
||||
items: [
|
||||
{
|
||||
kind: "company",
|
||||
id: "company/1",
|
||||
label: "Muster GmbH",
|
||||
detail: null,
|
||||
href: "/demo%20tenant/contacts/companies/company%2F1",
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("deduplicates and bounds untrusted repository rows to ten", () => {
|
||||
const vm = buildChatMentionAutocompleteVM({
|
||||
tenantSlug: "acme",
|
||||
suggestions: Array.from({ length: 12 }, (_, index) => ({
|
||||
kind: "user" as const,
|
||||
id: `user_${Math.min(index, 10)}`,
|
||||
label: `User ${index}`,
|
||||
detail: null,
|
||||
})),
|
||||
});
|
||||
expect(vm.total).toBe(10);
|
||||
expect(vm.groups[0]?.items).toHaveLength(10);
|
||||
});
|
||||
});
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export type ChatMentionSuggestionKind = "user" | "project" | "contact" | "company";
|
||||
|
||||
export interface ChatMentionSuggestionInput {
|
||||
readonly kind: ChatMentionSuggestionKind;
|
||||
readonly id: string;
|
||||
readonly label: string;
|
||||
readonly detail: string | null;
|
||||
}
|
||||
|
||||
export interface ChatMentionSuggestionVM extends ChatMentionSuggestionInput {
|
||||
readonly href: string | null;
|
||||
}
|
||||
|
||||
export interface ChatMentionSuggestionGroupVM {
|
||||
readonly kind: ChatMentionSuggestionKind;
|
||||
readonly labelKey: string;
|
||||
readonly items: readonly ChatMentionSuggestionVM[];
|
||||
}
|
||||
|
||||
export interface ChatMentionAutocompleteVM {
|
||||
readonly groups: readonly ChatMentionSuggestionGroupVM[];
|
||||
readonly total: number;
|
||||
}
|
||||
|
||||
const KIND_ORDER = ["user", "project", "contact", "company"] as const;
|
||||
const GROUP_LABEL_KEYS = {
|
||||
user: "chat.mention.groups.users",
|
||||
project: "chat.mention.groups.projects",
|
||||
contact: "chat.mention.groups.contacts",
|
||||
company: "chat.mention.groups.companies",
|
||||
} as const;
|
||||
|
||||
const suggestionSchema = z
|
||||
.object({
|
||||
kind: z.enum(KIND_ORDER),
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
detail: z.string().min(1).nullable(),
|
||||
href: z.string().min(1).nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const autocompleteSchema = z
|
||||
.object({
|
||||
groups: z.array(
|
||||
z
|
||||
.object({
|
||||
kind: z.enum(KIND_ORDER),
|
||||
labelKey: z.string().min(1),
|
||||
items: z.array(suggestionSchema),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
total: z.number().int().nonnegative().max(10),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Pure route-record to combobox contract mapper. */
|
||||
export function buildChatMentionAutocompleteVM(input: {
|
||||
readonly tenantSlug: string;
|
||||
readonly suggestions: readonly ChatMentionSuggestionInput[];
|
||||
}): ChatMentionAutocompleteVM {
|
||||
const seen = new Set<string>();
|
||||
const bounded = input.suggestions
|
||||
.filter((suggestion) => {
|
||||
const key = `${suggestion.kind}\u0000${suggestion.id}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.slice(0, 10);
|
||||
const groups = KIND_ORDER.flatMap((kind) => {
|
||||
const items = bounded
|
||||
.filter((suggestion) => suggestion.kind === kind)
|
||||
.map((suggestion) => ({ ...suggestion, href: mentionHref(input.tenantSlug, suggestion) }));
|
||||
return items.length > 0 ? [{ kind, labelKey: GROUP_LABEL_KEYS[kind], items }] : [];
|
||||
});
|
||||
return autocompleteSchema.parse({ groups, total: bounded.length });
|
||||
}
|
||||
|
||||
function mentionHref(tenantSlug: string, mention: Pick<ChatMentionSuggestionInput, "kind" | "id">): string | null {
|
||||
const tenant = encodeURIComponent(tenantSlug);
|
||||
const id = encodeURIComponent(mention.id);
|
||||
if (mention.kind === "project") return `/${tenant}/projects/${id}`;
|
||||
if (mention.kind === "contact") return `/${tenant}/contacts/${id}`;
|
||||
if (mention.kind === "company") return `/${tenant}/contacts/companies/${id}`;
|
||||
return null;
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatMessageDiscoveryVM, ChatMessageDiscoveryVMSchema } from "./message-discovery.vm.js";
|
||||
|
||||
const hrefs = {
|
||||
chat: "/demo/chat",
|
||||
search: "/demo/chat/search",
|
||||
mentions: "/demo/chat/mentions",
|
||||
} as const;
|
||||
|
||||
describe("chat message discovery VM", () => {
|
||||
it("builds a serializable search result and trims a long snippet", () => {
|
||||
const body = ` Heat pump follow-up ${"x".repeat(300)} `;
|
||||
const vm = buildChatMessageDiscoveryVM({
|
||||
mode: "search",
|
||||
query: " heat pump ",
|
||||
hrefs,
|
||||
nextCursor: "cursor_1",
|
||||
rows: [
|
||||
{
|
||||
id: "message_1",
|
||||
chatId: "chat_1",
|
||||
channelKind: "project",
|
||||
channelTitle: "HG-42 · Heat pump",
|
||||
authorLabel: "Ada Lovelace",
|
||||
authorAvatar: { imageUrl: null, fallbackLabel: "AL" },
|
||||
body,
|
||||
createdAtIso: "2026-07-16T11:00:00.000Z",
|
||||
detailHref: "/demo/chat/chat_1?message=message_1",
|
||||
isThreadReply: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status).toBe("ready");
|
||||
if (vm.status !== "ready") throw new Error("expected ready VM");
|
||||
expect(vm.data.query).toBe("heat pump");
|
||||
expect(vm.data.rows[0]).toMatchObject({
|
||||
channelKindLabelKey: "chat.channel.kind.project",
|
||||
snippet: expect.stringMatching(/^Heat pump follow-up/),
|
||||
});
|
||||
expect(vm.data.rows[0]?.snippet).toHaveLength(278);
|
||||
expect(vm.data.keys).toEqual({
|
||||
titleKey: "chat.messageDiscovery.search.title",
|
||||
subtitleKey: "chat.messageDiscovery.search.subtitle",
|
||||
emptyTitleKey: "chat.messageDiscovery.search.emptyTitle",
|
||||
emptyBodyKey: "chat.messageDiscovery.search.emptyBody",
|
||||
noResultsTitleKey: "chat.messageDiscovery.search.noResultsTitle",
|
||||
noResultsBodyKey: "chat.messageDiscovery.search.noResultsBody",
|
||||
});
|
||||
expect(ChatMessageDiscoveryVMSchema.parse(vm)).toEqual(vm);
|
||||
});
|
||||
|
||||
it("ignores query input for the mentions aggregate and exposes mention keys", () => {
|
||||
const vm = buildChatMessageDiscoveryVM({ mode: "mentions", query: "ignored", rows: [], hrefs });
|
||||
|
||||
expect(vm).toEqual({
|
||||
status: "ready",
|
||||
data: {
|
||||
mode: "mentions",
|
||||
query: "",
|
||||
rows: [],
|
||||
nextCursor: null,
|
||||
hrefs,
|
||||
keys: {
|
||||
titleKey: "chat.messageDiscovery.mentions.title",
|
||||
subtitleKey: "chat.messageDiscovery.mentions.subtitle",
|
||||
emptyTitleKey: "chat.messageDiscovery.mentions.emptyTitle",
|
||||
emptyBodyKey: "chat.messageDiscovery.mentions.emptyBody",
|
||||
noResultsTitleKey: "chat.messageDiscovery.mentions.emptyTitle",
|
||||
noResultsBodyKey: "chat.messageDiscovery.mentions.emptyBody",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ready, type VMState } from "../index.js";
|
||||
|
||||
import { chatAvatarVMSchema, chatChannelKindSchema, type ChatAvatarVM, type ChatChannelKind } from "./channel-list.vm.js";
|
||||
|
||||
export type ChatMessageDiscoveryMode = "search" | "mentions";
|
||||
|
||||
export interface ChatMessageDiscoveryRowInput {
|
||||
readonly id: string;
|
||||
readonly chatId: string;
|
||||
readonly channelKind: ChatChannelKind;
|
||||
readonly channelTitle: string;
|
||||
readonly authorLabel: string;
|
||||
readonly authorAvatar: ChatAvatarVM;
|
||||
readonly body: string;
|
||||
readonly createdAtIso: string;
|
||||
readonly detailHref: string;
|
||||
readonly isThreadReply: boolean;
|
||||
}
|
||||
|
||||
export interface ChatMessageDiscoveryRowVM extends Omit<ChatMessageDiscoveryRowInput, "body"> {
|
||||
readonly snippet: string;
|
||||
readonly channelKindLabelKey: string;
|
||||
}
|
||||
|
||||
export interface ChatMessageDiscoveryData {
|
||||
readonly mode: ChatMessageDiscoveryMode;
|
||||
readonly query: string;
|
||||
readonly rows: readonly ChatMessageDiscoveryRowVM[];
|
||||
readonly nextCursor: string | null;
|
||||
readonly hrefs: Readonly<{
|
||||
chat: string;
|
||||
search: string;
|
||||
mentions: string;
|
||||
}>;
|
||||
readonly keys: Readonly<{
|
||||
titleKey: "chat.messageDiscovery.search.title" | "chat.messageDiscovery.mentions.title";
|
||||
subtitleKey: "chat.messageDiscovery.search.subtitle" | "chat.messageDiscovery.mentions.subtitle";
|
||||
emptyTitleKey: "chat.messageDiscovery.search.emptyTitle" | "chat.messageDiscovery.mentions.emptyTitle";
|
||||
emptyBodyKey: "chat.messageDiscovery.search.emptyBody" | "chat.messageDiscovery.mentions.emptyBody";
|
||||
noResultsTitleKey: "chat.messageDiscovery.search.noResultsTitle" | "chat.messageDiscovery.mentions.emptyTitle";
|
||||
noResultsBodyKey: "chat.messageDiscovery.search.noResultsBody" | "chat.messageDiscovery.mentions.emptyBody";
|
||||
}>;
|
||||
}
|
||||
|
||||
export type ChatMessageDiscoveryVM = VMState<ChatMessageDiscoveryData>;
|
||||
|
||||
export interface BuildChatMessageDiscoveryVMInput {
|
||||
readonly mode: ChatMessageDiscoveryMode;
|
||||
readonly query?: string;
|
||||
readonly rows: readonly ChatMessageDiscoveryRowInput[];
|
||||
readonly nextCursor?: string | null;
|
||||
readonly hrefs: ChatMessageDiscoveryData["hrefs"];
|
||||
}
|
||||
|
||||
const modeSchema = z.enum(["search", "mentions"]);
|
||||
|
||||
export const chatMessageDiscoveryRowVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
chatId: z.string().min(1),
|
||||
channelKind: chatChannelKindSchema,
|
||||
channelTitle: z.string().min(1),
|
||||
authorLabel: z.string().min(1),
|
||||
authorAvatar: chatAvatarVMSchema,
|
||||
snippet: z.string().min(1),
|
||||
createdAtIso: z.string().datetime({ offset: true }),
|
||||
detailHref: z.string().min(1),
|
||||
isThreadReply: z.boolean(),
|
||||
channelKindLabelKey: z.enum(["chat.channel.kind.project", "chat.channel.kind.group", "chat.channel.kind.dm"]),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatMessageDiscoveryDataSchema = z
|
||||
.object({
|
||||
mode: modeSchema,
|
||||
query: z.string().max(200),
|
||||
rows: z.array(chatMessageDiscoveryRowVMSchema),
|
||||
nextCursor: z.string().min(1).nullable(),
|
||||
hrefs: z
|
||||
.object({
|
||||
chat: z.string().min(1),
|
||||
search: z.string().min(1),
|
||||
mentions: z.string().min(1),
|
||||
})
|
||||
.strict(),
|
||||
keys: z
|
||||
.object({
|
||||
titleKey: z.enum(["chat.messageDiscovery.search.title", "chat.messageDiscovery.mentions.title"]),
|
||||
subtitleKey: z.enum(["chat.messageDiscovery.search.subtitle", "chat.messageDiscovery.mentions.subtitle"]),
|
||||
emptyTitleKey: z.enum(["chat.messageDiscovery.search.emptyTitle", "chat.messageDiscovery.mentions.emptyTitle"]),
|
||||
emptyBodyKey: z.enum(["chat.messageDiscovery.search.emptyBody", "chat.messageDiscovery.mentions.emptyBody"]),
|
||||
noResultsTitleKey: z.enum(["chat.messageDiscovery.search.noResultsTitle", "chat.messageDiscovery.mentions.emptyTitle"]),
|
||||
noResultsBodyKey: z.enum(["chat.messageDiscovery.search.noResultsBody", "chat.messageDiscovery.mentions.emptyBody"]),
|
||||
})
|
||||
.strict(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const ChatMessageDiscoveryVMSchema = z
|
||||
.object({
|
||||
status: z.literal("ready"),
|
||||
data: chatMessageDiscoveryDataSchema,
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function buildChatMessageDiscoveryVM(input: BuildChatMessageDiscoveryVMInput): ChatMessageDiscoveryVM {
|
||||
const query = input.mode === "search" ? (input.query ?? "").trim().slice(0, 200) : "";
|
||||
const scope = input.mode === "search" ? "search" : "mentions";
|
||||
const vm = ready<ChatMessageDiscoveryData>({
|
||||
mode: input.mode,
|
||||
query,
|
||||
rows: input.rows.map(({ body, ...row }) => ({ ...row, snippet: buildSnippet(body), channelKindLabelKey: `chat.channel.kind.${row.channelKind}` })),
|
||||
nextCursor: input.nextCursor ?? null,
|
||||
hrefs: input.hrefs,
|
||||
keys: {
|
||||
titleKey: `chat.messageDiscovery.${scope}.title`,
|
||||
subtitleKey: `chat.messageDiscovery.${scope}.subtitle`,
|
||||
emptyTitleKey: `chat.messageDiscovery.${scope}.emptyTitle`,
|
||||
emptyBodyKey: `chat.messageDiscovery.${scope}.emptyBody`,
|
||||
noResultsTitleKey: input.mode === "search" ? "chat.messageDiscovery.search.noResultsTitle" : "chat.messageDiscovery.mentions.emptyTitle",
|
||||
noResultsBodyKey: input.mode === "search" ? "chat.messageDiscovery.search.noResultsBody" : "chat.messageDiscovery.mentions.emptyBody",
|
||||
},
|
||||
});
|
||||
ChatMessageDiscoveryVMSchema.parse(vm);
|
||||
return vm;
|
||||
}
|
||||
|
||||
function buildSnippet(body: string): string {
|
||||
const normalized = body.replace(/\s+/g, " ").trim();
|
||||
if (normalized.length <= 280) return normalized;
|
||||
return `${normalized.slice(0, 277).trimEnd()}…`;
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildChatPinnedMessagesVM, buildChatThreadVM, chatFeatureMessageVMSchema } from "./message-features.vm.js";
|
||||
|
||||
const message = {
|
||||
id: "message_parent",
|
||||
authorLabel: "Raffael Sheikh",
|
||||
authorAvatarUrl: null,
|
||||
bodyMarkdown: "Status **fertig**",
|
||||
createdAtIso: "2026-07-16T08:00:00.000Z",
|
||||
deleted: false,
|
||||
mentions: [],
|
||||
attachments: [],
|
||||
reactions: [{ emoji: "👍", count: 2, reactedByViewer: true }],
|
||||
pinned: true,
|
||||
canReact: true,
|
||||
canPin: true,
|
||||
canEdit: true,
|
||||
canDelete: true,
|
||||
} as const;
|
||||
|
||||
const attachment = {
|
||||
id: "message_parent:file_1",
|
||||
fileId: "file_1",
|
||||
kind: "file",
|
||||
fileName: "montageplan.pdf",
|
||||
mimeType: "application/pdf",
|
||||
sizeBytes: 1_024,
|
||||
downloadHref: "/demo/files/file_1/content/original",
|
||||
previewHref: null,
|
||||
altText: null,
|
||||
durationSeconds: null,
|
||||
scanStatus: "clean",
|
||||
} as const;
|
||||
|
||||
describe("chat message feature view-models", () => {
|
||||
it("builds a one-level thread with deterministic labels", () => {
|
||||
const vm = buildChatThreadVM({
|
||||
chatId: "chat_1",
|
||||
threadId: "message_parent",
|
||||
channelTitle: "Montage Nord",
|
||||
backHref: "/demo/chat/chat_1",
|
||||
parent: { ...message, attachments: [attachment] },
|
||||
replies: [],
|
||||
replyCount: 0,
|
||||
canReply: true,
|
||||
});
|
||||
|
||||
expect(vm).toMatchObject({
|
||||
status: "ready",
|
||||
data: {
|
||||
composerPlaceholderKey: "chat.thread.composerPlaceholder",
|
||||
emptyRepliesHeadlineKey: "chat.thread.empty.headline",
|
||||
},
|
||||
});
|
||||
expect(vm.status === "ready" ? vm.data.parent.attachments : []).toEqual([attachment]);
|
||||
});
|
||||
|
||||
it("sorts pinned messages newest first", () => {
|
||||
const vm = buildChatPinnedMessagesVM({
|
||||
chatId: "chat_1",
|
||||
channelTitle: "Montage Nord",
|
||||
backHref: "/demo/chat/chat_1",
|
||||
rows: [
|
||||
{ message, pinnedAtIso: "2026-07-15T08:00:00.000Z", pinnedByLabel: "A", note: null, messageHref: "#old", canUnpin: true },
|
||||
{ message: { ...message, id: "message_new" }, pinnedAtIso: "2026-07-16T08:00:00.000Z", pinnedByLabel: "B", note: null, messageHref: "#new", canUnpin: true },
|
||||
],
|
||||
});
|
||||
|
||||
expect(vm.status === "ready" ? vm.data.rows.map((row) => row.message.id) : []).toEqual(["message_new", "message_parent"]);
|
||||
});
|
||||
|
||||
it("rejects actions on deleted messages", () => {
|
||||
expect(() =>
|
||||
chatFeatureMessageVMSchema.parse({ ...message, deleted: true, bodyMarkdown: null, canReact: true, canPin: false })
|
||||
).toThrow("chat.errors.integrityFailure");
|
||||
});
|
||||
});
|
||||
+168
@@ -0,0 +1,168 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { ready, type VMState } from "../index.js";
|
||||
import { chatAttachmentVMSchema, type ChatAttachmentVM, type ChatResolvedMentionVM } from "./channel-detail.vm.js";
|
||||
|
||||
export interface ChatFeatureMessageVM {
|
||||
readonly id: string;
|
||||
readonly authorLabel: string;
|
||||
readonly authorAvatarUrl: string | null;
|
||||
readonly bodyMarkdown: string | null;
|
||||
readonly createdAtIso: string;
|
||||
readonly deleted: boolean;
|
||||
readonly mentions: readonly ChatResolvedMentionVM[];
|
||||
readonly attachments: readonly ChatAttachmentVM[];
|
||||
readonly reactions: readonly {
|
||||
readonly emoji: string;
|
||||
readonly count: number;
|
||||
readonly reactedByViewer: boolean;
|
||||
}[];
|
||||
readonly pinned: boolean;
|
||||
readonly canReact: boolean;
|
||||
readonly canPin: boolean;
|
||||
readonly canEdit: boolean;
|
||||
readonly canDelete: boolean;
|
||||
}
|
||||
|
||||
export interface ChatThreadDataVM {
|
||||
readonly chatId: string;
|
||||
readonly threadId: string;
|
||||
readonly channelTitle: string;
|
||||
readonly backHref: string;
|
||||
readonly parent: ChatFeatureMessageVM;
|
||||
readonly replies: readonly ChatFeatureMessageVM[];
|
||||
readonly replyCount: number;
|
||||
readonly canReply: boolean;
|
||||
readonly composerPlaceholderKey: "chat.thread.composerPlaceholder";
|
||||
readonly emptyRepliesHeadlineKey: "chat.thread.empty.headline";
|
||||
readonly emptyRepliesBodyKey: "chat.thread.empty.body";
|
||||
}
|
||||
|
||||
export type ChatThreadVM = VMState<ChatThreadDataVM>;
|
||||
|
||||
export interface ChatPinnedMessagesDataVM {
|
||||
readonly chatId: string;
|
||||
readonly channelTitle: string;
|
||||
readonly backHref: string;
|
||||
readonly rows: readonly {
|
||||
readonly message: ChatFeatureMessageVM;
|
||||
readonly pinnedAtIso: string;
|
||||
readonly pinnedByLabel: string;
|
||||
readonly note: string | null;
|
||||
readonly messageHref: string;
|
||||
readonly canUnpin: boolean;
|
||||
}[];
|
||||
readonly emptyHeadlineKey: "chat.pinned.empty.headline";
|
||||
readonly emptyBodyKey: "chat.pinned.empty.body";
|
||||
}
|
||||
|
||||
export type ChatPinnedMessagesVM = VMState<ChatPinnedMessagesDataVM>;
|
||||
|
||||
const reactionSchema = z
|
||||
.object({ emoji: z.string().min(1), count: z.number().int().positive(), reactedByViewer: z.boolean() })
|
||||
.strict();
|
||||
|
||||
const mentionSchema = z
|
||||
.object({
|
||||
kind: z.enum(["user", "project", "contact", "company"]),
|
||||
id: z.string().min(1),
|
||||
label: z.string().min(1),
|
||||
href: z.string().min(1).nullable(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const chatFeatureMessageVMSchema = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
authorLabel: z.string().min(1),
|
||||
authorAvatarUrl: z.string().min(1).nullable(),
|
||||
bodyMarkdown: z.string().nullable(),
|
||||
createdAtIso: z.string().datetime({ offset: true }),
|
||||
deleted: z.boolean(),
|
||||
mentions: z.array(mentionSchema),
|
||||
attachments: z.array(chatAttachmentVMSchema),
|
||||
reactions: z.array(reactionSchema),
|
||||
pinned: z.boolean(),
|
||||
canReact: z.boolean(),
|
||||
canPin: z.boolean(),
|
||||
canEdit: z.boolean(),
|
||||
canDelete: z.boolean(),
|
||||
})
|
||||
.strict()
|
||||
.refine(
|
||||
(message) =>
|
||||
!message.deleted ||
|
||||
(message.bodyMarkdown === null &&
|
||||
message.mentions.length === 0 &&
|
||||
message.attachments.length === 0 &&
|
||||
!message.canReact &&
|
||||
!message.canPin &&
|
||||
!message.canEdit &&
|
||||
!message.canDelete),
|
||||
{
|
||||
message: "chat.errors.integrityFailure",
|
||||
}
|
||||
);
|
||||
|
||||
export const chatThreadDataVMSchema = z
|
||||
.object({
|
||||
chatId: z.string().min(1),
|
||||
threadId: z.string().min(1),
|
||||
channelTitle: z.string().min(1),
|
||||
backHref: z.string().min(1),
|
||||
parent: chatFeatureMessageVMSchema,
|
||||
replies: z.array(chatFeatureMessageVMSchema),
|
||||
replyCount: z.number().int().nonnegative(),
|
||||
canReply: z.boolean(),
|
||||
composerPlaceholderKey: z.literal("chat.thread.composerPlaceholder"),
|
||||
emptyRepliesHeadlineKey: z.literal("chat.thread.empty.headline"),
|
||||
emptyRepliesBodyKey: z.literal("chat.thread.empty.body"),
|
||||
})
|
||||
.strict()
|
||||
.refine((data) => data.parent.id === data.threadId && data.replyCount === data.replies.length, {
|
||||
message: "chat.errors.integrityFailure",
|
||||
});
|
||||
|
||||
export const chatPinnedMessagesDataVMSchema = z
|
||||
.object({
|
||||
chatId: z.string().min(1),
|
||||
channelTitle: z.string().min(1),
|
||||
backHref: z.string().min(1),
|
||||
rows: z.array(
|
||||
z
|
||||
.object({
|
||||
message: chatFeatureMessageVMSchema,
|
||||
pinnedAtIso: z.string().datetime({ offset: true }),
|
||||
pinnedByLabel: z.string().min(1),
|
||||
note: z.string().nullable(),
|
||||
messageHref: z.string().min(1),
|
||||
canUnpin: z.boolean(),
|
||||
})
|
||||
.strict()
|
||||
),
|
||||
emptyHeadlineKey: z.literal("chat.pinned.empty.headline"),
|
||||
emptyBodyKey: z.literal("chat.pinned.empty.body"),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export function buildChatThreadVM(input: Omit<ChatThreadDataVM, "composerPlaceholderKey" | "emptyRepliesHeadlineKey" | "emptyRepliesBodyKey">): ChatThreadVM {
|
||||
const data = chatThreadDataVMSchema.parse({
|
||||
...input,
|
||||
composerPlaceholderKey: "chat.thread.composerPlaceholder",
|
||||
emptyRepliesHeadlineKey: "chat.thread.empty.headline",
|
||||
emptyRepliesBodyKey: "chat.thread.empty.body",
|
||||
});
|
||||
return ready(data);
|
||||
}
|
||||
|
||||
export function buildChatPinnedMessagesVM(
|
||||
input: Omit<ChatPinnedMessagesDataVM, "emptyHeadlineKey" | "emptyBodyKey">
|
||||
): ChatPinnedMessagesVM {
|
||||
const data = chatPinnedMessagesDataVMSchema.parse({
|
||||
...input,
|
||||
rows: [...input.rows].sort((left, right) => right.pinnedAtIso.localeCompare(left.pinnedAtIso)),
|
||||
emptyHeadlineKey: "chat.pinned.empty.headline",
|
||||
emptyBodyKey: "chat.pinned.empty.body",
|
||||
});
|
||||
return ready(data);
|
||||
}
|
||||
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user