Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,56 @@
import { describe, expect, it } from "vitest";
import { buildSelectTenantVM, toTenantCard, type SelectTenantInput } from "./select-tenant.vm.js";
function tenant(overrides: Partial<SelectTenantInput> & { id: string; name: string; slug: string }): SelectTenantInput {
return { ...overrides };
}
describe("buildSelectTenantVM", () => {
it("returns an empty state when the user has no tenants", () => {
expect(buildSelectTenantVM({ tenants: [] })).toEqual({ status: "empty" });
});
it("maps tenants to cards, derives initials, and assigns the role tag + tone", () => {
const vm = buildSelectTenantVM({
tenants: [tenant({ id: "t1", name: "Berger Bad", slug: "berger-bad", role: "owner", subtitle: "t.berger@berger-bad.de" })],
});
expect(vm.status).toBe("ready");
const card = vm.data!.tenants[0];
expect(card.avatarInitials).toBe("BB");
expect(card.role).toBe("owner");
expect(card.roleLabelKey).toBe("account.selectTenant.role.owner");
expect(card.roleTone).toBe("red-subtle");
expect(card.subtitle).toBe("t.berger@berger-bad.de");
expect(vm.data!.totalCount).toBe(1);
});
it("uses the image and a neutral avatar color when a logo/icon is present", () => {
const card = toTenantCard({ id: "t1", name: "Acme", slug: "acme", image: "https://x/y.png" });
expect(card.avatarImage).toBe("https://x/y.png");
expect(card.avatarColor).toBe("neutral");
});
it("derives a deterministic avatar color from the id when no image is present", () => {
const a = toTenantCard({ id: "t1", name: "Acme", slug: "acme" });
const b = toTenantCard({ id: "t1", name: "Acme", slug: "acme" });
expect(a.avatarColor).toBe(b.avatarColor);
expect(a.avatarColor).not.toBe("neutral");
expect(a.roleLabelKey).toBeUndefined();
expect(a.roleTone).toBeUndefined();
});
it("flags and sorts the current/last-used tenant to the front", () => {
const vm = buildSelectTenantVM({
tenants: [
tenant({ id: "t1", name: "Zeta", slug: "zeta" }),
tenant({ id: "t2", name: "Alpha", slug: "alpha" }),
tenant({ id: "t3", name: "Mu", slug: "mu" }),
],
currentTenantId: "t3",
});
expect(vm.data!.tenants[0].id).toBe("t3");
expect(vm.data!.tenants[0].isCurrent).toBe(true);
// restliche alphabetisch
expect(vm.data!.tenants.slice(1).map((c) => c.name)).toEqual(["Alpha", "Zeta"]);
});
});
@@ -0,0 +1,118 @@
import type { VMState } from "../index.js";
/**
* Tenant-/Profil-Auswahl View-Model (D-D0a, Flow "Login Tenantauswahl (Admin)", M013-Konvention).
*
* Reine Funktion: ein Loader holt die Tenants des Users (getMyTenants) + dessen Rolle je Tenant
* (getTenantUserType) und baut dieses VM; die UI (Davids Subframe-Karten) rendert nur. Kein React,
* kein Prisma, keine App-Imports (DoD A.3). Rollen-Labels werden als i18n-Key ausgegeben (kein
* vorformatierter Klartext, DoD i18n); die Tag-Tone-Zuordnung ist deterministisch.
*/
export type TenantRole = "owner" | "admin" | "member";
/** Tag_Label-Tone-Literale (Teilmenge), die die UI direkt durchreichen kann. */
export type RoleTone = "red-subtle" | "blue-subtle" | "green-subtle" | "neutral-subtle";
export type AvatarColor = "neutral" | "blue" | "green" | "red" | "yellow" | "purple";
export interface SelectTenantInput {
readonly id: string;
readonly name: string;
readonly slug: string;
/** Bild-Quelle (Tenant-Icon/Logo); fehlt -> Initialen-Avatar. */
readonly image?: string | null;
/** Rolle des aktuellen Users in diesem Tenant; fehlt -> kein Tag. */
readonly role?: TenantRole | null;
/** Optionaler Untertitel als DATEN (z.B. User-Email). */
readonly subtitle?: string | null;
}
export interface BuildSelectTenantInput {
readonly tenants: readonly SelectTenantInput[];
/** Tenant, der als "zuletzt genutzt" markiert wird (User.defaultTenantId). */
readonly currentTenantId?: string | null;
}
export interface TenantCardData {
readonly id: string;
readonly name: string;
readonly slug: string;
/** Bild-URL, wenn vorhanden; sonst undefined -> Initialen nutzen. */
readonly avatarImage?: string;
/** Bis zu zwei Großbuchstaben aus dem Tenant-Namen. */
readonly avatarInitials: string;
readonly avatarColor: AvatarColor;
readonly role?: TenantRole;
/** i18n-Key des Rollen-Labels (z.B. account.selectTenant.role.owner). */
readonly roleLabelKey?: string;
readonly roleTone?: RoleTone;
/** "zuletzt genutzt"-Markierung. */
readonly isCurrent: boolean;
readonly subtitle?: string;
}
export interface SelectTenantData {
readonly tenants: readonly TenantCardData[];
readonly totalCount: number;
}
const ROLE_TONE: Record<TenantRole, RoleTone> = {
owner: "red-subtle",
admin: "blue-subtle",
member: "green-subtle",
};
const AVATAR_PALETTE: readonly AvatarColor[] = ["blue", "green", "red", "yellow", "purple"];
/** Deterministische, stabile Farbe aus einem String (kein Math.random — testbar). */
function colorFor(seed: string): AvatarColor {
let hash = 0;
for (let i = 0; i < seed.length; i++) {
hash = (hash * 31 + seed.charCodeAt(i)) >>> 0;
}
return AVATAR_PALETTE[hash % AVATAR_PALETTE.length];
}
function initialsFor(name: string): string {
const words = name.trim().split(/\s+/).filter(Boolean);
if (words.length === 0) return "?";
if (words.length === 1) return words[0].slice(0, 2).toUpperCase();
return (words[0][0] + words[words.length - 1][0]).toUpperCase();
}
export function toTenantCard(input: SelectTenantInput, currentTenantId?: string | null): TenantCardData {
const role = input.role ?? undefined;
return {
id: input.id,
name: input.name,
slug: input.slug,
avatarImage: input.image ?? undefined,
avatarInitials: initialsFor(input.name),
avatarColor: input.image ? "neutral" : colorFor(input.id),
role,
roleLabelKey: role ? `account.selectTenant.role.${role}` : undefined,
roleTone: role ? ROLE_TONE[role] : undefined,
isCurrent: !!currentTenantId && input.id === currentTenantId,
subtitle: input.subtitle ?? undefined,
};
}
/**
* Baut das Auswahl-VM. Leere Liste -> "empty" (Empty-State in der UI, DoD 23).
* Der aktuelle/zuletzt genutzte Tenant wird nach vorne sortiert.
*/
export function buildSelectTenantVM(input: BuildSelectTenantInput): VMState<SelectTenantData> {
if (!input.tenants || input.tenants.length === 0) {
return { status: "empty" };
}
const cards = input.tenants.map((t) => toTenantCard(t, input.currentTenantId));
const sorted = [...cards].sort((a, b) => {
if (a.isCurrent !== b.isCurrent) return a.isCurrent ? -1 : 1;
return a.name.localeCompare(b.name);
});
return {
status: "ready",
data: { tenants: sorted, totalCount: sorted.length },
};
}
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { buildSessionListVM, type SessionDeviceInput } from "./session-list.vm.js";
const NOW = Date.UTC(2026, 5, 18, 12, 0, 0);
function session(overrides: Partial<SessionDeviceInput> & { id: string }): SessionDeviceInput {
return {
lastSeenAt: new Date(NOW),
...overrides,
};
}
describe("buildSessionListVM", () => {
it("returns an empty state when there are no sessions", () => {
expect(buildSessionListVM({ sessions: [], currentSessionId: "s1", nowMs: NOW })).toEqual({ status: "empty" });
});
it("flags the current device, forbids revoking it, and counts the others", () => {
const vm = buildSessionListVM({
sessions: [
session({ id: "s1", userAgent: "Firefox", approxLocation: "Germany" }),
session({ id: "s2", deviceLabel: "iPhone", trustedAt: new Date(NOW) }),
],
currentSessionId: "s1",
nowMs: NOW,
});
expect(vm.status).toBe("ready");
if (vm.status !== "ready") return;
const current = vm.data.devices.find((d) => d.id === "s1")!;
const other = vm.data.devices.find((d) => d.id === "s2")!;
expect(current.isCurrent).toBe(true);
expect(current.canRevoke).toBe(false);
expect(current.deviceLabel).toBe("Firefox");
expect(other.isCurrent).toBe(false);
expect(other.canRevoke).toBe(true);
expect(other.trusted).toBe(true);
expect(vm.data.otherActiveCount).toBe(1);
expect(vm.data.canRevokeOthers).toBe(true);
});
it("orders the current device first", () => {
const vm = buildSessionListVM({
sessions: [session({ id: "s2" }), session({ id: "s1" })],
currentSessionId: "s1",
nowMs: NOW,
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.devices[0].id).toBe("s1");
});
it("falls back to an i18n key when no device label or user agent is present", () => {
const vm = buildSessionListVM({ sessions: [session({ id: "s1" })], currentSessionId: null, nowMs: NOW });
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.devices[0].deviceLabel).toBeUndefined();
expect(vm.data.devices[0].deviceLabelFallbackKey).toBe("settings.security.sessions.unknownDevice");
});
it.each([
[30 * 1000, "justNow", undefined],
[5 * 60 * 1000, "minutes", 5],
[3 * 60 * 60 * 1000, "hours", 3],
[2 * 24 * 60 * 60 * 1000, "days", 2],
])("buckets last-seen %ims ago as %s", (ago, bucket, count) => {
const vm = buildSessionListVM({
sessions: [session({ id: "s1", lastSeenAt: new Date(NOW - (ago as number)) })],
currentSessionId: "s1",
nowMs: NOW,
});
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.devices[0].lastSeenBucket).toBe(bucket);
expect(vm.data.devices[0].lastSeenCount).toBe(count);
});
it("has no revocable others when only the current device is active", () => {
const vm = buildSessionListVM({ sessions: [session({ id: "s1" })], currentSessionId: "s1", nowMs: NOW });
if (vm.status !== "ready") throw new Error("expected ready");
expect(vm.data.otherActiveCount).toBe(0);
expect(vm.data.canRevokeOthers).toBe(false);
});
});
@@ -0,0 +1,115 @@
import type { VMState } from "../index.js";
/**
* Session-Geraeteliste View-Model (R-P2a S6, M013-Konvention).
*
* Reine Funktion: ein Loader holt die aktiven UserSession-Zeilen (sessionStore.listActiveUserSessions)
* und baut dieses VM; die UI (Settings > Sicherheit, Davids D-P2) rendert nur. Kein React, kein Prisma,
* keine App-Imports (DoD A.3). Last-Seen wird als i18n-Bucket + Count ausgegeben (kein vorformatierter
* Klartext, DoD i18n); `nowMs` ist Eingabe, damit die Funktion deterministisch testbar bleibt.
*/
export interface SessionDeviceInput {
readonly id: string;
readonly lastSeenAt: string | Date;
// AD-22: keine Klartext-IP — die Herkunft kommt als Land (approxLocation).
readonly userAgent?: string | null;
readonly deviceLabel?: string | null;
readonly approxLocation?: string | null;
readonly trustedAt?: string | Date | null;
}
export type LastSeenBucket = "justNow" | "minutes" | "hours" | "days";
export interface SessionDeviceData {
readonly id: string;
readonly isCurrent: boolean;
readonly trusted: boolean;
/** Roh-Label (deviceLabel oder userAgent) als DATEN; i18n-Fallback, wenn beides fehlt. */
readonly deviceLabel?: string;
readonly deviceLabelFallbackKey?: string;
readonly approxLocation?: string;
readonly lastSeenIso: string;
readonly lastSeenBucket: LastSeenBucket;
/** Zaehlwert fuer minutes/hours/days (fuer "vor N Minuten"); bei justNow undefined. */
readonly lastSeenCount?: number;
/** Aktuelle Session beendet man ueber normales Abmelden, nicht ueber die Geraeteliste. */
readonly canRevoke: boolean;
}
export interface SessionListData {
readonly devices: readonly SessionDeviceData[];
readonly currentDeviceId: string | null;
/** Anzahl anderer aktiver Geraete (fuer "ueberall abmelden (N)"). */
readonly otherActiveCount: number;
readonly canRevokeOthers: boolean;
}
export type SessionListVM = VMState<SessionListData>;
export interface BuildSessionListVMInput {
readonly sessions: readonly SessionDeviceInput[];
readonly currentSessionId: string | null;
readonly nowMs: number;
}
const MINUTE_MS = 60 * 1000;
const HOUR_MS = 60 * MINUTE_MS;
const DAY_MS = 24 * HOUR_MS;
function toMs(value: string | Date): number {
return value instanceof Date ? value.getTime() : new Date(value).getTime();
}
function relativeLastSeen(lastSeenMs: number, nowMs: number): { bucket: LastSeenBucket; count?: number } {
const diff = Math.max(0, nowMs - lastSeenMs);
if (diff < MINUTE_MS) {
return { bucket: "justNow" };
}
if (diff < HOUR_MS) {
return { bucket: "minutes", count: Math.floor(diff / MINUTE_MS) };
}
if (diff < DAY_MS) {
return { bucket: "hours", count: Math.floor(diff / HOUR_MS) };
}
return { bucket: "days", count: Math.floor(diff / DAY_MS) };
}
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 lastSeenMs = toMs(session.lastSeenAt);
const relative = relativeLastSeen(lastSeenMs, nowMs);
return {
id: session.id,
isCurrent,
trusted: Boolean(session.trustedAt),
deviceLabel: rawLabel,
deviceLabelFallbackKey: rawLabel ? undefined : "settings.security.sessions.unknownDevice",
approxLocation: session.approxLocation?.trim() || undefined,
lastSeenIso: new Date(lastSeenMs).toISOString(),
lastSeenBucket: relative.bucket,
lastSeenCount: relative.count,
canRevoke: !isCurrent,
};
}
export function buildSessionListVM(input: BuildSessionListVMInput): SessionListVM {
if (input.sessions.length === 0) {
return { status: "empty" };
}
const devices = input.sessions
.map((session) => toDevice(session, input.currentSessionId, input.nowMs))
// Aktuelles Geraet zuerst, der Rest nach zuletzt gesehen (Eingabe ist i.d.R. schon desc sortiert).
.sort((a, b) => (a.isCurrent === b.isCurrent ? 0 : a.isCurrent ? -1 : 1));
const otherActiveCount = devices.filter((device) => !device.isCurrent).length;
return {
status: "ready",
data: {
devices,
currentDeviceId: input.currentSessionId,
otherActiveCount,
canRevokeOthers: otherActiveCount > 0,
},
};
}