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,102 @@
import { describe, expect, it } from "vitest";
import { buildAnnouncementFeedVM, buildAnnouncementDetailVM, type HrAnnouncementFeedRow, type HrAnnouncementDetailData } from "./hr-announcement.vm.js";
// AK-P17b — announcement VMs are pure. These tests cover the unread-only feed
// filter, the acknowledgement/read flags and the manager-gated read receipts.
const feedRow = (overrides: Partial<HrAnnouncementFeedRow> = {}): HrAnnouncementFeedRow => ({
id: "a1",
title: "Office move",
snippet: "We are moving...",
pinned: false,
isRead: false,
requiresAcknowledgement: false,
isAcknowledged: false,
reactionCount: 2,
commentCount: 1,
publishedIso: new Date("2026-07-01").toISOString(),
detailHref: "/acme/hr/announcements/a1",
...overrides,
});
describe("buildAnnouncementFeedVM", () => {
it("keeps all rows when unreadOnly is off", () => {
const vm = buildAnnouncementFeedVM({
rows: [feedRow(), feedRow({ id: "a2", isRead: true })],
unreadOnly: false,
canManage: false,
manageHref: "/x",
});
expect(vm.status).toBe("ready");
expect(vm.data?.rows).toHaveLength(2);
expect(vm.data?.unreadOnly).toBe(false);
});
it("filters read announcements when unreadOnly is on", () => {
const vm = buildAnnouncementFeedVM({
rows: [feedRow(), feedRow({ id: "a2", isRead: true })],
unreadOnly: true,
canManage: false,
manageHref: "/x",
});
expect(vm.data?.rows).toHaveLength(1);
expect(vm.data?.rows[0]?.id).toBe("a1");
});
it("carries the acknowledgement flags through unchanged", () => {
const vm = buildAnnouncementFeedVM({
rows: [feedRow({ requiresAcknowledgement: true, isAcknowledged: false })],
unreadOnly: false,
canManage: true,
manageHref: "/acme/hr/announcements/manage",
});
expect(vm.data?.rows[0]?.requiresAcknowledgement).toBe(true);
expect(vm.data?.rows[0]?.isAcknowledged).toBe(false);
expect(vm.data?.canManage).toBe(true);
expect(vm.data?.manageHref).toBe("/acme/hr/announcements/manage");
});
it("keeps an empty feed in a ready state with the empty-state keys", () => {
const vm = buildAnnouncementFeedVM({ rows: [], unreadOnly: false, canManage: false, manageHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.emptyHeadlineKey).toBe("hr.announcements.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.announcements.empty.body");
});
});
describe("buildAnnouncementDetailVM", () => {
const detailInput: Omit<HrAnnouncementDetailData, "commentEmptyKey"> = {
id: "a1",
title: "Office move",
bodyMarkdown: "# We move\nDetails follow.",
authorLabel: "Alex Doe",
publishedIso: new Date("2026-07-01").toISOString(),
requiresAcknowledgement: true,
isAcknowledged: false,
reactions: [{ reaction: "👍", count: 3, mine: true }],
comments: [{ id: "c1", authorLabel: "Kim", body: "Nice!", createdIso: new Date("2026-07-02").toISOString(), canArchive: false }],
canManage: false,
readReceipts: [],
};
it("passes body/reactions/comments through and adds the comment empty key", () => {
const vm = buildAnnouncementDetailVM(detailInput);
expect(vm.status).toBe("ready");
expect(vm.data?.bodyMarkdown).toContain("# We move");
expect(vm.data?.reactions[0]?.mine).toBe(true);
expect(vm.data?.comments[0]?.authorLabel).toBe("Kim");
expect(vm.data?.commentEmptyKey).toBe("hr.announcements.comments.empty");
});
it("keeps read receipts empty for non-managers and carries them for managers", () => {
const nonManager = buildAnnouncementDetailVM(detailInput);
expect(nonManager.data?.readReceipts).toHaveLength(0);
const manager = buildAnnouncementDetailVM({
...detailInput,
canManage: true,
readReceipts: [{ userLabel: "Kim", readIso: new Date("2026-07-02").toISOString(), acknowledged: true }],
});
expect(manager.data?.readReceipts).toHaveLength(1);
expect(manager.data?.readReceipts[0]?.acknowledged).toBe(true);
});
});
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { buildHrDocumentListVM, hrDocumentKindKey, type HrDocumentRow, type HrDocumentKind } from "./hr-document.vm.js";
// AK-P17a — the document list VM is pure. These tests cover the kind → i18n-key
// mapping, the read-only office-upload flag, the expiry flag and the empty state.
const row = (overrides: Partial<HrDocumentRow> = {}): HrDocumentRow => ({
id: "d1",
title: "Contract",
documentKind: "contract",
kindKey: hrDocumentKindKey("contract"),
createdAtIso: new Date("2026-01-01").toISOString(),
validUntilIso: null,
isExpired: false,
readOnly: false,
fileHref: "/acme/files/f1",
...overrides,
});
describe("hrDocumentKindKey", () => {
it("maps every document kind to its i18n key", () => {
const kinds: HrDocumentKind[] = ["contract", "certificate", "identification", "qualification", "other"];
for (const kind of kinds) {
expect(hrDocumentKindKey(kind)).toBe(`hr.document.kind.${kind}`);
}
});
});
describe("buildHrDocumentListVM", () => {
it("flags office uploads as read-only while keeping the file link", () => {
const vm = buildHrDocumentListVM({ rows: [row({ readOnly: true })], canUpload: true, uploadHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows[0]?.readOnly).toBe(true);
expect(vm.data?.rows[0]?.fileHref).toBe("/acme/files/f1");
});
it("carries the loader-computed expiry flag through unchanged", () => {
const vm = buildHrDocumentListVM({
rows: [row({ validUntilIso: new Date("2025-12-31").toISOString(), isExpired: true })],
canUpload: false,
uploadHref: "/x",
});
expect(vm.data?.rows[0]?.isExpired).toBe(true);
expect(vm.data?.canUpload).toBe(false);
});
it("keeps an empty document list in a ready state with the empty-state keys", () => {
const vm = buildHrDocumentListVM({ rows: [], canUpload: true, uploadHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows).toHaveLength(0);
expect(vm.data?.emptyHeadlineKey).toBe("hr.documents.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.documents.empty.body");
});
});
@@ -0,0 +1,135 @@
import { describe, expect, it } from "vitest";
import { buildHrHubVM, type HrHubHrefs } from "./hr-hub.vm.js";
const ids = [
"leave",
"sick",
"documents",
"payslips",
"announcements",
"requests",
"surveys",
"teamDirectory",
"teamLeave",
"leaveApprovals",
"requestApprovals",
"directory",
"locations",
"announcementAdmin",
"payslipAdmin",
"requestTemplates",
"uploadReminders",
"surveyAdmin",
] as const;
const hrefs = Object.fromEntries(ids.map((id) => [id, `/acme/hr/${id}`])) as HrHubHrefs;
function build(
overrides: Partial<Parameters<typeof buildHrHubVM>[0]> = {},
): ReturnType<typeof buildHrHubVM> {
return buildHrHubVM({
moduleActive: true,
hrefs,
counts: {
ownLeave: 1,
ownSick: 1,
ownRequests: 1,
pendingLeaveApprovals: 0,
pendingRequestApprovals: 0,
visibleTeamMembers: 0,
},
capabilities: {
canReadAll: false,
canWrite: false,
canApproveLeave: false,
canViewSurveyResults: false,
},
...overrides,
});
}
describe("buildHrHubVM", () => {
it("shows the employee area and mobile-priority actions without admin links", () => {
const vm = build();
expect(vm.forMe.visible).toBe(true);
// leave + sick live in `priorityActions` only — no duplicate cards.
expect(vm.forMe.items.map((entry) => entry.id)).toEqual([
"documents",
"payslips",
"announcements",
"requests",
"surveys",
]);
expect(vm.priorityActions.map((entry) => entry.id)).toEqual(["sick", "leave"]);
expect(vm.administration.visible).toBe(false);
expect(vm.myTeam.visible).toBe(false);
expect(vm.openTaskCount).toBe(3);
});
it("does not infer HR administration from an unrelated tenant-admin role", () => {
const vm = build();
expect(vm.administration.items).toEqual([]);
expect(vm.myTeam.items).toEqual([]);
});
it("exposes only scoped team tasks to a team lead", () => {
const vm = build({
counts: {
ownLeave: 0,
ownSick: 0,
ownRequests: 0,
pendingLeaveApprovals: 2,
pendingRequestApprovals: 1,
visibleTeamMembers: 4,
},
capabilities: {
canReadAll: false,
canWrite: false,
canApproveLeave: true,
canViewSurveyResults: false,
},
});
expect(vm.myTeam.items.map((entry) => entry.id)).toEqual([
"teamDirectory",
"teamLeave",
"leaveApprovals",
"requestApprovals",
]);
expect(vm.myTeam.count).toBe(7);
expect(vm.administration.visible).toBe(false);
});
it("builds HR administration from granular capabilities", () => {
const vm = build({
capabilities: {
canReadAll: true,
canWrite: true,
canApproveLeave: true,
canViewSurveyResults: true,
},
});
expect(vm.administration.items.map((entry) => entry.id)).toEqual([
"directory",
"locations",
"announcementAdmin",
"payslipAdmin",
"requestTemplates",
"uploadReminders",
"surveyAdmin",
]);
});
it("returns a locked, data-free contract when the module is disabled", () => {
const vm = build({ moduleActive: false });
expect(vm.moduleActive).toBe(false);
expect(vm.openTaskCount).toBe(0);
expect(vm.forMe.items).toEqual([]);
expect(vm.myTeam.visible).toBe(false);
expect(vm.administration.visible).toBe(false);
});
});
@@ -0,0 +1,184 @@
export type HrHubItemId =
| "leave"
| "sick"
| "documents"
| "payslips"
| "announcements"
| "requests"
| "surveys"
| "teamDirectory"
| "teamLeave"
| "leaveApprovals"
| "requestApprovals"
| "directory"
| "locations"
| "announcementAdmin"
| "payslipAdmin"
| "requestTemplates"
| "uploadReminders"
| "surveyAdmin";
export type HrHubItem = {
readonly id: HrHubItemId;
readonly labelKey: string;
readonly descriptionKey: string;
readonly href: string;
readonly count: number;
readonly allowedActions: readonly string[];
};
export type HrHubSection = {
readonly id: "forMe" | "myTeam" | "administration";
readonly labelKey: string;
readonly descriptionKey: string;
readonly visible: boolean;
readonly count: number;
readonly items: readonly HrHubItem[];
readonly allowedActions: readonly string[];
};
export type HrHubVM = {
readonly moduleActive: boolean;
readonly openTaskCount: number;
readonly priorityActions: readonly HrHubItem[];
readonly forMe: HrHubSection;
readonly myTeam: HrHubSection;
readonly administration: HrHubSection;
};
export type HrHubHrefs = Readonly<Record<HrHubItemId, string>>;
export type BuildHrHubInput = {
readonly moduleActive: boolean;
readonly hrefs: HrHubHrefs;
readonly counts: {
readonly ownLeave: number;
readonly ownSick: number;
readonly ownRequests: number;
readonly pendingLeaveApprovals: number;
readonly pendingRequestApprovals: number;
readonly visibleTeamMembers: number;
};
readonly capabilities: {
readonly canReadAll: boolean;
readonly canWrite: boolean;
readonly canApproveLeave: boolean;
readonly canViewSurveyResults: boolean;
};
};
function item(
id: HrHubItemId,
hrefs: HrHubHrefs,
count = 0,
allowedActions: readonly string[] = ["open"],
): HrHubItem {
return {
id,
labelKey: `hr.hub.item.${id}.label`,
descriptionKey: `hr.hub.item.${id}.description`,
href: hrefs[id],
count,
allowedActions,
};
}
function section(
id: HrHubSection["id"],
items: readonly HrHubItem[],
allowedActions: readonly string[],
): HrHubSection {
return {
id,
labelKey: `hr.hub.section.${id}.label`,
descriptionKey: `hr.hub.section.${id}.description`,
visible: items.length > 0,
count: items.reduce((sum, current) => sum + current.count, 0),
items,
allowedActions,
};
}
export function buildHrHubVM(input: BuildHrHubInput): HrHubVM {
if (!input.moduleActive) {
return {
moduleActive: false,
openTaskCount: 0,
priorityActions: [],
forMe: section("forMe", [], []),
myTeam: section("myTeam", [], []),
administration: section("administration", [], []),
};
}
const ownLeave = item("leave", input.hrefs, input.counts.ownLeave, ["open", "submit"]);
const ownSick = item("sick", input.hrefs, input.counts.ownSick, ["open", "report"]);
const ownRequests = item("requests", input.hrefs, input.counts.ownRequests, ["open", "submit"]);
// `priorityActions` renders the same two entries above this section, so leave
// and sick leave are intentionally not repeated here — they used to appear
// twice on one screen with identical labels.
const forMeItems = [
item("documents", input.hrefs, 0, ["open", "upload"]),
item("payslips", input.hrefs),
item("announcements", input.hrefs),
ownRequests,
item("surveys", input.hrefs),
];
const teamItems: HrHubItem[] = [];
if (input.counts.visibleTeamMembers > 0 || input.capabilities.canReadAll) {
teamItems.push(
item("teamDirectory", input.hrefs, input.counts.visibleTeamMembers),
item("teamLeave", input.hrefs, 0),
);
}
if (input.counts.pendingLeaveApprovals > 0 || input.capabilities.canApproveLeave) {
teamItems.push(
item("leaveApprovals", input.hrefs, input.counts.pendingLeaveApprovals, [
"open",
"decide",
]),
);
}
if (input.counts.pendingRequestApprovals > 0 || input.capabilities.canWrite) {
teamItems.push(
item("requestApprovals", input.hrefs, input.counts.pendingRequestApprovals, [
"open",
"decide",
]),
);
}
const administrationItems: HrHubItem[] = [];
if (input.capabilities.canReadAll) {
administrationItems.push(item("directory", input.hrefs));
}
if (input.capabilities.canWrite) {
administrationItems.push(
item("locations", input.hrefs, 0, ["open", "manage"]),
item("announcementAdmin", input.hrefs, 0, ["open", "manage"]),
item("payslipAdmin", input.hrefs, 0, ["open", "manage"]),
item("requestTemplates", input.hrefs, 0, ["open", "manage"]),
item("uploadReminders", input.hrefs, 0, ["open", "manage"]),
);
}
if (input.capabilities.canWrite || input.capabilities.canViewSurveyResults) {
administrationItems.push(item("surveyAdmin", input.hrefs, 0, ["open", "manage"]));
}
const openTaskCount =
input.counts.ownLeave +
input.counts.ownSick +
input.counts.ownRequests +
input.counts.pendingLeaveApprovals +
input.counts.pendingRequestApprovals;
return {
moduleActive: true,
openTaskCount,
priorityActions: [ownSick, ownLeave],
forMe: section("forMe", forMeItems, ["open", "submit", "report", "upload"]),
myTeam: section("myTeam", teamItems, ["open", "decide"]),
administration: section("administration", administrationItems, ["open", "manage"]),
};
}
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { buildHrLocationListVM, type HrLocationRow } from "./hr-location.vm.js";
// AK-P17a — the location list VM is pure. These tests cover the pass-through of
// nullable address fields, the default flag/employee count and the empty state.
const row = (overrides: Partial<HrLocationRow> = {}): HrLocationRow => ({
id: "l1",
name: "HQ",
addressLine1: "Main St 1",
postalCode: "1010",
city: "Vienna",
country: "AT",
phone: null,
latitude: null,
longitude: null,
description: null,
isDefault: false,
employeeCount: 0,
detailHref: "/acme/hr/locations/l1",
...overrides,
});
describe("buildHrLocationListVM", () => {
it("exposes the default flag and the loader-computed employee count", () => {
const vm = buildHrLocationListVM({ rows: [row({ isDefault: true, employeeCount: 4 })], canManage: true, createHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows[0]?.isDefault).toBe(true);
expect(vm.data?.rows[0]?.employeeCount).toBe(4);
expect(vm.data?.canManage).toBe(true);
});
it("keeps nullable address/geo fields as null without inventing defaults", () => {
const vm = buildHrLocationListVM({
rows: [row({ addressLine1: null, postalCode: null, city: null, country: null })],
canManage: false,
createHref: "/x",
});
const data = vm.data!.rows[0]!;
expect(data.addressLine1).toBeNull();
expect(data.phone).toBeNull();
expect(data.latitude).toBeNull();
expect(data.longitude).toBeNull();
});
it("keeps an empty location list in a ready state with the empty-state keys", () => {
const vm = buildHrLocationListVM({ rows: [], canManage: true, createHref: "/acme/hr/locations/new" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows).toHaveLength(0);
expect(vm.data?.createHref).toBe("/acme/hr/locations/new");
expect(vm.data?.emptyHeadlineKey).toBe("hr.locations.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.locations.empty.body");
});
});
@@ -1,11 +1,5 @@
import { describe, expect, it } from "vitest";
import {
buildVaultDetailVM,
buildVaultListVM,
buildAdminVaultListVM,
PASSWORD_SAFE_COPY_AUTO_CLEAR_MS,
type EntryRow,
} from "./hr-password-safe.vm.js";
import { buildVaultDetailVM, buildVaultListVM, buildAdminVaultListVM, PASSWORD_SAFE_COPY_AUTO_CLEAR_MS, type EntryRow } from "./hr-password-safe.vm.js";
// AK-P17a — the password-safe VMs carry the security-critical "never list a
// secret value" contract. These pure-function tests lock that contract in.
@@ -18,7 +12,7 @@ const entry = (overrides: Partial<EntryRow> = {}): EntryRow => ({
hasUsername: true,
hasPassword: true,
hasNotes: false,
revealHref: "/acme/hr/password-safe/v1/reveal",
revealHref: "/acme/passwords/v1/reveal",
...overrides,
});
@@ -53,6 +47,15 @@ describe("buildVaultDetailVM", () => {
expect(vm.status).toBe("ready");
expect(vm.data?.rows).toHaveLength(0);
expect(vm.data?.emptyHeadlineKey).toBe("hr.passwordSafe.entries.empty.headline");
expect(vm.data?.archivedRows).toEqual([]);
});
it("keeps archived rows separate without adding secret values", () => {
const archived = entry({ id: "archived" });
const vm = buildVaultDetailVM({ vaultId: "v1", vaultName: "Ops", accessLevel: "write", rows: [], archivedRows: [archived], exportHref: "/x" });
expect(vm.data?.rows).toEqual([]);
expect(vm.data?.archivedRows).toEqual([archived]);
expect(vm.data?.archivedRows[0]).not.toHaveProperty("password");
});
});
@@ -24,19 +24,21 @@ export interface VaultListData {
readonly rows: readonly VaultRow[];
readonly canCreate: boolean;
readonly createHref: string;
readonly searchQuery: string;
readonly emptyHeadlineKey: string;
readonly emptyBodyKey: string;
}
export type VaultListVM = VMState<VaultListData>;
export function buildVaultListVM(input: { rows: readonly VaultRow[]; canCreate: boolean; createHref: string }): VaultListVM {
export function buildVaultListVM(input: { rows: readonly VaultRow[]; canCreate: boolean; createHref: string; searchQuery?: string }): VaultListVM {
return {
status: "ready",
data: {
rows: input.rows,
canCreate: input.canCreate,
createHref: input.createHref,
searchQuery: input.searchQuery ?? "",
emptyHeadlineKey: "hr.passwordSafe.empty.headline",
emptyBodyKey: "hr.passwordSafe.empty.body",
},
@@ -56,13 +58,43 @@ export interface EntryRow {
readonly revealHref: string;
}
export interface VaultAccessRow {
readonly userId: string;
readonly displayName: string;
readonly email: string;
readonly roleNames: readonly string[];
readonly permissionLevel: PasswordSafePermissionLevel;
}
export interface VaultMemberOption {
readonly userId: string;
readonly displayName: string;
readonly email: string;
readonly roleNames: readonly string[];
readonly hasAccess: boolean;
}
export interface PasswordSafeActivityRow {
readonly id: string;
readonly createdAtLabel: string;
readonly actionLabelKey: string;
readonly actorLabel: string;
readonly successful: boolean;
}
export interface VaultDetailData {
readonly vaultId: string;
readonly vaultName: string;
readonly accessLevel: PasswordSafePermissionLevel;
readonly canWrite: boolean;
readonly canManageAccess: boolean;
readonly canExport: boolean;
readonly rows: readonly EntryRow[];
/** Archived entries remain metadata-only and can be restored by writers. */
readonly archivedRows: readonly EntryRow[];
readonly accessRows: readonly VaultAccessRow[];
readonly memberOptions: readonly VaultMemberOption[];
readonly activityRows: readonly PasswordSafeActivityRow[];
/** 30s clipboard auto-clear window (ms) the UI enforces after a copy (DoD #3). */
readonly copyAutoClearMs: number;
readonly exportHref: string;
@@ -79,6 +111,11 @@ export interface BuildVaultDetailVMInput {
readonly vaultName: string;
readonly accessLevel: PasswordSafePermissionLevel;
readonly rows: readonly EntryRow[];
readonly archivedRows?: readonly EntryRow[];
readonly accessRows?: readonly VaultAccessRow[];
readonly memberOptions?: readonly VaultMemberOption[];
readonly activityRows?: readonly PasswordSafeActivityRow[];
readonly canExport?: boolean;
readonly exportHref: string;
}
@@ -92,7 +129,12 @@ export function buildVaultDetailVM(input: BuildVaultDetailVMInput): VaultDetailV
accessLevel: input.accessLevel,
canWrite,
canManageAccess: input.accessLevel === "admin",
canExport: input.canExport ?? false,
rows: input.rows,
archivedRows: input.archivedRows ?? [],
accessRows: input.accessRows ?? [],
memberOptions: input.memberOptions ?? [],
activityRows: input.activityRows ?? [],
copyAutoClearMs: PASSWORD_SAFE_COPY_AUTO_CLEAR_MS,
exportHref: input.exportHref,
emptyHeadlineKey: "hr.passwordSafe.entries.empty.headline",
@@ -101,7 +143,7 @@ export function buildVaultDetailVM(input: BuildVaultDetailVMInput): VaultDetailV
};
}
/** Tenant-wide admin vault list (/admin/hr/password-safe) — metadata only, never
/** Tenant-wide admin vault list (/password-safe/admin) — metadata only, never
* content access. */
export interface AdminVaultRow {
readonly id: string;
@@ -109,22 +151,31 @@ export interface AdminVaultRow {
readonly entryCount: number;
readonly accessCount: number;
readonly archived: boolean;
readonly detailHref: string;
/** Null for a tenant metadata admin without a per-vault content grant. */
readonly detailHref: string | null;
}
export interface AdminVaultListData {
readonly rows: readonly AdminVaultRow[];
readonly activityRows: readonly PasswordSafeActivityRow[];
readonly searchQuery: string;
readonly emptyHeadlineKey: string;
readonly emptyBodyKey: string;
}
export type AdminVaultListVM = VMState<AdminVaultListData>;
export function buildAdminVaultListVM(input: { rows: readonly AdminVaultRow[] }): AdminVaultListVM {
export function buildAdminVaultListVM(input: {
rows: readonly AdminVaultRow[];
activityRows?: readonly PasswordSafeActivityRow[];
searchQuery?: string;
}): AdminVaultListVM {
return {
status: "ready",
data: {
rows: input.rows,
activityRows: input.activityRows ?? [],
searchQuery: input.searchQuery ?? "",
emptyHeadlineKey: "hr.admin.passwordSafe.empty.headline",
emptyBodyKey: "hr.admin.passwordSafe.empty.body",
},
@@ -0,0 +1,92 @@
import { describe, expect, it } from "vitest";
import { buildHrPayslipOwnVM, buildHrPayslipAdminVM, buildHrPayslipMatchPreviewVM, type HrPayslipMatchInputRow } from "./hr-payslip.vm.js";
// AK-P17b — payslip VMs are pure. These tests cover the period-label derivation,
// the read flag pass-through and the match-preview confidence key/tone/counts.
describe("buildHrPayslipOwnVM", () => {
const row = { id: "p1", periodYear: 2026, periodMonth: 7, isRead: false, openHref: "/acme/hr/payslips/p1" };
it("derives a zero-padded numeric period label", () => {
const vm = buildHrPayslipOwnVM({ rows: [row, { ...row, id: "p2", periodMonth: 12 }] });
expect(vm.status).toBe("ready");
expect(vm.data?.rows[0]?.periodLabel).toBe("2026-07");
expect(vm.data?.rows[1]?.periodLabel).toBe("2026-12");
});
it("carries the read flag through unchanged", () => {
const vm = buildHrPayslipOwnVM({ rows: [{ ...row, isRead: true }] });
expect(vm.data?.rows[0]?.isRead).toBe(true);
});
it("keeps an empty list in a ready state with the empty-state keys", () => {
const vm = buildHrPayslipOwnVM({ rows: [] });
expect(vm.status).toBe("ready");
expect(vm.data?.emptyHeadlineKey).toBe("hr.payslips.own.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.payslips.own.empty.body");
});
});
describe("buildHrPayslipAdminVM", () => {
it("adds employee/uploader labels and the derived period label", () => {
const vm = buildHrPayslipAdminVM({
rows: [{ id: "p1", periodYear: 2026, periodMonth: 1, isRead: false, openHref: "/x", employeeLabel: "Alex Doe", uploadedByLabel: "Kim Office" }],
uploadHref: "/acme/hr/payslips/upload",
});
expect(vm.data?.rows[0]?.employeeLabel).toBe("Alex Doe");
expect(vm.data?.rows[0]?.uploadedByLabel).toBe("Kim Office");
expect(vm.data?.rows[0]?.periodLabel).toBe("2026-01");
expect(vm.data?.uploadHref).toBe("/acme/hr/payslips/upload");
expect(vm.data?.emptyHeadlineKey).toBe("hr.payslips.admin.empty.headline");
});
});
describe("buildHrPayslipMatchPreviewVM", () => {
const matchRow = (overrides: Partial<HrPayslipMatchInputRow> = {}): HrPayslipMatchInputRow => ({
fileId: "f1",
fileName: "payslip-doe-2026-07.pdf",
confidence: "hard",
employeeUserId: "u1",
employeeLabel: "Alex Doe",
candidateUserIds: [],
...overrides,
});
it("maps confidence to i18n key and color tone", () => {
const vm = buildHrPayslipMatchPreviewVM({
rows: [
matchRow(),
matchRow({ fileId: "f2", confidence: "soft", employeeUserId: null, employeeLabel: null, candidateUserIds: ["u1", "u2"] }),
matchRow({ fileId: "f3", confidence: "none", employeeUserId: null, employeeLabel: null }),
],
});
expect(vm.data?.rows[0]?.confidenceKey).toBe("hr.payslips.match.confidence.hard");
expect(vm.data?.rows[0]?.confidenceTone).toBe("success");
expect(vm.data?.rows[1]?.confidenceKey).toBe("hr.payslips.match.confidence.soft");
expect(vm.data?.rows[1]?.confidenceTone).toBe("warning");
expect(vm.data?.rows[2]?.confidenceTone).toBe("neutral");
});
it("counts rows per confidence bucket", () => {
const vm = buildHrPayslipMatchPreviewVM({
rows: [
matchRow(),
matchRow({ fileId: "f2" }),
matchRow({ fileId: "f3", confidence: "soft" }),
matchRow({ fileId: "f4", confidence: "none" }),
],
});
expect(vm.data?.hardCount).toBe(2);
expect(vm.data?.softCount).toBe(1);
expect(vm.data?.noneCount).toBe(1);
});
it("keeps an empty preview in a ready state with zero counts", () => {
const vm = buildHrPayslipMatchPreviewVM({ rows: [] });
expect(vm.status).toBe("ready");
expect(vm.data?.hardCount).toBe(0);
expect(vm.data?.softCount).toBe(0);
expect(vm.data?.noneCount).toBe(0);
expect(vm.data?.emptyHeadlineKey).toBe("hr.payslips.match.empty.headline");
});
});
@@ -0,0 +1,79 @@
import { describe, expect, it } from "vitest";
import { buildHrRequestOwnVM, buildHrRequestApproverVM, buildHrRequestTemplateListVM, type HrRequestStatus } from "./hr-request.vm.js";
// AK-P17b — request VMs are pure. These tests cover the kind/status → i18n-key
// mapping, the open-status withdraw flag and the template picker shape.
describe("buildHrRequestOwnVM", () => {
const row = (id: string, status: HrRequestStatus) => ({
id,
title: "New laptop",
kind: "hardware" as const,
status,
createdIso: new Date("2026-07-01").toISOString(),
detailHref: `/acme/hr/requests/${id}`,
});
it("maps kind/status to i18n keys", () => {
const vm = buildHrRequestOwnVM({ rows: [row("r1", "submitted")], newHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows[0]?.kindLabelKey).toBe("hr.requests.kind.hardware");
expect(vm.data?.rows[0]?.statusLabelKey).toBe("hr.requests.status.submitted");
});
it("allows withdraw only while the request is open", () => {
const vm = buildHrRequestOwnVM({
rows: [row("r1", "submitted"), row("r2", "clarification"), row("r3", "approved"), row("r4", "rejected"), row("r5", "withdrawn")],
newHref: "/x",
});
const byId = new Map(vm.data!.rows.map((r) => [r.id, r.canWithdraw]));
expect(byId.get("r1")).toBe(true);
expect(byId.get("r2")).toBe(true);
expect(byId.get("r3")).toBe(false);
expect(byId.get("r4")).toBe(false);
expect(byId.get("r5")).toBe(false);
});
it("keeps an empty list in a ready state with the empty-state keys", () => {
const vm = buildHrRequestOwnVM({ rows: [], newHref: "/acme/hr/requests/new" });
expect(vm.status).toBe("ready");
expect(vm.data?.newHref).toBe("/acme/hr/requests/new");
expect(vm.data?.emptyHeadlineKey).toBe("hr.requests.own.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.requests.own.empty.body");
});
});
describe("buildHrRequestApproverVM", () => {
it("adds the employee label and drops the raw kind/status from the row", () => {
const vm = buildHrRequestApproverVM({
rows: [{ id: "r1", title: "Training", employeeLabel: "Alex Doe", kind: "training", status: "submitted", createdIso: new Date("2026-07-01").toISOString(), detailHref: "/x" }],
});
const row = vm.data!.rows[0]! as unknown as Record<string, unknown>;
expect(row.employeeLabel).toBe("Alex Doe");
expect(row.kindLabelKey).toBe("hr.requests.kind.training");
expect(row.statusLabelKey).toBe("hr.requests.status.submitted");
// The approver row carries only the derived keys, not the raw unions.
expect(row).not.toHaveProperty("kind");
expect(row).not.toHaveProperty("status");
});
it("keeps an empty approver list in a ready state", () => {
const vm = buildHrRequestApproverVM({ rows: [] });
expect(vm.status).toBe("ready");
expect(vm.data?.emptyHeadlineKey).toBe("hr.requests.approver.empty.headline");
});
});
describe("buildHrRequestTemplateListVM", () => {
it("maps the template kind to its i18n key and keeps the active flag", () => {
const vm = buildHrRequestTemplateListVM({
rows: [{ id: "t1", title: "Expense claim", kind: "expense", description: null, isActive: true, editHref: "/x" }],
createHref: "/acme/hr/requests/templates/new",
});
expect(vm.data?.rows[0]?.kindLabelKey).toBe("hr.requests.kind.expense");
expect(vm.data?.rows[0]?.isActive).toBe(true);
expect(vm.data?.rows[0]?.description).toBeNull();
expect(vm.data?.createHref).toBe("/acme/hr/requests/templates/new");
expect(vm.data?.emptyHeadlineKey).toBe("hr.requests.templates.empty.headline");
});
});
@@ -58,10 +58,19 @@ export interface HrRequestTemplateRow {
readonly description: string | null;
readonly isActive: boolean;
readonly editHref: string;
/** Resolved name of the linked M05 form (AK-P16c reuse), null when unlinked. */
readonly linkedFormLabel: string | null;
}
/** A published `hr_request` form the admin can link to a template (M05 reuse). */
export interface HrLinkableFormOption {
readonly id: string;
readonly label: string;
}
export interface HrRequestTemplateListData {
readonly rows: readonly HrRequestTemplateRow[];
readonly linkableForms: readonly HrLinkableFormOption[];
readonly createHref: string;
readonly emptyHeadlineKey: string;
readonly emptyBodyKey: string;
@@ -114,9 +123,27 @@ interface TemplateInputRow {
readonly description: string | null;
readonly isActive: boolean;
readonly editHref: string;
readonly linkedFormLabel?: string | null;
}
export function buildHrRequestTemplateListVM(input: { rows: readonly TemplateInputRow[]; createHref: string }): HrRequestTemplateListVM {
const rows: HrRequestTemplateRow[] = input.rows.map((row) => ({ ...row, kindLabelKey: `hr.requests.kind.${row.kind}` }));
return { status: "ready", data: { rows, createHref: input.createHref, emptyHeadlineKey: "hr.requests.templates.empty.headline", emptyBodyKey: "hr.requests.templates.empty.body" } };
export function buildHrRequestTemplateListVM(input: {
rows: readonly TemplateInputRow[];
createHref: string;
linkableForms?: readonly HrLinkableFormOption[];
}): HrRequestTemplateListVM {
const rows: HrRequestTemplateRow[] = input.rows.map((row) => ({
...row,
kindLabelKey: `hr.requests.kind.${row.kind}`,
linkedFormLabel: row.linkedFormLabel ?? null,
}));
return {
status: "ready",
data: {
rows,
linkableForms: input.linkableForms ?? [],
createHref: input.createHref,
emptyHeadlineKey: "hr.requests.templates.empty.headline",
emptyBodyKey: "hr.requests.templates.empty.body",
},
};
}
@@ -0,0 +1,74 @@
import { describe, expect, it } from "vitest";
import { buildHrSickOwnVM, buildHrSickOfficeVM, type HrSickLeaveInputRow } from "./hr-sickleave.vm.js";
// AK-P17b — sick-leave VMs are pure and carry the AU-certificate "never leak the
// file id/ciphertext" contract. These tests lock that contract plus the
// status-derived close/cancel flags and the status → i18n-key mapping.
const row = (overrides: Partial<HrSickLeaveInputRow> = {}): HrSickLeaveInputRow => ({
id: "s1",
status: "reported",
startDateIso: "2026-07-01",
expectedReturnDateIso: "2026-07-04",
returnDateIso: null,
note: null,
hasCertificate: false,
revealHref: "/acme/hr/sick/s1/certificate",
...overrides,
});
describe("buildHrSickOwnVM", () => {
it("never exposes the certificate id or ciphertext, only the presence flag", () => {
const vm = buildHrSickOwnVM({ rows: [row({ hasCertificate: true })], canReport: true });
const data = vm.data!.rows[0]! as unknown as Record<string, unknown>;
expect(data).not.toHaveProperty("certificateFileId");
expect(data).not.toHaveProperty("certificateRefCiphertext");
expect(data.hasCertificate).toBe(true);
expect(data.revealHref).toBe("/acme/hr/sick/s1/certificate");
});
it("maps each status to its i18n key", () => {
const vm = buildHrSickOwnVM({
rows: [row(), row({ id: "s2", status: "closed" }), row({ id: "s3", status: "cancelled" })],
canReport: false,
});
expect(vm.data?.rows[0]?.statusLabelKey).toBe("hr.sick.status.reported");
expect(vm.data?.rows[1]?.statusLabelKey).toBe("hr.sick.status.closed");
expect(vm.data?.rows[2]?.statusLabelKey).toBe("hr.sick.status.cancelled");
});
it("derives close/cancel flags from the status", () => {
const vm = buildHrSickOwnVM({
rows: [row(), row({ id: "s2", status: "closed" }), row({ id: "s3", status: "cancelled" })],
canReport: true,
});
// reported → can close and cancel
expect(vm.data?.rows[0]?.canClose).toBe(true);
expect(vm.data?.rows[0]?.canCancel).toBe(true);
// closed → no close, cancel still possible
expect(vm.data?.rows[1]?.canClose).toBe(false);
expect(vm.data?.rows[1]?.canCancel).toBe(true);
// cancelled → terminal
expect(vm.data?.rows[2]?.canClose).toBe(false);
expect(vm.data?.rows[2]?.canCancel).toBe(false);
});
it("keeps an empty list in a ready state with the empty-state keys", () => {
const vm = buildHrSickOwnVM({ rows: [], canReport: true });
expect(vm.status).toBe("ready");
expect(vm.data?.canReport).toBe(true);
expect(vm.data?.emptyHeadlineKey).toBe("hr.sick.own.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.sick.own.empty.body");
});
});
describe("buildHrSickOfficeVM", () => {
it("adds the employee label while keeping the certificate contract", () => {
const vm = buildHrSickOfficeVM({ rows: [{ ...row({ hasCertificate: true }), employeeLabel: "Alex Doe" }] });
const data = vm.data!.rows[0]! as unknown as Record<string, unknown>;
expect(data.employeeLabel).toBe("Alex Doe");
expect(data).not.toHaveProperty("certificateFileId");
expect(data.hasCertificate).toBe(true);
expect(vm.data?.emptyHeadlineKey).toBe("hr.sick.office.empty.headline");
});
});
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vitest";
import { buildHrSurveyListVM, buildHrSurveyParticipationVM, buildHrSurveyResultsVM, type HrSurveyItemResult } from "./hr-survey.vm.js";
// AK-P17b — survey VMs are pure. These tests cover the status → i18n-key
// mapping, the anonymity hints and the results shape. Anonymous submissions are
// identified only via a submitter hash server-side; that hash must never reach
// the VM — the results carry aggregates only.
describe("buildHrSurveyListVM", () => {
const row = {
id: "sv1",
title: "Pulse check",
status: "open" as const,
isAnonymous: true,
hasSubmitted: false,
canViewResults: false,
participateHref: "/acme/hr/surveys/sv1",
resultsHref: "/acme/hr/surveys/sv1/results",
};
it("maps the survey status to its i18n key and keeps the flags", () => {
const vm = buildHrSurveyListVM({ rows: [row, { ...row, id: "sv2", status: "closed", hasSubmitted: true }], canManage: true, createHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.rows[0]?.statusLabelKey).toBe("hr.surveys.status.open");
expect(vm.data?.rows[1]?.statusLabelKey).toBe("hr.surveys.status.closed");
expect(vm.data?.rows[0]?.isAnonymous).toBe(true);
expect(vm.data?.rows[1]?.hasSubmitted).toBe(true);
});
it("keeps an empty list in a ready state with the empty-state keys", () => {
const vm = buildHrSurveyListVM({ rows: [], canManage: false, createHref: "/x" });
expect(vm.status).toBe("ready");
expect(vm.data?.emptyHeadlineKey).toBe("hr.surveys.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.surveys.empty.body");
});
});
describe("buildHrSurveyParticipationVM", () => {
it("maps item types to i18n keys and adds the anonymity/submitted hints", () => {
const vm = buildHrSurveyParticipationVM({
surveyId: "sv1",
title: "Pulse check",
description: null,
isAnonymous: true,
items: [
{ id: "i1", itemType: "rating_5", prompt: "How happy are you?", required: true, options: [] },
{ id: "i2", itemType: "choice", prompt: "Pick one", required: false, options: ["A", "B"] },
],
alreadySubmitted: false,
});
expect(vm.status).toBe("ready");
expect(vm.data?.items[0]?.typeLabelKey).toBe("hr.surveys.itemType.rating_5");
expect(vm.data?.items[1]?.typeLabelKey).toBe("hr.surveys.itemType.choice");
expect(vm.data?.items[1]?.options).toEqual(["A", "B"]);
expect(vm.data?.anonymousHintKey).toBe("hr.surveys.participation.anonymousHint");
expect(vm.data?.submittedHintKey).toBe("hr.surveys.participation.submittedHint");
});
it("carries the alreadySubmitted flag through unchanged", () => {
const vm = buildHrSurveyParticipationVM({ surveyId: "sv1", title: "T", description: "D", isAnonymous: false, items: [], alreadySubmitted: true });
expect(vm.data?.alreadySubmitted).toBe(true);
expect(vm.data?.isAnonymous).toBe(false);
});
});
describe("buildHrSurveyResultsVM", () => {
const itemResult: HrSurveyItemResult = {
itemId: "i1",
prompt: "How happy are you?",
itemType: "rating_5",
responseCount: 3,
distribution: { "4": 2, "5": 1 },
average: 4.33,
textResponses: [],
};
it("carries aggregates only and never a submitter hash or user id", () => {
const vm = buildHrSurveyResultsVM({ surveyId: "sv1", title: "Pulse check", submissionCount: 3, isAnonymous: true, items: [itemResult] });
expect(vm.status).toBe("ready");
const item = vm.data!.items[0]! as unknown as Record<string, unknown>;
// Never-leak contract: anonymous results expose no per-submitter identity.
expect(item).not.toHaveProperty("submitterHash");
expect(item).not.toHaveProperty("userId");
expect(item).not.toHaveProperty("submitterUserId");
expect(item.responseCount).toBe(3);
expect(item.distribution).toEqual({ "4": 2, "5": 1 });
expect(item.average).toBe(4.33);
});
it("keeps a zero-submission result in a ready state with the empty-state keys", () => {
const vm = buildHrSurveyResultsVM({ surveyId: "sv1", title: "T", submissionCount: 0, isAnonymous: false, items: [] });
expect(vm.status).toBe("ready");
expect(vm.data?.submissionCount).toBe(0);
expect(vm.data?.emptyHeadlineKey).toBe("hr.surveys.results.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.surveys.results.empty.body");
});
});
@@ -0,0 +1,69 @@
import { describe, expect, it } from "vitest";
import { buildHrReminderListVM, type HrReminderInputRow } from "./hr-upload-reminder.vm.js";
// AK-P17b — the upload-reminder admin list VM is pure. These tests cover the
// cadence/document-kind/audience/status → i18n-key mapping and the pass-through
// of interval, escalation and pending-count fields.
const row = (overrides: Partial<HrReminderInputRow> = {}): HrReminderInputRow => ({
id: "rem1",
title: "Renew first-aid certificate",
cadenceKind: "yearly",
intervalMonths: null,
documentKind: "certificate",
audienceKind: "all",
mandatory: true,
escalateToManager: false,
status: "active",
dueIso: "2026-09-01",
pendingCount: 5,
detailHref: "/acme/hr/reminders/rem1",
...overrides,
});
describe("buildHrReminderListVM", () => {
it("maps cadence, document kind, audience and status to i18n keys", () => {
const vm = buildHrReminderListVM({ rows: [row()], createHref: "/x" });
expect(vm.status).toBe("ready");
const built = vm.data!.rows[0]!;
expect(built.cadenceLabelKey).toBe("hr.reminders.cadence.yearly");
expect(built.documentKindKey).toBe("hr.document.kind.certificate");
expect(built.audienceLabelKey).toBe("hr.audience.all");
expect(built.statusLabelKey).toBe("hr.reminders.status.active");
});
it("derives the key for every cadence kind and status", () => {
const vm = buildHrReminderListVM({
rows: [
row({ id: "r1", cadenceKind: "once" }),
row({ id: "r2", cadenceKind: "every_n_months", intervalMonths: 6 }),
row({ id: "r3", cadenceKind: "on_expiry", status: "paused" }),
row({ id: "r4", status: "completed" }),
],
createHref: "/x",
});
expect(vm.data?.rows[0]?.cadenceLabelKey).toBe("hr.reminders.cadence.once");
expect(vm.data?.rows[1]?.cadenceLabelKey).toBe("hr.reminders.cadence.every_n_months");
expect(vm.data?.rows[1]?.intervalMonths).toBe(6);
expect(vm.data?.rows[2]?.cadenceLabelKey).toBe("hr.reminders.cadence.on_expiry");
expect(vm.data?.rows[2]?.statusLabelKey).toBe("hr.reminders.status.paused");
expect(vm.data?.rows[3]?.statusLabelKey).toBe("hr.reminders.status.completed");
});
it("carries mandatory/escalation flags and the pending count through unchanged", () => {
const vm = buildHrReminderListVM({ rows: [row({ escalateToManager: true, pendingCount: 0, dueIso: null })], createHref: "/x" });
const built = vm.data!.rows[0]!;
expect(built.mandatory).toBe(true);
expect(built.escalateToManager).toBe(true);
expect(built.pendingCount).toBe(0);
expect(built.dueIso).toBeNull();
});
it("keeps an empty reminder list in a ready state with the empty-state keys", () => {
const vm = buildHrReminderListVM({ rows: [], createHref: "/acme/hr/reminders/new" });
expect(vm.status).toBe("ready");
expect(vm.data?.createHref).toBe("/acme/hr/reminders/new");
expect(vm.data?.emptyHeadlineKey).toBe("hr.reminders.empty.headline");
expect(vm.data?.emptyBodyKey).toBe("hr.reminders.empty.body");
});
});