Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -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" });
});
});
@@ -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 } };
}
@@ -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,
},
};
}
@@ -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[];
}
@@ -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",
},
};
}
@@ -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");
});
});