Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/integrations.aircall-routing.test.ts
T

403 lines
17 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
context: {
tenantId: "tenant_1",
userId: "user_1",
permissions: ["integrations.read", "integrations.connect", "integrations.disconnect"],
hasModule: true,
},
loadIntegrationsContext: vi.fn(),
listConnections: vi.fn(),
createConnection: vi.fn(),
reconnectConnection: vi.fn(),
disconnectConnection: vi.fn(),
runSyncForConnection: vi.fn(),
getConnectionOrThrow: vi.fn(),
listSyncRuns: vi.fn(),
getSyncRunWithItems: vi.fn(),
hasKwpIntegrationModule: vi.fn(),
requireKwpIntegrationModule: vi.fn(),
validateCSRFToken: vi.fn(),
}));
vi.mock("~/components/screens/integrations/IntegrationsCatalogPage", () => ({
IntegrationsCatalogPage: () => null,
}));
vi.mock("~/components/screens/integrations/ConnectionDetailPage", () => ({
ConnectionDetailPage: () => null,
}));
vi.mock("~/components/ui/errors/ServerError", () => ({ default: () => null }));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: () => Promise.resolve({ t: (key: string) => key }),
}));
vi.mock("~/utils/integrations/integrationsAccess.server", () => ({
badRequestResponse: () => new Response("Bad Request", { status: 400 }),
integrationsActionErrorResponse: () => Response.json({ error: "integrations.errors.mutationFailed" }, { status: 400 }),
integrationsHasPermission: () => true,
loadIntegrationsContext: mocks.loadIntegrationsContext,
notFoundResponse: () => new Response("Not Found", { status: 404 }),
requireIntegrationsPermission: () => undefined,
}));
vi.mock("~/utils/integrations/appsEngineService.server", () => ({
createConnection: mocks.createConnection,
disconnectConnection: mocks.disconnectConnection,
getConnectionOrThrow: mocks.getConnectionOrThrow,
getSyncRunWithItems: mocks.getSyncRunWithItems,
listConnections: mocks.listConnections,
listSyncRuns: mocks.listSyncRuns,
reconnectConnection: mocks.reconnectConnection,
runSyncForConnection: mocks.runSyncForConnection,
}));
vi.mock("~/modules/kwp/routes/kwpAccess.server", () => ({
hasKwpIntegrationModule: mocks.hasKwpIntegrationModule,
requireKwpIntegrationModule: mocks.requireKwpIntegrationModule,
}));
vi.mock("~/utils/session.server", () => ({ validateCSRFToken: mocks.validateCSRFToken }));
import { loader as catalogLoader } from "./integrations._index";
import { action as appAction, loader as appLoader } from "./integrations.$app._index";
import { loader as syncHistoryLoader } from "./integrations.$app.$connectionId.syncs._index";
import { loader as syncRunDetailLoader } from "./integrations.$app.$connectionId.syncs.$runId";
beforeEach(() => {
vi.clearAllMocks();
mocks.loadIntegrationsContext.mockResolvedValue(mocks.context);
mocks.listConnections.mockResolvedValue([]);
mocks.createConnection.mockResolvedValue({ id: "connection_new" });
mocks.listSyncRuns.mockResolvedValue([]);
mocks.runSyncForConnection.mockResolvedValue({ runId: "run_1", status: "completed" });
mocks.hasKwpIntegrationModule.mockResolvedValue(true);
mocks.requireKwpIntegrationModule.mockImplementation(async (context: unknown) => context);
mocks.validateCSRFToken.mockResolvedValue(undefined);
});
describe("telephony integration routing", () => {
it("links the Aircall and HalloPetra catalog cards to the dedicated telephony settings", async () => {
const response = await catalogLoader({
request: new Request("https://app.example.test/acme/settings/integrations"),
params: { tenant: "acme" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations",
});
const body = (await response.json()) as {
vm: { status: string; data?: { rows: Array<{ key: string; detailHref: string }> } };
};
expect(body.vm.data?.rows.find((row) => row.key === "aircall")?.detailHref).toBe("/acme/settings/integrations/telephony");
expect(body.vm.data?.rows.find((row) => row.key === "hallopetra")?.detailHref).toBe("/acme/settings/integrations/telephony");
});
it("hides KWP from the catalog when the dedicated add-on is unavailable", async () => {
mocks.hasKwpIntegrationModule.mockResolvedValueOnce(false);
const response = await catalogLoader({
request: new Request("https://app.example.test/acme/settings/integrations"),
params: { tenant: "acme" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations",
});
const body = (await response.json()) as {
vm: { data?: { rows: Array<{ key: string }> } };
};
expect(body.vm.data?.rows.some((row) => row.key === "kwp")).toBe(false);
});
it.each(["aircall", "hallopetra"])("redirects the generic %s detail loader to telephony settings", async (app) => {
const thrown = await appLoader({
request: new Request(`https://app.example.test/acme/settings/integrations/${app}`),
params: { tenant: "acme", app },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(302);
expect((thrown as Response).headers.get("location")).toBe("/acme/settings/integrations/telephony");
expect(mocks.listConnections).not.toHaveBeenCalled();
});
it.each(["aircall", "hallopetra"])("blocks generic lifecycle mutations for %s", async (app) => {
for (const intent of ["connect", "reconnect", "disconnect", "manual-sync"]) {
const request = new Request(`https://app.example.test/acme/settings/integrations/${app}`, {
method: "POST",
body: new URLSearchParams({ intent, connectionId: "connection_1", label: app }),
});
const thrown = await appAction({
request,
params: { tenant: "acme", app },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(303);
expect((thrown as Response).headers.get("location")).toBe("/acme/settings/integrations/telephony");
expect(mocks.createConnection).not.toHaveBeenCalled();
expect(mocks.reconnectConnection).not.toHaveBeenCalled();
expect(mocks.disconnectConnection).not.toHaveBeenCalled();
expect(mocks.runSyncForConnection).not.toHaveBeenCalled();
}
});
it.each(["connect", "reconnect"])("routes the KWP %s mutation through the protected OAuth setup", async (intent) => {
const request = new Request("https://app.example.test/acme/settings/integrations/kwp", {
method: "POST",
body: new URLSearchParams({ intent, connectionId: "connection_1", label: "KWP" }),
});
const thrown = await appAction({
request,
params: { tenant: "acme", app: "kwp" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(303);
expect((thrown as Response).headers.get("location")).toBe("/integrations/kwp/setup?tenant=acme");
expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledWith(mocks.context);
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
expect(mocks.createConnection).not.toHaveBeenCalled();
expect(mocks.reconnectConnection).not.toHaveBeenCalled();
});
it("renders callback feedback and hides manual sync for the callback-only KWP slice", async () => {
mocks.listConnections.mockResolvedValueOnce([
{
id: "connection_1",
label: "KWP Geerkens",
connectionStatus: "active",
healthMessageKey: null,
lastHealthCheck: null,
tokenExpiresAt: null,
},
]);
const response = await appLoader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp?kwp=connected"),
params: { tenant: "acme", app: "kwp" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
await expect(response.json()).resolves.toMatchObject({
feedback: {
variant: "success",
titleKey: "integrations.kwp.oauth.connected",
descriptionKey: "integrations.kwp.oauth.connectedBody",
},
vm: {
data: {
connectHref: "/integrations/kwp/setup?tenant=acme",
canDisconnect: false,
canManualSync: false,
rows: [{ id: "connection_1", syncsHref: null }],
},
},
});
});
it("does not trust a connected query flag without an active KWP connection", async () => {
const response = await appLoader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp?kwp=connected"),
params: { tenant: "acme", app: "kwp" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
await expect(response.json()).resolves.toMatchObject({ feedback: null });
});
it("blocks the direct KWP sync-history route after the dedicated module gate", async () => {
const thrown = await syncHistoryLoader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/connection_1/syncs"),
params: { tenant: "acme", app: "kwp", connectionId: "connection_1" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app/:connectionId/syncs",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(404);
expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledWith(mocks.context);
expect(mocks.getConnectionOrThrow).not.toHaveBeenCalled();
expect(mocks.listSyncRuns).not.toHaveBeenCalled();
});
it("blocks KWP manual sync before creating a false successful empty run", async () => {
const request = new Request("https://app.example.test/acme/settings/integrations/kwp", {
method: "POST",
body: new URLSearchParams({ intent: "manual-sync", connectionId: "connection_1", csrf: "csrf-token" }),
});
const thrown = await appAction({
request,
params: { tenant: "acme", app: "kwp" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(404);
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
expect(mocks.runSyncForConnection).not.toHaveBeenCalled();
});
it("blocks a local-only KWP disconnect until provider revocation is verified", async () => {
const request = new Request("https://app.example.test/acme/settings/integrations/kwp", {
method: "POST",
body: new URLSearchParams({ intent: "disconnect", connectionId: "connection_1", csrf: "csrf-token" }),
});
const thrown = await appAction({
request,
params: { tenant: "acme", app: "kwp" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(404);
expect(mocks.validateCSRFToken).toHaveBeenCalledWith(request, { formData: expect.anything() });
expect(mocks.disconnectConnection).not.toHaveBeenCalled();
});
it("passes the URL app key into every generic connection mutation", async () => {
await appAction({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync", {
method: "POST",
body: new URLSearchParams({ intent: "reconnect", connectionId: "connection_1", apiKey: "fixture" }),
}),
params: { tenant: "acme", app: "sample-data-sync" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
expect(mocks.reconnectConnection).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: "connection_1", expectedAppId: "sample-data-sync" }),
);
await appAction({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync", {
method: "POST",
body: new URLSearchParams({ intent: "disconnect", connectionId: "connection_1" }),
}),
params: { tenant: "acme", app: "sample-data-sync" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
expect(mocks.disconnectConnection).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: "connection_1", expectedAppId: "sample-data-sync" }),
);
await appAction({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync", {
method: "POST",
body: new URLSearchParams({ intent: "manual-sync", connectionId: "connection_1" }),
}),
params: { tenant: "acme", app: "sample-data-sync" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
expect(mocks.runSyncForConnection).toHaveBeenCalledWith(
expect.objectContaining({ connectionId: "connection_1", expectedAppId: "sample-data-sync" }),
);
});
it.each([
["connect", "integrations.connections.feedback.connected"],
["reconnect", "integrations.connections.feedback.reconnected"],
["disconnect", "integrations.connections.feedback.disconnected"],
["manual-sync", "integrations.connections.feedback.syncStarted"],
] as const)("returns action-specific toast feedback for %s", async (intent, messageKey) => {
const response = await appAction({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync", {
method: "POST",
body: new URLSearchParams({
intent,
connectionId: "connection_1",
label: "Sample Sync",
apiKey: "fixture",
}),
}),
params: { tenant: "acme", app: "sample-data-sync" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
await expect(response.json()).resolves.toMatchObject({ intent, ok: true, messageKey });
});
it("keeps the manual-sync intent on a mapped action error", async () => {
mocks.runSyncForConnection.mockRejectedValueOnce(new Error("provider unavailable"));
const response = await appAction({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync", {
method: "POST",
body: new URLSearchParams({ intent: "manual-sync", connectionId: "connection_1" }),
}),
params: { tenant: "acme", app: "sample-data-sync" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app",
});
expect(response.status).toBe(400);
await expect(response.json()).resolves.toEqual({
intent: "manual-sync",
error: "integrations.errors.mutationFailed",
});
});
it("passes the URL app key through sync history and run-detail reads", async () => {
mocks.getSyncRunWithItems.mockResolvedValueOnce({
run: {
id: "run_1",
dataConnectionId: "connection_1",
kind: "manual",
status: "completed",
itemsTotal: 0,
itemsSucceeded: 0,
itemsFailed: 0,
summaryText: null,
startedAt: null,
completedAt: null,
},
items: [],
logs: [],
});
await syncHistoryLoader({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync/connection_1/syncs"),
params: { tenant: "acme", app: "sample-data-sync", connectionId: "connection_1" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app/:connectionId/syncs",
});
expect(mocks.getConnectionOrThrow).toHaveBeenCalledWith("tenant_1", "connection_1", "sample-data-sync");
expect(mocks.listSyncRuns).toHaveBeenCalledWith("tenant_1", "connection_1", "sample-data-sync");
await syncRunDetailLoader({
request: new Request("https://app.example.test/acme/settings/integrations/sample-data-sync/connection_1/syncs/run_1"),
params: { tenant: "acme", app: "sample-data-sync", connectionId: "connection_1", runId: "run_1" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app/:connectionId/syncs/:runId",
});
expect(mocks.getSyncRunWithItems).toHaveBeenCalledWith(
"tenant_1",
"run_1",
"connection_1",
"sample-data-sync",
);
});
it("blocks the direct KWP sync-run detail route after the dedicated module gate", async () => {
const thrown = await syncRunDetailLoader({
request: new Request("https://app.example.test/acme/settings/integrations/kwp/connection_1/syncs/run_1"),
params: { tenant: "acme", app: "kwp", connectionId: "connection_1", runId: "run_1" },
context: undefined,
unstable_pattern: "/:tenant/settings/integrations/:app/:connectionId/syncs/:runId",
}).catch((error: unknown) => error);
expect(thrown).toBeInstanceOf(Response);
expect((thrown as Response).status).toBe(404);
expect(mocks.requireKwpIntegrationModule).toHaveBeenCalledWith(mocks.context);
expect(mocks.getConnectionOrThrow).not.toHaveBeenCalled();
expect(mocks.getSyncRunWithItems).not.toHaveBeenCalled();
});
});