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

@@ -17,10 +17,12 @@
// tenant-scoped, so it stays on the db singleton.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { logActivity } from "@hivegrid/activity";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import { db } from "~/utils/db.server";
import { withTenantRLS, type TenantRlsClient } from "~/utils/db/.server/tenantRls.server";
import { getHrFieldCrypto, type HrFieldCrypto } from "./hrFieldCrypto.server";
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
const HR_AUDIT_MODULE = "hr";
@@ -68,9 +70,9 @@ export type HrEmployeeProfileRow = {
updatedAt: Date;
};
/** Fields an employee may edit on their OWN profile (MA self-service). Everything
* else (personal number, hire date, manager, location) is HR-admin managed. */
const SELF_EDITABLE_FIELDS = ["position", "team"] as const;
/** Fields an employee may edit on their OWN profile (MA self-service). Team,
* personal number, hire date, manager and location are HR-managed assignments. */
const SELF_EDITABLE_FIELDS = ["position"] as const;
export type SelfEditableProfileInput = Partial<Pick<HrEmployeeProfileRow, (typeof SELF_EDITABLE_FIELDS)[number]>>;
/** Load a single employee profile (tenant-scoped), or null. */
@@ -100,6 +102,60 @@ export async function listDirectory(tenantId: string): Promise<DirectoryEntryRow
return rows;
}
/**
* Directory visibility for one viewer. HR readers see the full tenant;
* employees see only themselves and their direct reports. This is deliberately
* a server-side predicate so query-string filters cannot widen the audience.
*/
export async function listDirectoryForViewer(input: {
tenantId: string;
viewerUserId: string;
canReadAll: boolean;
}): Promise<DirectoryEntryRow[]> {
const rows = await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeProfile.findMany({
where: {
tenantId: input.tenantId,
...(input.canReadAll
? {}
: {
OR: [{ userId: input.viewerUserId }, { managerUserId: input.viewerUserId }],
}),
},
select: { userId: true, position: true, team: true, locationId: true, managerUserId: true },
orderBy: [{ team: "asc" }, { userId: "asc" }],
}),
);
return rows;
}
/** Fail closed when an employee target is outside self/direct-team/HR scope. */
export async function requireEmployeeObjectAccess(input: {
tenantId: string;
viewerUserId: string;
employeeUserId: string;
canReadAll: boolean;
}): Promise<{ isSelf: boolean; isDirectReport: boolean }> {
const isSelf = input.viewerUserId === input.employeeUserId;
if (isSelf) {
return { isSelf: true, isDirectReport: false };
}
const row = await withTenantRLS(input.tenantId, (tx) =>
tx.hrEmployeeProfile.findFirst({
where: {
tenantId: input.tenantId,
userId: input.employeeUserId,
...(input.canReadAll ? {} : { managerUserId: input.viewerUserId }),
},
select: { userId: true, managerUserId: true },
}),
);
if (!row) {
throw new CatalogError(foundationErrors.notFound, { userId: input.employeeUserId });
}
return { isSelf, isDirectReport: row.managerUserId === input.viewerUserId };
}
/** Upsert the caller's OWN profile, restricted to self-editable fields. */
export async function updateOwnProfile(input: { tenantId: string; userId: string; data: SelfEditableProfileInput }): Promise<void> {
const data: SelfEditableProfileInput = {};
@@ -431,6 +487,84 @@ export async function createDocument(input: CreateDocumentInput): Promise<HrEmpl
return created as HrEmployeeDocumentRow;
}
/**
* Atomically creates the HR document row and its Files ownership link after the
* object bytes have been accepted by the file service. Callers must hard-delete
* the newly-created File as compensation when this transaction fails.
*/
export async function createDocumentWithLink(input: CreateDocumentInput): Promise<HrEmployeeDocumentRow> {
const title = input.title.trim();
if (!title) {
throw new HrServiceError("hr.error.documentTitleRequired");
}
const created = await withTenantRLS(input.tenantId, async (tx) => {
const file = await tx.file.findFirst({
where: { id: input.fileId, tenantId: input.tenantId, archivedAt: null },
select: { id: true },
});
if (!file) {
throw new CatalogError(foundationErrors.notFound, { fileId: input.fileId });
}
const document = await tx.hrEmployeeDocument.create({
data: {
tenantId: input.tenantId,
employeeUserId: input.employeeUserId,
uploadedByUserId: input.uploadedByUserId,
title: title.slice(0, MAX_NAME_LENGTH),
documentKind: input.documentKind ?? "other",
fileId: input.fileId,
visibility: input.visibility ?? "employee",
uploadedByOffice: input.uploadedByOffice ?? false,
validUntil: input.validUntil ?? null,
isDemoData: input.isDemoData ?? false,
},
});
await tx.fileEntityLink.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.uploadedByUserId,
fileId: input.fileId,
entityType: "user",
entityId: input.employeeUserId,
linkRole: "hr_employee_document",
},
});
await logActivity(
{
tenantId: input.tenantId,
actorUserId: input.uploadedByUserId,
actorKind: "user",
activityType: "file_uploaded",
subjectType: "tenant",
subjectId: input.tenantId,
summaryText: "activity.runtime.hr.documentUploaded",
metadata: {
documentId: document.id,
employeeUserId: input.employeeUserId,
process: "hr_document",
},
},
{ client: tx },
);
return document as HrEmployeeDocumentRow;
});
await createAuditEvent({
tenantId: input.tenantId,
actorId: input.uploadedByUserId,
actorType: "user",
action: "HR_DOCUMENT_CREATE",
targetType: "HrEmployeeDocument",
targetId: created.id,
sourceModule: HR_AUDIT_MODULE,
outcome: "success",
metadata: {
employeeUserId: input.employeeUserId,
documentKind: created.documentKind,
},
});
return created;
}
/**
* Archive a document. An employee may only archive their OWN, non-office
* documents (office-uploaded = read-only). HR (viewerIsEmployee=false) may
@@ -467,6 +601,71 @@ export async function archiveDocument(input: {
export type LabeledUser = { id: string; label: string; email: string };
export type HrMemberOption = {
userId: string;
displayName: string;
email: string;
team: string | null;
position: string | null;
roleNames: string[];
};
/** Active tenant members for named employee/approver pickers. */
export async function listHrMemberOptions(tenantId: string): Promise<HrMemberOption[]> {
return withTenantRLS(tenantId, async (tx) => {
const [memberships, profiles, roles] = await Promise.all([
tx.tenantUser.findMany({
where: { tenantId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: {
userId: true,
user: { select: { firstName: true, lastName: true, email: true } },
},
orderBy: { user: { lastName: "asc" } },
}),
tx.hrEmployeeProfile.findMany({
where: { tenantId },
select: { userId: true, team: true, position: true },
}),
tx.userRole.findMany({
where: { tenantId },
select: { userId: true, role: { select: { name: true } } },
}),
]);
const profileByUser = new Map(profiles.map((profile) => [profile.userId, profile]));
const roleNamesByUser = new Map<string, string[]>();
for (const role of roles) {
const names = roleNamesByUser.get(role.userId) ?? [];
names.push(role.role.name);
roleNamesByUser.set(role.userId, names);
}
return memberships.map(({ userId, user }) => {
const profile = profileByUser.get(userId);
const name = `${user.firstName} ${user.lastName}`.trim();
return {
userId,
displayName: name || user.email,
email: user.email,
team: profile?.team ?? null,
position: profile?.position ?? null,
roleNames: roleNamesByUser.get(userId) ?? [],
};
});
});
}
/** Validates a posted picker target against the active tenant membership. */
export async function requireActiveHrMember(tenantId: string, userId: string): Promise<void> {
const member = await withTenantRLS(tenantId, (tx) =>
tx.tenantUser.findFirst({
where: { tenantId, userId, status: TenantUserStatus.ACTIVE, user: { active: true } },
select: { id: true },
}),
);
if (!member) {
throw new CatalogError(foundationErrors.notFound, { userId });
}
}
function userLabel(user: { firstName: string; lastName: string; email: string }): string {
const name = `${user.firstName} ${user.lastName}`.trim();
return name || user.email;