Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/db/src/rows.server.test.ts
T

1097 lines
44 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import {
buildLegacyReadableRowsWhere,
buildLegacyRowPropertyFiltersWhere,
changeLegacyRowOrder,
countLegacyRows,
createLegacyEntityRowInclude,
createLegacyRowDetailsInclude,
createLegacyEntityRow,
createRowWithValues,
deleteLegacyEntityRow,
deletedRowInclude,
findLegacyRelationshipRowById,
hardDeleteRowById,
getAllLegacyEntityRows,
getLegacyEntityRow,
getLegacyRow,
getLegacyRowById,
getLegacyWorkflowRowForRead,
legacyEntityRowInclude,
legacyRowDetailsInclude,
legacyWorkflowRowGetSelect,
listLegacyRows,
updateLegacyEntityRow,
type LegacyEntityRowCollectionClient,
type LegacyRelationshipRowReaderClient,
type LegacyRowReadClient,
type LegacyWorkflowRowGetClient,
type RowMutationClient,
updateRowWithValues,
} from "./rows.server.js";
import type { LegacyEntityWithDetails, LegacyPropertyWithDetails } from "./entities.server.js";
describe("legacy row read boundary", () => {
it("uses redacted API-key creator selects for all row read includes", () => {
const serializedInclude = JSON.stringify(legacyEntityRowInclude);
expect(legacyEntityRowInclude.createdByApiKey).toEqual({
select: {
id: true,
alias: true,
tenantId: true,
keyPrefix: true,
keyLastFour: true,
},
});
expect(serializedInclude).not.toContain('"key":true');
expect(serializedInclude).not.toContain("keyHash");
expect(serializedInclude).not.toContain("hashedAt");
});
it("counts rows with caller filters wrapped in the non-deleted guard", async () => {
const client = createRowReadClient({ count: 7 });
const where = { tenantId: "tenant_1", entityId: "entity_1" };
await expect(countLegacyRows({ where }, client)).resolves.toBe(7);
expect(client.row.count).toHaveBeenCalledWith({ where: { AND: [{ deletedAt: null }, where] } });
});
it("lists rows with pagination, ordering, caller filters, and tenant-scoped relationship include", async () => {
const rows = [rowDetailsFixture("row_1")];
const client = createRowReadClient({ findMany: rows });
const where = { tenantId: "tenant_1", OR: [{ entityId: "entity_1" }, { entity: { name: "contacts" } }] };
const orderBy = [{ createdAt: "desc" as const }];
await expect(listLegacyRows({ where, take: 25, skip: 50, orderBy, tenantId: "tenant_1" }, client)).resolves.toBe(rows);
expect(client.row.findMany).toHaveBeenCalledWith({
take: 25,
skip: 50,
where: { AND: [{ deletedAt: null }, where] },
include: createLegacyRowDetailsInclude("tenant_1"),
orderBy,
});
});
it("gets one entity row with caller access filters and tenant-scoped relationship include", async () => {
const row = rowDetailsFixture("row_1");
const client = createRowReadClient({ findFirst: row });
const where = { tenantId: "tenant_1", permissions: { some: { userId: "user_1" } } };
await expect(getLegacyRow({ entityId: "entity_1", id: "row_1", where, tenantId: "tenant_1" }, client)).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: { AND: [{ deletedAt: null }, { ...where, entityId: "entity_1", id: "row_1" }] },
include: createLegacyRowDetailsInclude("tenant_1"),
});
});
it("enforces tenant scope on single row reads when tenant id is provided separately", async () => {
const row = rowDetailsFixture("row_1");
const client = createRowReadClient({ findFirst: row });
await expect(getLegacyRow({ entityId: "entity_1", id: "row_1", where: { permissions: { some: { userId: "user_1" } } }, tenantId: "tenant_1" }, client)).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: { AND: [{ deletedAt: null }, { permissions: { some: { userId: "user_1" } }, entityId: "entity_1", id: "row_1", tenantId: "tenant_1" }] },
include: createLegacyRowDetailsInclude("tenant_1"),
});
});
it("filters nested related row includes by tenant and deletion state", () => {
const include = createLegacyRowDetailsInclude("tenant_1");
expect(include.parentRows).toMatchObject({
where: { parent: { tenantId: "tenant_1", deletedAt: null } },
include: {
parent: {
include: {
parentRows: { where: { parent: { tenantId: "tenant_1", deletedAt: null } } },
childRows: { where: { child: { tenantId: "tenant_1", deletedAt: null } } },
},
},
},
});
expect(include.childRows).toMatchObject({
where: { child: { tenantId: "tenant_1", deletedAt: null } },
include: {
child: {
include: {
parentRows: { where: { parent: { tenantId: "tenant_1", deletedAt: null } } },
childRows: { where: { child: { tenantId: "tenant_1", deletedAt: null } } },
},
},
},
});
});
it("gets a row by id with the deleted guard and returns null when missing", async () => {
const client = createRowReadClient({ findUnique: null });
await expect(getLegacyRowById("row_missing", client)).resolves.toBeNull();
expect(client.row.findUnique).toHaveBeenCalledWith({ where: { deletedAt: null, id: "row_missing" }, include: legacyRowDetailsInclude });
});
it("gets a row by id within explicit tenant scope", async () => {
const row = rowDetailsFixture("row_1");
const client = createRowReadClient({ findFirst: row });
await expect(getLegacyRowById("row_1", client, "tenant_1")).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: { id: "row_1", tenantId: "tenant_1", deletedAt: null },
include: createLegacyRowDetailsInclude("tenant_1"),
});
expect(client.row.findUnique).not.toHaveBeenCalled();
});
it("builds dynamic property filters for exact matching with AND/OR semantics", () => {
expect(
buildLegacyRowPropertyFiltersWhere([
{ property: { id: "prop_text", type: "TEXT" }, value: "alice", condition: "equals" },
{ property: { id: "prop_number", type: "NUMBER" }, value: "42", condition: "equals", match: "or" },
{ property: undefined, value: "ignored", condition: "equals" },
]),
).toEqual({
AND: [{ values: { some: { propertyId: "prop_text", textValue: { equals: "alice" } } } }],
OR: [{ values: { some: { propertyId: "prop_number", numberValue: { equals: 42 } } } }],
});
});
it("changes row order through the package-owned row transaction boundary", async () => {
const row = { ...rowDetailsFixture("row_1"), order: 3 };
const swapRow = { ...rowDetailsFixture("row_2"), order: 4 };
const client = createRowReadClient({ findFirst: [row, swapRow], findMany: [row] });
await expect(changeLegacyRowOrder({ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" }, "up", client)).resolves.toBeUndefined();
expect(client.row.findFirst).toHaveBeenNthCalledWith(1, {
where: { AND: [{ deletedAt: null }, { id: "row_1", entityId: "entity_1", tenantId: "tenant_1" }] },
include: legacyRowDetailsInclude,
});
expect(client.row.findFirst).toHaveBeenNthCalledWith(2, {
where: { AND: [{ deletedAt: null }, { entityId: row.entityId, tenantId: row.tenantId, order: 4 }] },
include: legacyRowDetailsInclude,
});
expect(client.$transaction).toHaveBeenCalledWith([expect.any(Promise), expect.any(Promise)]);
expect(client.row.update).toHaveBeenCalledWith({ where: { id: "row_1" }, data: { order: 4 } });
expect(client.row.update).toHaveBeenCalledWith({ where: { id: "row_2" }, data: { order: 3 } });
});
it("rejects row order changes outside the requested tenant and entity scope", async () => {
const client = createRowReadClient({ findFirst: null });
await expect(changeLegacyRowOrder({ id: "foreign_row", entityId: "entity_1", tenantId: "tenant_1" }, "up", client)).rejects.toThrow("Row not found");
expect(client.row.findFirst).toHaveBeenCalledWith({
where: { AND: [{ deletedAt: null }, { id: "foreign_row", entityId: "entity_1", tenantId: "tenant_1" }] },
include: legacyRowDetailsInclude,
});
expect(client.$transaction).not.toHaveBeenCalled();
});
});
describe("legacy relationship row reads", () => {
it("fetches the minimal row shape needed by relationship API routes", async () => {
const row = { id: "row_1", entityId: "entity_1", tenantId: "tenant_1" };
const client: LegacyRelationshipRowReaderClient = {
row: {
findFirst: vi.fn().mockResolvedValue(row),
},
};
await expect(findLegacyRelationshipRowById({ id: "row_1", tenantId: "tenant_1" }, client)).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: {
AND: [{ deletedAt: null }, { id: "row_1" }, { tenantId: "tenant_1" }],
},
select: {
id: true,
entityId: true,
tenantId: true,
},
});
});
it("treats explicit null tenant as a scoped relationship row lookup", async () => {
const row = { id: "row_1", entityId: "entity_1", tenantId: null };
const client: LegacyRelationshipRowReaderClient = {
row: {
findFirst: vi.fn().mockResolvedValue(row),
},
};
await expect(findLegacyRelationshipRowById({ id: "row_1", tenantId: null }, client)).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: {
AND: [{ deletedAt: null }, { id: "row_1" }, { tenantId: null }],
},
select: {
id: true,
entityId: true,
tenantId: true,
},
});
});
});
describe("legacy workflow rowGet reads", () => {
it("uses the shared tenant and row-permission read boundary for worker-native rowGet", async () => {
const row = workflowRowGetFixture("row_1");
const client = createWorkflowRowGetClient({ findFirst: row, userRoles: [{ roleId: "role_viewer" }], groups: [{ id: "group_ops" }] });
await expect(getLegacyWorkflowRowForRead({ entity: "contact", id: "row_1", tenantId: "tenant_1", userId: "user_1" }, client)).resolves.toBe(row);
expect(client.userRole.findMany).toHaveBeenCalledWith({ where: { userId: "user_1", tenantId: "tenant_1" }, select: { roleId: true } });
expect(client.group.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", OR: [{ createdByUserId: "user_1" }, { users: { some: { userId: "user_1" } } }] },
select: { id: true },
});
expect(client.row.findFirst).toHaveBeenCalledWith({
where: {
AND: [
{ deletedAt: null },
{
id: "row_1",
AND: [
{ OR: [{ entityId: "contact" }, { entity: { name: "contact" } }] },
{ OR: [{ tenantId: "tenant_1" }, { permissions: { some: { tenantId: "tenant_1" } } }] },
{
OR: [
{ permissions: { some: { tenantId: "tenant_1", access: { not: "none" } } } },
{ createdByUserId: "user_1" },
{ permissions: { some: { userId: "user_1", access: { not: "none" } } } },
{ permissions: { some: { roleId: "role_viewer", access: { not: "none" } } } },
{ permissions: { some: { groupId: "group_ops", access: { not: "none" } } } },
],
},
],
},
],
},
select: legacyWorkflowRowGetSelect,
});
});
it("builds a closed readable-row predicate when the caller has no matching role or group grants", async () => {
const client = createWorkflowRowGetClient({ findFirst: null, userRoles: [], groups: [] });
await expect(getLegacyWorkflowRowForRead({ entity: "contact", id: "row_blocked", tenantId: "tenant_1", userId: "user_1" }, client)).resolves.toBeNull();
expect(client.row.findFirst).toHaveBeenCalledWith(
expect.objectContaining({
where: expect.objectContaining({
AND: [
{ deletedAt: null },
expect.objectContaining({
id: "row_blocked",
AND: expect.arrayContaining([
{
OR: [
{ permissions: { some: { tenantId: "tenant_1", access: { not: "none" } } } },
{ createdByUserId: "user_1" },
{ permissions: { some: { userId: "user_1", access: { not: "none" } } } },
],
},
]),
}),
],
}),
})
);
});
it("can build readable-row filters for public row reads without a user", async () => {
const client = createWorkflowRowGetClient({ findFirst: null });
await expect(buildLegacyReadableRowsWhere({ tenantId: "tenant_1", includePublic: true }, client)).resolves.toEqual({
OR: [{ permissions: { some: { tenantId: "tenant_1", access: { not: "none" } } } }, { permissions: { some: { public: true } } }],
});
expect(client.userRole.findMany).not.toHaveBeenCalled();
expect(client.group.findMany).not.toHaveBeenCalled();
});
});
describe("legacy entity row collections", () => {
it("counts and reads a tenant-scoped non-deleted page ordered by newest rows", async () => {
const items = [rowFixture("row_1")];
const client = createRowCollectionClient({ count: 24, findMany: items });
await expect(
getAllLegacyEntityRows({ entityId: "entity_1", tenantId: "tenant_1", page: 2, pageSize: 10 }, client),
).resolves.toEqual({ page: 2, totalPages: 3, totalItems: 24, items });
expect(client.row.count).toHaveBeenCalledWith({ where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1" } });
expect(client.row.findMany).toHaveBeenCalledWith({
where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1" },
orderBy: { createdAt: "desc" },
skip: 10,
take: 10,
include: createLegacyEntityRowInclude("tenant_1"),
});
});
it("maps visible JSON payload fields and computes next folio and order before reloading the row", async () => {
const created = rowFixture("row_9");
const client = createRowCollectionClient({ folio: 7, order: 11, create: { id: "row_9" }, findUnique: created });
const entity = entityFixture([
propertyFixture("prop_text", "title"),
propertyFixture("prop_number", "amount"),
propertyFixture("prop_date", "dueDate"),
propertyFixture("prop_boolean", "enabled"),
propertyFixture("prop_multiple", "labels"),
propertyFixture("prop_range", "budget"),
propertyFixture("prop_media", "attachments"),
propertyFixture("prop_hidden", "secret", true),
]);
const dueDate = new Date("2026-02-03T00:00:00.000Z");
await expect(
createLegacyEntityRow(
{
entity,
tenantId: "tenant_1",
createdByUserId: "user_1",
createdByApiKeyId: "api_key_1",
data: {
title: "Acme",
amount: 42,
dueDate,
enabled: true,
labels: [{ order: 1, value: "vip" }],
budget: { numberMin: 10, numberMax: 20 },
attachments: [{ name: "contract.pdf", title: "Contract", type: "application/pdf", file: "uploads/contract.pdf", publicUrl: null }],
secret: "ignored",
},
},
client,
),
).resolves.toBe(created);
expect(client.row.aggregate).toHaveBeenNthCalledWith(1, { where: { tenantId: "tenant_1", entityId: "entity_1" }, _max: { folio: true } });
expect(client.row.aggregate).toHaveBeenNthCalledWith(2, { where: { tenantId: "tenant_1", entityId: "entity_1" }, _max: { order: true } });
expect(client.row.create).toHaveBeenCalledWith({
data: {
entityId: "entity_1",
tenantId: "tenant_1",
createdByUserId: "user_1",
createdByApiKeyId: "api_key_1",
folio: 8,
order: 12,
values: {
create: [
{ propertyId: "prop_text", textValue: "Acme" },
{ propertyId: "prop_number", numberValue: 42 },
{ propertyId: "prop_date", dateValue: dueDate },
{ propertyId: "prop_boolean", booleanValue: true },
{ propertyId: "prop_multiple", multiple: { create: [{ order: 1, value: "vip" }] } },
{ propertyId: "prop_range", range: { create: { numberMin: 10, numberMax: 20 } } },
{
propertyId: "prop_media",
media: { create: [{ name: "contract.pdf", title: "Contract", type: "application/pdf", file: "uploads/contract.pdf", publicUrl: null }] },
},
],
},
},
});
expect(client.row.findUnique).toHaveBeenCalledWith({ where: { id: "row_9", deletedAt: null }, include: legacyEntityRowInclude });
});
it("rejects create dynamic values for properties outside the scoped entity", async () => {
const client = createRowMutationClient({ propertyCount: 0 });
await expect(
createRowWithValues(
{
entityId: "entity_1",
data: {
tenantId: "tenant_1",
dynamicProperties: [{ propertyId: "foreign_property", textValue: "Acme" }],
},
},
client,
),
).rejects.toThrow("Invalid row property.");
expect(client.property.count).toHaveBeenCalledWith({
where: {
id: { in: ["foreign_property"] },
entityId: "entity_1",
OR: [{ tenantId: null }, { tenantId: "tenant_1" }],
},
});
expect(client.row.create).not.toHaveBeenCalled();
});
it("rejects invalid array, range, and media payloads before creating malformed values", async () => {
const invalidPayloads = [
{ labels: [{ order: "1", value: "vip" }] },
{ budget: { numberMin: 1, unexpected: 2 } },
{ attachments: [{ name: "contract.pdf", type: "application/pdf", file: "uploads/contract.pdf" }] },
];
for (const data of invalidPayloads) {
const client = createRowCollectionClient({ folio: 0, order: 0 });
await expect(createLegacyEntityRow({ entity: entityFixture([propertyFixture("prop", Object.keys(data)[0])]), tenantId: "tenant_1", data }, client)).rejects.toThrow(
/Invalid value for property/,
);
expect(client.row.create).not.toHaveBeenCalled();
}
});
it("throws a stable error when the created row cannot be reloaded", async () => {
const client = createRowCollectionClient({ folio: null, order: null, create: { id: "row_missing" }, findUnique: null });
await expect(createLegacyEntityRow({ entity: entityFixture([propertyFixture("prop_text", "title")]), tenantId: null, data: { title: "Acme" } }, client)).rejects.toThrow(
"Created row row_missing could not be reloaded",
);
expect(client.row.findUnique).toHaveBeenCalledWith({ where: { id: "row_missing", deletedAt: null }, include: legacyEntityRowInclude });
});
it("gets one tenant-scoped non-deleted row with the full legacy include", async () => {
const row = rowFixture("row_1");
const client = createRowCollectionClient({ findFirst: row });
await expect(getLegacyEntityRow({ entityId: "entity_1", tenantId: "tenant_1", rowId: "row_1" }, client)).resolves.toBe(row);
expect(client.row.findFirst).toHaveBeenCalledWith({
where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1", id: "row_1" },
include: createLegacyEntityRowInclude("tenant_1"),
});
});
it("updates only visible submitted values after verifying row scope", async () => {
vi.useFakeTimers();
const now = new Date("2026-03-04T05:06:07.000Z");
vi.setSystemTime(now);
const updated = rowFixture("row_1");
const client = createRowCollectionClient({ findFirst: [rowFixture("row_1"), updated] });
const entity = entityFixture([propertyFixture("prop_text", "title"), propertyFixture("prop_hidden", "secret", true)]);
try {
await expect(updateLegacyEntityRow({ entity, tenantId: "tenant_1", rowId: "row_1", data: { title: "Updated", secret: "ignored" } }, client)).resolves.toBe(updated);
} finally {
vi.useRealTimers();
}
expect(client.row.findFirst).toHaveBeenNthCalledWith(1, { where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1", id: "row_1" }, include: createLegacyEntityRowInclude("tenant_1") });
expect(client.rowValue.deleteMany).toHaveBeenCalledWith({
where: { rowId: "row_1", propertyId: { in: ["prop_text"] }, row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null } },
});
expect(client.row.update).toHaveBeenCalledWith({
where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
data: { updatedAt: now, values: { create: [{ propertyId: "prop_text", textValue: "Updated" }] } },
});
expect(client.row.findFirst).toHaveBeenNthCalledWith(2, { where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1", id: "row_1" }, include: createLegacyEntityRowInclude("tenant_1") });
});
it("rejects invalid update payloads before deleting or creating values", async () => {
const client = createRowCollectionClient({ findFirst: rowFixture("row_1") });
await expect(
updateLegacyEntityRow({ entity: entityFixture([propertyFixture("prop_media", "attachments")]), tenantId: "tenant_1", rowId: "row_1", data: { attachments: [{ name: "bad" }] } }, client),
).rejects.toThrow(/Invalid value for property/);
expect(client.rowValue.deleteMany).not.toHaveBeenCalled();
expect(client.row.update).not.toHaveBeenCalled();
});
it("throws a stable error when updating a missing row", async () => {
const client = createRowCollectionClient({ findFirst: null });
await expect(updateLegacyEntityRow({ entity: entityFixture([propertyFixture("prop_text", "title")]), tenantId: "tenant_1", rowId: "row_missing", data: { title: "Updated" } }, client)).rejects.toThrow(
"Row row_missing not found",
);
expect(client.rowValue.deleteMany).not.toHaveBeenCalled();
expect(client.row.update).not.toHaveBeenCalled();
});
it("soft-deletes a tenant-scoped non-deleted row", async () => {
vi.useFakeTimers();
const now = new Date("2026-04-05T06:07:08.000Z");
vi.setSystemTime(now);
const client = createRowCollectionClient({ findFirst: rowFixture("row_1") });
try {
await expect(deleteLegacyEntityRow({ entityId: "entity_1", tenantId: "tenant_1", rowId: "row_1" }, client)).resolves.toBe("row_1");
} finally {
vi.useRealTimers();
}
expect(client.row.findFirst).toHaveBeenCalledWith({ where: { deletedAt: null, entityId: "entity_1", tenantId: "tenant_1", id: "row_1" }, include: createLegacyEntityRowInclude("tenant_1") });
expect(client.row.update).toHaveBeenCalledWith({ where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null }, data: { deletedAt: now } });
});
it("throws a stable error when deleting a missing row", async () => {
const client = createRowCollectionClient({ findFirst: null });
await expect(deleteLegacyEntityRow({ entityId: "entity_1", tenantId: "tenant_1", rowId: "row_missing" }, client)).rejects.toThrow("Row row_missing not found");
expect(client.row.update).not.toHaveBeenCalled();
});
});
describe("row mutation boundary", () => {
it("creates rows with dynamic values, relationships, explicit row input, and computed folio/order", async () => {
const client = createRowMutationClient({ folio: 4, order: 8, create: { id: "row_9" } });
const dueDate = new Date("2026-02-03T00:00:00.000Z");
await expect(
createRowWithValues(
{
entityId: "entity_1",
data: {
tenantId: "tenant_1",
createdByUserId: "user_1",
createdByApiKeyId: "api_key_1",
properties: { sampleCustomEntity: { create: { name: "custom" } } },
dynamicProperties: [
{ propertyId: "prop_text", textValue: "Acme" },
{ propertyId: "prop_number", numberValue: 42 },
{ propertyId: "prop_date", dateValue: dueDate },
{ propertyId: "prop_boolean", booleanValue: true },
{ propertyId: "prop_media", media: [{ name: "contract.pdf", title: "Contract", type: "application/pdf", file: "uploads/contract.pdf", publicUrl: null }] },
{ propertyId: "prop_multiple", multiple: [{ order: 1, value: "vip" }] },
{ propertyId: "prop_range", range: { numberMin: 10, numberMax: 20 } },
],
parentRows: [{ relationshipId: "rel_parent", parentId: "parent_1" }],
childRows: [{ relationshipId: "rel_child", childId: "child_1" }],
rowCreateInput: { createdByUserId: "row_input_user" },
},
},
client,
),
).resolves.toEqual({ id: "row_9" });
expect(client.row.aggregate).toHaveBeenNthCalledWith(1, { where: { tenantId: "tenant_1", entityId: "entity_1" }, _max: { folio: true } });
expect(client.row.aggregate).toHaveBeenNthCalledWith(2, { where: { tenantId: "tenant_1", entityId: "entity_1" }, _max: { order: true } });
expect(client.property.count).toHaveBeenCalledWith({
where: {
id: { in: ["prop_text", "prop_number", "prop_date", "prop_boolean", "prop_media", "prop_multiple", "prop_range"] },
entityId: "entity_1",
OR: [{ tenantId: null }, { tenantId: "tenant_1" }],
},
});
expect(client.row.create).toHaveBeenCalledWith({
data: {
folio: 5,
order: 9,
entityId: "entity_1",
tenantId: "tenant_1",
createdByUserId: "row_input_user",
createdByApiKeyId: "api_key_1",
sampleCustomEntity: { create: { name: "custom" } },
values: {
create: [
{ propertyId: "prop_text", textValue: "Acme", numberValue: undefined, dateValue: undefined, booleanValue: undefined },
{ propertyId: "prop_number", textValue: undefined, numberValue: 42, dateValue: undefined, booleanValue: undefined },
{ propertyId: "prop_date", textValue: undefined, numberValue: undefined, dateValue: dueDate, booleanValue: undefined },
{ propertyId: "prop_boolean", textValue: undefined, numberValue: undefined, dateValue: undefined, booleanValue: true },
{ propertyId: "prop_media", textValue: undefined, numberValue: undefined, dateValue: undefined, booleanValue: undefined, media: { create: [{ name: "contract.pdf", title: "Contract", type: "application/pdf", file: "uploads/contract.pdf", publicUrl: null }] } },
{ propertyId: "prop_multiple", textValue: undefined, numberValue: undefined, dateValue: undefined, booleanValue: undefined, multiple: { create: [{ order: 1, value: "vip" }] } },
{ propertyId: "prop_range", textValue: undefined, numberValue: undefined, dateValue: undefined, booleanValue: undefined, range: { create: { numberMin: 10, numberMax: 20, dateMin: undefined, dateMax: undefined } } },
],
},
parentRows: { create: [{ relationshipId: "rel_parent", parentId: "parent_1" }] },
childRows: { create: [{ relationshipId: "rel_child", childId: "child_1" }] },
},
});
expect(client.entityRelationship.findMany).toHaveBeenCalledWith({
where: { id: { in: ["rel_parent", "rel_child"] } },
select: { id: true, parentId: true, childId: true },
});
expect(client.entityRelationship.findUnique).not.toHaveBeenCalled();
expect(client.row.findMany).toHaveBeenCalledWith({
where: {
tenantId: "tenant_1",
deletedAt: null,
OR: [
{ id: "parent_1", entityId: "parent_entity" },
{ id: "child_1", entityId: "child_entity" },
],
},
select: { id: true, entityId: true, tenantId: true },
});
});
it("rejects create relationships that point outside the current tenant or entity", async () => {
const client = createRowMutationClient({ findFirst: null });
await expect(
createRowWithValues(
{
entityId: "entity_1",
data: {
tenantId: "tenant_1",
dynamicProperties: [],
parentRows: [{ relationshipId: "rel_parent", parentId: "foreign_parent" }],
},
},
client,
),
).rejects.toThrow("Related row not found.");
expect(client.row.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", deletedAt: null, OR: [{ id: "foreign_parent", entityId: "parent_entity" }] },
select: { id: true, entityId: true, tenantId: true },
});
expect(client.row.create).not.toHaveBeenCalled();
});
it("rejects create relationships that do not belong to the current entity side", async () => {
const client = createRowMutationClient({
entityRelationships: {
rel_parent: { id: "rel_parent", parentId: "parent_entity", childId: "other_entity" },
},
});
await expect(
createRowWithValues(
{
entityId: "entity_1",
data: {
tenantId: "tenant_1",
dynamicProperties: [],
parentRows: [{ relationshipId: "rel_parent", parentId: "parent_1" }],
},
},
client,
),
).rejects.toThrow("Invalid row relationship.");
expect(client.row.create).not.toHaveBeenCalled();
});
it("uses explicit folio and order without aggregate queries", async () => {
const client = createRowMutationClient({ create: { id: "row_10" } });
await createRowWithValues({ entityId: "entity_1", nextFolio: 20, nextOrder: 30, data: { tenantId: null, dynamicProperties: [] } }, client);
expect(client.row.aggregate).not.toHaveBeenCalled();
expect(client.row.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ folio: 20, order: 30 }) }));
});
it("replaces update relationships and dynamic value children before reloading", async () => {
const updated = rowDetailsFixture("row_1");
const client = createRowMutationClient({
findFirst: [rowFixture("row_1"), updated],
});
await expect(
updateRowWithValues(
{ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" },
{
properties: { order: 12 },
dynamicProperties: [{ id: "value_1", propertyId: "prop_text", textValue: "Updated" }, { propertyId: "prop_new", numberValue: 10 }],
parentRows: [{ relationshipId: "rel_parent", parentId: "parent_1" }],
childRows: [{ relationshipId: "rel_child", childId: "child_1" }],
rowUpdateInput: { folio: 44 },
},
client,
),
).resolves.toBe(updated);
expect(client.rowRelationship.deleteMany).toHaveBeenNthCalledWith(1, {
where: {
childId: "row_1",
child: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
parent: { tenantId: "tenant_1", deletedAt: null },
},
});
expect(client.rowRelationship.deleteMany).toHaveBeenNthCalledWith(2, {
where: {
parentId: "row_1",
parent: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
});
expect(client.rowMedia.deleteMany).toHaveBeenCalledWith({ where: { rowValue: { rowId: "row_1", propertyId: { in: ["prop_text", "prop_new"] }, row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null } } } });
expect(client.rowValueMultiple.deleteMany).toHaveBeenCalledWith({ where: { rowValue: { rowId: "row_1", propertyId: { in: ["prop_text", "prop_new"] }, row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null } } } });
expect(client.rowValueRange.deleteMany).toHaveBeenCalledWith({ where: { rowValue: { rowId: "row_1", propertyId: { in: ["prop_text", "prop_new"] }, row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null } } } });
expect(client.rowValue.count).toHaveBeenCalledWith({
where: {
id: { in: ["value_1"] },
rowId: "row_1",
row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
},
});
expect(client.property.count).toHaveBeenCalledWith({
where: {
id: { in: ["prop_text", "prop_new"] },
entityId: "entity_1",
OR: [{ tenantId: null }, { tenantId: "tenant_1" }],
},
});
expect(client.row.update).toHaveBeenCalledWith({
where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
data: expect.objectContaining({
order: 12,
folio: 44,
parentRows: { create: [{ relationshipId: "rel_parent", parentId: "parent_1" }] },
childRows: { create: [{ relationshipId: "rel_child", childId: "child_1" }] },
}),
});
expect(client.row.findFirst).toHaveBeenLastCalledWith({
where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
include: createLegacyRowDetailsInclude("tenant_1"),
});
});
it("rejects update dynamic values for properties outside the scoped entity", async () => {
const client = createRowMutationClient({ findFirst: rowFixture("row_1"), propertyCount: 0 });
await expect(
updateRowWithValues(
{ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" },
{
dynamicProperties: [{ propertyId: "foreign_property", textValue: "Updated" }],
},
client,
),
).rejects.toThrow("Invalid row property.");
expect(client.property.count).toHaveBeenCalledWith({
where: {
id: { in: ["foreign_property"] },
entityId: "entity_1",
OR: [{ tenantId: null }, { tenantId: "tenant_1" }],
},
});
expect(client.rowValue.count).not.toHaveBeenCalled();
expect(client.row.update).not.toHaveBeenCalled();
});
it("rejects update relationships before deleting existing links when related rows are out of scope", async () => {
const client = createRowMutationClient({ findFirst: [rowFixture("row_1"), null] });
await expect(
updateRowWithValues(
{ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" },
{
dynamicProperties: [],
childRows: [{ relationshipId: "rel_child", childId: "foreign_child" }],
},
client,
),
).rejects.toThrow("Related row not found.");
expect(client.row.findFirst).toHaveBeenNthCalledWith(1, {
where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
select: { id: true, entityId: true, tenantId: true },
});
expect(client.row.findMany).toHaveBeenCalledWith({
where: { tenantId: "tenant_1", deletedAt: null, OR: [{ id: "foreign_child", entityId: "child_entity" }] },
select: { id: true, entityId: true, tenantId: true },
});
expect(client.rowRelationship.deleteMany).not.toHaveBeenCalled();
expect(client.row.update).not.toHaveBeenCalled();
});
it("rejects nested row value updates that are not owned by the scoped row", async () => {
const client = createRowMutationClient({ findFirst: rowFixture("row_1"), rowValueCount: 0 });
await expect(
updateRowWithValues(
{ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" },
{
dynamicProperties: [{ id: "foreign_value", propertyId: "prop_text", textValue: "Updated" }],
},
client,
),
).rejects.toThrow("Row value not found.");
expect(client.rowValue.count).toHaveBeenCalledWith({
where: {
id: { in: ["foreign_value"] },
rowId: "row_1",
row: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
},
});
expect(client.rowMedia.deleteMany).not.toHaveBeenCalled();
expect(client.rowValueMultiple.deleteMany).not.toHaveBeenCalled();
expect(client.rowValueRange.deleteMany).not.toHaveBeenCalled();
expect(client.row.update).not.toHaveBeenCalled();
});
it("throws a stable error when an updated row cannot be reloaded", async () => {
const client = createRowMutationClient({ findFirst: [rowFixture("row_missing"), null] });
await expect(updateRowWithValues({ id: "row_missing", entityId: "entity_1", tenantId: "tenant_1" }, { dynamicProperties: [] }, client)).rejects.toThrow("Updated row row_missing could not be reloaded");
});
it("runs relationship replacement and row updates inside one transaction", async () => {
const updateError = new Error("write failed");
const client = createRowMutationClient({ findFirst: [rowFixture("row_1"), { ...rowFixture("child_1"), entityId: "child_entity" }], updateError });
await expect(
updateRowWithValues(
{ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" },
{
dynamicProperties: [],
childRows: [{ relationshipId: "rel_child", childId: "child_1" }],
},
client,
),
).rejects.toThrow(updateError);
expect(client.$transaction).toHaveBeenCalledTimes(1);
expect(client.rowRelationship.deleteMany).toHaveBeenCalledWith({
where: {
parentId: "row_1",
parent: { entityId: "entity_1", tenantId: "tenant_1", deletedAt: null },
child: { tenantId: "tenant_1", deletedAt: null },
},
});
});
it("hard deletes rows with the legacy include shape", async () => {
const deleted = { ...rowFixture("row_1"), logs: [], values: [] };
const client = createRowMutationClient({ findFirst: deleted });
await expect(hardDeleteRowById({ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" }, client)).resolves.toBe(deleted);
expect(client.row.findFirst).toHaveBeenCalledWith({ where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null }, include: deletedRowInclude });
expect(client.row.deleteMany).toHaveBeenCalledWith({ where: { id: "row_1", entityId: "entity_1", tenantId: "tenant_1", deletedAt: null } });
});
});
function createRowReadClient({
count = 0,
findMany = [],
findFirst = null,
findUnique = null,
}: {
count?: number;
findMany?: unknown[];
findFirst?: unknown | unknown[];
findUnique?: unknown;
} = {}): LegacyRowReadClient {
const findFirstMock = vi.fn();
if (Array.isArray(findFirst)) {
for (const value of findFirst) {
findFirstMock.mockResolvedValueOnce(value);
}
} else {
findFirstMock.mockResolvedValue(findFirst);
}
const client = {
row: {
count: vi.fn().mockResolvedValue(count),
findMany: vi.fn().mockResolvedValue(findMany),
findFirst: findFirstMock,
findUnique: vi.fn().mockResolvedValue(findUnique),
update: vi.fn((args: { where: { id: string } }) => Promise.resolve({ id: `updated_${args.where.id}` })),
},
$transaction: vi.fn((queries: Promise<unknown>[]) => Promise.all(queries)),
} as unknown as LegacyRowReadClient;
return client;
}
function createRowMutationClient({
folio = null,
order = null,
create = { id: "created_row" },
findFirst = rowFixture("row_1"),
findUnique = null,
deleteResult = { ...rowFixture("deleted_row"), logs: [], values: [] },
entityRelationships = {
rel_parent: { id: "rel_parent", parentId: "parent_entity", childId: "entity_1" },
rel_child: { id: "rel_child", parentId: "entity_1", childId: "child_entity" },
},
propertyCount,
rowValueCount,
updateError,
relatedRows,
}: {
folio?: number | null;
order?: number | null;
create?: { id: string };
findFirst?: unknown | unknown[];
findUnique?: unknown;
deleteResult?: unknown;
entityRelationships?: Record<string, { id: string; parentId: string; childId: string }>;
propertyCount?: number;
rowValueCount?: number;
updateError?: Error;
relatedRows?: Array<{ id: string; entityId: string; tenantId: string | null }> | null;
} = {}): RowMutationClient {
const findFirstMock = vi.fn();
if (Array.isArray(findFirst)) {
for (const value of findFirst) {
findFirstMock.mockResolvedValueOnce(value);
}
} else {
findFirstMock.mockResolvedValue(findFirst);
}
const resolveRelatedRows = (where: { OR?: Array<{ id: string; entityId: string }>; tenantId?: string | null }) => {
if (relatedRows !== undefined) {
return relatedRows;
}
if (findFirst === null || (Array.isArray(findFirst) && findFirst.some((value) => value === null))) {
return [];
}
return (where.OR ?? []).map(({ id, entityId }) => ({
id,
entityId,
tenantId: where.tenantId ?? null,
}));
};
const client = {
row: {
aggregate: vi.fn().mockResolvedValueOnce({ _max: { folio } }).mockResolvedValueOnce({ _max: { order } }),
create: vi.fn().mockResolvedValue(create),
findFirst: findFirstMock,
findMany: vi.fn(({ where }: { where: { OR?: Array<{ id: string; entityId: string }>; tenantId?: string | null } }) => Promise.resolve(resolveRelatedRows(where))),
findUnique: vi.fn().mockResolvedValue(findUnique),
update: updateError ? vi.fn().mockRejectedValue(updateError) : vi.fn().mockResolvedValue({ id: "updated_row" }),
deleteMany: vi.fn().mockResolvedValue({ count: 1 }),
delete: vi.fn().mockResolvedValue(deleteResult),
},
entityRelationship: {
findMany: vi.fn(({ where }: { where: { id: { in: string[] } } }) => Promise.resolve(where.id.in.map((id) => entityRelationships[id]).filter(Boolean))),
findUnique: vi.fn(({ where }: { where: { id: string } }) => Promise.resolve(entityRelationships[where.id] ?? null)),
},
rowRelationship: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
rowMedia: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
rowValue: {
count: vi.fn(({ where }: { where: { id?: { in?: unknown[] } } }) => Promise.resolve(rowValueCount ?? where.id?.in?.length ?? 0)),
},
property: {
count: vi.fn(({ where }: { where: { id?: { in?: unknown[] } } }) => Promise.resolve(propertyCount ?? where.id?.in?.length ?? 0)),
},
rowValueMultiple: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
rowValueRange: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
$transaction: vi.fn((fn: (tx: RowMutationClient) => Promise<unknown>) => fn(client as unknown as RowMutationClient)),
} as unknown as RowMutationClient;
return client;
}
function createRowCollectionClient({
count = 0,
findMany = [],
folio = null,
order = null,
create = { id: "created_row" },
findFirst = null,
findUnique = null,
}: {
count?: number;
findMany?: unknown[];
folio?: number | null;
order?: number | null;
create?: { id: string };
findFirst?: unknown | unknown[];
findUnique?: unknown;
} = {}): LegacyEntityRowCollectionClient {
const findFirstMock = vi.fn();
if (Array.isArray(findFirst)) {
for (const value of findFirst) {
findFirstMock.mockResolvedValueOnce(value);
}
} else {
findFirstMock.mockResolvedValue(findFirst);
}
return {
row: {
count: vi.fn().mockResolvedValue(count),
findMany: vi.fn().mockResolvedValue(findMany),
aggregate: vi.fn().mockResolvedValueOnce({ _max: { folio } }).mockResolvedValueOnce({ _max: { order } }),
create: vi.fn().mockResolvedValue(create),
findFirst: findFirstMock,
findUnique: vi.fn().mockResolvedValue(findUnique),
update: vi.fn().mockResolvedValue({ id: "updated_row" }),
},
rowValue: {
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
},
} as unknown as LegacyEntityRowCollectionClient;
}
function rowFixture(id: string) {
const now = new Date("2026-01-01T00:00:00.000Z");
return {
id,
createdAt: now,
updatedAt: now,
deletedAt: null,
entityId: "entity_1",
tenantId: "tenant_1",
folio: 1,
createdByUserId: null,
createdByApiKeyId: null,
order: 1,
createdByUser: null,
createdByApiKey: null,
values: [],
parentRows: [],
childRows: [],
};
}
function rowDetailsFixture(id: string) {
return {
...rowFixture(id),
tenant: null,
tags: [],
permissions: [],
sampleCustomEntity: null,
};
}
function workflowRowGetFixture(id: string) {
return {
id,
entityId: "entity_contact",
tenantId: "tenant_1",
folio: 1,
order: 1,
createdAt: new Date("2026-05-26T01:02:03.000Z"),
updatedAt: new Date("2026-05-26T02:03:04.000Z"),
values: [],
};
}
function createWorkflowRowGetClient({
findFirst,
userRoles = [],
groups = [],
}: {
findFirst: Awaited<ReturnType<LegacyWorkflowRowGetClient["row"]["findFirst"]>>;
userRoles?: Array<{ roleId: string }>;
groups?: Array<{ id: string }>;
}): LegacyWorkflowRowGetClient {
return {
row: {
findFirst: vi.fn().mockResolvedValue(findFirst),
},
userRole: {
findMany: vi.fn().mockResolvedValue(userRoles),
},
group: {
findMany: vi.fn().mockResolvedValue(groups),
},
};
}
function entityFixture(properties: LegacyPropertyWithDetails[]): LegacyEntityWithDetails {
return {
id: "entity_1",
properties,
} as LegacyEntityWithDetails;
}
function propertyFixture(id: string, name: string, isHidden = false): LegacyPropertyWithDetails {
return {
id,
name,
isHidden,
attributes: [],
options: [],
formula: null,
} as unknown as LegacyPropertyWithDetails;
}