381 lines
16 KiB
TypeScript
381 lines
16 KiB
TypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
const mocks = vi.hoisted(() => {
|
|
const tx = {
|
|
event: {
|
|
create: vi.fn(),
|
|
},
|
|
};
|
|
|
|
return {
|
|
tx,
|
|
db: {
|
|
$transaction: vi.fn(async (runner: (tx: unknown) => Promise<unknown>) => runner(tx)),
|
|
},
|
|
rows: {
|
|
buildLegacyRowPropertyFiltersWhere: vi.fn(() => ({})),
|
|
buildLegacyRowQueryWhere: vi.fn(() => ({})),
|
|
changeLegacyRowOrder: vi.fn(),
|
|
countLegacyRows: vi.fn(),
|
|
createRowWithValues: vi.fn(),
|
|
hardDeleteRowById: vi.fn(),
|
|
getLegacyRow: vi.fn(),
|
|
getLegacyRowById: vi.fn(),
|
|
listLegacyRows: vi.fn(),
|
|
updateRowWithValuesInTransaction: vi.fn(),
|
|
},
|
|
entities: {
|
|
getEntityByIdOrName: vi.fn(),
|
|
},
|
|
entityViews: {
|
|
getEntityViews: vi.fn(),
|
|
},
|
|
entityTags: {
|
|
createEntityTag: vi.fn(),
|
|
getEntityTag: vi.fn(),
|
|
getEntityTags: vi.fn(),
|
|
},
|
|
permissions: {
|
|
getEntityPermission: vi.fn((entity: { name: string }, name: string) => `${entity.name}.${name}`),
|
|
getRowPermissionsCondition: vi.fn(() => ({})),
|
|
getUserPermission: vi.fn(async () => ({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } })),
|
|
getUserRowPermission: vi.fn(async () => ({ canRead: true, canUpdate: true, canDelete: true })),
|
|
getRowPermissions: vi.fn(),
|
|
getUserRoleInTenant: vi.fn(),
|
|
},
|
|
pagination: {
|
|
getPaginationFromCurrentUrl: vi.fn(() => ({ page: 1, pageSize: 25, sortedBy: [] })),
|
|
getEntityFiltersFromCurrentUrl: vi.fn(() => ({ query: "" })),
|
|
},
|
|
rowFiltersHelper: {
|
|
getRowFiltersCondition: vi.fn(() => ({})),
|
|
},
|
|
logs: {
|
|
createManualRowLog: vi.fn(),
|
|
getRowLogs: vi.fn(),
|
|
},
|
|
rowComments: {
|
|
getRowComments: vi.fn(),
|
|
},
|
|
rowTasks: {
|
|
getAllRowTasks: vi.fn(),
|
|
getRowTasks: vi.fn(),
|
|
},
|
|
rowTags: {
|
|
createRowTag: vi.fn(),
|
|
deleteRowTags: vi.fn(),
|
|
getRowTagByIds: vi.fn(),
|
|
getRowTags: vi.fn(),
|
|
},
|
|
subscription: {
|
|
getPlanFeatureUsage: vi.fn(),
|
|
reportUsage: vi.fn(),
|
|
},
|
|
rowHelper: {
|
|
getTextDescription: vi.fn(() => "Contact row"),
|
|
getDiff: vi.fn(() => ({ firstName: { before: "Ada", after: "Grace" } })),
|
|
},
|
|
relationshipHelper: {
|
|
getInputType: vi.fn(),
|
|
},
|
|
media: {
|
|
storeRowMediaInStorageProvider: vi.fn(),
|
|
},
|
|
rowPermissionsApi: {
|
|
shareWithDefault: vi.fn(),
|
|
},
|
|
rowEventsHelper: {
|
|
getRowUserOrApiKey: vi.fn(async () => ({ user: null, apiKey: null })),
|
|
},
|
|
events: {
|
|
getDescription: vi.fn((event: string) => `${event} description`),
|
|
publishOutboxEvent: vi.fn(),
|
|
},
|
|
apiHelper: {
|
|
getApiFormat: vi.fn((entity: { name: string }, row: { id: string }) => ({ id: row.id, entity: entity.name })),
|
|
},
|
|
entityViewsApi: {
|
|
getCurrentEntityView: vi.fn(),
|
|
},
|
|
entitiesApi: {
|
|
fillSystemProperties: vi.fn(),
|
|
},
|
|
pluginHooks: {
|
|
emitPluginHookFireAndForget: vi.fn(),
|
|
},
|
|
rowSearchOutbox: {
|
|
emitRowSearchDelete: vi.fn(),
|
|
emitRowSearchUpsert: vi.fn(),
|
|
},
|
|
rowSearch: {
|
|
searchRows: vi.fn(),
|
|
},
|
|
crmContactSearch: {
|
|
searchCrmContacts: vi.fn(),
|
|
},
|
|
notifications: {
|
|
sendToRoles: vi.fn(),
|
|
},
|
|
eventWebhookAttempts: {
|
|
createEventWebhookAttempt: vi.fn(),
|
|
updateEventWebhookAttempt: vi.fn(),
|
|
},
|
|
logger: {
|
|
info: vi.fn(),
|
|
warn: vi.fn(),
|
|
error: vi.fn(),
|
|
},
|
|
};
|
|
});
|
|
|
|
vi.mock("@toolctrl/db/client.server", () => ({
|
|
getDbClient: () => mocks.db,
|
|
}));
|
|
|
|
vi.mock("~/utils/db.server", () => ({
|
|
db: mocks.db,
|
|
}));
|
|
|
|
vi.mock("@toolctrl/db/rows.server", () => mocks.rows);
|
|
vi.mock("~/utils/db/entities/entities.db.server", () => mocks.entities);
|
|
vi.mock("~/utils/db/entities/entityViews.db.server", () => mocks.entityViews);
|
|
vi.mock("../../db/entities/entityTags.db.server", () => mocks.entityTags);
|
|
vi.mock("../../helpers/PermissionsHelper", () => mocks.permissions);
|
|
vi.mock("../../helpers/.server/PermissionsService", () => mocks.permissions);
|
|
vi.mock("../../helpers/RowPaginationHelper", () => mocks.pagination);
|
|
vi.mock("~/utils/helpers/RowFiltersHelper", () => ({ default: mocks.rowFiltersHelper }));
|
|
vi.mock("~/application/Constants", () => ({ default: { DEFAULT_PAGE_SIZE: 25 } }));
|
|
vi.mock("../../db/logs.db.server", () => mocks.logs);
|
|
vi.mock("../../db/entities/rowComments.db.server", () => mocks.rowComments);
|
|
vi.mock("../../db/entities/rowTasks.db.server", () => mocks.rowTasks);
|
|
vi.mock("../../db/entities/rowTags.db.server", () => mocks.rowTags);
|
|
vi.mock("../../db/permissions/rowPermissions.db.server", () => mocks.permissions);
|
|
vi.mock("../../services/.server/subscriptionService", () => mocks.subscription);
|
|
vi.mock("i18next", () => ({ t: (key: string) => key }));
|
|
vi.mock("../../helpers/RowHelper", () => ({ default: mocks.rowHelper }));
|
|
vi.mock("../../helpers/RelationshipHelper", () => ({ default: mocks.relationshipHelper }));
|
|
vi.mock("~/utils/helpers/.server/MediaService", () => mocks.media);
|
|
vi.mock("./RowPermissionsApi", () => ({ RowPermissionsApi: mocks.rowPermissionsApi }));
|
|
vi.mock("../../helpers/RowEventsHelper", () => mocks.rowEventsHelper);
|
|
vi.mock("@toolctrl/db/outbox", () => ({ publishOutboxEvent: mocks.events.publishOutboxEvent }));
|
|
vi.mock("../../utils/EventUtils", () => ({ default: mocks.events }));
|
|
vi.mock("../../db/eventWebhookAttempts.db.server", () => mocks.eventWebhookAttempts);
|
|
vi.mock("~/modules/notifications/services/.server/NotificationService", () => ({ default: mocks.notifications }));
|
|
vi.mock("~/utils/url.server", () => ({
|
|
getAbsoluteApiUrl: vi.fn(() => "https://api.example.test/v1/events/webhooks/attempts/attempt_1"),
|
|
getBaseURL: vi.fn(() => "https://app.example.test"),
|
|
}));
|
|
vi.mock("~/utils/app/CanonicalUrlUtils", () => ({
|
|
adminPath: vi.fn((path: string) => `/admin/${path}`),
|
|
appPath: vi.fn(({ path }: { path: string }) => `/app/${path}`),
|
|
}));
|
|
vi.mock("~/utils/logger.server", () => ({
|
|
createScopedLogger: vi.fn(() => mocks.logger),
|
|
}));
|
|
vi.mock("../../helpers/ApiHelper", () => ({ default: mocks.apiHelper }));
|
|
vi.mock("./EntityViewsApi", () => ({ EntityViewsApi: mocks.entityViewsApi }));
|
|
vi.mock("./EntitiesApi", () => ({ EntitiesApi: mocks.entitiesApi }));
|
|
vi.mock("~/utils/db/permissions/userRoles.db.server", () => mocks.permissions);
|
|
vi.mock("~/modules/plugins/services/.server/pluginHookPublisher", () => mocks.pluginHooks);
|
|
vi.mock("@toolctrl/plugin-runtime", () => ({
|
|
PLUGIN_HOOK_ENTITY_CREATED: "entity.created",
|
|
PLUGIN_HOOK_ENTITY_DELETED: "entity.deleted",
|
|
PLUGIN_HOOK_ENTITY_UPDATED: "entity.updated",
|
|
}));
|
|
vi.mock("~/modules/rows/services/rowSearchOutbox.server", () => mocks.rowSearchOutbox);
|
|
vi.mock("~/modules/rows/services/rowSearch.server", () => mocks.rowSearch);
|
|
vi.mock("~/modules/crm/services/crmContactSearch.server", () => mocks.crmContactSearch);
|
|
|
|
import { RowApiError, RowsApi } from "./RowsApi";
|
|
|
|
const entity = {
|
|
id: "entity_contact",
|
|
name: "contact",
|
|
slug: "contacts",
|
|
title: "Contact",
|
|
defaultVisibility: "private",
|
|
properties: [],
|
|
parentEntities: [],
|
|
childEntities: [],
|
|
};
|
|
|
|
function row(id: string, patch: Record<string, unknown> = {}) {
|
|
return {
|
|
id,
|
|
entityId: entity.id,
|
|
tenantId: "tenant_1",
|
|
createdByUserId: "user_1",
|
|
createdByApiKeyId: null,
|
|
values: [],
|
|
parentRows: [],
|
|
childRows: [],
|
|
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
|
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
|
...patch,
|
|
};
|
|
}
|
|
|
|
describe("RowsApi workflow row events", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.db.$transaction.mockImplementation(async (runner: (tx: unknown) => Promise<unknown>) => runner(mocks.tx));
|
|
mocks.tx.event.create.mockImplementation(async ({ data }: { data: Record<string, unknown> }) => ({
|
|
id: `event_${mocks.tx.event.create.mock.calls.length}`,
|
|
...data,
|
|
}));
|
|
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
|
|
mocks.subscription.getPlanFeatureUsage.mockResolvedValue(null);
|
|
mocks.permissions.getUserPermission.mockResolvedValue({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } });
|
|
mocks.permissions.getUserRowPermission.mockResolvedValue({ canRead: true, canUpdate: true, canDelete: true });
|
|
mocks.entityViews.getEntityViews.mockResolvedValue([]);
|
|
mocks.entityViewsApi.getCurrentEntityView.mockResolvedValue(null);
|
|
mocks.entityTags.getEntityTags.mockResolvedValue([]);
|
|
mocks.rows.listLegacyRows.mockResolvedValue([]);
|
|
mocks.rows.countLegacyRows.mockResolvedValue(0);
|
|
});
|
|
|
|
it("publishes tenant-scoped workflow outbox events for row create, update, and delete", async () => {
|
|
const created = row("row_created");
|
|
const beforeUpdate = row("row_updated", { values: [{ id: "value_before" }] });
|
|
const afterUpdate = row("row_updated", { values: [{ id: "value_after" }] });
|
|
const deleted = row("row_deleted");
|
|
const rowsById = new Map([
|
|
[created.id, created],
|
|
[beforeUpdate.id, beforeUpdate],
|
|
[deleted.id, deleted],
|
|
]);
|
|
const request = new Request("https://app.example.test/app/acme/contacts");
|
|
|
|
mocks.rows.createRowWithValues.mockResolvedValue({ id: created.id });
|
|
mocks.rows.getLegacyRowById.mockImplementation(async (id: string) => rowsById.get(id) ?? null);
|
|
mocks.rows.updateRowWithValuesInTransaction.mockResolvedValue(afterUpdate);
|
|
mocks.rows.hardDeleteRowById.mockResolvedValue(deleted);
|
|
|
|
await RowsApi.create({ entity, tenantId: "tenant_1", userId: "user_1", request, rowValues: { dynamicProperties: [] } });
|
|
await RowsApi.update(beforeUpdate.id, { entity, tenantId: "tenant_1", userId: "user_1", request, rowValues: { dynamicProperties: [] } });
|
|
await RowsApi.del(deleted.id, { entity, tenantId: "tenant_1", userId: "user_1", request });
|
|
|
|
expect(mocks.events.publishOutboxEvent).toHaveBeenCalledTimes(3);
|
|
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(1, mocks.tx, {
|
|
tenantId: "tenant_1",
|
|
type: "workflow.trigger.event",
|
|
payload: expect.objectContaining({ event: "row.created", userId: "user_1" }),
|
|
dispatchKey: "workflow-trigger:event_1",
|
|
});
|
|
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(2, mocks.tx, {
|
|
tenantId: "tenant_1",
|
|
type: "workflow.trigger.event",
|
|
payload: expect.objectContaining({ event: "row.updated", userId: "user_1" }),
|
|
dispatchKey: "workflow-trigger:event_2",
|
|
});
|
|
expect(mocks.events.publishOutboxEvent).toHaveBeenNthCalledWith(3, mocks.tx, {
|
|
tenantId: "tenant_1",
|
|
type: "workflow.trigger.event",
|
|
payload: expect.objectContaining({ event: "row.deleted", userId: "user_1" }),
|
|
dispatchKey: "workflow-trigger:event_3",
|
|
});
|
|
expect(mocks.tx.event.create).toHaveBeenCalledTimes(3);
|
|
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(1, expect.objectContaining({ data: expect.objectContaining({ name: "row.created", tenantId: "tenant_1", userId: "user_1" }) }));
|
|
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(2, expect.objectContaining({ data: expect.objectContaining({ name: "row.updated", tenantId: "tenant_1", userId: "user_1" }) }));
|
|
expect(mocks.tx.event.create).toHaveBeenNthCalledWith(3, expect.objectContaining({ data: expect.objectContaining({ name: "row.deleted", tenantId: "tenant_1", userId: "user_1" }) }));
|
|
expect(mocks.notifications.sendToRoles).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
it("does not publish duplicate workflow outbox events when row event creation is disabled", async () => {
|
|
const deleted = row("row_parent");
|
|
mocks.rows.getLegacyRowById.mockResolvedValue(deleted);
|
|
mocks.rows.hardDeleteRowById.mockResolvedValue(deleted);
|
|
|
|
await RowsApi.del(deleted.id, {
|
|
entity,
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
request: new Request("https://app.example.test/app/acme/contacts"),
|
|
options: { createEvent: false },
|
|
});
|
|
|
|
expect(mocks.tx.event.create).not.toHaveBeenCalled();
|
|
expect(mocks.events.publishOutboxEvent).not.toHaveBeenCalled();
|
|
expect(mocks.notifications.sendToRoles).not.toHaveBeenCalled();
|
|
expect(mocks.rowSearchOutbox.emitRowSearchDelete).toHaveBeenCalledWith({ tenantId: "tenant_1", entity: { name: "contact" }, rowId: deleted.id });
|
|
});
|
|
});
|
|
|
|
describe("RowsApi row error codes", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
|
|
});
|
|
|
|
it("throws a stable code for denied row reads", async () => {
|
|
mocks.rows.getLegacyRow.mockResolvedValue(row("row_private"));
|
|
mocks.permissions.getUserRowPermission.mockResolvedValue({ canRead: false, canUpdate: false, canDelete: false });
|
|
|
|
try {
|
|
await RowsApi.get("row_private", { entity, tenantId: "tenant_1", userId: "user_2" });
|
|
throw new Error("Expected RowsApi.get to reject");
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(RowApiError);
|
|
expect(error).toMatchObject({ code: "row-access-denied", status: 403 });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("RowsApi CRM contact list search", () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
mocks.entities.getEntityByIdOrName.mockResolvedValue(entity);
|
|
mocks.permissions.getUserPermission.mockResolvedValue({ permission: { id: "permission_1" }, userPermission: { id: "user_permission_1" } });
|
|
mocks.entityViews.getEntityViews.mockResolvedValue([]);
|
|
mocks.entityViewsApi.getCurrentEntityView.mockResolvedValue(null);
|
|
mocks.pagination.getPaginationFromCurrentUrl.mockReturnValue({ page: 1, pageSize: 25, sortedBy: [] });
|
|
mocks.pagination.getEntityFiltersFromCurrentUrl.mockReturnValue({ query: "ada" });
|
|
mocks.permissions.getRowPermissionsCondition.mockResolvedValue({});
|
|
mocks.rowFiltersHelper.getRowFiltersCondition.mockReturnValue({});
|
|
mocks.rows.buildLegacyRowQueryWhere.mockReturnValue({ id: { in: ["contact_row_1"] } });
|
|
mocks.rows.listLegacyRows.mockResolvedValue([]);
|
|
mocks.rows.countLegacyRows.mockResolvedValue(0);
|
|
mocks.entityTags.getEntityTags.mockResolvedValue([]);
|
|
mocks.crmContactSearch.searchCrmContacts.mockResolvedValue({
|
|
hits: [{ id: "contact_row_1", firstName: "Ada", lastName: "Lovelace", email: "ada@example.test", company: "", jobTitle: "" }],
|
|
total: 1,
|
|
fellBack: false,
|
|
});
|
|
mocks.rowSearch.searchRows.mockResolvedValue({ hits: [{ id: "row_1", folio: 1, entityName: "company" }], total: 1, fellBack: false });
|
|
});
|
|
|
|
it("routes contact-list freetext through searchCrmContacts and keeps the legacy SQL hydration path", async () => {
|
|
await RowsApi.getAll({
|
|
entity,
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
urlSearchParams: new URLSearchParams("q=ada"),
|
|
});
|
|
|
|
expect(mocks.crmContactSearch.searchCrmContacts).toHaveBeenCalledWith({ tenantId: "tenant_1", query: "ada", limit: 1000 });
|
|
expect(mocks.rowSearch.searchRows).not.toHaveBeenCalled();
|
|
expect(mocks.rows.buildLegacyRowQueryWhere).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
rowWhere: { id: { in: ["contact_row_1"] } },
|
|
})
|
|
);
|
|
expect(mocks.rows.listLegacyRows).toHaveBeenCalled();
|
|
expect(mocks.rows.countLegacyRows).toHaveBeenCalled();
|
|
});
|
|
|
|
it("keeps non-contact freetext on the generic rows search helper", async () => {
|
|
const companyEntity = { ...entity, id: "entity_company", name: "company", slug: "companies", title: "Company" };
|
|
mocks.entities.getEntityByIdOrName.mockResolvedValue(companyEntity);
|
|
|
|
await RowsApi.getAll({
|
|
entity: companyEntity,
|
|
tenantId: "tenant_1",
|
|
userId: "user_1",
|
|
urlSearchParams: new URLSearchParams("q=ada"),
|
|
});
|
|
|
|
expect(mocks.rowSearch.searchRows).toHaveBeenCalledWith({ tenantId: "tenant_1", entityId: "entity_company", query: "ada", limit: 1000 });
|
|
expect(mocks.crmContactSearch.searchCrmContacts).not.toHaveBeenCalled();
|
|
});
|
|
});
|