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
+2
-2
@@ -372,7 +372,7 @@ async function getFromRequest({ appConfiguration, request, userId }: { appConfig
|
||||
if (process.env.NODE_ENV === "development") {
|
||||
ip = "134.201.250.155";
|
||||
}
|
||||
const userAgent = request.headers.get("user-agent") ?? navigator.userAgent;
|
||||
const userAgent = request.headers.get("user-agent") ?? "";
|
||||
const httpReferrer = request.headers.get("referer")?.toString();
|
||||
const ref = searchParams.get("ref")?.toString();
|
||||
const via = searchParams.get("via")?.toString();
|
||||
@@ -397,7 +397,7 @@ async function getFromRequest({ appConfiguration, request, userId }: { appConfig
|
||||
|
||||
const analytics: AnalyticsInfoDto = {
|
||||
ip,
|
||||
userAgent: AnalyticsHelper.getUserAgentDetails(userAgent),
|
||||
userAgent: await AnalyticsHelper.getUserAgentDetails(userAgent),
|
||||
referrer: {
|
||||
http: httpReferrer,
|
||||
via,
|
||||
|
||||
+47
@@ -25,12 +25,16 @@ vi.mock("@hivegrid/db/auth-boundary.server", () => ({
|
||||
vi.mock("~/utils/services/.server/billingStatusService", () => ({
|
||||
getTenantBillingReadOnlyState: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/tenantDeletionStatusService", () => ({
|
||||
getTenantDeletionReadOnlyState: vi.fn(),
|
||||
}));
|
||||
|
||||
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
|
||||
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
|
||||
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { verifyUserHasPermission } from "./PermissionsService";
|
||||
@@ -62,6 +66,7 @@ describe("verifyUserHasPermission billing read-only guard", () => {
|
||||
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
|
||||
vi.mocked(userHasPermission).mockResolvedValue(true);
|
||||
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false, status: null });
|
||||
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValue({ readOnly: false, status: "none" });
|
||||
});
|
||||
|
||||
it("blocks mutating tenant requests when billing is read-only", async () => {
|
||||
@@ -89,3 +94,45 @@ describe("verifyUserHasPermission billing read-only guard", () => {
|
||||
expect(userHasPermission).toHaveBeenCalledWith("user-1", "tenant-1", "app.settings.subscription.update");
|
||||
});
|
||||
});
|
||||
|
||||
describe("verifyUserHasPermission deletion_pending read-only guard (AK-P21)", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getUserInfo).mockResolvedValue(userInfo);
|
||||
vi.mocked(getUser).mockResolvedValue(null);
|
||||
vi.mocked(getIsSuperAdminByUserId).mockResolvedValue(false);
|
||||
vi.mocked(getUserRoleInAdmin).mockResolvedValue(null);
|
||||
vi.mocked(getPermissionName).mockResolvedValue({ id: "perm-1", name: "tasks.create" } as never);
|
||||
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
|
||||
vi.mocked(userHasPermission).mockResolvedValue(true);
|
||||
// mockReset also drops un-consumed mockResolvedValueOnce queues from the
|
||||
// billing describe above (clearAllMocks alone keeps them).
|
||||
vi.mocked(getTenantBillingReadOnlyState).mockReset().mockResolvedValue({ readOnly: false, status: null });
|
||||
vi.mocked(getTenantDeletionReadOnlyState).mockReset().mockResolvedValue({ readOnly: false, status: "none" });
|
||||
});
|
||||
|
||||
it("blocks mutating tenant requests during the deletion grace window", async () => {
|
||||
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "pending" });
|
||||
|
||||
await expectStatus(verifyUserHasPermission(request("POST", "/acme/tasks/new"), "tasks.create", "tenant-1"), 423);
|
||||
|
||||
expect(getTenantDeletionReadOnlyState).toHaveBeenCalledWith("tenant-1");
|
||||
expect(userHasPermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps the privacy area writable so the deletion can be withdrawn", async () => {
|
||||
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValueOnce({ readOnly: true, status: "pending" });
|
||||
|
||||
await expect(
|
||||
verifyUserHasPermission(request("POST", "/acme/settings/privacy/deletion"), "privacy.tenant_deletion", "tenant-1")
|
||||
).resolves.toBe(true);
|
||||
|
||||
expect(getTenantDeletionReadOnlyState).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not run the deletion guard on read-only requests", async () => {
|
||||
await expect(verifyUserHasPermission(request("GET", "/acme/tasks"), "tasks.create", "tenant-1")).resolves.toBe(true);
|
||||
|
||||
expect(getTenantDeletionReadOnlyState).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/utils/db/permissions/permissions.db.server", () => ({ getPermissionName: vi.fn() }));
|
||||
vi.mock("~/utils/db/permissions/userRoles.db.server", () => ({
|
||||
findPermissionByUser: vi.fn(),
|
||||
userHasPermission: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/tenants.db.server", () => ({ getTenantMember: vi.fn() }));
|
||||
vi.mock("~/utils/session.server", () => ({ getUserInfo: vi.fn() }));
|
||||
vi.mock("~/utils/services/.server/billingStatusService", () => ({
|
||||
getTenantBillingReadOnlyState: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/services/.server/tenantDeletionStatusService", () => ({
|
||||
getTenantDeletionReadOnlyState: vi.fn(),
|
||||
}));
|
||||
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { findPermissionByUser, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
|
||||
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
|
||||
import { getUserPermission, verifyUserHasPermission } from "./PermissionsService";
|
||||
|
||||
describe("tenant authorization without platform-admin bypass", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(getPermissionName).mockResolvedValue({ id: "permission_1", name: "app.settings.members.view" } as never);
|
||||
vi.mocked(findPermissionByUser).mockResolvedValue(null);
|
||||
vi.mocked(userHasPermission).mockResolvedValue(false);
|
||||
vi.mocked(getUserInfo).mockResolvedValue({ userId: "user_1" } as never);
|
||||
vi.mocked(getTenantMember).mockResolvedValue({ status: TenantUserStatus.ACTIVE } as never);
|
||||
vi.mocked(getTenantBillingReadOnlyState).mockResolvedValue({ readOnly: false } as never);
|
||||
vi.mocked(getTenantDeletionReadOnlyState).mockResolvedValue({ readOnly: false, status: "none" });
|
||||
});
|
||||
|
||||
it("does not grant a tenant permission without a tenant role", async () => {
|
||||
await expect(
|
||||
getUserPermission({ userId: "user_1", permissionName: "app.settings.members.view", tenantId: "tenant_1" }),
|
||||
).resolves.toEqual({
|
||||
permission: { id: "permission_1", name: "app.settings.members.view" },
|
||||
userPermission: null,
|
||||
});
|
||||
|
||||
expect(findPermissionByUser).toHaveBeenCalledWith("app.settings.members.view", "user_1", "tenant_1");
|
||||
});
|
||||
|
||||
it("ignores retired platform role assignments when resolving tenant permissions", async () => {
|
||||
vi.mocked(findPermissionByUser).mockResolvedValue(null);
|
||||
|
||||
await expect(
|
||||
getUserPermission({ userId: "user_1", permissionName: "app.settings.members.view", tenantId: "tenant_1" }),
|
||||
).resolves.toEqual({
|
||||
permission: { id: "permission_1", name: "app.settings.members.view" },
|
||||
userPermission: null,
|
||||
});
|
||||
|
||||
expect(getPermissionName).toHaveBeenCalledWith("app.settings.members.view");
|
||||
expect(findPermissionByUser).toHaveBeenCalledWith("app.settings.members.view", "user_1", "tenant_1");
|
||||
});
|
||||
|
||||
it("denies an active staff user who lacks the requested tenant permission", async () => {
|
||||
await expect(
|
||||
verifyUserHasPermission(
|
||||
new Request("https://app.example.test/acme/settings/members"),
|
||||
"app.settings.members.view",
|
||||
"tenant_1",
|
||||
),
|
||||
).rejects.toMatchObject({ status: 302 });
|
||||
|
||||
expect(userHasPermission).toHaveBeenCalledWith("user_1", "tenant_1", "app.settings.members.view");
|
||||
});
|
||||
});
|
||||
+20
-17
@@ -24,15 +24,19 @@ vi.mock("~/utils/session.server", () => ({
|
||||
getUserInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/loaders.middleware", () => ({
|
||||
getIsSuperAdminByUserId: vi.fn(),
|
||||
vi.mock("~/utils/app/HostRouting.server", () => ({
|
||||
getHostRoutingContextFromRequest: vi.fn((request: Request) => (new URL(request.url).hostname.startsWith("admin.") ? "admin" : "app")),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({
|
||||
requireAdminIdentityPermission: vi.fn(),
|
||||
}));
|
||||
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import {
|
||||
buildPermissionDeniedUrl,
|
||||
@@ -44,7 +48,7 @@ import {
|
||||
const mocks = {
|
||||
getPermissionName: vi.mocked(getPermissionName),
|
||||
getTenantMember: vi.mocked(getTenantMember),
|
||||
getIsSuperAdminByUserId: vi.mocked(getIsSuperAdminByUserId),
|
||||
requireAdminIdentityPermission: vi.mocked(requireAdminIdentityPermission),
|
||||
getUserInfo: vi.mocked(getUserInfo),
|
||||
userHasPermission: vi.mocked(userHasPermission),
|
||||
};
|
||||
@@ -64,7 +68,7 @@ describe("verifyUserHasPermission", () => {
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_123" });
|
||||
mocks.getPermissionName.mockResolvedValue({ id: "perm_123", name: permissionName, description: "Dashboard" });
|
||||
mocks.getTenantMember.mockResolvedValue({ id: "tenant_user_123", status: TenantUserStatus.ACTIVE } as Awaited<ReturnType<typeof getTenantMember>>);
|
||||
mocks.getIsSuperAdminByUserId.mockResolvedValue(false);
|
||||
mocks.requireAdminIdentityPermission.mockResolvedValue({ adminUserId: "admin_123" } as never);
|
||||
mocks.userHasPermission.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
@@ -135,19 +139,18 @@ describe("verifyUserHasPermission", () => {
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("redirects denied admin permissions without tenant scope", async () => {
|
||||
mocks.userHasPermission.mockResolvedValue(false);
|
||||
it("delegates admin-host checks to dedicated AdminRBAC without reading tenant roles", async () => {
|
||||
await expect(verifyUserHasPermission(new Request("https://admin.example.com/users?jwt=secret"), "admin.users.view", null)).resolves.toBe(true);
|
||||
expect(mocks.requireAdminIdentityPermission).toHaveBeenCalledWith(expect.any(Request), "admin.users.view");
|
||||
expect(mocks.getUserInfo).not.toHaveBeenCalled();
|
||||
expect(mocks.userHasPermission).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
let location: string | null = null;
|
||||
try {
|
||||
await verifyUserHasPermission(new Request("https://admin.example.com/users?jwt=secret"), "admin.users.view", null);
|
||||
} catch (error) {
|
||||
location = await expectRedirect(error);
|
||||
}
|
||||
|
||||
expect(location).toBe("/unauthorized/admin.users.view?redirect=%2Fusers");
|
||||
expect(location).not.toContain("jwt=secret");
|
||||
expect(mocks.userHasPermission).toHaveBeenCalledWith("user_123", null, "admin.users.view");
|
||||
it("preserves the AdminRBAC 404 denial contract", async () => {
|
||||
mocks.requireAdminIdentityPermission.mockRejectedValueOnce(Response.json({}, { status: 404 }));
|
||||
await expect(verifyUserHasPermission(new Request("https://admin.example.com/users"), "admin.users.view", null)).rejects.toMatchObject({
|
||||
status: 404,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+37
-31
@@ -1,17 +1,19 @@
|
||||
import { redirect } from "react-router";
|
||||
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
|
||||
import { isAdminPermissionName } from "@hivegrid/db/admin-permissions";
|
||||
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
|
||||
import { TenantUserStatus } from "~/application/enums/tenants/TenantUserStatus";
|
||||
import { getPermissionName } from "~/utils/db/permissions/permissions.db.server";
|
||||
import { findPermissionByUser, getUserRoleInAdmin, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { findPermissionByUser, userHasPermission } from "~/utils/db/permissions/userRoles.db.server";
|
||||
import { getTenantMember } from "~/utils/db/tenants.db.server";
|
||||
import { getIsSuperAdminByUserId } from "~/utils/loaders.middleware";
|
||||
import { getUserInfo } from "~/utils/session.server";
|
||||
import { getAuthUserWithoutPasswordById as getUser } from "@hivegrid/db/auth-boundary.server";
|
||||
import { getTenantBillingReadOnlyState } from "~/utils/services/.server/billingStatusService";
|
||||
import { getTenantDeletionReadOnlyState } from "~/utils/services/.server/tenantDeletionStatusService";
|
||||
import { getHostRoutingContextFromRequest } from "~/utils/app/HostRouting.server";
|
||||
import { requireAdminIdentityPermission } from "~/services/admin/admin-identity.server";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
|
||||
const OPERATOR_ADMIN_BYPASS_DESCRIPTION = "Operator admin tenant permission bypass";
|
||||
const BILLING_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "billing:status.readOnly" } };
|
||||
const DELETION_READ_ONLY_MUTATION_ENVELOPE = { error: { code: "READ_ONLY", messageKey: "settings.privacy.deletion.readOnly" } };
|
||||
|
||||
function isMutatingRequest(request: Request): boolean {
|
||||
return !["GET", "HEAD", "OPTIONS"].includes(request.method.toUpperCase());
|
||||
@@ -22,34 +24,40 @@ export function isBillingReadOnlyBypassPath(requestUrl: string): boolean {
|
||||
return /\/settings\/subscription\/?$/.test(pathname);
|
||||
}
|
||||
|
||||
/**
|
||||
* AK-P21 — during the tenant-deletion grace window the privacy area stays
|
||||
* writable: admins must be able to withdraw the request and pull a GDPR
|
||||
* export; users must be able to manage their account deletion.
|
||||
*/
|
||||
export function isDeletionReadOnlyBypassPath(requestUrl: string): boolean {
|
||||
const pathname = new URL(requestUrl).pathname;
|
||||
return /\/settings\/privacy(\/|$)/.test(pathname);
|
||||
}
|
||||
|
||||
export async function assertTenantWritableForRequest(request: Request, tenantId: string | null) {
|
||||
if (!tenantId || !isMutatingRequest(request) || isBillingReadOnlyBypassPath(request.url)) {
|
||||
if (!tenantId || !isMutatingRequest(request)) {
|
||||
return;
|
||||
}
|
||||
const billingState = await getTenantBillingReadOnlyState(tenantId);
|
||||
if (billingState.readOnly) {
|
||||
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
|
||||
if (!isBillingReadOnlyBypassPath(request.url)) {
|
||||
const billingState = await getTenantBillingReadOnlyState(tenantId);
|
||||
if (billingState.readOnly) {
|
||||
throw Response.json(BILLING_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
|
||||
}
|
||||
}
|
||||
// AK-P21 deletion_pending read-only: reuse of the AK-P20 frozen mechanism.
|
||||
if (!isDeletionReadOnlyBypassPath(request.url)) {
|
||||
const deletionState = await getTenantDeletionReadOnlyState(tenantId);
|
||||
if (deletionState.readOnly) {
|
||||
throw Response.json(DELETION_READ_ONLY_MUTATION_ENVELOPE, { status: 423 });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function getUserPermission({ userId, permissionName, tenantId }: { userId: string; permissionName: string; tenantId?: string | null }) {
|
||||
if (tenantId) {
|
||||
const user = await getUser(userId);
|
||||
const isOperatorAdmin = !!user?.admin || (await getIsSuperAdminByUserId(userId)) || !!(await getUserRoleInAdmin(userId, DefaultAdminRoles.SuperAdmin));
|
||||
if (isOperatorAdmin) {
|
||||
return {
|
||||
permission: { id: "operator-admin-bypass", name: permissionName, description: OPERATOR_ADMIN_BYPASS_DESCRIPTION },
|
||||
userPermission: permissionName,
|
||||
};
|
||||
}
|
||||
}
|
||||
const permission = await getPermissionName(permissionName);
|
||||
if (!permission) {
|
||||
return { permission, userPermission: undefined };
|
||||
}
|
||||
if (tenantId && (await getIsSuperAdminByUserId(userId))) {
|
||||
return { permission, userPermission: permission.name };
|
||||
}
|
||||
// const userRoles = await getUserRoles(userId ?? undefined, tenantId ?? null);
|
||||
// let userPermission: Permission | undefined = undefined;
|
||||
// userRoles.forEach((userRole) => {
|
||||
@@ -102,6 +110,13 @@ export function shapePermissionCheckResult({
|
||||
}
|
||||
|
||||
export async function verifyUserHasPermission(request: Request, permissionName: DefaultPermission, tenantId: string | null = null) {
|
||||
if (getHostRoutingContextFromRequest(request) === "admin") {
|
||||
if (!isAdminPermissionName(permissionName)) {
|
||||
throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
}
|
||||
await requireAdminIdentityPermission(request, permissionName);
|
||||
return true;
|
||||
}
|
||||
// if (permissionName.startsWith("entity.")) {
|
||||
// return true;
|
||||
// }
|
||||
@@ -112,15 +127,6 @@ export async function verifyUserHasPermission(request: Request, permissionName:
|
||||
throw Error("Unauthorized");
|
||||
}
|
||||
await assertTenantWritableForRequest(request, tenantId);
|
||||
if (tenantId) {
|
||||
const user = await getUser(userInfo.userId);
|
||||
const isOperatorAdmin =
|
||||
!!user?.admin || (await getIsSuperAdminByUserId(userInfo.userId)) || !!(await getUserRoleInAdmin(userInfo.userId, DefaultAdminRoles.SuperAdmin));
|
||||
if (isOperatorAdmin) {
|
||||
shapePermissionCheckResult({ allowed: true, permissionName, tenantId });
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const permission = await getPermissionName(permissionName);
|
||||
if (!permission) {
|
||||
shapePermissionCheckResult({ allowed: false, permissionName, tenantId, reason: "permission-denied" });
|
||||
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
import { TFunction } from "i18next";
|
||||
import { EntityWithDetails } from "../../db/entities/entities.db.server";
|
||||
import { RowWithDetails, getRowById } from "../../db/entities/rows.db.server";
|
||||
import ApiHelper, { ApiFormatOptions } from "../ApiHelper";
|
||||
import RowHelper from "../RowHelper";
|
||||
import { getTenant } from "../../db/tenants.db.server";
|
||||
import { RowAsJson } from "../TemplateApiHelper";
|
||||
|
||||
async function fetchRowWithRelationships({
|
||||
rowId,
|
||||
scope,
|
||||
entities,
|
||||
processedRows = new Set<string>(),
|
||||
backlog = [], // This will be used to store the deferred relationships to be fetched later.
|
||||
}: {
|
||||
rowId: string;
|
||||
scope: { entityId?: string; tenantId: string | null };
|
||||
entities: EntityWithDetails[];
|
||||
processedRows?: Set<string>;
|
||||
backlog?: { rowId: string; relation: "parent" | "child"; attachTo: RowWithDetails; scope: { entityId?: string; tenantId: string | null } }[];
|
||||
}): Promise<RowWithDetails | null> {
|
||||
if (processedRows.has(rowId)) {
|
||||
return null;
|
||||
}
|
||||
processedRows.add(rowId);
|
||||
|
||||
const row = await getRowById(rowId, scope);
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fetch parent relationships.
|
||||
for (const parentRow of row.parentRows) {
|
||||
backlog.push({ rowId: parentRow.parent.id, relation: "parent", attachTo: row, scope: { entityId: parentRow.parent.entityId, tenantId: parentRow.parent.tenantId } });
|
||||
}
|
||||
|
||||
// Fetch child relationships.
|
||||
for (const childRow of row.childRows) {
|
||||
backlog.push({ rowId: childRow.child.id, relation: "child", attachTo: row, scope: { entityId: childRow.child.entityId, tenantId: childRow.child.tenantId } });
|
||||
}
|
||||
|
||||
// Process the backlog.
|
||||
while (backlog.length > 0) {
|
||||
const { rowId: backlogRowId, relation, attachTo, scope: backlogScope } = backlog.shift()!;
|
||||
if (relation === "parent") {
|
||||
const parent = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
|
||||
if (parent) {
|
||||
const parentRow = attachTo.parentRows.find((p) => p.parent.id === backlogRowId);
|
||||
if (parentRow) {
|
||||
parentRow.parent = parent;
|
||||
}
|
||||
}
|
||||
} else if (relation === "child") {
|
||||
const child = await fetchRowWithRelationships({ rowId: backlogRowId, scope: backlogScope, entities, processedRows, backlog });
|
||||
if (child) {
|
||||
const childRow = attachTo.childRows.find((c) => c.child.id === backlogRowId);
|
||||
if (childRow) {
|
||||
childRow.child = child;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
async function getRowInApiFormatWithRecursiveRelationships({
|
||||
entities,
|
||||
rowId,
|
||||
scope,
|
||||
t,
|
||||
options,
|
||||
}: {
|
||||
entities: EntityWithDetails[];
|
||||
rowId: string;
|
||||
scope: { entityId?: string; tenantId: string | null };
|
||||
t: TFunction;
|
||||
options: ApiFormatOptions;
|
||||
}): Promise<RowAsJson | null> {
|
||||
const row = await fetchRowWithRelationships({ rowId, scope, entities });
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
pruneDuplicateRows(row);
|
||||
const entity = entities.find((entity) => entity.id === row.entityId);
|
||||
if (!entity) {
|
||||
throw new Error(`Entity ${row.entityId} not found.`);
|
||||
}
|
||||
|
||||
const apiFormat = ApiHelper.getApiFormatWithRelationships({ entities, item: row, options });
|
||||
|
||||
return {
|
||||
id: row.id,
|
||||
name: RowHelper.getTextDescription({ entity, item: row, t }),
|
||||
entityId: entity.id,
|
||||
tenant: row.tenantId ? await getTenant(row.tenantId) : null,
|
||||
data: {
|
||||
[entity.name]: apiFormat,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function pruneDuplicateRows(mainRow: RowWithDetails): void {
|
||||
const seenRowIds: Set<string> = new Set();
|
||||
|
||||
let currentLevelRows: RowWithDetails[] = [mainRow];
|
||||
while (currentLevelRows.length > 0) {
|
||||
const nextLevelRows: RowWithDetails[] = [];
|
||||
|
||||
for (const row of currentLevelRows) {
|
||||
if (!row) continue;
|
||||
|
||||
// Process parent rows
|
||||
if (row.parentRows) {
|
||||
for (let i = row.parentRows.length - 1; i >= 0; i--) {
|
||||
const parent = row.parentRows[i].parent;
|
||||
if (seenRowIds.has(parent.id)) {
|
||||
row.parentRows.splice(i, 1); // Remove this parent
|
||||
} else {
|
||||
nextLevelRows.push(parent as RowWithDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process child rows
|
||||
if (row.childRows) {
|
||||
for (let i = row.childRows.length - 1; i >= 0; i--) {
|
||||
const child = row.childRows[i].child;
|
||||
if (seenRowIds.has(child.id)) {
|
||||
row.childRows.splice(i, 1); // Remove this child
|
||||
} else {
|
||||
nextLevelRows.push(child as RowWithDetails);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Mark the row as seen
|
||||
seenRowIds.add(row.id);
|
||||
}
|
||||
|
||||
// Move to the next level
|
||||
currentLevelRows = nextLevelRows;
|
||||
}
|
||||
}
|
||||
|
||||
export default {
|
||||
getRowInApiFormatWithRecursiveRelationships,
|
||||
};
|
||||
Reference in new issue
Block a user