Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -3,10 +3,10 @@
*
* Centralises action names + metadata sanitization for the login / logout
* / fallback / mfa-challenge paths. Sits on top of
* `@toolctrl/db/audit-events.server` which already handles redaction.
* `@hivegrid/db/audit-events.server` which already handles redaction.
*/
import { createAuditEvent } from "@toolctrl/db/audit-events.server";
import type { Prisma } from "@toolctrl/db/prisma-browser";
import { createAuditEvent } from "@hivegrid/db/audit-events.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
export type AdminSsoAuditAction =
| "admin.login.sso.success"
@@ -2,16 +2,16 @@ import { describe, expect, it } from "vitest";
import { extractAdminSsoClaims, hasAllowedAdminGroup, isAllowedAdminGroup, mapGroupsToRole } from "./claims.server";
describe("mapGroupsToRole", () => {
it("maps toolctrl-admin to super_admin", () => {
expect(mapGroupsToRole(["toolctrl-admin"])).toBe("super_admin");
it("maps hivegrid-admin to super_admin", () => {
expect(mapGroupsToRole(["hivegrid-admin"])).toBe("super_admin");
});
it("maps toolctrl-staff to staff", () => {
expect(mapGroupsToRole(["toolctrl-staff"])).toBe("staff");
it("maps hivegrid-staff to staff", () => {
expect(mapGroupsToRole(["hivegrid-staff"])).toBe("staff");
});
it("prefers super_admin when both groups are present", () => {
expect(mapGroupsToRole(["toolctrl-staff", "toolctrl-admin"])).toBe("super_admin");
expect(mapGroupsToRole(["hivegrid-staff", "hivegrid-admin"])).toBe("super_admin");
});
it("returns null for an unknown group", () => {
@@ -30,9 +30,9 @@ describe("mapGroupsToRole", () => {
describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
it("recognizes the two allowlisted groups", () => {
expect(isAllowedAdminGroup("toolctrl-admin")).toBe(true);
expect(isAllowedAdminGroup("toolctrl-staff")).toBe(true);
expect(isAllowedAdminGroup("toolctrl-rando")).toBe(false);
expect(isAllowedAdminGroup("hivegrid-admin")).toBe(true);
expect(isAllowedAdminGroup("hivegrid-staff")).toBe(true);
expect(isAllowedAdminGroup("hivegrid-rando")).toBe(false);
});
it("returns false when claim list has no allowed group", () => {
@@ -42,7 +42,7 @@ describe("isAllowedAdminGroup / hasAllowedAdminGroup", () => {
});
it("returns true when at least one allowed group is present", () => {
expect(hasAllowedAdminGroup(["other", "toolctrl-staff"])).toBe(true);
expect(hasAllowedAdminGroup(["other", "hivegrid-staff"])).toBe(true);
});
});
@@ -52,7 +52,7 @@ describe("extractAdminSsoClaims", () => {
email: "Admin@Example.test",
email_verified: true,
name: "Admin Person",
groups: ["toolctrl-admin"],
groups: ["hivegrid-admin"],
};
it("extracts and normalizes a valid claim set", () => {
@@ -62,7 +62,7 @@ describe("extractAdminSsoClaims", () => {
expect(result.claims.subject).toBe("auth-uid-123");
expect(result.claims.email).toBe("admin@example.test");
expect(result.claims.name).toBe("Admin Person");
expect(result.claims.groups).toEqual(["toolctrl-admin"]);
expect(result.claims.groups).toEqual(["hivegrid-admin"]);
expect(result.claims.emailVerified).toBe(true);
}
});
@@ -105,9 +105,9 @@ describe("extractAdminSsoClaims", () => {
});
it("filters non-string entries from groups", () => {
const result = extractAdminSsoClaims({ ...validClaims, groups: ["toolctrl-admin", null, 7, "ok"] });
const result = extractAdminSsoClaims({ ...validClaims, groups: ["hivegrid-admin", null, 7, "ok"] });
expect(result.ok).toBe(true);
if (result.ok) expect(result.claims.groups).toEqual(["toolctrl-admin", "ok"]);
if (result.ok) expect(result.claims.groups).toEqual(["hivegrid-admin", "ok"]);
});
it("returns missing-sub for null claims", () => {
@@ -2,18 +2,18 @@
* Phase 09 Task #82 — OIDC ID-token claim extraction + group→role mapping.
*
* The "role" returned here is the *current* AdminUser identity layer in the
* Toolctrl boilerplate. Today the only durable AdminUser concept is "exists
* HiveGrid boilerplate. Today the only durable AdminUser concept is "exists
* or not"; the spec adds two granular roles (`super_admin`, `staff`) that
* we persist as `ssoGroups` snapshots while we wait for the permissions
* matrix to grow first-class role columns. Callers should treat the role
* as advisory + future-proof.
*/
export type AuthentikGroup = "toolctrl-admin" | "toolctrl-staff";
export type AuthentikGroup = "hivegrid-admin" | "hivegrid-staff";
export type AdminSsoRole = "super_admin" | "staff";
export const ADMIN_GROUP: AuthentikGroup = "toolctrl-admin";
export const STAFF_GROUP: AuthentikGroup = "toolctrl-staff";
export const ADMIN_GROUP: AuthentikGroup = "hivegrid-admin";
export const STAFF_GROUP: AuthentikGroup = "hivegrid-staff";
export const ALLOWED_ADMIN_GROUPS: readonly AuthentikGroup[] = [ADMIN_GROUP, STAFF_GROUP];
@@ -3,17 +3,17 @@ import { AdminSsoConfigError, isAdminSsoConfigured, readAdminSsoEnv } from "./cl
describe("readAdminSsoEnv", () => {
const baseEnv = {
AUTHENTIK_ISSUER_URL: "https://auth.example.test/application/o/toolctrl-admin-panel/",
AUTHENTIK_ADMIN_CLIENT_ID: "toolctrl-admin-panel",
AUTHENTIK_ISSUER_URL: "https://auth.example.test/application/o/hivegrid-admin-panel/",
AUTHENTIK_ADMIN_CLIENT_ID: "hivegrid-admin-panel",
AUTHENTIK_ADMIN_CLIENT_SECRET: "shh",
AUTHENTIK_ADMIN_REDIRECT_URI: "https://admin.example.test/auth/admin/callback",
};
it("returns trimmed values when all required keys are present", () => {
const env = readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI: "https://admin.example.test/admin/login?logged_out=1" });
const env = readAdminSsoEnv({ ...baseEnv, AUTHENTIK_ADMIN_POST_LOGOUT_REDIRECT_URI: "https://admin.example.test/login?logged_out=1" });
expect(env.issuerUrl).toBe(baseEnv.AUTHENTIK_ISSUER_URL);
expect(env.clientId).toBe("toolctrl-admin-panel");
expect(env.postLogoutRedirectUri).toBe("https://admin.example.test/admin/login?logged_out=1");
expect(env.clientId).toBe("hivegrid-admin-panel");
expect(env.postLogoutRedirectUri).toBe("https://admin.example.test/login?logged_out=1");
});
it("throws when a required key is missing", () => {
@@ -99,7 +99,7 @@ function buildClaims(overrides: Partial<AdminSsoClaims> = {}): AdminSsoClaims {
email: "admin@example.test",
emailVerified: true,
name: "Admin Person",
groups: ["toolctrl-admin"],
groups: ["hivegrid-admin"],
...overrides,
};
}
@@ -111,7 +111,7 @@ describe("jitProvisionAdmin", () => {
env = buildFakeDb();
});
it("creates User+AdminUser for a brand new toolctrl-admin claim and returns super_admin", async () => {
it("creates User+AdminUser for a brand new hivegrid-admin claim and returns super_admin", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims() }, env.db);
expect(result.ok).toBe(true);
if (result.ok) {
@@ -124,11 +124,11 @@ describe("jitProvisionAdmin", () => {
const admin = [...env.adminRows.values()][0]!;
expect(admin.ssoProvider).toBe(ADMIN_SSO_PROVIDER);
expect(admin.ssoSubjectId).toBe("authentik-sub-1");
expect(admin.ssoGroups).toEqual(["toolctrl-admin"]);
expect(admin.ssoGroups).toEqual(["hivegrid-admin"]);
});
it("maps toolctrl-staff to staff role", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["toolctrl-staff"] }) }, env.db);
it("maps hivegrid-staff to staff role", async () => {
const result = await jitProvisionAdmin({ claims: buildClaims({ groups: ["hivegrid-staff"] }) }, env.db);
expect(result.ok).toBe(true);
if (result.ok) expect(result.admin.role).toBe("staff");
});
@@ -156,7 +156,7 @@ describe("jitProvisionAdmin", () => {
// Second login with same sub but new groups + later timestamp.
const t1 = new Date("2026-02-01T00:00:00Z");
const result = await jitProvisionAdmin(
{ claims: buildClaims({ groups: ["toolctrl-staff"] }), now: t1 },
{ claims: buildClaims({ groups: ["hivegrid-staff"] }), now: t1 },
env.db,
);
expect(result.ok).toBe(true);
@@ -166,7 +166,7 @@ describe("jitProvisionAdmin", () => {
expect(result.admin.role).toBe("staff");
}
const refreshed = [...env.adminRows.values()][0]!;
expect(refreshed.ssoGroups).toEqual(["toolctrl-staff"]);
expect(refreshed.ssoGroups).toEqual(["hivegrid-staff"]);
expect(refreshed.lastSsoLoginAt).toEqual(t1);
// No new user row.
expect(env.userRows.size).toBe(1);
@@ -7,9 +7,9 @@
* session cookie or persisting tokens in the DB.
*/
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
export const ADMIN_SSO_ID_TOKEN_COOKIE = "admin_sso_id_token";
export const ADMIN_SSO_ID_TOKEN_COOKIE = "hivegrid_admin_sso_id_token";
export const ADMIN_SSO_ID_TOKEN_TTL_MS = 12 * 60 * 60 * 1000; // mirror app-session lifetime
const COOKIE_PATH = "/auth/admin";
@@ -17,10 +17,10 @@
* server-side (cookie Max-Age is best-effort; clients lie).
*/
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@toolctrl/config";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { generators } from "openid-client";
export const ADMIN_SSO_CHALLENGE_COOKIE = "admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_COOKIE = "hivegrid_admin_sso_challenge";
export const ADMIN_SSO_CHALLENGE_TTL_MS = 10 * 60 * 1000;
const COOKIE_PATH = "/auth/admin";
const PAYLOAD_VERSION = "v1";
@@ -1,4 +1,4 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { dbRead } from "~/utils/db.server";
export async function groupUniqueVisitorsBy(by: Prisma.AnalyticsUniqueVisitorScalarFieldEnum) {
@@ -1,36 +0,0 @@
import { ApiEndpointDto } from "../dtos/ApiEndpointDto";
import { useTranslation } from "react-i18next";
import CollapsibleRow from "~/components/ui/tables/CollapsibleRow";
import ApiEndpointTitle from "./ApiEndpointTitle";
import MonacoEditor from "~/components/editors/MonacoEditor";
export default function ApiEndpoint({ item }: { item: ApiEndpointDto }) {
const { t } = useTranslation();
return (
<div>
<CollapsibleRow className="bg-secondary" value={<ApiEndpointTitle item={item} />} title={<ApiEndpointTitle item={item} />}>
<div className="space-y-1 overflow-hidden pt-2">
<div className="space-y-2">
{item.responseSchema && (
<>
<div className="text-foreground text-sm font-bold">{t("api.docs.responseSchema")}</div>
<div className="h-96 overflow-auto p-2">
<MonacoEditor value={item.responseSchema} onChange={() => {}} theme="vs-dark" language="json" />
</div>
</>
)}
{item.bodyExample && (
<>
<div className="text-foreground text-sm font-bold">{t("api.docs.bodyExample")}</div>
<div className="h-96 overflow-auto p-2">
<MonacoEditor value={item.bodyExample} onChange={() => {}} theme="vs-dark" language="json" />
</div>
</>
)}
</div>
</div>
</CollapsibleRow>
</div>
);
}
@@ -1,15 +0,0 @@
import ApiUtils from "~/utils/app/ApiUtils";
import { ApiEndpointDto } from "../dtos/ApiEndpointDto";
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
export default function ApiEndpointTitle({ item }: { item: ApiEndpointDto }) {
return (
<div className="flex flex-col truncate">
<div className="flex items-center space-x-2">
<SimpleBadge title={item.method} color={ApiUtils.getMethodColor(item.method)} />
<h3 className="text-foreground text-sm font-bold">{item.route}</h3>
</div>
<div className="text-muted-foreground truncate text-xs italic">{item.description}</div>
</div>
);
}
@@ -1,43 +0,0 @@
import InputSearch from "~/components/ui/input/InputSearch";
import type { ApiEndpointDto } from "../dtos/ApiEndpointDto";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import EmptyState from "~/components/ui/emptyState/EmptyState";
import ApiEndpoint from "./ApiEndpoint";
export default function ApiEndpointsTable({ items }: { items: ApiEndpointDto[] }) {
const { t } = useTranslation();
const [searchInput, setSearchInput] = useState("");
const filteredItems = useMemo(() => {
const normalizedSearch = searchInput.trim().toLowerCase();
if (!normalizedSearch) return items;
return items.filter((f) => {
return (
f.route.toLowerCase().includes(normalizedSearch) ||
f.method.toLowerCase().includes(normalizedSearch) ||
f.description.toLowerCase().includes(normalizedSearch) ||
f.entity.name.toLowerCase().includes(normalizedSearch) ||
f.entity.title.toLowerCase().includes(normalizedSearch) ||
f.entity.titlePlural.toLowerCase().includes(normalizedSearch) ||
t(f.entity.title).toLowerCase().includes(normalizedSearch) ||
t(f.entity.titlePlural).toLowerCase().includes(normalizedSearch)
);
});
}, [items, searchInput, t]);
return (
<div className="space-y-2">
<InputSearch value={searchInput} setValue={setSearchInput} />
{filteredItems.length === 0 && (
<EmptyState
captions={{
thereAreNo: t("api.endpoints.empty"),
}}
/>
)}
{filteredItems.map((endpoint, idx) => {
return <ApiEndpoint key={idx} item={endpoint} />;
})}
</div>
);
}
@@ -7,8 +7,6 @@ describe("ApiKeyLogsSummary i18n", () => {
"apps/web/app/modules/api/components/ApiKeyLogsSummary.tsx",
"apps/web/app/modules/api/components/ApiCallSpeedBadge.tsx",
"apps/web/app/modules/metrics/components/SpeedBadge.tsx",
"apps/web/app/modules/api/components/ApiEndpoint.tsx",
"apps/web/app/modules/api/services/ApiSpecsService.ts",
]
.map((file) => readRepoFile(file))
.join("\n");
@@ -18,10 +16,6 @@ describe("ApiKeyLogsSummary i18n", () => {
expect(source).toContain("models.apiKeyLog.avgDuration");
expect(source).toContain("metrics.speed.lightningFast");
expect(source).toContain("metrics.speed.verySlow");
expect(source).toContain("api.docs.responseSchema");
expect(source).toContain("api.docs.bodyExample");
expect(source).toContain("api.specs.hostDescription");
expect(source).toContain("api.specs.operations.getAll");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain("lightning_fast");
expect(source).not.toContain("response_schema");
@@ -1,44 +0,0 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import type { ApiSpecsDto } from "../services/ApiSpecsService";
import ApiSpecs from "./ApiSpecs";
vi.mock("~/components/editors/MonacoEditor", () => ({ default: ({ value }: { value: string }) => <pre data-testid="monaco">{value}</pre> }));
vi.mock("~/components/ui/icons/ExternalLinkEmptyIcon", () => ({ default: () => null }));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
const item = {
openApi: { openapi: "3.1.0" },
postmanCollection: { info: { name: "API" }, item: [] },
apiDocsUrl: "https://api.example.com/v1/docs",
} as unknown as ApiSpecsDto;
describe("ApiSpecs", () => {
it("can hide the admin-only Postman download while still rendering the collection preview", () => {
render(
<MemoryRouter>
<ApiSpecs item={item} postmanCollectionUrl={null} />
</MemoryRouter>
);
expect(screen.getByText("docs.openApi")).toBeInTheDocument();
expect(screen.queryByText("docs.downloadPostmanCollection")).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: /postman/i })).not.toBeInTheDocument();
expect(screen.getAllByTestId("monaco")).toHaveLength(2);
});
it("can hide the full Postman collection preview on tenant-facing docs", () => {
render(
<MemoryRouter>
<ApiSpecs item={item} postmanCollectionUrl={null} showPostmanCollection={false} />
</MemoryRouter>
);
expect(screen.queryByText("docs.downloadPostmanCollection")).not.toBeInTheDocument();
expect(screen.getAllByTestId("monaco")).toHaveLength(1);
});
});
@@ -1,148 +0,0 @@
import MonacoEditor from "~/components/editors/MonacoEditor";
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
import { ApiSpecsDto } from "../services/ApiSpecsService";
import { Link } from "react-router";
import clsx from "clsx";
import { useTranslation } from "react-i18next";
export default function ApiSpecs({
item,
className = "h-96 overflow-auto",
withLinkToDocs = true,
postmanCollectionUrl = "/postman_collection.json",
showPostmanCollection = true,
}: {
item: ApiSpecsDto;
className?: string;
withLinkToDocs?: boolean;
postmanCollectionUrl?: string | null;
showPostmanCollection?: boolean;
}) {
const { t } = useTranslation();
const shouldShowPostmanCollection = showPostmanCollection && Boolean(item.postmanCollection);
return (
<div className={clsx("grid gap-4", shouldShowPostmanCollection ? "grid-cols-2" : "grid-cols-1")}>
<div className="space-y-2">
{withLinkToDocs && (
<Link to={item.apiDocsUrl} target="_blank">
<div className="hover:border-border hover:bg-background rounded-md border border-transparent px-2 py-1.5">
<div className="flex items-center justify-between space-x-2">
<div className="flex items-center space-x-2">
<svg className="h-5 w-5" xmlns="http://www.w3.org/2000/svg" width="256" height="256" preserveAspectRatio="xMidYMid" viewBox="0 0 256 256">
<path
fill="#fff"
d="M127.06 255.997C58.85 255.527-.457 198.918.003 126.998.445 57.796 57.952-.469 129.11.003c69.157.46 127.503 57.864 126.885 128.191.573 69.69-58.06 128.295-128.935 127.803zm0 0C58.85 255.527-.457 198.918.003 126.998.445 57.796 57.952-.469 129.11.003c69.157.46 127.503 57.864 126.885 128.191.573 69.69-58.06 128.295-128.935 127.803z"
/>
<path
fill="#49a32b"
d="M127.185 238.997C68.032 238.59 16.604 189.5 17.002 127.131c.384-60.012 50.253-110.54 111.961-110.129 59.972.399 110.569 50.18 110.033 111.167.496 60.433-50.349 111.255-111.811 110.828zm0 0C68.032 238.59 16.604 189.5 17.002 127.131c.384-60.012 50.253-110.54 111.961-110.129 59.972.399 110.569 50.18 110.033 111.167.496 60.433-50.349 111.255-111.811 110.828z"
/>
<path
fill="#fff"
d="M169.327 127.956c-.284 5.29-4.906 9.683-9.46 8.917h-.069a9.133 9.133 0 0 1-9.145-9.124 9.276 9.276 0 0 1 9.427-8.96c5.045.025 9.52 4.288 9.247 9.167zM88.201 179.22c1.902.056 3.806.015 6 .015v13.786c-13.635 2.305-24.866-1.566-27.622-13.091a76.501 76.501 0 0 1-1.736-12.886c-.293-4.592.213-9.235-.137-13.819-.97-12.612-2.603-16.918-14.706-17.514v-15.696a22.665 22.665 0 0 1 2.632-.452c6.636-.327 9.433-2.362 10.917-8.898a74.57 74.57 0 0 0 1.194-11.122c.526-7.217.34-14.551 1.542-21.651 1.737-10.267 8.111-15.255 18.64-15.814 2.996-.16 6.001-.024 9.396-.024v14.09c-1.397.1-2.677.303-3.95.265-8.58-.263-9.023 2.66-9.65 9.762-.39 4.454.149 8.984-.155 13.454a107.113 107.113 0 0 1-1.781 13.245c-1.238 6.339-5.135 11.053-10.535 15.053 10.483 6.823 11.676 17.423 12.357 28.188.366 5.784.199 11.61.786 17.366.457 4.467 2.195 5.607 6.808 5.743zm8.836-60.43h.162a9.078 9.078 0 0 1 8.928 9.226 8.884 8.884 0 0 1-9.396 8.851 9.046 9.046 0 1 1 .306-18.078zm31.236 0c5.483-.043 9.124 3.51 9.152 8.93.03 5.565-3.422 9.125-8.868 9.149-5.54.024-9.186-3.48-9.216-8.867a8.671 8.671 0 0 1 8.933-9.213zm65.4-6.867c1.459 5.447 4.298 7.362 10.032 7.623.94.044 1.875.203 3.163.346v15.692c-.697.23-1.412.4-2.138.512-7.684.478-11.186 3.63-11.962 11.335-.496 4.919-.455 9.892-.796 14.828a125.806 125.806 0 0 1-1.476 16.18c-1.96 9.703-8.019 14.544-18.029 15.135-3.221.19-6.466.03-9.94.03v-14.026c1.87-.115 3.52-.275 5.174-.314 5.981-.143 8.096-2.071 8.389-8.011.324-6.525.465-13.059.757-19.586.423-9.433 3.006-17.861 11.795-23.745-5.03-3.585-9.067-7.928-10.112-13.783-1.265-7.097-1.674-14.351-2.355-21.548-.336-3.597-.32-7.226-.671-10.821-.379-3.88-3.045-5.224-6.577-5.31-2.024-.05-4.055-.01-6.642-.01V62.754c16.509-2.741 27.913 2.752 28.973 18.548.443 6.632.378 13.297.803 19.93.186 3.608.726 7.19 1.612 10.691z"
/>
</svg>
<div className="text-foreground truncate text-sm font-medium">{t("docs.openApi")}</div>
</div>
<ExternalLinkEmptyIcon className="ml-2 h-4 w-4" />
</div>
</div>
</Link>
)}
<div className={clsx(className)}>
<MonacoEditor value={JSON.stringify(item.openApi, null, 2)} theme="vs-dark" language="json" />
</div>
</div>
{shouldShowPostmanCollection && (
<div className="space-y-2">
{withLinkToDocs && postmanCollectionUrl && (
<Link to={postmanCollectionUrl} target="_blank">
<div className="hover:border-border hover:bg-background rounded-md border border-transparent px-2 py-1.5">
<div className="flex items-center justify-between space-x-2">
<div className="flex items-center space-x-2">
<svg className="h-4 w-4" xmlns="http://www.w3.org/2000/svg" width="800" height="800" preserveAspectRatio="xMidYMid" viewBox="0 0 256 256">
<path
fill="#FF6C37"
d="M254.953 144.253c8.959-70.131-40.569-134.248-110.572-143.206C74.378-7.912 10.005 41.616 1.047 111.619c-8.959 70.003 40.569 134.248 110.572 143.334 70.131 8.959 134.248-40.569 143.334-110.7Z"
/>
<path fill="#FFF" d="m174.2 82.184-54.007 54.007-15.229-15.23c53.11-53.11 58.358-48.503 69.236-38.777Z" />
<path
fill="#FF6C37"
d="M120.193 137.47c-.384 0-.64-.128-.895-.384l-15.358-15.229a1.237 1.237 0 0 1 0-1.792c54.007-54.006 59.638-48.887 71.028-38.649.255.256.383.512.383.896s-.128.64-.383.896l-54.007 53.878c-.128.256-.512.384-.768.384Zm-13.437-16.509 13.437 13.438 52.087-52.087c-9.47-8.446-15.87-11.006-65.524 38.65Z"
/>
<path fill="#FFF" d="m135.679 151.676-14.718-14.718 54.007-54.006c14.46 14.59-7.167 38.265-39.29 68.724Z" />
<path
fill="#FF6C37"
d="M135.679 152.956c-.384 0-.64-.128-.896-.384l-14.718-14.718c-.256-.256-.256-.512-.256-.896s.128-.64.384-.895L174.2 82.056a1.237 1.237 0 0 1 1.791 0 15.58 15.58 0 0 1 4.991 11.902c-.256 14.206-16.38 32.25-44.28 58.614-.383.256-.767.384-1.023.384Zm-12.926-15.998c8.19 8.319 11.646 11.646 12.926 12.926 21.5-20.476 42.36-41.464 42.488-55.926.128-3.327-1.152-6.655-3.327-9.214l-52.087 52.214Z"
/>
<path
fill="#FFF"
d="m105.22 121.345 10.878 10.878c.256.256.256.512 0 .768-.128.128-.128.128-.256.128l-22.524 4.863c-1.152.128-2.175-.64-2.431-1.791-.128-.64.128-1.28.512-1.664l13.053-13.054c.256-.256.64-.384.768-.128Z"
/>
<path
fill="#FF6C37"
d="M92.934 139.262c-1.92 0-3.327-1.536-3.327-3.455 0-.896.384-1.792 1.024-2.432l13.053-13.054c.768-.64 1.792-.64 2.56 0l10.878 10.878c.768.64.768 1.792 0 2.56-.256.256-.512.384-.896.512l-22.524 4.863c-.256 0-.512.128-.768.128Zm11.902-16.51-12.542 12.543c-.256.256-.383.64-.128 1.024.128.383.512.511.896.383l21.116-4.607-9.342-9.342Z"
/>
<path
fill="#FFF"
d="M202.739 52.238c-8.191-7.935-21.373-7.679-29.307.64-7.935 8.318-7.679 21.372.64 29.306A20.678 20.678 0 0 0 199.155 85l-14.59-14.59 18.174-18.172Z"
/>
<path
fill="#FF6C37"
d="M188.405 89.223c-12.158 0-22.012-9.854-22.012-22.012 0-12.158 9.854-22.012 22.012-22.012 5.631 0 11.134 2.176 15.23 6.143.255.256.383.512.383.896s-.128.64-.384.895L186.357 70.41l13.566 13.566c.512.512.512 1.28 0 1.792l-.256.256c-3.327 2.047-7.295 3.199-11.262 3.199Zm0-41.337c-10.75 0-19.452 8.703-19.324 19.453 0 10.75 8.702 19.452 19.452 19.324 2.944 0 5.887-.64 8.575-2.047l-13.438-13.31c-.256-.256-.384-.512-.384-.896s.128-.64.384-.895l17.149-17.15c-3.456-2.943-7.807-4.479-12.414-4.479Z"
/>
<path
fill="#FFF"
d="m203.122 52.622-.255-.256-18.301 18.044 14.461 14.462c1.408-.896 2.816-1.92 3.967-3.072a20.51 20.51 0 0 0 .128-29.178Z"
/>
<path
fill="#FF6C37"
d="M199.155 86.28c-.384 0-.64-.128-.896-.384l-14.589-14.59c-.256-.256-.384-.512-.384-.896s.128-.64.384-.895l18.173-18.173a1.237 1.237 0 0 1 1.791 0l.384.256c8.575 8.574 8.575 22.396.128 31.098-1.28 1.28-2.687 2.432-4.223 3.328-.384.128-.64.256-.768.256Zm-12.798-15.87 12.926 12.926c1.024-.64 2.048-1.536 2.816-2.304 7.294-7.294 7.678-19.196.64-26.875L186.357 70.41Z"
/>
<path
fill="#FFF"
d="M176.375 84.488a7.879 7.879 0 0 0-11.134 0l-48.247 48.247 8.063 8.063 51.062-44.792c3.328-2.816 3.584-7.807.768-11.134-.256-.128-.384-.256-.512-.384Z"
/>
<path
fill="#FF6C37"
d="M124.929 142.077c-.384 0-.64-.128-.896-.383l-8.063-8.063a1.237 1.237 0 0 1 0-1.792l48.247-48.247a9.115 9.115 0 0 1 12.926 0 9.115 9.115 0 0 1 0 12.926l-.384.384-51.063 44.792c-.128.255-.384.383-.767.383Zm-6.143-9.342 6.27 6.271 50.167-44.024c2.816-2.304 3.072-6.527.768-9.342-2.303-2.816-6.526-3.072-9.342-.768-.128.128-.256.256-.512.384l-47.351 47.48Z"
/>
<path
fill="#FFF"
d="M80.009 187.637c-.512.256-.768.768-.64 1.28l2.175 9.214c.512 1.28-.256 2.816-1.663 3.2-1.024.384-2.176 0-2.816-.768l-14.077-13.95 45.943-45.943 15.87.256 10.75 10.75c-2.56 2.175-18.045 17.149-55.542 35.961Z"
/>
<path
fill="#FF6C37"
d="M78.985 202.61c-1.024 0-2.048-.383-2.688-1.151l-13.95-13.95c-.255-.256-.383-.512-.383-.896 0-.383.128-.64.384-.895l45.944-45.944c.256-.256.64-.384.895-.384l15.87.256c.383 0 .64.128.895.384l10.75 10.75c.256.256.384.64.384 1.024s-.128.64-.512.896l-.895.767c-13.566 11.902-31.995 23.804-54.902 35.194l2.175 9.086c.384 1.664-.384 3.456-1.92 4.352-.767.384-1.407.512-2.047.512Zm-14.078-15.997 13.182 13.054c.384.64 1.152.896 1.792.512.64-.384.896-1.152.512-1.792l-2.176-9.214c-.256-1.152.256-2.176 1.28-2.688 22.652-11.39 40.952-23.163 54.39-34.81l-9.47-9.47-14.718-.256-44.792 44.664Z"
/>
<path
fill="#FFF"
d="m52.11 197.62 11.006-11.007 16.38 16.381-26.107-1.791c-1.151-.128-1.92-1.152-1.791-2.304 0-.512.128-1.024.512-1.28Z"
/>
<path
fill="#FF6C37"
d="m79.497 204.146-26.236-1.791c-1.92-.128-3.199-1.792-3.071-3.712.128-.768.384-1.535 1.024-2.047L62.22 185.59a1.237 1.237 0 0 1 1.792 0l16.38 16.38c.385.385.512.897.257 1.408-.256.512-.64.768-1.152.768Zm-16.381-15.74-10.11 10.11c-.384.255-.384.895 0 1.151.127.128.255.256.511.256l22.652 1.536-13.053-13.054ZM104.452 146.557c-.768 0-1.28-.64-1.28-1.28 0-.384.128-.64.384-.896l12.414-12.414a1.237 1.237 0 0 1 1.792 0l8.062 8.063c.384.384.512.768.384 1.28-.128.384-.512.767-1.023.895l-20.477 4.352h-.256Zm12.414-11.902-8.446 8.446 13.821-2.943-5.375-5.503Z"
/>
<path fill="#FFF" d="m124.8 140.926-14.077 3.071c-1.024.256-2.048-.384-2.303-1.408-.128-.64 0-1.28.511-1.791l7.807-7.807 8.063 7.935Z" />
<path
fill="#FF6C37"
d="M110.467 145.277a3.168 3.168 0 0 1-3.2-3.2c0-.895.385-1.663.897-2.303l7.806-7.807a1.237 1.237 0 0 1 1.792 0l8.062 8.063c.384.384.512.768.384 1.28-.128.384-.512.767-1.023.895l-14.078 3.072h-.64Zm6.399-10.622-6.91 6.91c-.257.257-.257.512-.129.768s.384.384.768.384l11.774-2.56-5.503-5.502ZM203.25 64.907c-.256-.767-1.151-1.151-1.92-.895-.767.255-1.151 1.151-.895 1.92 0 .127.128.255.128.383.768 1.536.512 3.455-.512 4.863-.512.64-.384 1.536.128 2.048.64.512 1.536.384 2.048-.256 1.92-2.432 2.303-5.503 1.023-8.063Z"
/>
</svg>
<div className="text-foreground truncate text-sm font-medium">{t("docs.downloadPostmanCollection")}</div>
</div>
<ExternalLinkEmptyIcon className="ml-2 h-4 w-4" />
</div>
</div>
</Link>
)}
<div className={clsx(className)}>
<MonacoEditor value={JSON.stringify(item.postmanCollection, null, 2)} theme="vs-dark" language="json" />
</div>
</div>
)}
</div>
);
}
@@ -1,10 +0,0 @@
import type { LegacyEntityWithDetails } from "@toolctrl/db/entities.server";
export type ApiEndpointDto = {
entity: LegacyEntityWithDetails;
route: string;
method: string;
description: string;
responseSchema: string;
bodyExample: string;
};
@@ -1,4 +1,4 @@
import { ApiKeyLog } from "@toolctrl/db/prisma-browser";
import { ApiKeyLog } from "@hivegrid/db/prisma-browser";
export type ApiKeyLogDto = ApiKeyLog & {
apiKey: { alias: string; tenant: { id: string; name: string } } | null;
@@ -1,4 +1,4 @@
import { adminGetAllLegacyTenantSummaries } from "@toolctrl/db/accounts.server";
import { adminGetAllLegacyTenantSummaries } from "@hivegrid/db/accounts.server";
import {
adminDeleteLegacyApiKeyLogsByIds,
countLegacyApiKeyLogs,
@@ -8,8 +8,8 @@ import {
tenantLegacyApiKeyLogScope,
type LegacyApiKeyLogOrderByInput,
type LegacyApiKeyLogWhereInput,
} from "@toolctrl/db/api-keys.server";
import { Prisma } from "@toolctrl/db/prisma-browser";
} from "@hivegrid/db/api-keys.server";
import { Prisma } from "@hivegrid/db/prisma-browser";
import { Params } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { getFiltersFromCurrentUrl, getPaginationFromCurrentUrl } from "~/utils/helpers/RowPaginationHelper";
@@ -1,95 +0,0 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("@toolctrl/db/entities.server", () => ({
getAllLegacyEntities: vi.fn(),
}));
vi.mock("~/locale/i18next.server", () => ({
getTranslations: vi.fn(async () => ({ t: (value: string) => value, translations: {}, locale: "en" })),
}));
vi.mock("~/utils/url.server", () => ({
getAbsoluteApiUrl: vi.fn((_request: Request, path: string) => `https://api.example.com${path.startsWith("/") ? path : `/${path}`}`),
}));
import { getAllLegacyEntities } from "@toolctrl/db/entities.server";
import ApiSpecsService from "./ApiSpecsService";
const entity = {
id: "entity_1",
slug: "contacts",
title: "Contact",
titlePlural: "Contacts",
hasApi: true,
active: true,
properties: [],
childEntities: [{ id: "child_relation" }],
parentEntities: [],
};
describe("ApiSpecsService", () => {
it("documents canonical API auth and idempotency for generated specs and Postman requests", async () => {
vi.mocked(getAllLegacyEntities).mockResolvedValue([entity] as never);
const specs = await ApiSpecsService.generateSpecs({ request: new Request("https://admin.example.com/api/docs") });
const openApi = specs.openApi;
expect(openApi.servers).toEqual([{ url: "https://api.example.com", description: "API host" }]);
expect(openApi.components.securitySchemes.bearerAuth).toMatchObject({
type: "http",
scheme: "bearer",
bearerFormat: "service-token",
});
expect(openApi.paths["/v1/entities/{entity}/rows"].post.parameters).toContainEqual(expect.objectContaining({ name: "Idempotency-Key", required: true }));
expect(openApi.paths["/v1/entities/{entity}/rows/{rowId}"].patch.parameters).toContainEqual(expect.objectContaining({ name: "Idempotency-Key", required: true }));
expect(openApi.paths["/v1/entities/{entity}/rows/{rowId}"].delete.parameters).toContainEqual(expect.objectContaining({ name: "Idempotency-Key", required: true }));
expect(openApi.paths["/v1/relationships"].post.parameters).toContainEqual(expect.objectContaining({ name: "Idempotency-Key", required: true }));
expect(openApi.paths["/v1/relationships/{id}"].delete.parameters).toContainEqual(expect.objectContaining({ name: "Idempotency-Key", required: true }));
const postmanItems = specs.postmanCollection.item as Array<{
name: string;
request: { header: Array<{ key: string; value?: string }>; url: { raw: string; query?: Array<{ key: string; value: string; disabled?: boolean }> } };
}>;
expect(postmanItems.find((item) => item.name === "GET /v1/session/current-user")?.request.header).toEqual([
expect.objectContaining({ key: "Authorization", value: "Bearer <token>" }),
]);
expect(postmanItems.find((item) => item.name === "POST /v1/api-keys/validate")?.request.header).toEqual([
expect.objectContaining({ key: "x-api-key", value: "<api-key-or-service-token>" }),
]);
expect(postmanItems.some((item) => item.name.startsWith("POST /v1/workflows") || item.name.startsWith("GET /v1/workflows"))).toBe(false);
expect(postmanItems.find((item) => item.name === "GET /v1/entities/:entity/rows")?.request.header).toEqual([
expect.objectContaining({ key: "x-api-key", value: "<api-key>" }),
]);
expect(postmanItems.find((item) => item.name === "GET /v1/entities/:entity/rows")?.request.url.query).toContainEqual(
expect.objectContaining({ key: "tenantId", value: "<tenantId>" })
);
expect(postmanItems.find((item) => item.name === "GET /v1/entities/:entity/rows")?.request.url.raw).toContain("tenantId=%3CtenantId%3E");
expect(postmanItems.find((item) => item.name === "POST /v1/entities/:entity/rows")?.request.header).toEqual([
expect.objectContaining({ key: "x-api-key", value: "<api-key>" }),
expect.objectContaining({ key: "Idempotency-Key" }),
]);
expect(postmanItems.find((item) => item.name === "POST /v1/ai/upload")?.request.header).toContainEqual(
expect.objectContaining({ key: "x-tenant-id", value: "<x-tenant-id>" })
);
expect(postmanItems.find((item) => item.name === "POST /v1/analytics/events")?.request.header).toEqual([
expect.objectContaining({ key: "x-analytics-token" }),
]);
expect(postmanItems.find((item) => item.name === "GET /v1/exports/:exportJobId/download-url")?.request.header).toEqual([
expect.objectContaining({ key: "x-api-key", value: "<api-key>" }),
]);
expect(postmanItems.find((item) => item.name === "POST /v1/billing/stripe/webhooks")?.request.header).toEqual([
expect.objectContaining({ key: "stripe-signature" }),
]);
expect(postmanItems.find((item) => item.name === "POST /v1/events/webhooks/attempts/:id")?.request.header).toEqual([
expect.objectContaining({ key: "Authorization", value: "Basic <base64(mailjet:webhook-secret)>" }),
]);
expect((specs.endpoints ?? []).map((endpoint) => endpoint.route)).toEqual([
"https://api.example.com/v1/entities/contacts/rows",
"https://api.example.com/v1/entities/contacts/rows/:rowId",
"https://api.example.com/v1/entities/contacts/rows",
"https://api.example.com/v1/entities/contacts/rows/:rowId",
"https://api.example.com/v1/entities/contacts/rows/:rowId",
]);
});
});
@@ -1,340 +0,0 @@
import { openApiDocument } from "@toolctrl/api/openapi";
import { getAllLegacyEntities, type LegacyEntityWithDetails } from "@toolctrl/db/entities.server";
import type { TFunction } from "i18next";
import type { ApiEndpointDto } from "../dtos/ApiEndpointDto";
import ApiHelper from "~/utils/helpers/ApiHelper";
import { getTranslations } from "~/locale/i18next.server";
import { getAbsoluteApiUrl } from "~/utils/url.server";
import { apiPath } from "~/utils/app/CanonicalUrlUtils";
export type ApiSpecsDto = {
endpoints?: ApiEndpointDto[];
openApi: CanonicalOpenApiDocument;
postmanCollection: PostmanCollection;
apiDocsUrl: string;
};
type CanonicalOpenApiDocument = typeof openApiDocument & {
servers: Array<{ url: string; description: string }>;
};
type PostmanCollection = {
info: {
_postman_id: string;
name: string;
schema: string;
};
item: Array<ReturnType<typeof toPostmanItem>>;
};
type PostmanHeader = { key: string; value: string; type: "text"; description?: string };
type PostmanQueryParam = { key: string; value: string; disabled?: boolean; description?: string };
async function generateSpecs({ request }: { request: Request }): Promise<ApiSpecsDto> {
const { t } = await getTranslations(request);
const entities = (await getAllLegacyEntities({ tenantId: null, active: true })).filter((entity) => entity.hasApi);
const openApi = generateCanonicalOpenApiSpecs({ request, t });
return {
endpoints: entities.flatMap((entity) => getEntityEndpoints({ entity, t, apiOrigin: getApiOrigin(request) })),
openApi,
postmanCollection: generatePostmanCollection({ request, openApi }),
apiDocsUrl: getAbsoluteApiUrl(request, apiPath("docs", { mode: "host-aware" })),
};
}
function getApiOrigin(request: Request) {
return new URL(getAbsoluteApiUrl(request, "/")).origin;
}
function generateCanonicalOpenApiSpecs({ request, t }: { request: Request; t: TFunction }): CanonicalOpenApiDocument {
return {
...openApiDocument,
servers: [
{
url: getApiOrigin(request),
description: translateApiSpec(t, "api.specs.hostDescription", "API host"),
},
],
} as CanonicalOpenApiDocument;
}
function getEntityApiRoute(apiOrigin: string, path: string) {
return new URL(apiPath(path, { mode: "host-aware" }), apiOrigin).toString();
}
function getEntityEndpoints({ entity, t, apiOrigin }: { entity: LegacyEntityWithDetails; t: TFunction; apiOrigin: string }) {
const body = Object.fromEntries(
entity.properties
.filter((property) => !property.isDefault)
.map((property) => [property.name, ApiHelper.getSampleValue({ property: property as never }) ?? ""])
);
const schema = Object.fromEntries(
entity.properties
.filter((property) => !property.isDefault)
.map((property) => [property.name, ApiHelper.getSchemaType({ property: property as never }) ?? ""])
);
return [
{
entity,
route: getEntityApiRoute(apiOrigin, `entities/${entity.slug}/rows`),
method: "GET",
description: translateApiSpec(t, "api.specs.operations.getAll", `Get all ${t(entity.titlePlural)}`, { name: t(entity.titlePlural) }),
responseSchema: JSON.stringify(schema, null, 2),
bodyExample: "",
},
{
entity,
route: getEntityApiRoute(apiOrigin, `entities/${entity.slug}/rows/:rowId`),
method: "GET",
description: translateApiSpec(t, "api.specs.operations.get", `Get ${t(entity.title)}`, { name: t(entity.title) }),
responseSchema: JSON.stringify(schema, null, 2),
bodyExample: "",
},
{
entity,
route: getEntityApiRoute(apiOrigin, `entities/${entity.slug}/rows`),
method: "POST",
description: translateApiSpec(t, "api.specs.operations.create", `Create ${t(entity.title)}`, { name: t(entity.title) }),
responseSchema: JSON.stringify(schema, null, 2),
bodyExample: JSON.stringify(body, null, 2),
},
{
entity,
route: getEntityApiRoute(apiOrigin, `entities/${entity.slug}/rows/:rowId`),
method: "PATCH",
description: translateApiSpec(t, "api.specs.operations.update", `Update ${t(entity.title)}`, { name: t(entity.title) }),
responseSchema: JSON.stringify(schema, null, 2),
bodyExample: JSON.stringify(body, null, 2),
},
{
entity,
route: getEntityApiRoute(apiOrigin, `entities/${entity.slug}/rows/:rowId`),
method: "DELETE",
description: translateApiSpec(t, "api.specs.operations.delete", `Delete ${t(entity.title)}`, { name: t(entity.title) }),
responseSchema: "",
bodyExample: "",
},
] satisfies ApiEndpointDto[];
}
function translateApiSpec(t: TFunction, key: string, fallback: string, options?: Record<string, unknown>) {
const translated = t(key, options);
return translated === key ? fallback : translated;
}
function generatePostmanCollection({ request, openApi }: { request: Request; openApi: CanonicalOpenApiDocument }): PostmanCollection {
const serverUrl = getApiOrigin(request);
const paths = openApi.paths as Record<string, Record<string, unknown>>;
return {
info: {
_postman_id: "canonical-api",
name: `${process.env.APP_NAME ?? "Boilerplate"} API`,
schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
},
item: Object.entries(paths).flatMap(([path, operations]) =>
Object.entries(operations)
.filter(([method]) => isHttpMethod(method))
.map(([method, operation]) => toPostmanItem({ serverUrl, path, method: method.toUpperCase(), operation }))
),
};
}
function toPostmanItem({ serverUrl, path, method, operation }: { serverUrl: string; path: string; method: string; operation: unknown }) {
const description = getOperationString(operation, "description") ?? getOperationString(operation, "summary") ?? "";
const postmanPath = path.replace(/\{([^}]+)\}/g, ":$1");
const request: Record<string, unknown> = {
url: getPostmanUrl(serverUrl, postmanPath, operation),
method,
header: getPostmanHeaders(operation),
description,
};
if (hasRequestBody(operation)) {
request.body = {
mode: "raw",
raw: "{}",
options: { raw: { language: "json" } },
};
}
return {
name: `${method} ${postmanPath}`,
request,
};
}
function getPostmanUrl(serverUrl: string, route: string, operation: unknown) {
const url = new URL(route, serverUrl);
const query = getPostmanQueryParams(operation);
for (const parameter of query) {
if (!parameter.disabled) {
url.searchParams.set(parameter.key, parameter.value);
}
}
return {
raw: url.toString(),
protocol: url.protocol.replace(":", ""),
host: [url.hostname],
path: url.pathname.replace(/^\//, "").split("/"),
port: url.port,
...(query.length > 0 ? { query } : {}),
};
}
function getPostmanHeaders(operation: unknown) {
const headers: PostmanHeader[] = [];
const securityScheme = getPreferredPostmanSecurityScheme(getOperationArray(operation, "security"));
const parameters = getOperationArray(operation, "parameters");
if (securityScheme === "apiKeyHeader") {
headers.push({ key: "x-api-key", value: getApiKeyHeaderPlaceholder(operation), type: "text" });
}
if (securityScheme === "analyticsTokenHeader") {
headers.push({ key: "x-analytics-token", value: "<analytics-token>", type: "text" });
}
if (securityScheme === "stripeWebhookSignature") {
headers.push({ key: "stripe-signature", value: "<stripe-signature>", type: "text" });
}
if (securityScheme === "mailjetWebhookAuth") {
headers.push({ key: "Authorization", value: "Basic <base64(mailjet:webhook-secret)>", type: "text" });
}
if (securityScheme === "bearerAuth" || securityScheme === "apiSessionBearer") {
headers.push({ key: "Authorization", value: "Bearer <token>", type: "text" });
}
if (parameters.some((entry) => isParameterNamed(entry, "Idempotency-Key"))) {
headers.push({ key: "Idempotency-Key", value: "<unique-operation-key>", type: "text" });
}
for (const parameter of getPostmanHeaderParams(parameters)) {
if (!headers.some((header) => header.key.toLowerCase() === parameter.key.toLowerCase())) {
headers.push(parameter);
}
}
return headers;
}
function getPostmanQueryParams(operation: unknown): PostmanQueryParam[] {
return getOperationArray(operation, "parameters")
.filter((parameter) => getParameterLocation(parameter) === "query")
.map((parameter) => {
const key = getParameterName(parameter);
return {
key,
value: `<${key}>`,
...(getParameterRequired(parameter) ? {} : { disabled: true }),
...getParameterDescription(parameter),
};
})
.filter((parameter) => parameter.key.length > 0);
}
function getPostmanHeaderParams(parameters: unknown[]): PostmanHeader[] {
return parameters
.filter((parameter) => getParameterLocation(parameter) === "header")
.map((parameter) => {
const key = getParameterName(parameter);
return {
key,
value: `<${key}>`,
type: "text" as const,
...getParameterDescription(parameter),
};
})
.filter((parameter) => parameter.key.length > 0);
}
function getPreferredPostmanSecurityScheme(security: unknown[]) {
if (security.some((entry) => isSecurityScheme(entry, "apiKeyHeader"))) {
return "apiKeyHeader";
}
if (security.some((entry) => isSecurityScheme(entry, "analyticsTokenHeader"))) {
return "analyticsTokenHeader";
}
if (security.some((entry) => isSecurityScheme(entry, "stripeWebhookSignature"))) {
return "stripeWebhookSignature";
}
if (security.some((entry) => isSecurityScheme(entry, "mailjetWebhookAuth"))) {
return "mailjetWebhookAuth";
}
if (security.some((entry) => isSecurityScheme(entry, "bearerAuth"))) {
return "bearerAuth";
}
if (security.some((entry) => isSecurityScheme(entry, "apiSessionBearer"))) {
return "apiSessionBearer";
}
return null;
}
function getOperationString(operation: unknown, key: string) {
return operation && typeof operation === "object" && typeof (operation as Record<string, unknown>)[key] === "string"
? (operation as Record<string, string>)[key]
: undefined;
}
function getOperationArray(operation: unknown, key: string) {
const value = operation && typeof operation === "object" ? (operation as Record<string, unknown>)[key] : undefined;
return Array.isArray(value) ? value : [];
}
function hasRequestBody(operation: unknown) {
return Boolean(operation && typeof operation === "object" && "requestBody" in operation);
}
function hasScopedApiKeyPermissions(operation: unknown) {
return Boolean(operation && typeof operation === "object" && "x-api-key-permissions" in operation);
}
function getApiKeyHeaderPlaceholder(operation: unknown) {
if (operation && typeof operation === "object" && "x-api-key-placeholder" in operation) {
const placeholder = (operation as { "x-api-key-placeholder"?: unknown })["x-api-key-placeholder"];
if (typeof placeholder === "string" && placeholder.length > 0) {
return placeholder;
}
}
return hasScopedApiKeyPermissions(operation) ? "<api-key>" : "<service-token>";
}
function isSecurityScheme(value: unknown, scheme: string) {
return Boolean(value && typeof value === "object" && scheme in value);
}
function isParameterNamed(value: unknown, name: string) {
return Boolean(value && typeof value === "object" && (value as Record<string, unknown>).name === name);
}
function getParameterName(value: unknown) {
return value && typeof value === "object" && typeof (value as Record<string, unknown>).name === "string"
? ((value as Record<string, string>).name as string)
: "";
}
function getParameterLocation(value: unknown) {
return value && typeof value === "object" && typeof (value as Record<string, unknown>).in === "string"
? ((value as Record<string, string>).in as string)
: "";
}
function getParameterRequired(value: unknown) {
return Boolean(value && typeof value === "object" && (value as Record<string, unknown>).required === true);
}
function getParameterDescription(value: unknown) {
if (value && typeof value === "object" && typeof (value as Record<string, unknown>).description === "string") {
return { description: (value as Record<string, string>).description };
}
return {};
}
function isHttpMethod(value: string) {
return ["get", "post", "put", "patch", "delete", "options", "head"].includes(value);
}
export default {
generateSpecs,
getEntityEndpoints,
};
@@ -1,101 +0,0 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@toolctrl/db/logs.server", () => ({
createLegacyEntityWebhookLog: vi.fn(async (data) => data),
createLegacyRowLog: vi.fn(async () => ({ id: "log_1" })),
getLegacyEntityWebhooksByAction: vi.fn(),
}));
vi.mock("~/utils/url.server", () => ({
getBaseURL: vi.fn((request: Request) => new URL(request.url).origin),
}));
vi.mock("~/utils/helpers/ApiHelper", () => ({
default: {
getApiFormat: vi.fn(() => ({ formatted: true })),
},
}));
import { createLegacyEntityWebhookLog, createLegacyRowLog, getLegacyEntityWebhooksByAction } from "@toolctrl/db/logs.server";
import { createApiRowLog } from "./RowLogService.server";
describe("RowLogService webhook delivery", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 202 })));
});
it("resolves relative webhook URLs against the request base before validation", async () => {
vi.mocked(getLegacyEntityWebhooksByAction).mockResolvedValueOnce([{ id: "webhook_relative", method: "POST", endpoint: "/webhooks/row" }]);
await createApiRowLog(new Request("https://tenant.example.com/api/rows"), {
tenantId: "tenant_1",
action: "created",
entity: { id: "entity_1" },
item: { id: "row_1" },
});
expect(fetch).toHaveBeenCalledWith(
"https://tenant.example.com/webhooks/row",
expect.objectContaining({ method: "POST", redirect: "manual", signal: expect.any(AbortSignal) })
);
expect(createLegacyEntityWebhookLog).toHaveBeenCalledWith({ webhookId: "webhook_relative", logId: "log_1", status: 202 });
});
it("follows safe redirects after validating the redirect target", async () => {
vi.stubGlobal(
"fetch",
vi
.fn()
.mockResolvedValueOnce(new Response(null, { status: 307, headers: { location: "https://hooks.example.com/row-next" } }))
.mockResolvedValueOnce(new Response(null, { status: 202 }))
);
vi.mocked(getLegacyEntityWebhooksByAction).mockResolvedValueOnce([{ id: "webhook_redirect", method: "POST", endpoint: "https://hooks.example.com/row" }]);
await createApiRowLog(new Request("https://tenant.example.com/api/rows"), {
tenantId: "tenant_1",
action: "created",
entity: { id: "entity_1" },
item: { id: "row_1" },
});
expect(fetch).toHaveBeenNthCalledWith(1, "https://hooks.example.com/row", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(fetch).toHaveBeenNthCalledWith(2, "https://hooks.example.com/row-next", expect.objectContaining({ method: "POST", redirect: "manual" }));
expect(createLegacyEntityWebhookLog).toHaveBeenCalledWith({ webhookId: "webhook_redirect", logId: "log_1", status: 202 });
});
it("blocks unsafe redirect targets without following them", async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response(null, { status: 302, headers: { location: "http://127.0.0.1/webhook" } })));
vi.mocked(getLegacyEntityWebhooksByAction).mockResolvedValueOnce([{ id: "webhook_redirect_blocked", method: "POST", endpoint: "https://hooks.example.com/row" }]);
await createApiRowLog(new Request("https://tenant.example.com/api/rows"), {
tenantId: "tenant_1",
action: "created",
entity: { id: "entity_1" },
item: { id: "row_1" },
});
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith("https://hooks.example.com/row", expect.objectContaining({ redirect: "manual" }));
expect(createLegacyEntityWebhookLog).toHaveBeenCalledWith({ webhookId: "webhook_redirect_blocked", logId: "log_1", status: 0 });
});
it("blocks unsafe webhook URLs and records failed delivery status without fetching", async () => {
vi.mocked(getLegacyEntityWebhooksByAction).mockResolvedValueOnce([
{ id: "webhook_loopback", method: "POST", endpoint: "http://127.0.0.1/webhook" },
{ id: "webhook_relative_localhost", method: "POST", endpoint: "/webhooks/row" },
]);
await createApiRowLog(new Request("https://localhost/api/rows"), {
tenantId: "tenant_1",
action: "created",
entity: { id: "entity_1" },
item: { id: "row_1" },
});
expect(fetch).not.toHaveBeenCalled();
expect(createLegacyRowLog).toHaveBeenCalledTimes(1);
expect(createLegacyEntityWebhookLog).toHaveBeenCalledWith({ webhookId: "webhook_loopback", logId: "log_1", status: 0 });
expect(createLegacyEntityWebhookLog).toHaveBeenCalledWith({ webhookId: "webhook_relative_localhost", logId: "log_1", status: 0 });
});
});
@@ -1,285 +0,0 @@
import { createLegacyEntityWebhookLog, createLegacyRowLog, getLegacyEntityWebhooksByAction } from "@toolctrl/db/logs.server";
import { getBaseURL } from "~/utils/url.server";
import ApiHelper from "~/utils/helpers/ApiHelper";
const LEGACY_WEBHOOK_FETCH_TIMEOUT_MS = 10_000;
const BLOCKED_WEBHOOK_STATUS = 0;
const LEGACY_WEBHOOK_REDIRECT_LIMIT = 5;
const INTERNAL_WEBHOOK_HOST_SUFFIXES = [".localhost", ".local", ".internal", ".lan", ".home", ".corp", ".intranet", ".svc"] as const;
type ApiRowLogEntity = {
id: string;
[key: string]: unknown;
};
type ApiRowLogItem = {
id: string;
[key: string]: unknown;
} | null;
export async function createApiRowLog(
request: Request,
data: {
tenantId: string | null;
createdByUserId?: string | null;
createdByApiKey?: string | null;
action: string;
entity: ApiRowLogEntity;
item: ApiRowLogItem;
commentId?: string | null;
details?: string;
},
) {
const log = await createLegacyRowLog({
tenantId: data.tenantId,
userId: data.createdByUserId ?? null,
apiKeyId: data.createdByApiKey ?? null,
url: new URL(request.url).pathname,
rowId: data.item?.id ?? null,
action: data.action,
details: data.details ?? null,
commentId: data.commentId ?? null,
});
const apiFormat = ApiHelper.getApiFormat(data.entity as never, data.item as never);
await callApiEntityWebhooks({
logId: log.id,
entityId: data.entity.id,
action: data.action,
body: apiFormat,
request,
});
return log;
}
async function callApiEntityWebhooks({
logId,
entityId,
action,
body,
request,
}: {
logId: string;
entityId: string;
action: string;
body: string;
request: Request;
}) {
const webhooks = await getLegacyEntityWebhooksByAction(entityId, action);
return Promise.all(
webhooks.map(async (webhook) => {
if (!webhook.endpoint) {
return undefined;
}
const status = await fetchLegacyWebhookStatus(webhook.endpoint, request, {
method: webhook.method,
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
});
return createLegacyEntityWebhookLog({
webhookId: webhook.id,
logId,
status,
});
}),
);
}
function resolveWebhookEndpoint(endpoint: string, request: Request): string {
const resolvedEndpoint = endpoint.startsWith("/") ? getBaseURL(request) + endpoint : endpoint;
return validateOutboundWebhookUrl(resolvedEndpoint);
}
async function fetchLegacyWebhookStatus(endpoint: string, request: Request, init: RequestInit): Promise<number> {
try {
const response = await fetchWebhookWithRedirects(resolveWebhookEndpoint(endpoint, request), init);
return response.status;
} catch {
return BLOCKED_WEBHOOK_STATUS;
}
}
async function fetchWithTimeout(input: Parameters<typeof fetch>[0], init: RequestInit): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), LEGACY_WEBHOOK_FETCH_TIMEOUT_MS);
try {
return await fetch(input, { ...init, redirect: "manual", signal: controller.signal });
} finally {
clearTimeout(timeout);
}
}
async function fetchWebhookWithRedirects(input: string, init: RequestInit): Promise<Response> {
let currentUrl = input;
let currentInit = init;
for (let redirects = 0; redirects <= LEGACY_WEBHOOK_REDIRECT_LIMIT; redirects += 1) {
const response = await fetchWithTimeout(currentUrl, currentInit);
if (!isRedirectResponse(response.status)) {
return response;
}
const location = response.headers.get("location");
if (!location) {
return response;
}
if (redirects === LEGACY_WEBHOOK_REDIRECT_LIMIT) {
throw new Error("Webhook redirect limit exceeded.");
}
currentUrl = resolveOutboundWebhookRedirect(currentUrl, location);
currentInit = buildRedirectRequestInit(currentInit, response.status);
}
throw new Error("Webhook redirect limit exceeded.");
}
function resolveOutboundWebhookRedirect(currentUrl: string, location: string): string {
let redirectUrl: URL;
try {
redirectUrl = new URL(location, currentUrl);
} catch {
throw new Error("Webhook redirect location must be a valid URL.");
}
return validateOutboundWebhookUrl(redirectUrl.toString());
}
function isRedirectResponse(status: number): boolean {
return status >= 300 && status < 400;
}
function buildRedirectRequestInit(init: RequestInit, status: number): RequestInit {
const method = typeof init.method === "string" ? init.method.toUpperCase() : undefined;
if (status === 303 || ((status === 301 || status === 302) && method === "POST")) {
const headers = new Headers(init.headers);
headers.delete("content-type");
headers.delete("content-length");
return { ...init, method: "GET", body: undefined, headers };
}
return init;
}
function validateOutboundWebhookUrl(endpoint: string): string {
let url: URL;
try {
url = new URL(endpoint);
} catch {
throw new Error("Webhook endpoint must be an absolute URL.");
}
if (url.protocol !== "http:" && url.protocol !== "https:") {
throw new Error("Webhook endpoint must use http or https.");
}
if (isBlockedWebhookHostname(url.hostname)) {
throw new Error("Webhook endpoint host is not allowed.");
}
return url.toString();
}
function isBlockedWebhookHostname(hostname: string): boolean {
const normalizedHostname = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
if (!normalizedHostname) {
return true;
}
const ipv4 = parseIpv4Address(normalizedHostname);
if (ipv4) {
return isBlockedIpv4Address(ipv4);
}
const ipv6 = parseIpv6Address(normalizedHostname);
if (ipv6) {
return isBlockedIpv6Address(ipv6);
}
return (
normalizedHostname === "localhost" ||
!normalizedHostname.includes(".") ||
INTERNAL_WEBHOOK_HOST_SUFFIXES.some((suffix) => normalizedHostname.endsWith(suffix))
);
}
function parseIpv4Address(hostname: string): [number, number, number, number] | undefined {
const parts = hostname.split(".");
if (parts.length !== 4) {
return undefined;
}
const octets = parts.map((part) => Number(part));
if (octets.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) {
return undefined;
}
return octets as [number, number, number, number];
}
function isBlockedIpv4Address([first, second]: [number, number, number, number]): boolean {
return (
first === 0 ||
first === 10 ||
first === 127 ||
first >= 224 ||
(first === 100 && second >= 64 && second <= 127) ||
(first === 169 && second === 254) ||
(first === 172 && second >= 16 && second <= 31) ||
(first === 192 && second === 168) ||
(first === 198 && (second === 18 || second === 19))
);
}
function parseIpv6Address(hostname: string): number[] | undefined {
if (!hostname.includes(":")) {
return undefined;
}
const [head = "", tail = "", extra] = hostname.split("::");
if (extra !== undefined) {
return undefined;
}
const headParts = head ? head.split(":") : [];
const tailParts = tail ? tail.split(":") : [];
const missingPartCount = 8 - headParts.length - tailParts.length;
if (missingPartCount < 0 || (!hostname.includes("::") && missingPartCount !== 0)) {
return undefined;
}
const parts = [...headParts, ...Array(missingPartCount).fill("0"), ...tailParts];
if (parts.length !== 8) {
return undefined;
}
const hextets = parts.map((part) => Number.parseInt(part, 16));
if (hextets.some((part) => !Number.isInteger(part) || part < 0 || part > 0xffff)) {
return undefined;
}
return hextets;
}
function isBlockedIpv6Address(hextets: number[]): boolean {
const first = hextets[0] ?? 0;
const isUnspecified = hextets.every((part) => part === 0);
const isLoopback = hextets.slice(0, 7).every((part) => part === 0) && hextets[7] === 1;
const isUniqueLocal = (first & 0xfe00) === 0xfc00;
const isLinkLocal = (first & 0xffc0) === 0xfe80;
const isIpv4Mapped = hextets.slice(0, 5).every((part) => part === 0) && hextets[5] === 0xffff;
const isIpv4Compatible = hextets.slice(0, 6).every((part) => part === 0);
if (isUnspecified || isLoopback || isUniqueLocal || isLinkLocal) {
return true;
}
if (isIpv4Mapped || isIpv4Compatible) {
const ipv4: [number, number, number, number] = [hextets[6] >> 8, hextets[6] & 0xff, hextets[7] >> 8, hextets[7] & 0xff];
return isBlockedIpv4Address(ipv4);
}
return false;
}
@@ -1,4 +1,4 @@
import { Prisma } from "@toolctrl/db/prisma-browser";
import { Prisma } from "@hivegrid/db/prisma-browser";
import ApiKeyLogsConstants from "./ApiKeyLogsConstants";
function getGroupByValues(searchParams: URLSearchParams) {
@@ -0,0 +1,89 @@
// AK-P16b · booking-page editor UI (M06 Block E.2 + H). Minimal FUNCTIONAL form
// (bespoke polish follows D-P16): grunddata + providers + confirmation template +
// publish toggle, and the public-URL + iframe embed-code generator with copy buttons.
import { Form, useActionData, useLoaderData } from "react-router";
import { useTranslation } from "react-i18next";
import { useRootData } from "~/utils/data/useRootData";
import type { BookingPageEditorLoaderData, BookingPageEditorActionData } from "../routes/BookingPageEditor.server";
function CopyField({ label, value }: { label: string; value: string }): JSX.Element {
return (
<div className="mt-2">
<span className="text-muted-foreground text-xs">{label}</span>
<div className="flex gap-2">
<input readOnly value={value} className="w-full rounded border px-2 py-1 text-xs" data-ui-id="ui.booking.pages.embed.value" />
<button type="button" className="rounded border px-2 py-1 text-xs" onClick={() => navigator.clipboard?.writeText(value)}>
⧉
</button>
</div>
</div>
);
}
export default function BookingPageEditorRoute(): JSX.Element {
const { t } = useTranslation();
const vm = useLoaderData<BookingPageEditorLoaderData>();
const actionData = useActionData<BookingPageEditorActionData>();
const rootData = useRootData();
const page = vm.page;
return (
<main className="mx-auto max-w-2xl px-4 py-10" data-ui-id="ui.booking.pages.editor">
<h1 className="text-foreground text-xl font-semibold">{t("bookings.pages.editor.title")}</h1>
{actionData && !actionData.ok ? (
<p role="alert" className="mt-4 text-red-600" data-ui-id="ui.booking.pages.editor.error">
{t(actionData.errorKey)}
</p>
) : null}
<Form method="post" className="mt-6 space-y-3">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.slug")}</span>
<input name="slug" defaultValue={page?.slug ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.pageTitle")}</span>
<input name="title" defaultValue={page?.title ?? ""} required className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.description")}</span>
<textarea name="description" defaultValue={page?.description ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.duration")}</span>
<input name="durationMinutes" type="number" defaultValue={page?.durationMinutes ?? 30} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.providers")}</span>
<input name="providers" defaultValue={page?.providerUserIds.join(",") ?? ""} placeholder="userId1,userId2" className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationSubject")}</span>
<input name="confirmationEmailSubject" defaultValue={page?.confirmationEmailSubject ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="block">
<span className="text-sm">{t("bookings.pages.editor.confirmationBody")}</span>
<textarea name="confirmationEmailBody" defaultValue={page?.confirmationEmailBody ?? ""} className="w-full rounded border px-2 py-1" />
</label>
<label className="flex items-center gap-2 text-sm">
<input type="checkbox" name="isPublished" defaultChecked={page?.isPublished ?? false} />
{t("bookings.pages.editor.publishToggle")}
</label>
<button type="submit" className="rounded bg-primary px-4 py-2 text-primary-foreground" data-ui-id="ui.booking.pages.editor.save">
{t("bookings.pages.editor.save")}
</button>
</Form>
{vm.publicUrl && vm.embedCode ? (
<section className="mt-8" data-ui-id="ui.booking.pages.embed">
<h2 className="font-medium">{t("bookings.pages.embedCode")}</h2>
<CopyField label={t("bookings.pages.publicUrl")} value={vm.publicUrl} />
<CopyField label={t("bookings.pages.embedCode")} value={vm.embedCode} />
</section>
) : null}
</main>
);
}
@@ -0,0 +1,90 @@
// AK-P16b · public booking page (M06 Block G) — minimal FUNCTIONAL UI (reachable +
// i18n + states), NOT the bespoke Calendly-polish screen (that waits on David D-P16).
// Single-page flow: pick a slot → fill the mini-form (GDPR required) → confirmation
// with an "add to calendar" (.ics) download. The component reads route-injected data
// only (no DB import); it is in apps/web so useLoaderData is allowed here.
import { Form, useActionData, useLoaderData, useNavigation } from "react-router";
import { useTranslation } from "react-i18next";
import type { PublicBookingLoaderData, PublicBookingActionData } from "../routes/PublicBooking.server";
export default function PublicBookingRoute(): JSX.Element {
const vm = useLoaderData<PublicBookingLoaderData>();
const actionData = useActionData<PublicBookingActionData>();
const navigation = useNavigation();
const { t } = useTranslation();
const submitting = navigation.state === "submitting";
if (actionData?.ok) {
const icsHref = `data:text/calendar;base64,${actionData.icsBase64}`;
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<h1 className="text-xl font-semibold">{t("bookings.public.confirmedHeadline")}</h1>
<p className="mt-2">
{t("bookings.public.confirmedBody", { title: actionData.titleLabel, date: actionData.dateLabel, time: actionData.timeLabel })}
</p>
<a data-ui-id="ui.booking.public.ics" href={icsHref} download="termin.ics" className="mt-4 inline-block underline">
{t("bookings.public.addToCalendar")}
</a>
</main>
);
}
return (
<main data-ui-id="ui.booking.public" className={vm.isEmbed ? "p-4" : "mx-auto max-w-xl p-6"}>
<header>
<p className="text-sm text-muted-foreground">{vm.tenantName}</p>
<h1 className="text-xl font-semibold">{vm.title}</h1>
{vm.description ? <p className="mt-1 text-muted-foreground">{vm.description}</p> : null}
<p className="mt-1 text-sm">{t("bookings.public.duration", { minutes: vm.durationMinutes })}</p>
</header>
{actionData && !actionData.ok ? (
<p data-ui-id="ui.booking.public.error" role="alert" className="mt-4 text-red-600">
{t(actionData.errorKey)}
</p>
) : null}
{vm.slots.length === 0 ? (
<p data-ui-id="ui.booking.public.empty" className="mt-6">
{t("bookings.public.noSlots")}
</p>
) : (
<Form method="post" className="mt-6 space-y-4" data-ui-id="ui.booking.public.form">
<input type="hidden" name="date" value={vm.date} />
<input type="hidden" name="tz" value={vm.timezone} />
{/* Honeypot — hidden from real users (M06 abuse guard). */}
<input type="text" name="company" tabIndex={-1} autoComplete="off" className="hidden" aria-hidden="true" />
<fieldset>
<legend className="text-sm font-medium">{t("bookings.public.chooseSlot", { date: vm.date })}</legend>
<div className="mt-2 flex flex-wrap gap-2">
{vm.slots.map((slot, index) => (
<label key={slot.startAtIso} className="cursor-pointer rounded border px-3 py-1">
<input type="radio" name="startAt" value={slot.startAtIso} defaultChecked={index === 0} className="mr-1" />
{slot.label}
</label>
))}
</div>
</fieldset>
<div className="grid grid-cols-2 gap-3">
<input name="vorname" placeholder={t("bookings.public.firstName")} className="rounded border px-3 py-2" required />
<input name="nachname" placeholder={t("bookings.public.lastName")} className="rounded border px-3 py-2" required />
</div>
<input name="email" type="email" placeholder={t("bookings.public.email")} className="w-full rounded border px-3 py-2" required />
<input name="telefon" placeholder={t("bookings.public.phone")} className="w-full rounded border px-3 py-2" />
<label className="flex items-start gap-2 text-sm">
<input type="checkbox" name="gdpr" required className="mt-1" />
<span>{t("bookings.public.gdpr")}</span>
</label>
<button type="submit" disabled={submitting} data-ui-id="ui.booking.public.submit" className="rounded bg-primary px-4 py-2 text-primary-foreground disabled:opacity-50">
{submitting ? t("bookings.public.submitting") : t("bookings.public.submit")}
</button>
</Form>
)}
</main>
);
}
@@ -0,0 +1,318 @@
// AK-P16b · booking DB access (thin Prisma wrappers). Public reads resolve the
// tenant from the URL slug (no logged-in user); admin reads are tenant-scoped by the
// guard. Slot config + provider list feed the pure slot engine.
import { db } from "~/utils/db.server";
import type { SlotEngineConfig } from "../services/slotEngine";
export interface PublicBookingPage {
tenantId: string;
tenantName: string;
tenantSlug: string;
pageId: string;
slug: string;
title: string;
description: string | null;
durationMinutes: number;
intakeFormId: string | null;
assignmentStrategy: string;
confirmationEmailSubject: string;
confirmationEmailBody: string;
internalEventTitleTemplate: string | null;
redirectUrlAfterBooking: string | null;
providerUserIds: string[];
config: SlotEngineConfig;
}
const PAGE_SELECT = {
id: true,
slug: true,
title: true,
description: true,
durationMinutes: true,
intakeFormId: true,
bufferBeforeMinutes: true,
bufferAfterMinutes: true,
slotIncrementMinutes: true,
minNoticeHours: true,
maxAdvanceDays: true,
assignmentStrategy: true,
confirmationEmailSubject: true,
confirmationEmailBody: true,
internalEventTitleTemplate: true,
redirectUrlAfterBooking: true,
} as const;
function toConfig(page: { durationMinutes: number; bufferBeforeMinutes: number; bufferAfterMinutes: number; slotIncrementMinutes: number; minNoticeHours: number; maxAdvanceDays: number }): SlotEngineConfig {
return {
durationMinutes: page.durationMinutes,
bufferBeforeMinutes: page.bufferBeforeMinutes,
bufferAfterMinutes: page.bufferAfterMinutes,
slotIncrementMinutes: page.slotIncrementMinutes,
minNoticeHours: page.minNoticeHours,
maxAdvanceDays: page.maxAdvanceDays,
};
}
/**
* Resolve a public booking page by tenant slug + page slug. Returns null when the
* tenant is inactive/unknown or the page is unpublished/archived (M06 G.4/K.6 — a
* 404 with the same Klartext, never leaking tenant existence). Active providers only.
*/
export async function resolvePublicBookingPage(tenantSlug: string, pageSlug: string): Promise<PublicBookingPage | null> {
const tenant = await db.tenant.findUnique({ where: { slug: tenantSlug }, select: { id: true, name: true, active: true } });
if (!tenant || !tenant.active) {
return null;
}
const page = await db.bookingPage.findFirst({
where: { tenantId: tenant.id, slug: pageSlug, isPublished: true, archivedAt: null },
select: PAGE_SELECT,
});
if (!page) {
return null;
}
const providers = await db.bookingPageProvider.findMany({
where: { bookingPageId: page.id, tenantId: tenant.id, isActive: true },
select: { providerUserId: true },
orderBy: { displayOrder: "asc" },
});
return {
tenantId: tenant.id,
tenantName: tenant.name,
tenantSlug,
pageId: page.id,
slug: page.slug,
title: page.title,
description: page.description,
durationMinutes: page.durationMinutes,
intakeFormId: page.intakeFormId,
assignmentStrategy: page.assignmentStrategy,
confirmationEmailSubject: page.confirmationEmailSubject,
confirmationEmailBody: page.confirmationEmailBody,
internalEventTitleTemplate: page.internalEventTitleTemplate,
redirectUrlAfterBooking: page.redirectUrlAfterBooking,
providerUserIds: providers.map((p) => p.providerUserId),
config: toConfig(page),
};
}
export interface AppointmentListRow {
id: string;
startAt: Date;
endAt: Date;
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
providerUserId: string;
pageTitle: string;
customerName: string;
customerEmail: string;
}
function intakeName(intakeAnswers: unknown): { name: string; email: string } {
if (intakeAnswers && typeof intakeAnswers === "object") {
const a = intakeAnswers as { vorname?: unknown; nachname?: unknown; email?: unknown };
const name = [a.vorname, a.nachname].filter((v) => typeof v === "string" && v).join(" ");
return { name, email: typeof a.email === "string" ? a.email : "" };
}
return { name: "", email: "" };
}
/**
* List a tenant's appointments (M06 Block C). When `ownerUserId` is set (read_own),
* only that provider's appointments are returned — the server-side owner filter
* (M06 K.5), never a client filter.
*/
export async function listAppointmentsForTenant(input: { tenantId: string; ownerUserId?: string | null }): Promise<AppointmentListRow[]> {
const rows = await db.appointment.findMany({
where: { tenantId: input.tenantId, ...(input.ownerUserId ? { providerUserId: input.ownerUserId } : {}) },
select: { id: true, startAt: true, endAt: true, status: true, providerUserId: true, intakeAnswers: true, bookingPage: { select: { title: true } } },
orderBy: { startAt: "desc" },
take: 200,
});
return rows.map((r) => {
const { name, email } = intakeName(r.intakeAnswers);
return { id: r.id, startAt: r.startAt, endAt: r.endAt, status: r.status, providerUserId: r.providerUserId, pageTitle: r.bookingPage.title, customerName: name, customerEmail: email };
});
}
export interface AppointmentDetail {
id: string;
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
providerUserId: string;
startAt: Date;
endAt: Date;
timezone: string;
pageTitle: string;
customerName: string;
customerEmail: string;
intakeAnswers: Record<string, unknown>;
cancellationReason: string | null;
notesInternal: string | null;
}
/** One appointment's detail (M06 Block D). Returns providerUserId so the route owner-checks. */
export async function getAppointmentDetail(tenantId: string, appointmentId: string): Promise<AppointmentDetail | null> {
const row = await db.appointment.findFirst({
where: { id: appointmentId, tenantId },
select: {
id: true,
status: true,
providerUserId: true,
startAt: true,
endAt: true,
timezone: true,
intakeAnswers: true,
cancellationReason: true,
notesInternal: true,
bookingPage: { select: { title: true } },
},
});
if (!row) {
return null;
}
const { name, email } = intakeName(row.intakeAnswers);
return {
id: row.id,
status: row.status,
providerUserId: row.providerUserId,
startAt: row.startAt,
endAt: row.endAt,
timezone: row.timezone,
pageTitle: row.bookingPage.title,
customerName: name,
customerEmail: email,
intakeAnswers: (row.intakeAnswers as Record<string, unknown>) ?? {},
cancellationReason: row.cancellationReason,
notesInternal: row.notesInternal,
};
}
export interface BookingPageListRow {
id: string;
slug: string;
title: string;
durationMinutes: number;
isPublished: boolean;
providerCount: number;
}
/** List a tenant's booking pages (M06 Block E.1). */
export async function listBookingPages(tenantId: string): Promise<BookingPageListRow[]> {
const rows = await db.bookingPage.findMany({
where: { tenantId, archivedAt: null },
select: { id: true, slug: true, title: true, durationMinutes: true, isPublished: true, _count: { select: { providers: true } } },
orderBy: { createdAt: "desc" },
});
return rows.map((r) => ({ id: r.id, slug: r.slug, title: r.title, durationMinutes: r.durationMinutes, isPublished: r.isPublished, providerCount: r._count.providers }));
}
export interface BookingPageEdit {
id: string;
slug: string;
title: string;
description: string | null;
durationMinutes: number;
confirmationEmailSubject: string;
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
}
/** Load a booking page for the editor (M06 Block E.2). */
export async function getBookingPageForEdit(tenantId: string, pageId: string): Promise<BookingPageEdit | null> {
const row = await db.bookingPage.findFirst({
where: { id: pageId, tenantId, archivedAt: null },
select: { id: true, slug: true, title: true, description: true, durationMinutes: true, confirmationEmailSubject: true, confirmationEmailBody: true, isPublished: true, providers: { select: { providerUserId: true } } },
});
if (!row) {
return null;
}
return {
id: row.id,
slug: row.slug,
title: row.title,
description: row.description,
durationMinutes: row.durationMinutes,
confirmationEmailSubject: row.confirmationEmailSubject,
confirmationEmailBody: row.confirmationEmailBody,
isPublished: row.isPublished,
providerUserIds: row.providers.map((p) => p.providerUserId),
};
}
export interface BookingPageInput {
tenantId: string;
createdByUserId: string;
slug: string;
title: string;
description?: string | null;
durationMinutes: number;
confirmationEmailSubject: string;
confirmationEmailBody: string;
isPublished: boolean;
providerUserIds: string[];
}
/** Create a booking page + its provider links (M06 Block E.2). */
export async function createBookingPage(input: BookingPageInput): Promise<string> {
return db.$transaction(async (tx) => {
const page = await tx.bookingPage.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.createdByUserId,
slug: input.slug,
title: input.title,
description: input.description ?? null,
durationMinutes: input.durationMinutes,
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
},
select: { id: true },
});
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: page.id, providerUserId, displayOrder: index })),
});
return page.id;
});
}
/** Update a booking page + replace its provider links (M06 Block E.2). */
export async function updateBookingPage(pageId: string, input: BookingPageInput): Promise<void> {
await db.$transaction(async (tx) => {
await tx.bookingPage.update({
where: { id: pageId },
data: {
slug: input.slug,
title: input.title,
description: input.description ?? null,
durationMinutes: input.durationMinutes,
confirmationEmailSubject: input.confirmationEmailSubject,
confirmationEmailBody: input.confirmationEmailBody,
isPublished: input.isPublished,
},
});
await tx.bookingPageProvider.deleteMany({ where: { bookingPageId: pageId } });
await tx.bookingPageProvider.createMany({
data: input.providerUserIds.map((providerUserId, index) => ({ tenantId: input.tenantId, bookingPageId: pageId, providerUserId, displayOrder: index })),
});
});
}
/** True when `slug` is already used by another page in the tenant (M06 E.2 validation). */
export async function isSlugTaken(tenantId: string, slug: string, exceptPageId?: string): Promise<boolean> {
const row = await db.bookingPage.findFirst({ where: { tenantId, slug, ...(exceptPageId ? { NOT: { id: exceptPageId } } : {}) }, select: { id: true } });
return row !== null;
}
/** Match an incoming booker email to an existing tenant contact (M06 J.1). */
export async function findKontaktIdByEmail(tenantId: string, email: string): Promise<string | null> {
const normalized = email.trim().toLowerCase();
if (!normalized) {
return null;
}
const row = await db.kontaktEmail.findFirst({
where: { tenantId, email: { equals: normalized, mode: "insensitive" } },
select: { kontaktId: true },
});
return row?.kontaktId ?? null;
}
@@ -0,0 +1,88 @@
// AK-P16b · booking-page editor (M06 Block E.2) — shared loader/action for the `new`
// and `:id` routes. bookings.admin only. Validates the slug (reserved + unique) and
// upserts the page + its provider links. The loader exposes the absolute public URL +
// an iframe embed snippet (M06 Block H, DoD 3) for the copy-to-clipboard generator.
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { validateCSRFToken } from "~/utils/session.server";
import { loadBookingContext, requireBookingPermission, BOOKING_PERMISSIONS } from "./bookingAccess.server";
import { RESERVED_BOOKING_SLUGS, bookingPagesListPath, publicBookingPath, publicBookingEmbedPath, notFoundResponse } from "./bookingRoutePaths";
import { getBookingPageForEdit, createBookingPage, updateBookingPage, isSlugTaken, type BookingPageEdit } from "../db/booking.db.server";
export interface BookingPageEditorLoaderData {
readonly mode: "new" | "edit";
readonly tenantSlug: string;
readonly page: BookingPageEdit | null;
readonly publicUrl: string | null;
readonly embedCode: string | null;
}
export type BookingPageEditorActionData = { readonly ok: false; readonly errorKey: string; readonly field?: string };
function embedSnippet(url: string): string {
return `<iframe src="${url}" width="100%" height="700" frameborder="0" style="border:none"></iframe>`;
}
export async function bookingPageEditorLoader({ request, params }: LoaderFunctionArgs) {
const ctx = await loadBookingContext({ request, params, requireModule: true });
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
const tenantSlug = params.tenant ?? "";
const origin = new URL(request.url).origin;
const page = params.id ? await getBookingPageForEdit(ctx.tenantId, params.id) : null;
if (params.id && !page) {
throw notFoundResponse();
}
const publicUrl = page ? `${origin}${publicBookingPath(tenantSlug, page.slug)}` : null;
const embedCode = page ? embedSnippet(`${origin}${publicBookingEmbedPath(tenantSlug, page.slug)}`) : null;
return data<BookingPageEditorLoaderData>({ mode: params.id ? "edit" : "new", tenantSlug, page, publicUrl, embedCode });
}
export async function bookingPageEditorAction({ request, params }: ActionFunctionArgs) {
const ctx = await loadBookingContext({ request, params, requireModule: true });
requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin);
await validateCSRFToken(request);
const form = await request.formData();
const slug = ((form.get("slug") as string | null) ?? "").trim().toLowerCase();
const title = ((form.get("title") as string | null) ?? "").trim();
if (!/^[a-z0-9-]{3,60}$/u.test(slug)) {
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugReserved", field: "slug" }, { status: 400 });
}
if (RESERVED_BOOKING_SLUGS.has(slug)) {
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugReserved", field: "slug" }, { status: 400 });
}
if (await isSlugTaken(ctx.tenantId, slug, params.id)) {
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.slugTaken", field: "slug" }, { status: 409 });
}
const providerUserIds = ((form.get("providers") as string | null) ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
if (providerUserIds.length === 0) {
return data<BookingPageEditorActionData>({ ok: false, errorKey: "bookings.error.providerRequired", field: "providers" }, { status: 400 });
}
const input = {
tenantId: ctx.tenantId,
createdByUserId: ctx.userId,
slug,
title: title || slug,
description: (form.get("description") as string | null) ?? null,
durationMinutes: Number(form.get("durationMinutes")) || 30,
confirmationEmailSubject: ((form.get("confirmationEmailSubject") as string | null) ?? "").trim() || `Bestätigung: ${title || slug}`,
confirmationEmailBody: ((form.get("confirmationEmailBody") as string | null) ?? "").trim() || "Dein Termin ist bestätigt.",
isPublished: form.get("isPublished") === "on" || form.get("isPublished") === "true",
providerUserIds,
};
if (params.id) {
await updateBookingPage(params.id, input);
} else {
await createBookingPage(input);
}
return redirect(bookingPagesListPath(params.tenant ?? ""));
}
@@ -0,0 +1,136 @@
// AK-P16b · public booking flow (M06 Block G) — loader + action shared by the
// canonical `/b/{tenant}/{slug}` route and its `/embed` iframe variant. NO auth, NO
// session CSRF (there is no logged-in user); abuse is bounded by a honeypot + the
// GDPR-acceptance gate + the slot re-check on submit. The tenant is resolved from
// the URL slug; an unknown/inactive tenant or unpublished page is a 404 with the
// same Klartext (never leaks tenant existence, M06 G.4/K.6).
import { type LoaderFunctionArgs, type ActionFunctionArgs, data, redirect } from "react-router";
import { formatInTimeZone } from "date-fns-tz";
import { notFoundResponse } from "./bookingRoutePaths";
import { resolvePublicBookingPage } from "../db/booking.db.server";
import { loadSlotsForDate } from "../services/SlotQueryService.server";
import { pickFirstAvailableProvider } from "../services/slotEngine";
import { submitBooking, BookingValidationError, BookingSlotTakenError } from "../services/BookingSubmitService.server";
const DEFAULT_TZ = "Europe/Berlin";
export interface PublicBookingSlotVM {
readonly startAtIso: string;
readonly label: string;
}
export interface PublicBookingLoaderData {
readonly tenantSlug: string;
readonly slug: string;
readonly title: string;
readonly description: string | null;
readonly tenantName: string;
readonly durationMinutes: number;
readonly date: string;
readonly timezone: string;
readonly slots: PublicBookingSlotVM[];
readonly isEmbed: boolean;
}
export type PublicBookingActionData =
| { readonly ok: true; readonly titleLabel: string; readonly dateLabel: string; readonly timeLabel: string; readonly icsBase64: string }
| { readonly ok: false; readonly errorKey: string; readonly field?: string };
function resolveTimezone(url: URL): string {
return url.searchParams.get("tz") || DEFAULT_TZ;
}
function resolveDate(url: URL, timezone: string, now: Date): string {
const requested = url.searchParams.get("date");
if (requested && /^\d{4}-\d{2}-\d{2}$/u.test(requested)) {
return requested;
}
return formatInTimeZone(now, timezone, "yyyy-MM-dd");
}
async function buildSlots(tenantId: string, providerUserIds: string[], date: string, config: Parameters<typeof loadSlotsForDate>[0]["config"], timezone: string, now: Date): Promise<PublicBookingSlotVM[]> {
const slots = await loadSlotsForDate({ tenantId, providerUserIds, date, config, now });
return slots
.filter((slot) => pickFirstAvailableProvider(slot) !== null)
.map((slot) => ({ startAtIso: slot.startAt.toISOString(), label: formatInTimeZone(slot.startAt, timezone, "HH:mm") }));
}
export async function publicBookingLoader({ request, params }: LoaderFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const url = new URL(request.url);
const now = new Date();
const timezone = resolveTimezone(url);
const date = resolveDate(url, timezone, now);
const slots = await buildSlots(page.tenantId, page.providerUserIds, date, page.config, timezone, now);
const payload: PublicBookingLoaderData = {
tenantSlug: page.tenantSlug,
slug: page.slug,
title: page.title,
description: page.description,
tenantName: page.tenantName,
durationMinutes: page.durationMinutes,
date,
timezone,
slots,
isEmbed: url.pathname.endsWith("/embed"),
};
return data(payload);
}
export async function publicBookingAction({ request, params }: ActionFunctionArgs) {
const page = await resolvePublicBookingPage(params.tenant ?? "", params.slug ?? "");
if (!page) {
throw notFoundResponse();
}
const form = await request.formData();
// Honeypot: real users never fill this hidden field (M06 abuse guard).
if ((form.get("company") as string | null)?.trim()) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 400 });
}
const url = new URL(request.url);
const timezone = (form.get("tz") as string | null) || resolveTimezone(url);
const date = (form.get("date") as string | null) ?? "";
const startAtIso = (form.get("startAt") as string | null) ?? "";
try {
const result = await submitBooking({
page,
startAtIso,
date,
viewerTimeZone: timezone,
intake: {
vorname: (form.get("vorname") as string | null) ?? "",
nachname: (form.get("nachname") as string | null) ?? "",
email: (form.get("email") as string | null) ?? "",
telefon: (form.get("telefon") as string | null) ?? undefined,
gdprAccepted: form.get("gdpr") === "on" || form.get("gdpr") === "true",
},
now: new Date(),
});
if (result.redirectUrl) {
return redirect(result.redirectUrl);
}
return data<PublicBookingActionData>({
ok: true,
titleLabel: page.title,
dateLabel: formatInTimeZone(result.startAt, timezone, "dd.MM.yyyy"),
timeLabel: formatInTimeZone(result.startAt, timezone, "HH:mm"),
icsBase64: result.icsBase64,
});
} catch (error) {
if (error instanceof BookingValidationError) {
return data<PublicBookingActionData>({ ok: false, errorKey: error.code, field: error.field }, { status: 400 });
}
if (error instanceof BookingSlotTakenError) {
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.slotTaken" }, { status: 409 });
}
return data<PublicBookingActionData>({ ok: false, errorKey: "bookings.error.submitFailed" }, { status: 500 });
}
}
@@ -0,0 +1,54 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
// AK-P16b · static authorization-boundary guard for the booking mutation routes
// (DoD A.5 / DoD 6). Asserts every state-changing action runs the module/permission
// guard, the owner-check (where applicable) and CSRF validation BEFORE it reads the
// form body — so a missing module/permission/owner/CSRF can never reach a mutation.
const appRoot = resolveRepoPath("apps/web/app");
describe("booking route authorization boundary", () => {
test("appointment detail action guards permission + CSRF + owner before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/bookings.$id.tsx"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.readOwn)", source.indexOf("export const action"));
const csrfAt = source.indexOf("await validateCSRFToken(request)");
const ownerAt = source.indexOf("requireAppointmentOwner(ctx, appt.providerUserId)", source.indexOf("export const action"));
expect(permissionAt).toBeGreaterThanOrEqual(0);
expect(csrfAt).toBeGreaterThanOrEqual(0);
expect(ownerAt).toBeGreaterThanOrEqual(0);
expect(permissionAt).toBeLessThan(formDataAt);
expect(csrfAt).toBeLessThan(formDataAt);
expect(ownerAt).toBeLessThan(formDataAt);
});
test("appointment detail mutation intents use write/admin permissions for lifecycle changes", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/bookings.$id.tsx"), "utf8");
expect(source).toContain("rescheduleAppointment");
expect(source).toContain("reassignAppointment");
expect(source.match(/requireBookingPermission\(ctx, BOOKING_PERMISSIONS\.write\)/g)?.length ?? 0).toBeGreaterThanOrEqual(4);
expect(source).toContain("requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin)");
expect(source).toContain('intent === "reschedule"');
expect(source).toContain('intent === "reassign"');
});
test("booking-page editor action guards admin permission + CSRF before parsing the form", () => {
const source = fs.readFileSync(path.join(appRoot, "modules/booking/routes/BookingPageEditor.server.ts"), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireBookingPermission(ctx, BOOKING_PERMISSIONS.admin)", source.indexOf("bookingPageEditorAction"));
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(permissionAt).toBeGreaterThanOrEqual(0);
expect(csrfAt).toBeGreaterThanOrEqual(0);
expect(permissionAt).toBeLessThan(formDataAt);
expect(csrfAt).toBeLessThan(formDataAt);
});
});
@@ -0,0 +1,94 @@
// AK-P16b · shared loader/action guard for the booking module (mirrors
// calendarAccess). Booking is feature-gated by its OWN `booking` key
// (tenantHasModule, M06 DoD 7). The bookings.* bundle is cumulative (M06 Block K):
// read_own < read_all < write < admin. Module-off 404s on write (Bauprinzip
// A.5.3); a permission/owner miss is a 404, never a 403.
//
// The PUBLIC booking flow (/b/{tenant}/{slug}) does NOT use this guard — it resolves
// the tenant from the URL segment and has no logged-in user (see the public route).
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { BOOKING_MODULE_KEY } from "./bookingRoutePaths";
/** Booking atomic permissions, cumulative bundle (M06 Block K). */
export const BOOKING_PERMISSIONS = {
/** See your OWN appointments + edit your OWN availability (default capability). */
readOwn: "bookings.read_own",
/** See all tenant appointments / pages / availability. */
readAll: "bookings.read_all",
/** Manage appointments (held/no_show/cancel/reschedule). */
write: "bookings.write",
/** Booking-page CRUD, foreign availability, provider re-assign, hard-delete. */
admin: "bookings.admin",
} as const;
export type BookingRouteContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
hasModule: boolean;
};
/**
* Resolve the booking route context: auth + tenant + the `booking` module gate +
* the user's permissions. With `requireModule` a module-off tenant 404s (write
* paths); GET paths can render a locked empty VM from `hasModule === false`.
*/
export async function loadBookingContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<BookingRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: BOOKING_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: BOOKING_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True if the user holds `permission` or the broader `bookings.admin` bundle. */
export function bookingHasPermission(ctx: BookingRouteContext, permission: string): boolean {
return ctx.permissions.includes(permission) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
}
/** Require a bookings.* permission (admin-aware); 404 if missing (A.5.3). */
export function requireBookingPermission(ctx: BookingRouteContext, permission: string): BookingRouteContext {
if (!bookingHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
return ctx;
}
/** True if the user may see all appointments (read_all or admin), not just own. */
export function canReadAllBookings(ctx: BookingRouteContext): boolean {
return ctx.permissions.includes(BOOKING_PERMISSIONS.readAll) || ctx.permissions.includes(BOOKING_PERMISSIONS.admin);
}
/**
* Owner-check for appointment-scoped routes (M06 K.5): a `read_own` user may only
* see/act on appointments they hold (`providerUserId = self`) — UNLESS they hold
* read_all/admin. A miss is a 404, not a 403 (A.5.3).
*/
export function requireAppointmentOwner(ctx: BookingRouteContext, providerUserId: string): BookingRouteContext {
if (ctx.userId === providerUserId || canReadAllBookings(ctx)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { owner: "mismatch" });
}
@@ -0,0 +1,67 @@
// AK-P16b · pure client-safe route-path builders for the booking module. Loaders
// build these and pass them into the VMs so the VMs stay routing-agnostic (mirrors
// calendarRoutePaths). The module is feature-gated by its OWN `booking` key
// (tenantHasModule) — unlike calendar which reuses `integrations`.
/** Tenant-connector module key for the Booking feature (M06 / DoD 7). */
export const BOOKING_MODULE_KEY = "booking";
/** Reserved slugs that may not be used for a public booking page. */
export const RESERVED_BOOKING_SLUGS: ReadonlySet<string> = new Set([
"new",
"pages",
"embed",
"admin",
"api",
"settings",
]);
/** Appointments list (M06 Block C). */
export function bookingsListPath(tenantSlug: string): string {
return `/${tenantSlug}/bookings`;
}
/** A single appointment's detail (M06 Block D). */
export function bookingDetailPath(tenantSlug: string, appointmentId: string): string {
return `/${tenantSlug}/bookings/${appointmentId}`;
}
/** Booking-pages list (M06 Block E.1). */
export function bookingPagesListPath(tenantSlug: string): string {
return `/${tenantSlug}/bookings/pages`;
}
/** New booking-page editor (M06 Block E.2). */
export function bookingPageNewPath(tenantSlug: string): string {
return `/${tenantSlug}/bookings/pages/new`;
}
/** Edit an existing booking-page (M06 Block E.2). */
export function bookingPageEditPath(tenantSlug: string, bookingPageId: string): string {
return `/${tenantSlug}/bookings/pages/${bookingPageId}`;
}
/** Per-user availability editor (M06 Block F). */
export function availabilityPath(tenantSlug: string): string {
return `/${tenantSlug}/availability`;
}
/** Public booking page (M06 Block G). NOT tenant-login-scoped. */
export function publicBookingPath(tenantSlug: string, slug: string): string {
return `/b/${tenantSlug}/${slug}`;
}
/** Iframe embed variant of the public booking page (M06 Block H). */
export function publicBookingEmbedPath(tenantSlug: string, slug: string): string {
return `/b/${tenantSlug}/${slug}/embed`;
}
/** Absolute public URL (for the editor's copy-to-clipboard + iframe snippet). */
export function publicBookingUrl(origin: string, tenantSlug: string, slug: string): string {
return `${origin}${publicBookingPath(tenantSlug, slug)}`;
}
/** 404 helper (Bauprinzip A.5.3 — permission/owner miss renders 404, not 403). */
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -0,0 +1,97 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { AvailabilityValidationError, listProviderAvailability, replaceProviderAvailability } from "./AvailabilityService.server";
const dbMock = vi.hoisted(() => ({
availabilityRule: {
findMany: vi.fn(),
deleteMany: vi.fn(),
createMany: vi.fn(),
},
availabilityException: {
findMany: vi.fn(),
deleteMany: vi.fn(),
createMany: vi.fn(),
},
$transaction: vi.fn(),
}));
vi.mock("~/utils/db.server", () => ({ db: dbMock }));
describe("AvailabilityService.server", () => {
beforeEach(() => {
vi.clearAllMocks();
dbMock.$transaction.mockImplementation(async (fn: (tx: typeof dbMock) => Promise<unknown>) => fn(dbMock));
});
it("loads and sorts provider availability", async () => {
dbMock.availabilityRule.findMany.mockResolvedValue([
{ id: "rule_2", dayOfWeek: "wednesday", startTime: "14:00", endTime: "17:00", timezone: "Europe/Berlin" },
{ id: "rule_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" },
]);
dbMock.availabilityException.findMany.mockResolvedValue([
{ id: "ex_2", date: new Date("2026-07-11T00:00:00Z"), kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: "Workshop", timezone: "Europe/Berlin" },
{ id: "ex_1", date: new Date("2026-07-10T00:00:00Z"), kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
]);
await expect(listProviderAvailability("tenant_1", "user_1")).resolves.toEqual({
providerUserId: "user_1",
rules: [
{ id: "rule_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" },
{ id: "rule_2", dayOfWeek: "wednesday", startTime: "14:00", endTime: "17:00", timezone: "Europe/Berlin" },
],
exceptions: [
{ id: "ex_1", date: "2026-07-10", kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
{ id: "ex_2", date: "2026-07-11", kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: "Workshop", timezone: "Europe/Berlin" },
],
});
});
it("replaces rules and exceptions atomically with normalized values", async () => {
await replaceProviderAvailability({
tenantId: "tenant_1",
providerUserId: "user_1",
rules: [{ dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: " Europe/Berlin " }],
exceptions: [
{ date: "2026-07-10", kind: "unavailable", startTime: "09:00", endTime: "10:00", reason: " Urlaub ", timezone: "Europe/Berlin" },
{ date: "2026-07-11", kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: null, timezone: "Europe/Berlin" },
],
});
expect(dbMock.$transaction).toHaveBeenCalledOnce();
expect(dbMock.availabilityRule.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", providerUserId: "user_1" } });
expect(dbMock.availabilityException.deleteMany).toHaveBeenCalledWith({ where: { tenantId: "tenant_1", providerUserId: "user_1" } });
expect(dbMock.availabilityRule.createMany).toHaveBeenCalledWith({
data: [{ tenantId: "tenant_1", providerUserId: "user_1", dayOfWeek: "monday", startTime: "09:00", endTime: "12:00", timezone: "Europe/Berlin" }],
});
expect(dbMock.availabilityException.createMany).toHaveBeenCalledWith({
data: [
{ tenantId: "tenant_1", providerUserId: "user_1", date: new Date("2026-07-10T00:00:00Z"), kind: "unavailable", startTime: null, endTime: null, reason: "Urlaub", timezone: "Europe/Berlin" },
{ tenantId: "tenant_1", providerUserId: "user_1", date: new Date("2026-07-11T00:00:00Z"), kind: "custom_window", startTime: "10:00", endTime: "13:00", reason: null, timezone: "Europe/Berlin" },
],
});
});
it("rejects invalid time windows before writing", async () => {
await expect(
replaceProviderAvailability({
tenantId: "tenant_1",
providerUserId: "user_1",
rules: [{ dayOfWeek: "monday", startTime: "12:00", endTime: "09:00", timezone: "Europe/Berlin" }],
exceptions: [],
}),
).rejects.toBeInstanceOf(AvailabilityValidationError);
expect(dbMock.$transaction).not.toHaveBeenCalled();
});
it("requires custom-window exception times before writing", async () => {
await expect(
replaceProviderAvailability({
tenantId: "tenant_1",
providerUserId: "user_1",
rules: [],
exceptions: [{ date: "2026-07-10", kind: "custom_window", timezone: "Europe/Berlin" }],
}),
).rejects.toMatchObject({ code: "bookings.error.invalidTimeWindow" });
expect(dbMock.$transaction).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,207 @@
// AK-P16b · provider availability write/read service (M06 Block F). The screen is
// still D-P16-blocked, but the server-side contract is complete: rules and date
// exceptions are validated, tenant/provider-scoped, and replaced atomically.
import { db } from "~/utils/db.server";
import type { BookingWeekday } from "./slotEngine";
export type AvailabilityExceptionKind = "unavailable" | "custom_window";
export interface AvailabilityRuleInput {
readonly dayOfWeek: BookingWeekday;
readonly startTime: string;
readonly endTime: string;
readonly timezone: string;
}
export interface AvailabilityExceptionInput {
/** ISO calendar date `YYYY-MM-DD`. */
readonly date: string;
readonly kind: AvailabilityExceptionKind;
readonly startTime?: string | null;
readonly endTime?: string | null;
readonly reason?: string | null;
readonly timezone: string;
}
export interface AvailabilityRuleRow extends AvailabilityRuleInput {
readonly id: string;
}
export interface AvailabilityExceptionRow {
readonly id: string;
readonly date: string;
readonly kind: AvailabilityExceptionKind;
readonly startTime: string | null;
readonly endTime: string | null;
readonly reason: string | null;
readonly timezone: string;
}
export interface ProviderAvailabilitySettings {
readonly providerUserId: string;
readonly rules: AvailabilityRuleRow[];
readonly exceptions: AvailabilityExceptionRow[];
}
export class AvailabilityValidationError extends Error {
readonly code: string;
constructor(code: string) {
super(code);
this.name = "AvailabilityValidationError";
this.code = code;
}
}
const WEEKDAYS: readonly BookingWeekday[] = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
const WEEKDAY_ORDER = new Map(WEEKDAYS.map((day, index) => [day, index]));
const TIME_RE = /^([01]\d|2[0-3]):[0-5]\d$/u;
const DATE_RE = /^\d{4}-\d{2}-\d{2}$/u;
function assertTimezone(timezone: string): void {
try {
new Intl.DateTimeFormat("en", { timeZone: timezone }).format(new Date("2026-01-01T00:00:00Z"));
} catch {
throw new AvailabilityValidationError("bookings.error.invalidTimezone");
}
}
function minutesOf(time: string): number {
if (!TIME_RE.test(time)) {
throw new AvailabilityValidationError("bookings.error.invalidTime");
}
const [hours, minutes] = time.split(":").map(Number);
return hours * 60 + minutes;
}
function isoDateToDbDate(date: string): Date {
if (!DATE_RE.test(date)) {
throw new AvailabilityValidationError("bookings.error.invalidDate");
}
return new Date(`${date}T00:00:00Z`);
}
function dbDateToIso(date: Date): string {
return date.toISOString().slice(0, 10);
}
function validateWindow(startTime: string, endTime: string): void {
if (minutesOf(endTime) <= minutesOf(startTime)) {
throw new AvailabilityValidationError("bookings.error.invalidTimeWindow");
}
}
function normalizeRule(rule: AvailabilityRuleInput): AvailabilityRuleInput {
if (!WEEKDAY_ORDER.has(rule.dayOfWeek)) {
throw new AvailabilityValidationError("bookings.error.invalidWeekday");
}
const timezone = rule.timezone.trim();
assertTimezone(timezone);
validateWindow(rule.startTime, rule.endTime);
return { dayOfWeek: rule.dayOfWeek, startTime: rule.startTime, endTime: rule.endTime, timezone };
}
function normalizeException(exception: AvailabilityExceptionInput): AvailabilityExceptionInput & { dateObject: Date } {
if (exception.kind !== "unavailable" && exception.kind !== "custom_window") {
throw new AvailabilityValidationError("bookings.error.invalidAvailabilityException");
}
const timezone = exception.timezone.trim();
assertTimezone(timezone);
const dateObject = isoDateToDbDate(exception.date);
if (exception.kind === "custom_window") {
if (!exception.startTime || !exception.endTime) {
throw new AvailabilityValidationError("bookings.error.invalidTimeWindow");
}
validateWindow(exception.startTime, exception.endTime);
return {
...exception,
dateObject,
timezone,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason?.trim() || null,
};
}
return {
...exception,
dateObject,
timezone,
startTime: null,
endTime: null,
reason: exception.reason?.trim() || null,
};
}
/** Load one provider's persisted availability settings. */
export async function listProviderAvailability(tenantId: string, providerUserId: string): Promise<ProviderAvailabilitySettings> {
const [rules, exceptions] = await Promise.all([
db.availabilityRule.findMany({
where: { tenantId, providerUserId },
select: { id: true, dayOfWeek: true, startTime: true, endTime: true, timezone: true },
}),
db.availabilityException.findMany({
where: { tenantId, providerUserId },
select: { id: true, date: true, kind: true, startTime: true, endTime: true, reason: true, timezone: true },
}),
]);
return {
providerUserId,
rules: rules
.map((rule) => ({ id: rule.id, dayOfWeek: rule.dayOfWeek as BookingWeekday, startTime: rule.startTime, endTime: rule.endTime, timezone: rule.timezone }))
.sort((a, b) => (WEEKDAY_ORDER.get(a.dayOfWeek) ?? 99) - (WEEKDAY_ORDER.get(b.dayOfWeek) ?? 99) || a.startTime.localeCompare(b.startTime)),
exceptions: exceptions
.map((exception) => ({
id: exception.id,
date: dbDateToIso(exception.date),
kind: exception.kind as AvailabilityExceptionKind,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason,
timezone: exception.timezone,
}))
.sort((a, b) => a.date.localeCompare(b.date) || (a.startTime ?? "").localeCompare(b.startTime ?? "")),
};
}
/** Replace a provider's availability settings atomically. */
export async function replaceProviderAvailability(input: {
readonly tenantId: string;
readonly providerUserId: string;
readonly rules: readonly AvailabilityRuleInput[];
readonly exceptions: readonly AvailabilityExceptionInput[];
}): Promise<void> {
const rules = input.rules.map(normalizeRule);
const exceptions = input.exceptions.map(normalizeException);
await db.$transaction(async (tx) => {
await tx.availabilityRule.deleteMany({ where: { tenantId: input.tenantId, providerUserId: input.providerUserId } });
await tx.availabilityException.deleteMany({ where: { tenantId: input.tenantId, providerUserId: input.providerUserId } });
if (rules.length > 0) {
await tx.availabilityRule.createMany({
data: rules.map((rule) => ({
tenantId: input.tenantId,
providerUserId: input.providerUserId,
dayOfWeek: rule.dayOfWeek,
startTime: rule.startTime,
endTime: rule.endTime,
timezone: rule.timezone,
})),
});
}
if (exceptions.length > 0) {
await tx.availabilityException.createMany({
data: exceptions.map((exception) => ({
tenantId: input.tenantId,
providerUserId: input.providerUserId,
date: exception.dateObject,
kind: exception.kind,
startTime: exception.startTime,
endTime: exception.endTime,
reason: exception.reason ?? null,
timezone: exception.timezone,
})),
});
}
});
}
@@ -0,0 +1,228 @@
// AK-P16b · appointment lifecycle (M06 Block D / M129 VOLL): held / no-show / cancel
// / reschedule / re-assign. Transitions are validated by the pure state machine; the
// local CalendarEvent mirror is kept in sync (archived on cancel, moved on re-assign,
// superseded on reschedule). Customer-facing changes (cancel/reschedule/re-assign)
// send an auto-mail (best-effort, M06 I.3) and record an Activity (M06 J.4); an in-app
// notification goes to the provider via notify() (M011). External calendar push lands
// with the AK-P16a write-path (here only the local mirror is updated).
import { formatInTimeZone } from "date-fns-tz";
import { logActivity, type ActivityType } from "@hivegrid/activity";
import { notify, type NotificationClient } from "@hivegrid/foundation";
import { db } from "~/utils/db.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import { assertTransition, statusAfter, notifiesCustomer, type LifecycleAction } from "./bookingTransitions";
const MINUTE_MS = 60_000;
interface AppointmentForAction {
id: string;
status: "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
providerUserId: string;
bookingPageId: string;
kontaktId: string | null;
startAt: Date;
endAt: Date;
timezone: string;
internalCalendarEventId: string | null;
intakeAnswers: unknown;
pageTitle: string;
durationMinutes: number;
tenantName: string;
}
async function loadAppointmentForAction(tenantId: string, appointmentId: string): Promise<AppointmentForAction | null> {
const row = await db.appointment.findFirst({
where: { id: appointmentId, tenantId },
select: {
id: true,
status: true,
providerUserId: true,
bookingPageId: true,
kontaktId: true,
startAt: true,
endAt: true,
timezone: true,
internalCalendarEventId: true,
intakeAnswers: true,
bookingPage: { select: { title: true, durationMinutes: true } },
},
});
if (!row) {
return null;
}
const tenant = await db.tenant.findUnique({ where: { id: tenantId }, select: { name: true } });
return {
id: row.id,
status: row.status,
providerUserId: row.providerUserId,
bookingPageId: row.bookingPageId,
kontaktId: row.kontaktId,
startAt: row.startAt,
endAt: row.endAt,
timezone: row.timezone,
internalCalendarEventId: row.internalCalendarEventId,
intakeAnswers: row.intakeAnswers,
pageTitle: row.bookingPage.title,
durationMinutes: row.bookingPage.durationMinutes,
tenantName: tenant?.name ?? "",
};
}
function bookerEmail(intakeAnswers: unknown): string | null {
if (intakeAnswers && typeof intakeAnswers === "object" && "email" in intakeAnswers) {
const email = (intakeAnswers as { email?: unknown }).email;
return typeof email === "string" && email.trim() ? email.trim() : null;
}
return null;
}
async function recordActivity(tenantId: string, appt: AppointmentForAction, activityType: ActivityType, summaryText: string, actorUserId: string | null): Promise<void> {
if (!appt.kontaktId) {
return;
}
await logActivity({
tenantId,
actorUserId,
actorKind: actorUserId ? "user" : "system",
activityType,
subjectType: "contact",
subjectId: appt.kontaktId,
summaryText,
metadata: { appointmentId: appt.id },
}).catch(() => undefined);
}
async function notifyProvider(tenantId: string, providerUserId: string, messageKey: string, appointmentId: string): Promise<void> {
await notify(
{ tenantId, userId: providerUserId, channel: "IN_APP", category: "bookings", messageKey, sourceKey: `${messageKey}:${appointmentId}`, payloadMetadata: { appointmentId } },
db as unknown as NotificationClient
).catch(() => undefined);
}
async function sendLifecycleMail(appt: AppointmentForAction, subject: string, body: string): Promise<boolean> {
const to = bookerEmail(appt.intakeAnswers);
if (!to) {
return false;
}
try {
await sendEmailMailjet({ data: { to, subject, body: body.replace(/\r?\n/gu, "<br/>") } });
return true;
} catch {
return false;
}
}
function whenLabel(appt: AppointmentForAction): string {
return formatInTimeZone(appt.startAt, appt.timezone, "dd.MM.yyyy HH:mm");
}
/** Mark a past appointment as held (M06 D). */
export async function markAppointmentHeld(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_held", actorUserId, "appointment_held", "als stattgefunden markiert");
}
/** Mark an appointment as no-show (M06 D). */
export async function markAppointmentNoShow(tenantId: string, appointmentId: string, actorUserId: string): Promise<void> {
await applyStatusOnly(tenantId, appointmentId, "mark_no_show", actorUserId, "appointment_no_show", "als nicht erschienen markiert");
}
async function applyStatusOnly(tenantId: string, appointmentId: string, action: LifecycleAction, actorUserId: string, activityType: ActivityType, summaryVerb: string): Promise<void> {
const appt = await loadAppointmentForAction(tenantId, appointmentId);
if (!appt) {
return;
}
assertTransition(appt.status, action);
const next = statusAfter(action);
if (next) {
await db.appointment.update({ where: { id: appt.id }, data: { status: next } });
}
await recordActivity(tenantId, appt, activityType, `Termin ${appt.pageTitle} (${whenLabel(appt)}) ${summaryVerb}`, actorUserId);
}
/** Cancel an appointment with a reason + auto-mail (M06 D / I). */
export async function cancelAppointment(input: { tenantId: string; appointmentId: string; reason: string; byKind: "customer" | "provider" | "system"; actorUserId: string | null }): Promise<void> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
return;
}
assertTransition(appt.status, "cancel");
await db.$transaction(async (tx) => {
await tx.appointment.update({
where: { id: appt.id },
data: { status: "cancelled", cancelledAt: new Date(), cancelledByKind: input.byKind, cancellationReason: input.reason },
});
if (appt.internalCalendarEventId) {
// Free the slot: archive the local mirror so it stops blocking availability.
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
}
});
await sendLifecycleMail(appt, `Termin storniert: ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wurde storniert.\nGrund: ${input.reason}`);
await recordActivity(input.tenantId, appt, "appointment_cancelled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) storniert: ${input.reason}`, input.actorUserId);
if (notifiesCustomer("cancel")) {
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.cancelled", appt.id);
}
}
/** Reschedule to a new start time: supersede the old appointment with a successor (M06 D). */
export async function rescheduleAppointment(input: { tenantId: string; appointmentId: string; newStartAt: Date; actorUserId: string }): Promise<{ newAppointmentId: string }> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
throw new Error("appointment_not_found");
}
assertTransition(appt.status, "reschedule");
const newEndAt = new Date(input.newStartAt.getTime() + appt.durationMinutes * MINUTE_MS);
const newAppointmentId = await db.$transaction(async (tx) => {
await tx.appointment.update({ where: { id: appt.id }, data: { status: "rescheduled" } });
if (appt.internalCalendarEventId) {
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { archivedAt: new Date(), isBusyForAvailability: false } });
}
const successor = await tx.appointment.create({
data: {
tenantId: input.tenantId,
bookingPageId: appt.bookingPageId,
providerUserId: appt.providerUserId,
startAt: input.newStartAt,
endAt: newEndAt,
timezone: appt.timezone,
status: "scheduled",
kontaktId: appt.kontaktId,
intakeAnswers: appt.intakeAnswers as object,
rescheduledFromId: appt.id,
},
select: { id: true },
});
const calendarEvent = await tx.calendarEvent.create({
data: { tenantId: input.tenantId, userId: appt.providerUserId, source: "hivegrid_internal", title: appt.pageTitle, startsAt: input.newStartAt, endsAt: newEndAt, isBusyForAvailability: true, internalEntityLink: { type: "booking_appointment", id: successor.id } },
select: { id: true },
});
await tx.appointment.update({ where: { id: successor.id }, data: { internalCalendarEventId: calendarEvent.id } });
return successor.id;
});
const newWhen = formatInTimeZone(input.newStartAt, appt.timezone, "dd.MM.yyyy HH:mm");
await sendLifecycleMail(appt, `Termin verschoben: ${appt.pageTitle}`, `Dein Termin wurde von ${whenLabel(appt)} auf ${newWhen} verschoben.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} verschoben von ${whenLabel(appt)} auf ${newWhen}`, input.actorUserId);
await notifyProvider(input.tenantId, appt.providerUserId, "bookings.status.rescheduled", newAppointmentId);
return { newAppointmentId };
}
/** Re-assign the appointment to a different provider (M06 D, bookings.admin). */
export async function reassignAppointment(input: { tenantId: string; appointmentId: string; newProviderUserId: string; actorUserId: string }): Promise<void> {
const appt = await loadAppointmentForAction(input.tenantId, input.appointmentId);
if (!appt) {
return;
}
assertTransition(appt.status, "reassign");
await db.$transaction(async (tx) => {
await tx.appointment.update({ where: { id: appt.id }, data: { providerUserId: input.newProviderUserId } });
if (appt.internalCalendarEventId) {
// Move the local mirror to the new provider so availability follows.
await tx.calendarEvent.update({ where: { id: appt.internalCalendarEventId }, data: { userId: input.newProviderUserId } });
}
});
await sendLifecycleMail(appt, `Termin: neuer Ansprechpartner — ${appt.pageTitle}`, `Dein Termin am ${whenLabel(appt)} wird von einem anderen Mitarbeiter betreut.`);
await recordActivity(input.tenantId, appt, "appointment_rescheduled", `Termin ${appt.pageTitle} (${whenLabel(appt)}) neu zugewiesen`, input.actorUserId);
await notifyProvider(input.tenantId, input.newProviderUserId, "bookings.status.scheduled", appt.id);
}
@@ -0,0 +1,312 @@
// AK-P16b · public booking submit (race-safe) + post-booking wiring (M06 G/I/J).
//
// Race protection is two-layered (DoD 2): (1) a Serializable transaction re-checks
// slot freshness and inserts the appointment; (2) the PostgreSQL EXCLUDE USING gist
// constraint `appointment_no_overlap` is the hard backstop — a lost race surfaces as
// an exclusion violation that we map to the same Klartext "slot just taken".
//
// Post-booking (M06 J): email-match → existing Kontakt + Activity, otherwise a
// typed InboxLead (R-P7) is created and linked via Appointment.leadId. The v1 mini
// form remains in intakeAnswers and, when the booking page references an intake
// form, is mirrored to FormSubmission + Appointment.formSubmissionId; a local
// CalendarEvent blocks availability; confirmation mail carries an .ics attachment.
import { formatInTimeZone } from "date-fns-tz";
import { logActivity } from "@hivegrid/activity";
import { db } from "~/utils/db.server";
import { createLead } from "~/utils/integrations/leads/leadService.server";
import { sendEmailMailjet } from "~/modules/emails/services/MailjetEmailService";
import type { PublicBookingPage } from "../db/booking.db.server";
import { findKontaktIdByEmail } from "../db/booking.db.server";
import { loadSlotsForDate } from "./SlotQueryService.server";
import { pickFirstAvailableProvider } from "./slotEngine";
import { buildIcs, icsToBase64 } from "./ics";
const MINUTE_MS = 60_000;
export class BookingValidationError extends Error {
readonly code: string;
readonly field?: string;
constructor(code: string, field?: string) {
super(code);
this.name = "BookingValidationError";
this.code = code;
this.field = field;
}
}
export class BookingSlotTakenError extends Error {
readonly code = "slot_taken";
constructor() {
super("slot_taken");
this.name = "BookingSlotTakenError";
}
}
export interface BookingIntake {
readonly vorname: string;
readonly nachname: string;
readonly email: string;
readonly telefon?: string;
readonly gdprAccepted: boolean;
}
export interface BookingSubmitInput {
readonly page: PublicBookingPage;
/** Chosen slot start as a UTC ISO string. */
readonly startAtIso: string;
/** Provider-local date `YYYY-MM-DD` the slot belongs to. */
readonly date: string;
/** Booker's IANA timezone (for display + the appointment record). */
readonly viewerTimeZone: string;
readonly intake: BookingIntake;
readonly now: Date;
}
export interface BookingSubmitResult {
readonly appointmentId: string;
readonly providerUserId: string;
readonly startAt: Date;
readonly endAt: Date;
readonly icsBase64: string;
readonly redirectUrl: string | null;
}
function validateIntake(intake: BookingIntake): void {
if (!intake.vorname.trim()) {
throw new BookingValidationError("bookings.error.firstNameRequired", "vorname");
}
if (!intake.nachname.trim()) {
throw new BookingValidationError("bookings.error.lastNameRequired", "nachname");
}
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/u.test(intake.email.trim())) {
throw new BookingValidationError("bookings.error.emailInvalid", "email");
}
if (!intake.gdprAccepted) {
throw new BookingValidationError("bookings.error.gdprRequired", "gdpr");
}
}
/** Heuristic: a lost-race insert trips the gist exclusion constraint. */
function isOverlapViolation(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error);
return message.includes("appointment_no_overlap") || message.includes("23P01") || message.toLowerCase().includes("exclusion");
}
function renderTemplate(template: string, vars: Record<string, string>): string {
return template.replace(/\{\{\s*([\w.]+)\s*\}\}/gu, (_match, key: string) => vars[key] ?? "");
}
/** Submit a public booking. Throws BookingValidationError / BookingSlotTakenError. */
export async function submitBooking(input: BookingSubmitInput): Promise<BookingSubmitResult> {
validateIntake(input.intake);
const { page } = input;
// 1) Re-check the slot against live availability (M06 G.3).
const slots = await loadSlotsForDate({
tenantId: page.tenantId,
providerUserIds: page.providerUserIds,
date: input.date,
config: page.config,
now: input.now,
});
const slot = slots.find((s) => s.startAt.toISOString() === new Date(input.startAtIso).toISOString());
const providerUserId = slot ? pickFirstAvailableProvider(slot) : null;
if (!slot || !providerUserId) {
throw new BookingSlotTakenError();
}
const startAt = slot.startAt;
const endAt = new Date(startAt.getTime() + page.durationMinutes * MINUTE_MS);
// 2) Match an existing contact; otherwise create a typed InboxLead after the
// appointment exists so the lead can reference the booked appointment id.
const kontaktId = await findKontaktIdByEmail(page.tenantId, input.intake.email);
let leadId: string | null = null;
const intakeAnswers = {
vorname: input.intake.vorname.trim(),
nachname: input.intake.nachname.trim(),
email: input.intake.email.trim(),
telefon: input.intake.telefon?.trim() ?? null,
gdprAccepted: true,
};
const eventTitle = renderTemplate(page.internalEventTitleTemplate ?? "{{booking_page.title}}", {
"booking_page.title": page.title,
"contact.name": `${input.intake.vorname} ${input.intake.nachname}`.trim(),
});
// 3) Race-safe insert: Serializable re-check + gist backstop (DoD 2).
let appointmentId: string;
try {
appointmentId = await db.$transaction(
async (tx) => {
const clash = await tx.appointment.findFirst({
where: {
tenantId: page.tenantId,
providerUserId,
status: { in: ["scheduled", "held"] },
AND: [{ startAt: { lt: endAt } }, { endAt: { gt: startAt } }],
},
select: { id: true },
});
if (clash) {
throw new BookingSlotTakenError();
}
const appointment = await tx.appointment.create({
data: {
tenantId: page.tenantId,
bookingPageId: page.pageId,
providerUserId,
startAt,
endAt,
timezone: input.viewerTimeZone,
status: "scheduled",
kontaktId,
intakeAnswers,
},
select: { id: true },
});
const formSubmission = page.intakeFormId
? await tx.formSubmission.create({
data: {
formId: page.intakeFormId,
tenantId: page.tenantId,
payload: {
values: intakeAnswers,
booking: {
appointmentId: appointment.id,
bookingPageId: page.pageId,
bookingPageSlug: page.slug,
startAt: startAt.toISOString(),
endAt: endAt.toISOString(),
},
},
sourceOrigin: `/b/${page.tenantSlug}/${page.slug}`,
status: "received",
result: { target: "booking_intake" },
},
select: { id: true },
})
: null;
// Local calendar mirror so the slot blocks future availability (M06 J.2).
const calendarEvent = await tx.calendarEvent.create({
data: {
tenantId: page.tenantId,
userId: providerUserId,
source: "hivegrid_internal",
title: eventTitle,
startsAt: startAt,
endsAt: endAt,
isBusyForAvailability: true,
internalEntityLink: { type: "booking_appointment", id: appointment.id },
},
select: { id: true },
});
await tx.appointment.update({
where: { id: appointment.id },
data: { internalCalendarEventId: calendarEvent.id, formSubmissionId: formSubmission?.id ?? null },
});
return appointment.id;
},
{ isolationLevel: "Serializable" }
);
} catch (error) {
if (error instanceof BookingSlotTakenError || isOverlapViolation(error)) {
throw new BookingSlotTakenError();
}
throw error;
}
if (!kontaktId) {
const lead = await createLead({
tenantId: page.tenantId,
userId: null,
quelle: "form",
quelleDetail: { kind: "booking", bookingPageId: page.pageId, bookingPageSlug: page.slug },
sourceOrigin: `/b/${page.tenantSlug}/${page.slug}`,
vorname: input.intake.vorname,
nachname: input.intake.nachname,
email: input.intake.email,
telefon: input.intake.telefon,
message: page.title,
rohdaten: { bookingPageId: page.pageId, appointmentId, startAt: startAt.toISOString(), endAt: endAt.toISOString(), intakeAnswers },
zustaendigerUserId: providerUserId,
weiterverarbeitungFreigabe: "unklar",
});
leadId = lead.id;
await db.appointment.update({ where: { id: appointmentId }, data: { leadId } });
}
// 4) Activity on the contact/lead (M06 J.4). Best-effort — never break the booking.
const activitySubject = kontaktId ? ({ type: "contact" as const, id: kontaktId }) : leadId ? ({ type: "lead" as const, id: leadId }) : null;
if (activitySubject) {
await logActivity({
tenantId: page.tenantId,
actorUserId: null,
actorKind: "system",
activityType: "appointment_scheduled",
subjectType: activitySubject.type,
subjectId: activitySubject.id,
summaryText: `Termin ${page.title} am ${formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy HH:mm")} gebucht`,
metadata: { appointmentId, bookingPageId: page.pageId, leadId, kontaktId },
}).catch(() => undefined);
}
// 5) Confirmation mail + .ics (best-effort, M06 I.3).
const icsBase64 = await sendConfirmation({ input, providerUserId, startAt, endAt, appointmentId }).catch(async () => {
await db.appointment
.update({ where: { id: appointmentId }, data: { notesInternal: `Bestätigungsmail an ${input.intake.email} konnte nicht versendet werden — Endkunde bitte direkt informieren.` } })
.catch(() => undefined);
return buildBookingIcs({ input, providerUserId, startAt, endAt, appointmentId });
});
return { appointmentId, providerUserId, startAt, endAt, icsBase64, redirectUrl: page.redirectUrlAfterBooking };
}
function buildBookingIcs(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): string {
const { input, startAt, endAt, appointmentId } = args;
const ics = buildIcs({
uid: `${appointmentId}@hivegrid`,
start: startAt,
end: endAt,
dtstamp: input.now,
summary: input.page.title,
description: input.page.description ?? undefined,
organizerEmail: undefined,
organizerName: input.page.tenantName,
attendeeEmail: input.intake.email.trim(),
});
return icsToBase64(ics);
}
async function sendConfirmation(args: { input: BookingSubmitInput; providerUserId: string; startAt: Date; endAt: Date; appointmentId: string }): Promise<string> {
const { input, startAt, endAt } = args;
const { page } = input;
const icsBase64 = buildBookingIcs(args);
const vars: Record<string, string> = {
"contact.first_name": input.intake.vorname.trim(),
"contact.last_name": input.intake.nachname.trim(),
"contact.email": input.intake.email.trim(),
"booking_page.title": page.title,
"booking_page.description": page.description ?? "",
"booking_page.duration_minutes": String(page.durationMinutes),
"appointment.date": formatInTimeZone(startAt, input.viewerTimeZone, "dd.MM.yyyy"),
"appointment.time": formatInTimeZone(startAt, input.viewerTimeZone, "HH:mm"),
"appointment.duration": String(page.durationMinutes),
"tenant.company_name": page.tenantName,
};
const subject = renderTemplate(page.confirmationEmailSubject, vars);
const body = renderTemplate(page.confirmationEmailBody, vars);
await sendEmailMailjet({
data: {
to: input.intake.email.trim(),
subject,
body: body.replace(/\r?\n/gu, "<br/>"),
tenantId: page.tenantId,
attachments: [{ filename: "termin.ics", content: icsBase64, disposition: "attachment" }],
},
});
return icsBase64;
}
@@ -0,0 +1,87 @@
// AK-P16b · slot query service (loader-side). Loads availability rules, exceptions,
// existing appointments and Google busy intervals (AK-P16a) for a booking page's
// providers, then delegates the timezone-aware arithmetic to the pure slotEngine.
//
// Busy intervals fed to the engine combine, per provider:
// - existing appointments (status scheduled/held) → [startAt, endAt)
// - external/internal calendar events flagged busy → via availability.ts (leak-safe)
// The engine buffers the candidate slot, so raw occupied intervals are enough.
import { db } from "~/utils/db.server";
import { extractBusyIntervals, type BusyInterval } from "~/modules/calendar/services/availability";
import {
computeSlots,
type BookingWeekday,
type ComputedSlot,
type ProviderAvailabilityInput,
type SlotEngineConfig,
type SlotExceptionInput,
type SlotRuleInput,
} from "./slotEngine";
const DAY_MS = 86_400_000;
const OCCUPYING_STATUSES = ["scheduled", "held"] as const;
export interface SlotQueryInput {
readonly tenantId: string;
readonly providerUserIds: readonly string[];
/** Provider-local calendar date `YYYY-MM-DD`. */
readonly date: string;
readonly config: SlotEngineConfig;
readonly now: Date;
}
/** Broad UTC window around the requested local day (covers any provider timezone). */
function dayWindow(date: string): { from: Date; to: Date } {
const midnightUtc = new Date(`${date}T00:00:00Z`).getTime();
return { from: new Date(midnightUtc - DAY_MS), to: new Date(midnightUtc + 2 * DAY_MS) };
}
/** Load one provider's rules, exceptions and busy intervals for the day. */
async function loadProviderInput(tenantId: string, providerUserId: string, date: string): Promise<ProviderAvailabilityInput> {
const window = dayWindow(date);
const [rules, exceptions, appointments, events] = await Promise.all([
db.availabilityRule.findMany({
where: { tenantId, providerUserId },
select: { dayOfWeek: true, startTime: true, endTime: true, timezone: true },
}),
db.availabilityException.findMany({
where: { tenantId, providerUserId, date: new Date(`${date}T00:00:00Z`) },
select: { date: true, kind: true, startTime: true, endTime: true, timezone: true },
}),
db.appointment.findMany({
where: { tenantId, providerUserId, status: { in: [...OCCUPYING_STATUSES] }, startAt: { gte: window.from, lte: window.to } },
select: { startAt: true, endAt: true },
}),
db.calendarEvent.findMany({
where: { tenantId, userId: providerUserId, isBusyForAvailability: true, archivedAt: null, startsAt: { gte: window.from, lte: window.to } },
select: { startsAt: true, endsAt: true, isBusyForAvailability: true, archivedAt: true },
}),
]);
const appointmentBusy: BusyInterval[] = appointments.map((a) => ({ from: a.startAt, to: a.endAt }));
const calendarBusy = extractBusyIntervals(events);
return {
providerUserId,
rules: rules.map((r) => ({ dayOfWeek: r.dayOfWeek as BookingWeekday, startTime: r.startTime, endTime: r.endTime, timezone: r.timezone })) satisfies SlotRuleInput[],
exceptions: exceptions.map((e) => ({
date,
kind: e.kind as SlotExceptionInput["kind"],
startTime: e.startTime,
endTime: e.endTime,
timezone: e.timezone,
})) satisfies SlotExceptionInput[],
busyIntervals: [...appointmentBusy, ...calendarBusy],
};
}
/** Compute the bookable slots for a booking page's providers on a given local day. */
export async function loadSlotsForDate(input: SlotQueryInput): Promise<ComputedSlot[]> {
if (input.providerUserIds.length === 0) {
return [];
}
const providers = await Promise.all(input.providerUserIds.map((id) => loadProviderInput(input.tenantId, id, input.date)));
return computeSlots({ date: input.date, now: input.now, providers, config: input.config });
}
@@ -0,0 +1,38 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
const repoRoot = resolveRepoPath(".");
function readArtifact(relativePath: string): string {
return fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
}
describe("booking DB rollout artifacts", () => {
test("hard double-booking guard uses an idempotent exclusion constraint for active appointments", () => {
const sql = readArtifact("prisma/rls/booking-constraints.sql");
expect(sql).toContain("CREATE EXTENSION IF NOT EXISTS btree_gist");
expect(sql).toContain("appointment_no_overlap");
expect(sql).toContain('EXCLUDE USING gist');
expect(sql).toContain('"providerUserId" WITH =');
expect(sql).toContain('tstzrange("startAt", "endAt", \'\'[)\'\') WITH &&');
expect(sql).toContain("WHERE (status IN (''scheduled'', ''held''))");
expect(sql).toContain("23P01");
});
test("booking RLS artifact covers every tenant-scoped booking table and fails closed without tenant GUC", () => {
const sql = readArtifact("prisma/rls/booking-isolation.sql");
const expectedTables = ["BookingPage", "BookingPageProvider", "AvailabilityRule", "AvailabilityException", "Appointment"];
for (const table of expectedTables) {
expect(sql).toContain(`'${table}'`);
}
expect(sql).toContain("ENABLE ROW LEVEL SECURITY");
expect(sql).toContain("FORCE ROW LEVEL SECURITY");
expect(sql).toContain('"tenantId" = current_setting(\'\'app.tenant_id\'\', true)');
expect(sql).toContain("GRANT SELECT, INSERT, UPDATE, DELETE");
expect(sql).toContain("hivegrid_app");
});
});
@@ -0,0 +1,31 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
const servicePath = path.join(resolveRepoPath("apps/web/app"), "modules/booking/services/BookingSubmitService.server.ts");
describe("booking post-booking server wiring", () => {
test("public booking creates and links a typed InboxLead when no contact matches", () => {
const source = fs.readFileSync(servicePath, "utf8");
expect(source).toContain('import { createLead } from "~/utils/integrations/leads/leadService.server"');
expect(source).toContain("if (!kontaktId)");
expect(source).toContain("const lead = await createLead");
expect(source).toContain('quelle: "form"');
expect(source).toContain('kind: "booking"');
expect(source).toContain("appointmentId");
expect(source).toContain("data: { leadId }");
expect(source).toContain('type: "lead" as const');
});
test("public booking persists a FormSubmission when an intake form is configured", () => {
const source = fs.readFileSync(servicePath, "utf8");
expect(source).toContain("page.intakeFormId");
expect(source).toContain("tx.formSubmission.create");
expect(source).toContain("formId: page.intakeFormId");
expect(source).toContain("formSubmissionId: formSubmission?.id ?? null");
expect(source).toContain('target: "booking_intake"');
});
});
@@ -0,0 +1,50 @@
import { describe, expect, it } from "vitest";
import {
assertTransition,
BookingTransitionError,
canTransition,
notifiesCustomer,
statusAfter,
type AppointmentStatus,
type LifecycleAction,
} from "./bookingTransitions";
const ACTIONS: LifecycleAction[] = ["mark_held", "mark_no_show", "cancel", "reschedule", "reassign"];
const TERMINAL: AppointmentStatus[] = ["held", "cancelled", "no_show", "rescheduled"];
describe("booking lifecycle transitions (M06 A.5 / M129)", () => {
it("allows every action from scheduled", () => {
for (const action of ACTIONS) {
expect(canTransition("scheduled", action)).toBe(true);
}
});
it("forbids every action from a terminal status", () => {
for (const status of TERMINAL) {
for (const action of ACTIONS) {
expect(canTransition(status, action)).toBe(false);
}
}
});
it("assertTransition throws BookingTransitionError on an invalid transition", () => {
expect(() => assertTransition("cancelled", "cancel")).toThrow(BookingTransitionError);
expect(() => assertTransition("scheduled", "cancel")).not.toThrow();
});
it("maps actions to the resulting status (reassign keeps it unchanged)", () => {
expect(statusAfter("mark_held")).toBe("held");
expect(statusAfter("mark_no_show")).toBe("no_show");
expect(statusAfter("cancel")).toBe("cancelled");
expect(statusAfter("reschedule")).toBe("rescheduled");
expect(statusAfter("reassign")).toBeNull();
});
it("flags customer-notifying actions (cancel/reschedule/reassign)", () => {
expect(notifiesCustomer("cancel")).toBe(true);
expect(notifiesCustomer("reschedule")).toBe(true);
expect(notifiesCustomer("reassign")).toBe(true);
expect(notifiesCustomer("mark_held")).toBe(false);
expect(notifiesCustomer("mark_no_show")).toBe(false);
});
});
@@ -0,0 +1,63 @@
// AK-P16b · appointment lifecycle state machine (PURE, M06 A.5 / M129). The allowed
// transitions are validated here so the service + tests share one source of truth.
//
// scheduled ──mark_held──▶ held
// scheduled ──mark_no_show──▶ no_show
// scheduled ──cancel──▶ cancelled
// scheduled ──reschedule──▶ rescheduled (a successor appointment is created)
// scheduled ──reassign──▶ scheduled (provider changes, status unchanged)
// Terminal states (held/cancelled/no_show/rescheduled) accept no further action.
export type AppointmentStatus = "scheduled" | "held" | "cancelled" | "no_show" | "rescheduled";
export type LifecycleAction = "mark_held" | "mark_no_show" | "cancel" | "reschedule" | "reassign";
const ALLOWED_FROM: Record<LifecycleAction, readonly AppointmentStatus[]> = {
mark_held: ["scheduled"],
mark_no_show: ["scheduled"],
cancel: ["scheduled"],
reschedule: ["scheduled"],
reassign: ["scheduled"],
};
/** The status an action moves the appointment to, or null when it is unchanged. */
const STATUS_AFTER: Record<LifecycleAction, AppointmentStatus | null> = {
mark_held: "held",
mark_no_show: "no_show",
cancel: "cancelled",
reschedule: "rescheduled",
reassign: null,
};
export class BookingTransitionError extends Error {
readonly code = "invalid_transition";
readonly from: AppointmentStatus;
readonly action: LifecycleAction;
constructor(from: AppointmentStatus, action: LifecycleAction) {
super(`invalid_transition:${from}:${action}`);
this.name = "BookingTransitionError";
this.from = from;
this.action = action;
}
}
/** True when `action` is allowed from `status`. */
export function canTransition(status: AppointmentStatus, action: LifecycleAction): boolean {
return ALLOWED_FROM[action].includes(status);
}
/** Throw BookingTransitionError unless `action` is allowed from `status`. */
export function assertTransition(status: AppointmentStatus, action: LifecycleAction): void {
if (!canTransition(status, action)) {
throw new BookingTransitionError(status, action);
}
}
/** The resulting status for an action (null = unchanged, e.g. reassign). */
export function statusAfter(action: LifecycleAction): AppointmentStatus | null {
return STATUS_AFTER[action];
}
/** Whether the action sends a customer-facing email (M06 Block I/D). */
export function notifiesCustomer(action: LifecycleAction): boolean {
return action === "cancel" || action === "reschedule" || action === "reassign";
}
@@ -0,0 +1,49 @@
import { describe, expect, it } from "vitest";
import { buildIcs, icsToBase64 } from "./ics";
const base = {
uid: "appt-123@hivegrid",
start: new Date("2026-07-01T09:00:00Z"),
end: new Date("2026-07-01T10:00:00Z"),
dtstamp: new Date("2026-06-30T12:00:00Z"),
summary: "Wartungstermin",
};
describe("buildIcs (RFC 5545 minimal)", () => {
it("emits a single VEVENT with UTC timestamps + CRLF endings", () => {
const ics = buildIcs(base);
expect(ics).toContain("BEGIN:VCALENDAR");
expect(ics).toContain("BEGIN:VEVENT");
expect(ics).toContain("UID:appt-123@hivegrid");
expect(ics).toContain("DTSTART:20260701T090000Z");
expect(ics).toContain("DTEND:20260701T100000Z");
expect(ics).toContain("DTSTAMP:20260630T120000Z");
expect(ics).toContain("SUMMARY:Wartungstermin");
expect(ics).toContain("END:VCALENDAR");
expect(ics).toContain("\r\n");
});
it("escapes TEXT special chars (comma, semicolon, newline, backslash)", () => {
const ics = buildIcs({ ...base, summary: "A, B; C\\D", description: "line1\nline2" });
expect(ics).toContain("SUMMARY:A\\, B\\; C\\\\D");
expect(ics).toContain("DESCRIPTION:line1\\nline2");
});
it("includes organizer + attendee when provided", () => {
const ics = buildIcs({ ...base, organizerEmail: "host@acme.de", organizerName: "Acme GmbH", attendeeEmail: "kunde@example.com" });
expect(ics).toContain("ORGANIZER;CN=Acme GmbH:mailto:host@acme.de");
expect(ics).toContain("ATTENDEE;ROLE=REQ-PARTICIPANT:mailto:kunde@example.com");
});
it("omits optional fields when absent", () => {
const ics = buildIcs(base);
expect(ics).not.toContain("DESCRIPTION:");
expect(ics).not.toContain("LOCATION:");
expect(ics).not.toContain("ORGANIZER");
});
it("base64-encodes round-trippable content", () => {
const ics = buildIcs(base);
expect(Buffer.from(icsToBase64(ics), "base64").toString("utf8")).toEqual(ics);
});
});
@@ -0,0 +1,80 @@
// AK-P16b · minimal RFC-5545 .ics builder (PURE). The booking confirmation mail
// attaches an "add to calendar" file; rather than pull a dependency we hand-roll the
// tiny VEVENT subset the spec needs (EU/supply-chain clean, unit-tested). Only the
// fields the confirmation needs: UID, DTSTAMP, DTSTART, DTEND, SUMMARY, DESCRIPTION,
// LOCATION, optional ORGANIZER + ATTENDEE.
export interface IcsEventInput {
readonly uid: string;
readonly start: Date;
readonly end: Date;
readonly dtstamp: Date;
readonly summary: string;
readonly description?: string;
readonly location?: string;
readonly organizerEmail?: string;
readonly organizerName?: string;
readonly attendeeEmail?: string;
}
/** Format a Date as an RFC-5545 UTC timestamp `YYYYMMDDTHHMMSSZ`. */
function toIcsUtc(date: Date): string {
return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
}
/** Escape TEXT values per RFC 5545 §3.3.11 (backslash, semicolon, comma, newline). */
function escapeText(value: string): string {
return value.replace(/\\/g, "\\\\").replace(/;/g, "\\;").replace(/,/g, "\\,").replace(/\r?\n/g, "\\n");
}
/** Fold a content line to <=75 octets per RFC 5545 §3.1 (CRLF + leading space). */
function foldLine(line: string): string {
if (line.length <= 75) {
return line;
}
const parts: string[] = [line.slice(0, 75)];
let rest = line.slice(75);
while (rest.length > 74) {
parts.push(` ${rest.slice(0, 74)}`);
rest = rest.slice(74);
}
parts.push(` ${rest}`);
return parts.join("\r\n");
}
/** Build a single-VEVENT VCALENDAR string (CRLF line endings, as the spec mandates). */
export function buildIcs(input: IcsEventInput): string {
const lines: string[] = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
"PRODID:-//HiveGrid//Booking//EN",
"CALSCALE:GREGORIAN",
"METHOD:PUBLISH",
"BEGIN:VEVENT",
`UID:${input.uid}`,
`DTSTAMP:${toIcsUtc(input.dtstamp)}`,
`DTSTART:${toIcsUtc(input.start)}`,
`DTEND:${toIcsUtc(input.end)}`,
`SUMMARY:${escapeText(input.summary)}`,
];
if (input.description) {
lines.push(`DESCRIPTION:${escapeText(input.description)}`);
}
if (input.location) {
lines.push(`LOCATION:${escapeText(input.location)}`);
}
if (input.organizerEmail) {
const cn = input.organizerName ? `;CN=${escapeText(input.organizerName)}` : "";
lines.push(`ORGANIZER${cn}:mailto:${input.organizerEmail}`);
}
if (input.attendeeEmail) {
lines.push(`ATTENDEE;ROLE=REQ-PARTICIPANT:mailto:${input.attendeeEmail}`);
}
lines.push("STATUS:CONFIRMED", "END:VEVENT", "END:VCALENDAR");
return lines.map(foldLine).join("\r\n");
}
/** Base64-encode an .ics string for use as a mail attachment `content`. */
export function icsToBase64(ics: string): string {
return Buffer.from(ics, "utf8").toString("base64");
}
@@ -0,0 +1,142 @@
import { describe, expect, it } from "vitest";
import {
computeSlots,
pickFirstAvailableProvider,
weekdayOfIsoDate,
type ComputeSlotsInput,
type ProviderAvailabilityInput,
type SlotEngineConfig,
} from "./slotEngine";
const TZ = "Europe/Berlin"; // UTC+2 in July (summer), UTC+1 in January (winter)
const DATE = "2026-07-01";
const NOW = new Date("2026-06-01T00:00:00Z"); // ~1 month out: passes notice + advance
const config = (over: Partial<SlotEngineConfig> = {}): SlotEngineConfig => ({
durationMinutes: 60,
bufferBeforeMinutes: 0,
bufferAfterMinutes: 0,
slotIncrementMinutes: 60,
minNoticeHours: 4,
maxAdvanceDays: 60,
...over,
});
const provider = (over: Partial<ProviderAvailabilityInput> = {}): ProviderAvailabilityInput => ({
providerUserId: "u1",
rules: [{ dayOfWeek: weekdayOfIsoDate(DATE), startTime: "09:00", endTime: "12:00", timezone: TZ }],
exceptions: [],
busyIntervals: [],
...over,
});
const run = (over: Partial<ComputeSlotsInput> = {}): ReturnType<typeof computeSlots> =>
computeSlots({ date: DATE, now: NOW, providers: [provider()], config: config(), ...over });
const iso = (slots: ReturnType<typeof computeSlots>): string[] => slots.map((s) => s.startAt.toISOString());
describe("computeSlots (M06 A.6, timezone-aware)", () => {
it("generates slots inside a single window, converted to UTC (Berlin summer = UTC+2)", () => {
// 09:00-12:00 Berlin → 07:00-10:00 UTC; 60min slots stepping 60min.
expect(iso(run())).toEqual(["2026-07-01T07:00:00.000Z", "2026-07-01T08:00:00.000Z", "2026-07-01T09:00:00.000Z"]);
});
it("honours a lunch break (two rules on the same weekday)", () => {
const weekday = weekdayOfIsoDate(DATE);
const slots = run({
providers: [
provider({
rules: [
{ dayOfWeek: weekday, startTime: "09:00", endTime: "11:00", timezone: TZ },
{ dayOfWeek: weekday, startTime: "14:00", endTime: "16:00", timezone: TZ },
],
}),
],
});
// 09:00,10:00 + 14:00,15:00 Berlin → 07/08 + 12/13 UTC. Nothing 12:00-14:00 Berlin.
expect(iso(slots)).toEqual([
"2026-07-01T07:00:00.000Z",
"2026-07-01T08:00:00.000Z",
"2026-07-01T12:00:00.000Z",
"2026-07-01T13:00:00.000Z",
]);
});
it("returns no slots when an `unavailable` exception covers the day", () => {
const slots = run({
providers: [provider({ exceptions: [{ date: DATE, kind: "unavailable", startTime: null, endTime: null, timezone: TZ }] })],
});
expect(slots).toEqual([]);
});
it("custom_window exception replaces the standard rule", () => {
const slots = run({
providers: [provider({ exceptions: [{ date: DATE, kind: "custom_window", startTime: "15:00", endTime: "17:00", timezone: TZ }] })],
});
// 15:00-17:00 Berlin → 13:00-15:00 UTC, one 60min slot at 13:00 + 14:00.
expect(iso(slots)).toEqual(["2026-07-01T13:00:00.000Z", "2026-07-01T14:00:00.000Z"]);
});
it("subtracts a busy interval (calendar/appointment) from the slots", () => {
const slots = run({
providers: [provider({ busyIntervals: [{ from: new Date("2026-07-01T08:00:00Z"), to: new Date("2026-07-01T09:00:00Z") }] })],
});
// 08:00 UTC slot removed; 07:00 + 09:00 remain.
expect(iso(slots)).toEqual(["2026-07-01T07:00:00.000Z", "2026-07-01T09:00:00.000Z"]);
});
it("applies buffer-after so an adjacent busy block knocks out the touching slot", () => {
const slots = computeSlots({
date: DATE,
now: NOW,
providers: [provider({ busyIntervals: [{ from: new Date("2026-07-01T08:15:00Z"), to: new Date("2026-07-01T08:30:00Z") }] })],
config: config({ bufferAfterMinutes: 30 }),
});
// 07:00 slot ends 08:00, +30min buffer → occupies until 08:30, overlaps 08:15 busy → dropped.
// 08:00 slot directly overlaps busy → dropped. Only 09:00 survives.
expect(iso(slots)).toEqual(["2026-07-01T09:00:00.000Z"]);
});
it("enforces min-notice (no slots inside the notice horizon)", () => {
// now just before the day, minNotice 24h → 07:00/08:00/09:00 UTC all within 24h → none.
const slots = run({ now: new Date("2026-07-01T00:00:00Z"), config: config({ minNoticeHours: 24 }) });
expect(slots).toEqual([]);
});
it("enforces max-advance (date beyond the booking horizon)", () => {
const slots = run({ now: new Date("2026-01-01T00:00:00Z"), config: config({ maxAdvanceDays: 30 }) });
expect(slots).toEqual([]);
});
it("ignores rules for a different weekday", () => {
const wrong = weekdayOfIsoDate(DATE) === "monday" ? "tuesday" : "monday";
const slots = run({ providers: [provider({ rules: [{ dayOfWeek: wrong, startTime: "09:00", endTime: "12:00", timezone: TZ }] })] });
expect(slots).toEqual([]);
});
it("unions providers for first_available and picks the lowest-id provider", () => {
const slots = run({
providers: [
provider({ providerUserId: "u2" }),
provider({ providerUserId: "u1", busyIntervals: [{ from: new Date("2026-07-01T07:00:00Z"), to: new Date("2026-07-01T08:00:00Z") }] }),
],
});
const first = slots.find((s) => s.startAt.toISOString() === "2026-07-01T07:00:00.000Z");
expect(first?.providerUserIds).toEqual(["u2"]); // u1 busy at 07:00
const second = slots.find((s) => s.startAt.toISOString() === "2026-07-01T08:00:00.000Z");
expect(second?.providerUserIds).toEqual(["u1", "u2"]);
expect(pickFirstAvailableProvider(second!)).toBe("u1");
});
it("is DST-correct (Berlin winter = UTC+1)", () => {
const winter = "2026-01-07";
const slots = computeSlots({
date: winter,
now: new Date("2026-01-01T00:00:00Z"),
providers: [provider({ rules: [{ dayOfWeek: weekdayOfIsoDate(winter), startTime: "09:00", endTime: "11:00", timezone: TZ }] })],
config: config(),
});
// 09:00 Berlin winter → 08:00 UTC (not 07:00).
expect(iso(slots)).toEqual(["2026-01-07T08:00:00.000Z", "2026-01-07T09:00:00.000Z"]);
});
});
@@ -0,0 +1,178 @@
// AK-P16b · slot engine (PURE, timezone-aware) — M06 Block A.6.
//
// Computes bookable start slots for a booking page on a given provider-local day.
// No Prisma / no React: plain inputs in, UTC instants out. The loader-side wrapper
// (SlotQueryService.server.ts) loads rows and pre-merges busy intervals; this file
// holds only the deterministic, unit-testable arithmetic.
//
// Per provider, for the requested day:
// windows = exceptions(date) OR weekly rules(weekday) (M06 A.4 overrides A.3)
// for each window → step by slotIncrement, slot = [t, t+duration)
// keep slot when its buffered range [t-bufferBefore, end+bufferAfter) does NOT
// overlap the provider's busy intervals (other appointments ±buffer + Google
// busy from AK-P16a availability.ts — leak-safe {from,to} only)
// AND slot.start >= now + minNoticeHours AND slot.start <= now + maxAdvanceDays
// `first_available` (v1): union all providers' slots, each slot carrying the ids of
// every provider free at that exact instant.
//
// The requested `date` is the PROVIDER-LOCAL calendar date (each provider's rules /
// exceptions carry their own IANA timezone). The public UI formats the returned UTC
// instants in the viewer's timezone.
import { fromZonedTime } from "date-fns-tz";
import { mergeBusyIntervals, overlapsBusy, type BusyInterval } from "~/modules/calendar/services/availability";
export type BookingWeekday = "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday";
const WEEKDAY_BY_UTC_DAY: readonly BookingWeekday[] = [
"sunday",
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
];
/** Weekly standard-availability window (local "HH:mm" in `timezone`). */
export interface SlotRuleInput {
readonly dayOfWeek: BookingWeekday;
readonly startTime: string;
readonly endTime: string;
readonly timezone: string;
}
/** Date-specific override. `unavailable` clears the day; `custom_window` replaces it. */
export interface SlotExceptionInput {
/** ISO calendar date `YYYY-MM-DD`. */
readonly date: string;
readonly kind: "unavailable" | "custom_window";
readonly startTime: string | null;
readonly endTime: string | null;
readonly timezone: string;
}
/** One provider's availability inputs. `busyIntervals` is pre-merged + leak-safe. */
export interface ProviderAvailabilityInput {
readonly providerUserId: string;
readonly rules: readonly SlotRuleInput[];
readonly exceptions: readonly SlotExceptionInput[];
readonly busyIntervals: readonly BusyInterval[];
}
/** Booking-page slot parameters (M06 A.1). */
export interface SlotEngineConfig {
readonly durationMinutes: number;
readonly bufferBeforeMinutes: number;
readonly bufferAfterMinutes: number;
readonly slotIncrementMinutes: number;
readonly minNoticeHours: number;
readonly maxAdvanceDays: number;
}
export interface ComputeSlotsInput {
/** Provider-local calendar date `YYYY-MM-DD`. */
readonly date: string;
/** Injected wall clock (purity / testability). */
readonly now: Date;
readonly providers: readonly ProviderAvailabilityInput[];
readonly config: SlotEngineConfig;
}
/** A free slot. `providerUserIds` = everyone free at this exact instant (v1 union). */
export interface ComputedSlot {
readonly startAt: Date;
readonly endAt: Date;
readonly providerUserIds: string[];
}
const MINUTE_MS = 60_000;
const HOUR_MS = 3_600_000;
const DAY_MS = 86_400_000;
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/u;
/** Weekday of an ISO `YYYY-MM-DD` (tz-independent — the date string has no zone). */
export function weekdayOfIsoDate(date: string): BookingWeekday {
return WEEKDAY_BY_UTC_DAY[new Date(`${date}T00:00:00Z`).getUTCDay()];
}
/** Convert a local "HH:mm" on `date` in `timezone` to a UTC instant. */
function localTimeToUtc(date: string, time: string, timezone: string): Date {
return fromZonedTime(`${date}T${time}:00`, timezone);
}
interface Window {
readonly start: Date;
readonly end: Date;
}
/** Resolve the active windows for one provider on `date` (exceptions override rules). */
function windowsForProvider(provider: ProviderAvailabilityInput, date: string): Window[] {
const dayExceptions = provider.exceptions.filter((e) => e.date === date);
if (dayExceptions.some((e) => e.kind === "unavailable")) {
return [];
}
const customWindows = dayExceptions.filter((e) => e.kind === "custom_window" && e.startTime && e.endTime);
if (customWindows.length > 0) {
return customWindows
.map((e) => ({ start: localTimeToUtc(date, e.startTime as string, e.timezone), end: localTimeToUtc(date, e.endTime as string, e.timezone) }))
.filter((w) => w.end.getTime() > w.start.getTime());
}
const weekday = weekdayOfIsoDate(date);
return provider.rules
.filter((r) => r.dayOfWeek === weekday)
.map((r) => ({ start: localTimeToUtc(date, r.startTime, r.timezone), end: localTimeToUtc(date, r.endTime, r.timezone) }))
.filter((w) => w.end.getTime() > w.start.getTime());
}
/** Compute bookable slots for one booking page on `date` across all providers. */
export function computeSlots(input: ComputeSlotsInput): ComputedSlot[] {
if (!ISO_DATE.test(input.date)) {
return [];
}
const { config, now } = input;
const earliest = now.getTime() + config.minNoticeHours * HOUR_MS;
const latest = now.getTime() + config.maxAdvanceDays * DAY_MS;
const durationMs = config.durationMinutes * MINUTE_MS;
const stepMs = Math.max(config.slotIncrementMinutes, 1) * MINUTE_MS;
const bufferBeforeMs = config.bufferBeforeMinutes * MINUTE_MS;
const bufferAfterMs = config.bufferAfterMinutes * MINUTE_MS;
// instant(ms) → set of providers free there, so the union stays deduped + stable.
const byInstant = new Map<number, { startAt: Date; endAt: Date; providers: Set<string> }>();
for (const provider of input.providers) {
const busy = mergeBusyIntervals(provider.busyIntervals);
for (const window of windowsForProvider(provider, input.date)) {
for (let t = window.start.getTime(); t + durationMs <= window.end.getTime(); t += stepMs) {
const startAt = new Date(t);
const endAt = new Date(t + durationMs);
if (t < earliest || t > latest) {
continue;
}
// Buffered occupancy must be free of any existing busy block.
if (overlapsBusy(new Date(t - bufferBeforeMs), new Date(t + durationMs + bufferAfterMs), busy)) {
continue;
}
const existing = byInstant.get(t);
if (existing) {
existing.providers.add(provider.providerUserId);
} else {
byInstant.set(t, { startAt, endAt, providers: new Set([provider.providerUserId]) });
}
}
}
}
return [...byInstant.values()]
.sort((a, b) => a.startAt.getTime() - b.startAt.getTime())
.map((s) => ({ startAt: s.startAt, endAt: s.endAt, providerUserIds: [...s.providers].sort() }));
}
/**
* `first_available` provider pick (M06 A.2 v1): the deterministic choice for a slot
* is the lowest-id free provider. Returns null when nobody is free at that instant.
*/
export function pickFirstAvailableProvider(slot: ComputedSlot): string | null {
return slot.providerUserIds.length > 0 ? slot.providerUserIds[0] : null;
}
@@ -0,0 +1,115 @@
// AK-P16a · calendar DB access (thin Prisma wrappers). Every read is tenant- AND
// user-scoped (leak-protection, DoD 3). Token ciphertext columns are NEVER
// selected into these read shapes — only the connect/refresh services touch them.
import { db } from "~/utils/db.server";
/** Connection fields safe to surface (no token ciphertext). */
export type CalendarConnectionListRow = {
id: string;
userId: string;
provider: "google";
externalAccountEmail: string;
status: "active" | "paused" | "error" | "revoked";
syncDirection: "bidirectional" | "hivegrid_to_external_only" | "external_to_hivegrid_only";
lastSyncAt: Date | null;
lastErrorText: string | null;
selectedCalendars: unknown;
};
const CONNECTION_SAFE_SELECT = {
id: true,
userId: true,
provider: true,
externalAccountEmail: true,
status: true,
syncDirection: true,
lastSyncAt: true,
lastErrorText: true,
selectedCalendars: true,
} as const;
/** The current user's own calendar connections (newest first). */
export async function listConnectionsForUser(tenantId: string, userId: string): Promise<CalendarConnectionListRow[]> {
return db.calendarConnection.findMany({
where: { tenantId, userId, archivedAt: null },
select: CONNECTION_SAFE_SELECT,
orderBy: { createdAt: "desc" },
}) as unknown as Promise<CalendarConnectionListRow[]>;
}
/** One connection by id (tenant-scoped). Returns userId so the route owner-checks. */
export async function getConnectionForTenant(tenantId: string, connectionId: string): Promise<CalendarConnectionListRow | null> {
return db.calendarConnection.findFirst({
where: { id: connectionId, tenantId, archivedAt: null },
select: CONNECTION_SAFE_SELECT,
}) as unknown as Promise<CalendarConnectionListRow | null>;
}
/**
* Resolve the connection a Google push channel belongs to. The webhook entrypoint
* has NO tenant context (Google calls a fixed URL), so this is a deliberate
* cross-tenant lookup by the stored subscription id; the caller then scopes every
* follow-up to the returned tenantId.
*/
export async function findConnectionByWebhookSubscription(subscriptionId: string): Promise<{ id: string; tenantId: string; userId: string } | null> {
return db.calendarConnection.findFirst({
where: { webhookSubscriptionId: subscriptionId, archivedAt: null },
select: { id: true, tenantId: true, userId: true },
});
}
/** Persist an inbound webhook notification as pending (idempotency + retry). */
export async function recordWebhookEvent(input: {
tenantId: string;
connectionId: string;
notificationPayload: Record<string, unknown>;
externalResourceState: string | null;
}): Promise<void> {
await db.calendarWebhookEvent.create({
data: {
tenantId: input.tenantId,
connectionId: input.connectionId,
provider: "google",
notificationPayload: input.notificationPayload as never,
processingStatus: "pending",
externalResourceState: input.externalResourceState,
},
});
}
export type CalendarConflictRow = {
id: string;
resolution: "external_won" | "hivegrid_won" | "external_deleted" | "hivegrid_deleted";
descriptionText: string;
createdAt: Date;
};
/** The last `take` conflicts of a connection, newest first (DoD 4). */
export async function listConflictsForConnection(tenantId: string, connectionId: string, take = 50): Promise<CalendarConflictRow[]> {
return db.calendarConflict.findMany({
where: { tenantId, connectionId },
select: { id: true, resolution: true, descriptionText: true, createdAt: true },
orderBy: { createdAt: "desc" },
take,
}) as unknown as Promise<CalendarConflictRow[]>;
}
export type CalendarEventRow = {
id: string;
source: "hivegrid_internal" | "external_synced";
title: string | null;
startsAt: Date;
endsAt: Date;
isAllDay: boolean;
internalEntityLink: unknown;
};
/** The current user's own events in a window (for the calendar view, DoD 5). */
export async function listEventsForUser(tenantId: string, userId: string, rangeStart: Date, rangeEnd: Date): Promise<CalendarEventRow[]> {
return db.calendarEvent.findMany({
where: { tenantId, userId, archivedAt: null, startsAt: { gte: rangeStart, lte: rangeEnd } },
select: { id: true, source: true, title: true, startsAt: true, endsAt: true, isAllDay: true, internalEntityLink: true },
orderBy: { startsAt: "asc" },
}) as unknown as Promise<CalendarEventRow[]>;
}
@@ -0,0 +1,45 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { resolveRepoPath } from "~/utils/testing/repoPaths";
// AK-P16a · static authorization-boundary guard for the calendar mutation routes
// (DoD A.5 / DoD 3). Asserts every state-changing action runs the module/permission
// guard, the owner-check (where applicable) and CSRF validation BEFORE it reads the
// form body — so a missing module/permission/owner/CSRF can never reach a mutation.
const appRoot = resolveRepoPath("apps/web/app");
const mutationRoutes = [
"routes/app.$tenant/settings.integrations.calendar._index.tsx",
"routes/app.$tenant/settings.integrations.calendar.$id.tsx",
];
describe("calendar route authorization boundary", () => {
test("guards permission + CSRF before parsing the form body", () => {
for (const relativePath of mutationRoutes) {
const source = fs.readFileSync(path.join(appRoot, relativePath), "utf8");
const formDataAt = source.indexOf("await request.formData()");
expect(formDataAt, relativePath).toBeGreaterThanOrEqual(0);
const permissionAt = source.indexOf("requireCalendarPermission(ctx, CALENDAR_PERMISSIONS.connectOwn)");
expect(permissionAt, relativePath).toBeGreaterThanOrEqual(0);
expect(permissionAt, relativePath).toBeLessThan(formDataAt);
const csrfAt = source.indexOf("await validateCSRFToken(request)");
expect(csrfAt, relativePath).toBeGreaterThanOrEqual(0);
expect(csrfAt, relativePath).toBeLessThan(formDataAt);
}
});
test("detail route owner-checks the connection before mutating", () => {
const source = fs.readFileSync(path.join(appRoot, "routes/app.$tenant/settings.integrations.calendar.$id.tsx"), "utf8");
const ownerAt = source.indexOf("requireConnectionOwner(ctx, connection.userId)");
const formDataAt = source.indexOf("await request.formData()");
expect(ownerAt).toBeGreaterThanOrEqual(0);
// The action's owner-check (the second occurrence) precedes the form read.
const actionOwnerAt = source.indexOf("requireConnectionOwner(ctx, connection.userId)", ownerAt + 1);
expect(actionOwnerAt).toBeGreaterThanOrEqual(0);
expect(actionOwnerAt).toBeLessThan(formDataAt);
});
});
@@ -0,0 +1,85 @@
// AK-P16a · shared loader/action guard for the calendar module (mirrors
// integrationsAccess / taskAccess). Calendar is an Apps-Engine integration, so the
// MODULE gate reuses the `integrations` feature (tenantHasModule) — there is no
// separate plan-gated "calendar" feature (M25 Block I: connecting your own
// calendar is a default tenant-user capability). The PER-USER capability is gated
// by the `calendar.connect_own` permission; `calendar.admin` is tenant-wide
// oversight. Module-off renders a locked empty VM on GET and 404s on write
// (Bauprinzip A.5.3); a permission miss is also a 404, never a 403.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { INTEGRATIONS_MODULE_KEY } from "~/utils/integrations/integrationsRoutePaths";
/** Calendar atomic permissions (M25 Block I). */
export const CALENDAR_PERMISSIONS = {
/** Connect/manage your OWN calendar connection (default tenant-user capability). */
connectOwn: "calendar.connect_own",
/** Tenant-wide oversight + force-disconnect on user offboarding. */
admin: "calendar.admin",
} as const;
export type CalendarRouteContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
hasModule: boolean;
};
/**
* Resolve the calendar route context: auth + tenant + the integrations module gate
* + the user's permissions. With `requireModule` a module-off tenant 404s (write
* paths); GET paths can render a locked empty VM from `hasModule === false`.
*/
export async function loadCalendarContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<CalendarRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: INTEGRATIONS_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: INTEGRATIONS_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True if the user holds `permission` or the broader `calendar.admin` bundle. */
export function calendarHasPermission(ctx: CalendarRouteContext, permission: string): boolean {
return ctx.permissions.includes(permission) || ctx.permissions.includes(CALENDAR_PERMISSIONS.admin);
}
/** Require a calendar.* permission (admin-aware); 404 if missing (A.5.3). */
export function requireCalendarPermission(ctx: CalendarRouteContext, permission: string): CalendarRouteContext {
if (!calendarHasPermission(ctx, permission)) {
throw new CatalogError(foundationErrors.notFound, { permission });
}
return ctx;
}
/**
* Owner-check for connection-scoped routes (leak-protection, DoD 3): only the
* owning user may see/manage a connection's external event details — UNLESS the
* caller holds `calendar.admin` (tenant oversight). A miss is a 404, not a 403.
*/
export function requireConnectionOwner(ctx: CalendarRouteContext, connectionUserId: string): CalendarRouteContext {
if (ctx.userId === connectionUserId || ctx.permissions.includes(CALENDAR_PERMISSIONS.admin)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { owner: "mismatch" });
}
@@ -0,0 +1,33 @@
// AK-P16a · pure client-safe route-path builders for the calendar module. Loaders
// build these and pass them into the VMs so the VMs stay routing-agnostic (mirrors
// integrationsRoutePaths). Calendar reuses the `integrations` tenant-connector
// module key (calendar is an Apps-Engine integration; see calendarAccess.server).
export { INTEGRATIONS_MODULE_KEY as CALENDAR_MODULE_KEY } from "~/utils/integrations/integrationsRoutePaths";
/** The calendar grid view (all sources). */
export function calendarViewPath(tenantSlug: string): string {
return `/${tenantSlug}/calendar`;
}
/** The calendar connections settings list. */
export function calendarConnectionsPath(tenantSlug: string): string {
return `/${tenantSlug}/settings/integrations/calendar`;
}
/** A single connection's detail (selected calendars, status, conflict log). */
export function calendarConnectionDetailPath(tenantSlug: string, connectionId: string): string {
return `/${tenantSlug}/settings/integrations/calendar/${connectionId}`;
}
/**
* The OAuth callback URI. NOT tenant-scoped: EXT-10 registered exactly
* `/integrations/google/oauth/callback` at the app root (Google redirects here);
* the signed `state` carries the tenant + user.
*/
export const GOOGLE_OAUTH_CALLBACK_PATH = "/integrations/google/oauth/callback";
/** 404 helper (Bauprinzip A.5.3 — permission/owner miss renders 404, not 403). */
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -0,0 +1,163 @@
// AK-P16a · calendar connection lifecycle (connect / callback / disconnect).
//
// OAuth tokens are sealed with the per-tenant DEK envelope (AD-8) — never stored
// plain, never logged. Writes are audited automatically by the M001 Prisma
// middleware (DoD 13); connect/disconnect are USER-account events, not CRM
// activity-stream entries (the activity model is CRM-subject only — the
// appointment-sync activity belongs to AK-P16b's booking). Webhook subscription is
// best-effort: a failure degrades the connection with a Klartext hint, it does not
// block the connect.
import { decryptTenantField, encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { db } from "~/utils/db.server";
import { googleCalendarAdapter, CalendarNotConfiguredError } from "./adapters/GoogleCalendarAdapter.server";
import type { CalendarCreds } from "./adapters/CalendarAdapter";
import { signCalendarOAuthState, verifyCalendarOAuthState } from "./oauthState.server";
import { GOOGLE_OAUTH_CALLBACK_PATH } from "../routes/calendarRoutePaths";
export class CalendarConnectError extends Error {
readonly code: "not_configured" | "invalid_state" | "exchange_failed";
constructor(code: CalendarConnectError["code"]) {
super(code);
this.name = "CalendarConnectError";
this.code = code;
}
}
/** Build the Google consent URL for the current tenant user. */
export function buildConnectUrl(input: { tenantId: string; userId: string; tenantSlug: string }): string {
if (!googleCalendarAdapter.isConfigured()) {
throw new CalendarConnectError("not_configured");
}
const state = signCalendarOAuthState(input);
return googleCalendarAdapter.buildAuthorizationUrl(state);
}
/**
* Complete the OAuth callback: verify state, exchange the code, seal the tokens,
* upsert the per-user connection, and best-effort subscribe the push channel.
* Returns the tenant slug + ids so the callback route can trigger the initial sync
* (kept out of this service to avoid a CalendarSyncService import cycle).
*/
export async function completeOAuthCallback(input: { code: string; state: string }): Promise<{ tenantSlug: string; tenantId: string; connectionId: string }> {
const verified = verifyCalendarOAuthState(input.state);
if (!verified.ok) {
throw new CalendarConnectError("invalid_state");
}
const { tenantId, userId, tenantSlug } = verified.payload;
let exchange: Awaited<ReturnType<typeof googleCalendarAdapter.exchangeCode>>;
try {
exchange = await googleCalendarAdapter.exchangeCode(input.code);
} catch (error) {
if (error instanceof CalendarNotConfiguredError) {
throw new CalendarConnectError("not_configured");
}
throw new CalendarConnectError("exchange_failed");
}
const { tokens, account } = exchange;
// Seal refresh + access tokens separately (AD-8). A refresh token is only
// returned on first consent; keep an existing one if Google omits it.
const refreshCiphertext = tokens.refreshToken ? await encryptTenantField(tenantId, tokens.refreshToken) : null;
const accessCiphertext = await encryptTenantField(tenantId, tokens.accessToken);
const connection = await db.calendarConnection.upsert({
where: { tenantId_userId_provider_externalAccountId: { tenantId, userId, provider: "google", externalAccountId: account.accountId } },
create: {
tenantId,
userId,
provider: "google",
externalAccountEmail: account.email,
externalAccountId: account.accountId,
oauthRefreshTokenCiphertext: refreshCiphertext,
oauthAccessTokenCiphertext: accessCiphertext,
oauthAccessTokenExpiresAt: tokens.expiresAt,
oauthScopes: [...tokens.scopes],
status: "active",
},
update: {
externalAccountEmail: account.email,
// Preserve the stored refresh token when Google omits it on re-consent.
...(refreshCiphertext ? { oauthRefreshTokenCiphertext: refreshCiphertext } : {}),
oauthAccessTokenCiphertext: accessCiphertext,
oauthAccessTokenExpiresAt: tokens.expiresAt,
oauthScopes: [...tokens.scopes],
status: "active",
lastErrorText: null,
archivedAt: null,
},
select: { id: true },
});
await trySubscribeWebhook({ tenantId, connectionId: connection.id, accessToken: tokens.accessToken, refreshToken: tokens.refreshToken ?? "" });
return { tenantSlug, tenantId, connectionId: connection.id };
}
/**
* Best-effort push-channel subscription for the primary calendar. Needs a public
* webhook URL (GOOGLE_CALENDAR_WEBHOOK_URL); absent or failing it degrades the
* connection with a Klartext hint rather than failing the connect.
*/
async function trySubscribeWebhook(input: { tenantId: string; connectionId: string; accessToken: string; refreshToken: string }): Promise<void> {
const webhookUrl = process.env.GOOGLE_CALENDAR_WEBHOOK_URL;
if (!webhookUrl) {
return;
}
const creds: CalendarCreds = { accessToken: input.accessToken, refreshToken: input.refreshToken };
// The channel id doubles as the per-connection lookup; the token is the
// verification secret echoed back as X-Goog-Channel-Token.
const channelId = `cal_${input.connectionId}`;
try {
const sub = await googleCalendarAdapter.subscribeWebhook(creds, "primary", channelId, webhookUrl, input.connectionId);
await db.calendarConnection.update({
where: { id: input.connectionId },
data: { webhookSubscriptionId: sub.subscriptionId, webhookSubscriptionExpiresAt: sub.expiresAt },
});
} catch {
await db.calendarConnection.update({
where: { id: input.connectionId },
data: { status: "active", lastErrorText: "calendar.health.webhookSubscriptionFailed" },
});
}
}
/** Decrypt a connection's sealed tokens into adapter creds (server-only). */
export async function loadConnectionCreds(tenantId: string, connectionId: string): Promise<CalendarCreds | null> {
const row = await db.calendarConnection.findFirst({
where: { id: connectionId, tenantId },
select: { oauthRefreshTokenCiphertext: true, oauthAccessTokenCiphertext: true, oauthAccessTokenExpiresAt: true },
});
if (!row?.oauthRefreshTokenCiphertext || !row.oauthAccessTokenCiphertext) {
return null;
}
const [refreshToken, accessToken] = await Promise.all([
decryptTenantField(tenantId, row.oauthRefreshTokenCiphertext),
decryptTenantField(tenantId, row.oauthAccessTokenCiphertext),
]);
return { refreshToken, accessToken, expiresAt: row.oauthAccessTokenExpiresAt };
}
/**
* Disconnect a connection (owner or admin). Best-effort revoke of the push channel
* + provider tokens, then soft-revoke locally (status revoked, soft-delete). The
* external mirror events are optionally removed (M25 disconnect dialog) — deferred
* to the sync service; here we drop the local connection + its push channel.
*/
export async function disconnectConnection(input: { tenantId: string; connectionId: string }): Promise<void> {
const row = await db.calendarConnection.findFirst({
where: { id: input.connectionId, tenantId: input.tenantId, archivedAt: null },
select: { id: true, webhookSubscriptionId: true },
});
if (!row) {
return;
}
const creds = await loadConnectionCreds(input.tenantId, input.connectionId);
if (creds && row.webhookSubscriptionId) {
await googleCalendarAdapter.unsubscribeWebhook(creds, row.webhookSubscriptionId, row.webhookSubscriptionId).catch(() => undefined);
}
await db.calendarConnection.update({
where: { id: row.id },
data: { status: "revoked", archivedAt: new Date(), oauthRefreshTokenCiphertext: null, oauthAccessTokenCiphertext: null, webhookSubscriptionId: null },
});
}
@@ -0,0 +1,116 @@
// AK-P16a · calendar sync engine (M25 Block D/E). The external -> HiveGrid
// read-only path: pull the provider delta via the stored cursor and upsert each
// event into the CalendarEvent cache (through the pure eventMapping). Tokens are
// refreshed transparently when expired. The cache feeds availability (busy slots
// only — leak-protection happens at the availability boundary, not here).
//
// A 410 (sync_token_invalid) triggers a full re-pull of the rolling window. The
// bidirectional WRITE path (HiveGrid -> Google) + the conflict-on-mapped-event
// path build on top of this and the ConflictResolver; they require the write
// service (mappings) and are wired as that lands.
import { encryptTenantField } from "@hivegrid/db/crypto/tenant-envelope.server";
import { db } from "~/utils/db.server";
import { googleCalendarAdapter } from "./adapters/GoogleCalendarAdapter.server";
import type { CalendarCreds } from "./adapters/CalendarAdapter";
import { loadConnectionCreds } from "./CalendarConnectionService.server";
import { toExternalEventFields } from "./eventMapping";
const WINDOW_PAST_DAYS = 7;
const WINDOW_FUTURE_DAYS = 60;
const PRIMARY_CALENDAR = "primary";
/** Ensure the access token is fresh; refresh + re-seal when within 60s of expiry. */
async function ensureFreshCreds(tenantId: string, connectionId: string, creds: CalendarCreds): Promise<CalendarCreds> {
const soon = Date.now() + 60_000;
if (creds.expiresAt && creds.expiresAt.getTime() > soon) {
return creds;
}
const next = await googleCalendarAdapter.refreshTokens(creds.refreshToken);
const accessCiphertext = await encryptTenantField(tenantId, next.accessToken);
await db.calendarConnection.update({
where: { id: connectionId },
data: { oauthAccessTokenCiphertext: accessCiphertext, oauthAccessTokenExpiresAt: next.expiresAt, status: "active", lastErrorText: null },
});
return { accessToken: next.accessToken, refreshToken: creds.refreshToken, expiresAt: next.expiresAt };
}
export interface SyncResult {
readonly upserted: number;
readonly fullResync: boolean;
}
/**
* Run one incremental external -> cache sync for a connection's primary calendar.
* Idempotent: re-running with the same cursor is a no-op; a 410 forces a full
* window re-pull. Returns the number of events written.
*/
export async function syncConnection(tenantId: string, connectionId: string, now: Date = new Date()): Promise<SyncResult> {
const baseCreds = await loadConnectionCreds(tenantId, connectionId);
if (!baseCreds) {
return { upserted: 0, fullResync: false };
}
const connection = await db.calendarConnection.findFirst({ where: { id: connectionId, tenantId }, select: { userId: true } });
if (!connection) {
return { upserted: 0, fullResync: false };
}
let creds: CalendarCreds;
try {
creds = await ensureFreshCreds(tenantId, connectionId, baseCreds);
} catch {
await db.calendarConnection.update({ where: { id: connectionId }, data: { status: "error", lastErrorText: "calendar.health.tokenExpired" } });
return { upserted: 0, fullResync: false };
}
const cursor = await db.calendarSyncCursor.findFirst({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, select: { cursorToken: true } });
let upserted = 0;
let fullResync = false;
let pageToken: string | undefined;
let nextSyncToken: string | undefined;
let syncToken = cursor?.cursorToken ?? undefined;
do {
const page = await googleCalendarAdapter.fetchEvents(creds, PRIMARY_CALENDAR, {
syncToken,
pageToken,
timeMin: syncToken ? undefined : new Date(now.getTime() - WINDOW_PAST_DAYS * 86_400_000),
timeMax: syncToken ? undefined : new Date(now.getTime() + WINDOW_FUTURE_DAYS * 86_400_000),
});
if (page.fullResyncRequired) {
// Cursor expired (410): drop it and restart this run as an initial pull.
fullResync = true;
syncToken = undefined;
pageToken = undefined;
await db.calendarSyncCursor.updateMany({ where: { connectionId, externalCalendarId: PRIMARY_CALENDAR }, data: { cursorToken: null } });
continue;
}
for (const event of page.events) {
const fields = toExternalEventFields(event, { tenantId, userId: connection.userId, connectionId, provider: "google", externalCalendarId: PRIMARY_CALENDAR }, now);
await db.calendarEvent.upsert({
where: { tenantId_userId_provider_externalEventId: { tenantId, userId: connection.userId, provider: "google", externalEventId: event.externalId } },
create: fields,
update: { ...fields, createdAt: undefined } as never,
});
upserted += 1;
}
pageToken = page.nextPageToken;
nextSyncToken = page.nextSyncToken ?? nextSyncToken;
} while (pageToken);
// Persist the new cursor + stamp the successful sync.
if (nextSyncToken) {
await db.calendarSyncCursor.upsert({
where: { connectionId_externalCalendarId: { connectionId, externalCalendarId: PRIMARY_CALENDAR } },
create: { tenantId, connectionId, externalCalendarId: PRIMARY_CALENDAR, cursorToken: nextSyncToken, lastFullSyncAt: fullResync ? now : null },
update: { cursorToken: nextSyncToken, ...(fullResync ? { lastFullSyncAt: now } : {}) },
});
}
await db.calendarConnection.update({ where: { id: connectionId }, data: { lastSyncAt: now, status: "active" } });
return { upserted, fullResync };
}
@@ -0,0 +1,115 @@
// AK-P16a · provider-agnostic CalendarAdapter contract (M25 Block G).
//
// v1 ships only the Google implementation (GoogleCalendarAdapter.server.ts);
// Outlook/Microsoft is a v2 adapter against this SAME interface. The adapter is a
// thin PROVIDER BOUNDARY: given decrypted creds it performs one network op and
// returns provider-neutral data. The per-user orchestration (cursor persistence,
// mapping upserts, Last-Write-Wins) lives in the sync services, not here.
//
// Neutral types deliberately avoid any Google naming so a second provider drops in
// without leaking provider shapes into the domain layer.
/** A connection's decrypted OAuth credentials (the engine handles envelope crypto). */
export interface CalendarCreds {
readonly accessToken: string;
readonly refreshToken: string;
readonly expiresAt?: Date | null;
}
export interface CalendarTokens {
readonly accessToken: string;
/** Present on the initial code exchange; absent on a refresh. */
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}
export interface CalendarAccount {
readonly email: string;
readonly accountId: string;
}
export interface NeutralCalendar {
readonly id: string;
readonly name: string;
readonly isPrimary: boolean;
}
export interface NeutralEvent {
readonly externalId: string;
/** false when the provider reports the event as cancelled/deleted. */
readonly isActive: boolean;
readonly title: string | null;
readonly description: string | null;
readonly location: string | null;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay: boolean;
readonly timeZone: string | null;
readonly recurrenceRule: string | null;
readonly attendees: ReadonlyArray<{ email: string; status: string | null }>;
readonly etag: string | null;
readonly lastModifiedExternal: Date | null;
/** Whether this event blocks availability (false = provider "Free"). */
readonly isBusy: boolean;
}
export interface NeutralEventInput {
readonly title: string;
readonly description?: string;
readonly location?: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay?: boolean;
readonly timeZone?: string;
readonly attendees?: ReadonlyArray<{ email: string }>;
}
export interface DeltaResult {
readonly events: readonly NeutralEvent[];
/** Persist as the next cursor when present (page complete). */
readonly nextSyncToken?: string;
/** Continue paging within the same sync when present. */
readonly nextPageToken?: string;
/** True when the cursor expired (HTTP 410) → caller must full-resync. */
readonly fullResyncRequired?: boolean;
}
export interface WebhookSubscription {
readonly subscriptionId: string;
readonly resourceId: string;
readonly expiresAt: Date | null;
}
export interface WriteResult {
readonly externalId: string;
readonly etag: string | null;
}
/** Thrown by updateEvent when the provider reports a concurrent external edit. */
export class CalendarConflictError extends Error {
constructor(message = "external_concurrent_edit") {
super(message);
this.name = "CalendarConflictError";
}
}
export interface CalendarAdapter {
readonly provider: "google";
/** True only when the provider OAuth config is present (EXT-10 env). */
isConfigured(): boolean;
buildAuthorizationUrl(state: string): string;
exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }>;
refreshTokens(refreshToken: string): Promise<CalendarTokens>;
listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]>;
subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription>;
unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void>;
fetchEvents(
creds: CalendarCreds,
calendarId: string,
opts: { syncToken?: string; pageToken?: string; timeMin?: Date; timeMax?: Date },
): Promise<DeltaResult>;
createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult>;
updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult>;
deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void>;
}
@@ -0,0 +1,180 @@
// AK-P16a · Google implementation of the provider-agnostic CalendarAdapter.
//
// Maps the neutral domain shapes to/from the shared @hivegrid/integrations Google
// REST client. No Prisma here — the adapter only does network I/O against Google
// and provider↔neutral mapping. Token storage/crypto + orchestration live in the
// sync services.
import {
buildAuthorizationUrl,
deleteEvent as gDeleteEvent,
exchangeCodeForTokens,
fetchUserInfo,
GoogleCalendarError,
insertEvent,
listCalendars as gListCalendars,
listEvents,
patchEvent,
refreshAccessToken,
resolveGoogleOAuthConfig,
stopChannel,
watchCalendar,
type GoogleEvent,
type GoogleEventInput,
type GoogleOAuthConfig,
} from "@hivegrid/integrations";
import {
CalendarConflictError,
type CalendarAccount,
type CalendarAdapter,
type CalendarCreds,
type CalendarTokens,
type DeltaResult,
type NeutralCalendar,
type NeutralEvent,
type NeutralEventInput,
type WebhookSubscription,
type WriteResult,
} from "./CalendarAdapter";
/** Thrown when the OAuth config (EXT-10 env) is absent — surfaced as Klartext. */
export class CalendarNotConfiguredError extends Error {
constructor() {
super("calendar_not_configured");
this.name = "CalendarNotConfiguredError";
}
}
function requireConfig(): GoogleOAuthConfig {
const config = resolveGoogleOAuthConfig();
if (!config) {
throw new CalendarNotConfiguredError();
}
return config;
}
function parseBoundary(b: { dateTime?: string; date?: string } | undefined): { at: Date; isAllDay: boolean } {
if (b?.dateTime) {
return { at: new Date(b.dateTime), isAllDay: false };
}
if (b?.date) {
return { at: new Date(`${b.date}T00:00:00.000Z`), isAllDay: true };
}
return { at: new Date(0), isAllDay: false };
}
function toNeutralEvent(g: GoogleEvent): NeutralEvent {
const start = parseBoundary(g.start);
const end = parseBoundary(g.end);
return {
externalId: g.id,
isActive: g.status !== "cancelled",
title: g.summary ?? null,
description: g.description ?? null,
location: g.location ?? null,
startsAt: start.at,
endsAt: end.at,
isAllDay: start.isAllDay || end.isAllDay,
timeZone: g.start?.timeZone ?? null,
recurrenceRule: g.recurrence && g.recurrence.length > 0 ? g.recurrence[0] : null,
attendees: (g.attendees ?? []).map((a) => ({ email: a.email ?? "", status: a.responseStatus ?? null })),
etag: g.etag ?? null,
lastModifiedExternal: g.updated ? new Date(g.updated) : null,
// Google "transparent" == Free → not busy. Default (opaque/undefined) = busy.
isBusy: g.transparency !== "transparent",
};
}
function toGoogleInput(input: NeutralEventInput): GoogleEventInput {
const tz = input.timeZone ?? "UTC";
const boundary = (d: Date): GoogleEventInput["start"] =>
input.isAllDay ? { date: d.toISOString().slice(0, 10) } : { dateTime: d.toISOString(), timeZone: tz };
return {
summary: input.title,
description: input.description,
location: input.location,
start: boundary(input.startsAt),
end: boundary(input.endsAt),
attendees: input.attendees ? input.attendees.map((a) => ({ email: a.email })) : undefined,
};
}
export const googleCalendarAdapter: CalendarAdapter = {
provider: "google",
isConfigured(): boolean {
return resolveGoogleOAuthConfig() !== null;
},
buildAuthorizationUrl(state: string): string {
return buildAuthorizationUrl(requireConfig(), state);
},
async exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }> {
const config = requireConfig();
const tokenSet = await exchangeCodeForTokens(config, code);
const info = await fetchUserInfo(tokenSet.accessToken);
return {
tokens: { accessToken: tokenSet.accessToken, refreshToken: tokenSet.refreshToken, expiresAt: tokenSet.expiresAt, scopes: tokenSet.scopes },
account: { email: info.email, accountId: info.sub },
};
},
async refreshTokens(refreshToken: string): Promise<CalendarTokens> {
const set = await refreshAccessToken(requireConfig(), refreshToken);
return { accessToken: set.accessToken, refreshToken: set.refreshToken, expiresAt: set.expiresAt, scopes: set.scopes };
},
async listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]> {
const cals = await gListCalendars(creds.accessToken);
return cals.map((c) => ({ id: c.id, name: c.summary, isPrimary: c.primary }));
},
async subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription> {
const channel = await watchCalendar(creds.accessToken, calendarId, channelId, address, token);
return { subscriptionId: channel.channelId, resourceId: channel.resourceId, expiresAt: channel.expiresAt };
},
async unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void> {
await stopChannel(creds.accessToken, subscriptionId, resourceId);
},
async fetchEvents(creds: CalendarCreds, calendarId: string, opts): Promise<DeltaResult> {
try {
const page = await listEvents(creds.accessToken, calendarId, {
syncToken: opts.syncToken,
pageToken: opts.pageToken,
timeMin: opts.timeMin?.toISOString(),
timeMax: opts.timeMax?.toISOString(),
});
return { events: page.events.map(toNeutralEvent), nextSyncToken: page.nextSyncToken, nextPageToken: page.nextPageToken };
} catch (error) {
if (error instanceof GoogleCalendarError && error.fullResyncRequired) {
return { events: [], fullResyncRequired: true };
}
throw error;
}
},
async createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult> {
const result = await insertEvent(creds.accessToken, calendarId, toGoogleInput(input));
return { externalId: result.id, etag: result.etag ?? null };
},
async updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult> {
try {
const result = await patchEvent(creds.accessToken, calendarId, externalId, toGoogleInput(input), ifMatchEtag ?? undefined);
return { externalId: result.id, etag: result.etag ?? null };
} catch (error) {
// 412 precondition-failed = a concurrent external edit (M25 Block F).
if (error instanceof GoogleCalendarError && error.httpStatus === 412) {
throw new CalendarConflictError();
}
throw error;
}
},
async deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void> {
await gDeleteEvent(creds.accessToken, calendarId, externalId);
},
};
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { extractBusyIntervals, mergeBusyIntervals, overlapsBusy, type BusyCandidate, type BusyInterval } from "./availability";
const d = (iso: string): Date => new Date(iso);
describe("extractBusyIntervals (leak-protection, DoD 3)", () => {
const base: Omit<BusyCandidate, "startsAt" | "endsAt"> = { isBusyForAvailability: true, archivedAt: null };
it("returns only anonymous {from,to} — never any content field", () => {
const events: BusyCandidate[] = [{ ...base, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") }];
const result = extractBusyIntervals(events);
expect(result).toEqual([{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") }]);
// Structural leak check: the only keys are from/to.
expect(Object.keys(result[0]).sort()).toEqual(["from", "to"]);
});
it("drops non-busy (Free), archived, and zero/negative-length events", () => {
const events: BusyCandidate[] = [
{ ...base, isBusyForAvailability: false, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") },
{ ...base, archivedAt: d("2026-07-01T08:00:00Z"), startsAt: d("2026-07-01T11:00:00Z"), endsAt: d("2026-07-01T12:00:00Z") },
{ ...base, startsAt: d("2026-07-01T13:00:00Z"), endsAt: d("2026-07-01T13:00:00Z") },
];
expect(extractBusyIntervals(events)).toEqual([]);
});
it("sorts ascending by start", () => {
const events: BusyCandidate[] = [
{ ...base, startsAt: d("2026-07-01T15:00:00Z"), endsAt: d("2026-07-01T16:00:00Z") },
{ ...base, startsAt: d("2026-07-01T09:00:00Z"), endsAt: d("2026-07-01T10:00:00Z") },
];
expect(extractBusyIntervals(events).map((i) => i.from.toISOString())).toEqual(["2026-07-01T09:00:00.000Z", "2026-07-01T15:00:00.000Z"]);
});
});
describe("mergeBusyIntervals", () => {
it("merges overlapping and touching intervals", () => {
const intervals: BusyInterval[] = [
{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") },
{ from: d("2026-07-01T10:00:00Z"), to: d("2026-07-01T11:00:00Z") },
{ from: d("2026-07-01T10:30:00Z"), to: d("2026-07-01T12:00:00Z") },
];
expect(mergeBusyIntervals(intervals)).toEqual([{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T12:00:00Z") }]);
});
it("keeps disjoint intervals separate", () => {
const intervals: BusyInterval[] = [
{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") },
{ from: d("2026-07-01T11:00:00Z"), to: d("2026-07-01T12:00:00Z") },
];
expect(mergeBusyIntervals(intervals)).toHaveLength(2);
});
it("returns [] for empty input", () => {
expect(mergeBusyIntervals([])).toEqual([]);
});
});
describe("overlapsBusy", () => {
const intervals: BusyInterval[] = [{ from: d("2026-07-01T09:00:00Z"), to: d("2026-07-01T10:00:00Z") }];
it("detects an overlapping slot", () => {
expect(overlapsBusy(d("2026-07-01T09:30:00Z"), d("2026-07-01T10:30:00Z"), intervals)).toBe(true);
});
it("treats back-to-back as free (half-open)", () => {
expect(overlapsBusy(d("2026-07-01T10:00:00Z"), d("2026-07-01T11:00:00Z"), intervals)).toBe(false);
});
});
@@ -0,0 +1,67 @@
// AK-P16a · availability extraction (PURE) — the leak-protection boundary (DoD 3).
//
// External calendar events carry private content (title/description/attendees).
// Outside the owning user's own views, the ONLY thing other users (and the Booking
// slot calculator in AK-P16b) may learn is "busy from X to Y" — never a title or
// any other field. This module is the single chokepoint that turns rich events
// into anonymous busy intervals, so the leak-protection is enforced in one pure,
// unit-tested place rather than scattered across queries.
//
// No Prisma / no React import — pure functions over plain inputs.
/** The minimal event fields availability needs (a structural subset). */
export interface BusyCandidate {
readonly startsAt: Date;
readonly endsAt: Date;
readonly isBusyForAvailability: boolean;
readonly archivedAt: Date | null;
}
/** An anonymous busy interval — deliberately NO title/description/owner field. */
export interface BusyInterval {
readonly from: Date;
readonly to: Date;
}
/**
* Project events to anonymous busy intervals. Drops events that are not busy
* (provider "Free"), archived/cancelled, or zero/negative length. The result
* contains ONLY {from,to} — by construction it cannot leak event content (DoD 3).
*/
export function extractBusyIntervals(events: readonly BusyCandidate[]): BusyInterval[] {
return events
.filter((e) => e.isBusyForAvailability && e.archivedAt === null && e.endsAt.getTime() > e.startsAt.getTime())
.map((e) => ({ from: e.startsAt, to: e.endsAt }))
.sort((a, b) => a.from.getTime() - b.from.getTime());
}
/**
* Merge overlapping/adjacent busy intervals into a minimal set. Used by the
* Booking slot calculator (AK-P16b) so back-to-back external events read as one
* contiguous busy block. Input need not be sorted.
*/
export function mergeBusyIntervals(intervals: readonly BusyInterval[]): BusyInterval[] {
if (intervals.length === 0) {
return [];
}
const sorted = [...intervals].sort((a, b) => a.from.getTime() - b.from.getTime());
const merged: BusyInterval[] = [{ from: sorted[0].from, to: sorted[0].to }];
for (let i = 1; i < sorted.length; i += 1) {
const last = merged[merged.length - 1];
const cur = sorted[i];
if (cur.from.getTime() <= last.to.getTime()) {
// Overlapping or touching → extend the current block.
if (cur.to.getTime() > last.to.getTime()) {
merged[merged.length - 1] = { from: last.from, to: cur.to };
}
} else {
merged.push({ from: cur.from, to: cur.to });
}
}
return merged;
}
/** True when [from,to) overlaps any busy interval (used for anti-double-booking). */
export function overlapsBusy(from: Date, to: Date, intervals: readonly BusyInterval[]): boolean {
return intervals.some((iv) => from.getTime() < iv.to.getTime() && to.getTime() > iv.from.getTime());
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { resolveConflict, type ConflictInput } from "./conflictResolution";
const d = (iso: string): Date => new Date(iso);
const base: ConflictInput = { internalLastModified: null, externalLastModified: null, internalDeleted: false, externalDeleted: false };
describe("resolveConflict (Last-Write-Wins, M25 Block F)", () => {
it("external newer → external_won", () => {
const out = resolveConflict({ ...base, internalLastModified: d("2026-07-01T09:00:00Z"), externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("external_won");
expect(out.winner).toBe("external");
});
it("hivegrid newer → hivegrid_won", () => {
const out = resolveConflict({ ...base, internalLastModified: d("2026-07-01T11:00:00Z"), externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("hivegrid_won");
expect(out.winner).toBe("hivegrid");
});
it("tie → external wins (authoritative default)", () => {
const t = d("2026-07-01T10:00:00Z");
const out = resolveConflict({ ...base, internalLastModified: t, externalLastModified: t });
expect(out.resolution).toBe("external_won");
});
it("external deleted but internal alive → external_deleted, no overwrite", () => {
const out = resolveConflict({ ...base, externalDeleted: true });
expect(out.resolution).toBe("external_deleted");
expect(out.winner).toBe("none");
});
it("internal deleted → hivegrid_deleted (push delete) even if external also changed", () => {
const out = resolveConflict({ ...base, internalDeleted: true, externalLastModified: d("2026-07-01T10:00:00Z") });
expect(out.resolution).toBe("hivegrid_deleted");
expect(out.winner).toBe("hivegrid");
});
it("every decision carries a Klartext i18n key", () => {
for (const input of [
{ ...base, externalLastModified: d("2026-07-01T10:00:00Z") },
{ ...base, internalLastModified: d("2026-07-01T10:00:00Z") },
{ ...base, externalDeleted: true },
{ ...base, internalDeleted: true },
]) {
expect(resolveConflict(input).descriptionKey).toMatch(/^calendar\.conflict\./);
}
});
});
@@ -0,0 +1,56 @@
// AK-P16a · conflict resolution decision (PURE) — Last-Write-Wins (M25 Block F).
//
// When a calendar event changed on BOTH sides between two syncs, HiveGrid resolves
// with Last-Write-Wins and tells the user in Klartext (DoD 4). This module holds
// the DECISION only (no DB, no network) so it is unit-tested in isolation; the
// ConflictResolver service applies the decision (persist + notify + conflict-log).
//
// Default tie-breaker: the EXTERNAL provider wins (M25 Block F-1) — the user can
// then manually re-apply their HiveGrid edit from the Klartext notification.
/** Mirror of the Prisma enum CalendarConflictResolution (kept in sync). */
export type ConflictResolution = "external_won" | "hivegrid_won" | "external_deleted" | "hivegrid_deleted";
export interface ConflictInput {
/** Last HiveGrid-side modification (null = unknown/never). */
readonly internalLastModified: Date | null;
/** Last external modification reported by the provider (null = unknown). */
readonly externalLastModified: Date | null;
/** The HiveGrid-internal event was deleted. */
readonly internalDeleted: boolean;
/** The external mirror was deleted/cancelled at the provider. */
readonly externalDeleted: boolean;
}
export interface ConflictDecision {
readonly resolution: ConflictResolution;
/** Which side's state should be applied. `none` = no content overwrite. */
readonly winner: "external" | "hivegrid" | "none";
/** i18n key for the Klartext conflict-log entry + notification (M002/M003). */
readonly descriptionKey: string;
}
/**
* Decide a single event conflict. Deletion beats edit; otherwise the most-recent
* write wins, with the external provider winning ties (authoritative default).
*/
export function resolveConflict(input: ConflictInput): ConflictDecision {
// Deletion cases first — a delete is a terminal state, not a timestamp race.
if (input.externalDeleted && !input.internalDeleted) {
// External mirror gone; the HiveGrid event stays (e.g. a Booking still exists).
return { resolution: "external_deleted", winner: "none", descriptionKey: "calendar.conflict.externalDeleted" };
}
if (input.internalDeleted) {
// HiveGrid event deleted → push the delete to the external mirror.
return { resolution: "hivegrid_deleted", winner: "hivegrid", descriptionKey: "calendar.conflict.hivegridDeleted" };
}
const internalAt = input.internalLastModified?.getTime() ?? 0;
const externalAt = input.externalLastModified?.getTime() ?? 0;
if (internalAt > externalAt) {
return { resolution: "hivegrid_won", winner: "hivegrid", descriptionKey: "calendar.conflict.hivegridWon" };
}
// external newer OR tie → external wins (authoritative default, M25 Block F-1).
return { resolution: "external_won", winner: "external", descriptionKey: "calendar.conflict.externalWon" };
}
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import type { NeutralEvent } from "./adapters/CalendarAdapter";
import { toExternalEventFields, type EventOwnerContext } from "./eventMapping";
const ctx: EventOwnerContext = { tenantId: "t1", userId: "u1", connectionId: "c1", provider: "google", externalCalendarId: "primary" };
const now = new Date("2026-07-01T12:00:00Z");
function event(overrides: Partial<NeutralEvent> = {}): NeutralEvent {
return {
externalId: "ext-1",
isActive: true,
title: "Kundentermin",
description: "Details",
location: "Berlin",
startsAt: new Date("2026-07-02T09:00:00Z"),
endsAt: new Date("2026-07-02T10:00:00Z"),
isAllDay: false,
timeZone: "Europe/Berlin",
recurrenceRule: null,
attendees: [{ email: "kunde@example.com", status: "accepted" }],
etag: "etag-1",
lastModifiedExternal: new Date("2026-07-01T11:00:00Z"),
isBusy: true,
...overrides,
};
}
describe("toExternalEventFields", () => {
it("maps an active event to an external-synced cache row", () => {
const fields = toExternalEventFields(event(), ctx, now);
expect(fields.source).toBe("external_synced");
expect(fields.provider).toBe("google");
expect(fields.externalEventId).toBe("ext-1");
expect(fields.externalCalendarId).toBe("primary");
expect(fields.isBusyForAvailability).toBe(true);
expect(fields.archivedAt).toBeNull();
expect(fields.tenantId).toBe("t1");
expect(fields.userId).toBe("u1");
});
it("soft-archives and de-busies a cancelled event", () => {
const fields = toExternalEventFields(event({ isActive: false }), ctx, now);
expect(fields.archivedAt).toEqual(now);
expect(fields.isBusyForAvailability).toBe(false);
});
it("carries the Free flag through (provider transparency)", () => {
const fields = toExternalEventFields(event({ isBusy: false }), ctx, now);
expect(fields.isBusyForAvailability).toBe(false);
expect(fields.archivedAt).toBeNull();
});
});
@@ -0,0 +1,72 @@
// AK-P16a · external-event → cache-row mapping (PURE).
//
// Turns a provider-neutral NeutralEvent (from the CalendarAdapter) into the field
// set persisted in CalendarEvent for the external-synced cache. Pure + decoupled
// from Prisma's generated input types so it can be unit-tested with plain objects;
// the db wrapper spreads the result into `db.calendarEvent.upsert`.
import type { NeutralEvent } from "./adapters/CalendarAdapter";
export interface EventOwnerContext {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly provider: "google";
readonly externalCalendarId: string;
}
/** The persisted field set for an external-synced CalendarEvent row. */
export interface ExternalEventFields {
readonly tenantId: string;
readonly userId: string;
readonly connectionId: string;
readonly source: "external_synced";
readonly provider: "google";
readonly externalEventId: string;
readonly externalCalendarId: string;
readonly title: string | null;
readonly description: string | null;
readonly location: string | null;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay: boolean;
readonly timeZone: string | null;
readonly recurrenceRule: string | null;
readonly attendees: ReadonlyArray<{ email: string; status: string | null }>;
readonly etag: string | null;
readonly lastModifiedExternal: Date | null;
readonly isBusyForAvailability: boolean;
/** Set when the provider cancelled/deleted the event (soft-delete the cache). */
readonly archivedAt: Date | null;
}
/**
* Map one external event to its cache-row fields. A cancelled/deleted provider
* event (`isActive=false`) is soft-archived (`archivedAt`) and forced non-busy so
* it drops out of availability immediately.
*/
export function toExternalEventFields(event: NeutralEvent, ctx: EventOwnerContext, now: Date): ExternalEventFields {
const cancelled = !event.isActive;
return {
tenantId: ctx.tenantId,
userId: ctx.userId,
connectionId: ctx.connectionId,
source: "external_synced",
provider: ctx.provider,
externalEventId: event.externalId,
externalCalendarId: ctx.externalCalendarId,
title: event.title,
description: event.description,
location: event.location,
startsAt: event.startsAt,
endsAt: event.endsAt,
isAllDay: event.isAllDay,
timeZone: event.timeZone,
recurrenceRule: event.recurrenceRule,
attendees: event.attendees,
etag: event.etag,
lastModifiedExternal: event.lastModifiedExternal,
isBusyForAvailability: cancelled ? false : event.isBusy,
archivedAt: cancelled ? now : null,
};
}
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vitest";
import { signCalendarOAuthState, verifyCalendarOAuthState } from "./oauthState.server";
const secret = "test-calendar-oauth-secret-please-rotate-32b";
const input = { tenantId: "tenant-1", userId: "user-1", tenantSlug: "acme" };
describe("calendar OAuth state (CSRF)", () => {
it("round-trips a signed state", () => {
const token = signCalendarOAuthState(input, { secret });
const result = verifyCalendarOAuthState(token, { secret });
expect(result.ok).toBe(true);
if (!result.ok) throw new Error("expected ok");
expect(result.payload.tenantId).toBe("tenant-1");
expect(result.payload.userId).toBe("user-1");
expect(result.payload.tenantSlug).toBe("acme");
});
it("rejects a tampered payload", () => {
const token = signCalendarOAuthState(input, { secret });
const tampered = `x${token.slice(1)}`;
expect(verifyCalendarOAuthState(tampered, { secret })).toEqual({ ok: false, reason: "bad-signature" });
});
it("rejects a wrong-secret signature", () => {
const token = signCalendarOAuthState(input, { secret });
expect(verifyCalendarOAuthState(token, { secret: "a-different-secret-value-of-length-32xx" })).toEqual({ ok: false, reason: "bad-signature" });
});
it("rejects a malformed token", () => {
expect(verifyCalendarOAuthState("not-a-token", { secret })).toEqual({ ok: false, reason: "malformed" });
});
it("rejects an expired state", () => {
const token = signCalendarOAuthState(input, { secret, now: () => 1_000_000 });
const later = () => 1_000_000 + 11 * 60 * 1000; // 11 minutes later (> 10m TTL)
expect(verifyCalendarOAuthState(token, { secret, now: later })).toEqual({ ok: false, reason: "expired" });
});
});
@@ -0,0 +1,99 @@
// AK-P16a · OAuth state signing for the Google connect flow (CSRF + context).
//
// The OAuth callback at /integrations/google/oauth/callback is NOT tenant-scoped
// (Google redirects to a fixed URI), so the tenant + user travel inside a SIGNED
// `state` parameter rather than a cookie. We HMAC-SHA256 the JSON payload with
// CRYPTO_SECRET||SESSION_SECRET (same convention as admin-sso/state.server) and
// URL-safe-base64 encode it. 10-minute TTL bounds the replay window.
import { createHmac, timingSafeEqual } from "node:crypto";
import { loadRequiredWebConfig } from "@hivegrid/config";
const STATE_TTL_MS = 10 * 60 * 1000;
const PAYLOAD_VERSION = "v1";
export interface CalendarOAuthStatePayload {
readonly tenantId: string;
readonly userId: string;
readonly tenantSlug: string;
/** Epoch milliseconds. */
readonly createdAt: number;
}
export type VerifyStateResult =
| { readonly ok: true; readonly payload: CalendarOAuthStatePayload }
| { readonly ok: false; readonly reason: "malformed" | "bad-signature" | "expired" };
function getSecret(override?: string): string {
if (override) return override;
const { cryptoSecret, sessionSecret } = loadRequiredWebConfig();
const secret = cryptoSecret || sessionSecret;
if (!secret) {
throw new Error("CRYPTO_SECRET or SESSION_SECRET is required for calendar OAuth state.");
}
return secret;
}
function base64UrlEncode(input: string): string {
return Buffer.from(input, "utf8").toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
function base64UrlDecode(value: string): string {
const pad = value.length % 4 === 0 ? "" : "=".repeat(4 - (value.length % 4));
return Buffer.from(value.replace(/-/g, "+").replace(/_/g, "/") + pad, "base64").toString("utf8");
}
function sign(body: string, secret: string): string {
return Buffer.from(createHmac("sha256", secret).update(body).digest()).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
}
/** Sign a fresh state token for the consent redirect. */
export function signCalendarOAuthState(
input: { tenantId: string; userId: string; tenantSlug: string },
options: { now?: () => number; secret?: string } = {},
): string {
const payload: CalendarOAuthStatePayload = {
tenantId: input.tenantId,
userId: input.userId,
tenantSlug: input.tenantSlug,
createdAt: options.now ? options.now() : Date.now(),
};
const body = base64UrlEncode(JSON.stringify({ v: PAYLOAD_VERSION, p: payload }));
return `${body}.${sign(body, getSecret(options.secret))}`;
}
/** Verify + decode a state token returned by Google. */
export function verifyCalendarOAuthState(state: string, options: { now?: () => number; secret?: string } = {}): VerifyStateResult {
const dot = state.lastIndexOf(".");
if (dot <= 0) {
return { ok: false, reason: "malformed" };
}
const body = state.slice(0, dot);
const sig = state.slice(dot + 1);
let secret: string;
try {
secret = getSecret(options.secret);
} catch {
return { ok: false, reason: "malformed" };
}
const expected = sign(body, secret);
const a = Buffer.from(sig);
const b = Buffer.from(expected);
if (a.length !== b.length || !timingSafeEqual(a, b)) {
return { ok: false, reason: "bad-signature" };
}
let decoded: { v: string; p: CalendarOAuthStatePayload };
try {
decoded = JSON.parse(base64UrlDecode(body)) as { v: string; p: CalendarOAuthStatePayload };
} catch {
return { ok: false, reason: "malformed" };
}
if (decoded.v !== PAYLOAD_VERSION || !decoded.p || typeof decoded.p.createdAt !== "number") {
return { ok: false, reason: "malformed" };
}
const now = options.now ? options.now() : Date.now();
if (now - decoded.p.createdAt > STATE_TTL_MS) {
return { ok: false, reason: "expired" };
}
return { ok: true, payload: decoded.p };
}
@@ -1,271 +0,0 @@
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import { t as i18nT } from "i18next";
import CodeTemplateForm from "../templates/components/CodeTemplate.Form";
import CodeTemplateDto from "../templates/dtos/CodeTemplate.Dto";
import CodeTemplateDtoCreate from "../templates/dtos/CodeTemplate.Dto.Create";
import CodeTemplateHelper from "../templates/helpers/CodeTemplate.Helper";
import CodeTemplateRoutesActivityApi from "../templates/routes/api/CodeTemplate.Routes.Activity.Api";
import CodeTemplateRoutesEditApi from "../templates/routes/api/CodeTemplate.Routes.Edit.Api";
import CodeTemplateRoutesIndexApi from "../templates/routes/api/CodeTemplate.Routes.Index.Api";
import CodeTemplateRoutesNewApi from "../templates/routes/api/CodeTemplate.Routes.New.Api";
import CodeTemplateRoutesShareApi from "../templates/routes/api/CodeTemplate.Routes.Share.Api";
import CodeTemplateRoutesTagsApi from "../templates/routes/api/CodeTemplate.Routes.Tags.Api";
import CodeTemplateRoutesActivityComponent from "../templates/routes/components/CodeTemplate.Routes.Activity.Component";
import CodeTemplateRoutesEditComponent from "../templates/routes/components/CodeTemplate.Routes.Edit.Component";
import CodeTemplateRoutesIndexComponent from "../templates/routes/components/CodeTemplate.Routes.Index.Component";
import CodeTemplateRoutesNewComponent from "../templates/routes/components/CodeTemplate.Routes.New.Component";
import CodeTemplateRoutesShareComponent from "../templates/routes/components/CodeTemplate.Routes.Share.Component";
import CodeTemplateRoutesTagsComponent from "../templates/routes/components/CodeTemplate.Routes.Tags.Component";
import CodeTemplateRoutesActivityView from "../templates/routes/views/CodeTemplate.Routes.Activity.View";
import CodeTemplateRoutesEditView from "../templates/routes/views/CodeTemplate.Routes.Edit.View";
import CodeTemplateRoutesIndexView from "../templates/routes/views/CodeTemplate.Routes.Index.View";
import CodeTemplateRoutesNewView from "../templates/routes/views/CodeTemplate.Routes.New.View";
import CodeTemplateRoutesShareView from "../templates/routes/views/CodeTemplate.Routes.Share.View";
import CodeTemplateRoutesTagsView from "../templates/routes/views/CodeTemplate.Routes.Tags.View";
import CodeTemplateModelSchemaPrisma from "../templates/schemas/CodeTemplate.Model.Schema.Prisma";
import CodeTemplateService from "../templates/services/CodeTemplate.Service";
import CodeGeneratorHelper from "../utils/CodeGeneratorHelper";
import Constants from "~/application/Constants";
export type CodeGeneratorOptions = {
entity: EntityWithDetails;
type: string;
moduleDirectory: string;
routesDirectory: string;
deleteFilesOnFinish: boolean;
};
export type CodeGeneratorFileDto = {
type: "module" | "route" | "model";
directory?: string;
file: string;
content: string;
description: string;
};
function getModuleFiles(options: CodeGeneratorOptions): CodeGeneratorFileDto[] {
const { entity } = options;
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const files: CodeGeneratorFileDto[] = [
{
type: "module",
directory: `dtos`,
file: `${capitalized}Dto.ts`,
content: CodeTemplateDto.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.dto.rowInterface"),
},
{
type: "module",
directory: `dtos`,
file: `${capitalized}CreateDto.ts`,
content: CodeTemplateDtoCreate.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.dto.createInput"),
},
{
type: "module",
directory: `components`,
file: `${capitalized}Form.tsx`,
content: CodeTemplateForm.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.components.form"),
},
{
type: "module",
directory: `helpers`,
file: `${capitalized}Helpers.ts`,
content: CodeTemplateHelper.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.helpers.formDataTransformers"),
},
{
type: "module",
directory: `services`,
file: `${capitalized}Service.ts`,
content: CodeTemplateService.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.services.crud"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.Index.Api.ts`,
content: CodeTemplateRoutesIndexApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.index"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.New.Api.ts`,
content: CodeTemplateRoutesNewApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.new"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.Edit.Api.ts`,
content: CodeTemplateRoutesEditApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.edit"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.Activity.Api.ts`,
content: CodeTemplateRoutesActivityApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.activity"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.Share.Api.ts`,
content: CodeTemplateRoutesShareApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.share"),
},
{
type: "module",
directory: `routes/api`,
file: `${capitalized}Routes.Tags.Api.ts`,
content: CodeTemplateRoutesTagsApi.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.api.tags"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.Index.View.tsx`,
content: CodeTemplateRoutesIndexView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.index"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.New.View.tsx`,
content: CodeTemplateRoutesNewView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.new"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.Edit.View.tsx`,
content: CodeTemplateRoutesEditView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.edit"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.Activity.View.tsx`,
content: CodeTemplateRoutesActivityView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.activity"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.Share.View.tsx`,
content: CodeTemplateRoutesShareView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.share"),
},
{
type: "module",
directory: `routes/views`,
file: `${capitalized}Routes.Tags.View.tsx`,
content: CodeTemplateRoutesTagsView.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.views.tags"),
},
];
if (options.type === "custom") {
files.unshift({
type: "model",
file: `schema.prisma`,
content: CodeTemplateModelSchemaPrisma.generate({ entity }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.schema.prisma"),
});
}
addTopComments(files, entity);
return files;
}
function getRouteFiles({ type, entity, moduleDirectory }: CodeGeneratorOptions) {
let moduleLocation = moduleDirectory.replace("./app", "");
if (moduleLocation.startsWith("/")) {
moduleLocation = moduleLocation.substring(1);
}
const files: CodeGeneratorFileDto[] = [
{
type: "route",
file: `index.tsx`,
content: CodeTemplateRoutesIndexComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.index"),
},
{
type: "route",
file: `new.tsx`,
content: CodeTemplateRoutesNewComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.new"),
},
{
type: "route",
file: `$id.tsx`,
content: CodeTemplateRoutesEditComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.edit"),
},
{
type: "route",
file: `activity.tsx`,
directory: "$id",
content: CodeTemplateRoutesActivityComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.activity"),
},
{
type: "route",
file: `share.tsx`,
directory: "$id",
content: CodeTemplateRoutesShareComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.share"),
},
{
type: "route",
file: `tags.tsx`,
directory: "$id",
content: CodeTemplateRoutesTagsComponent.generate({ entity, moduleLocation }),
description: i18nT("models.entity.codeGenerator.fileDescriptions.routeShells.tags"),
},
];
addTopComments(files, entity);
return files;
}
function addTopComments(files: CodeGeneratorFileDto[], entity: EntityWithDetails) {
const rawLabelWarnings = CodeGeneratorHelper.getRawLabelWarnings(entity);
files.forEach((file) => {
const comments: string[] = [];
comments.push(file.description);
comments.push(...rawLabelWarnings);
comments.push("Date: " + new Date().toISOString().slice(0, 10));
comments.push("Version: App v" + Constants.VERSION);
file.content = comments.map((comment) => `// ${comment}`).join("\n") + "\n\n" + file.content;
});
}
function moduleDirectoryOptions(entity: EntityWithDetails) {
let tests = `./apps/web/app/modules/codeGeneratorTests/` + entity.slug;
let app = `./apps/web/app/modules/` + entity.slug;
return [
{ name: tests, value: tests },
{ name: app, value: app },
];
}
function routeDirectoryOptions(entity: EntityWithDetails) {
let tests = `./apps/web/app/routes/admin/entities/code-generator/tests/` + entity.slug;
let app = `./apps/web/app/routes/app.$tenant/` + entity.slug;
return [
{ name: tests, value: tests },
{ name: app, value: app },
];
}
export default {
getModuleFiles,
getRouteFiles,
moduleDirectoryOptions,
routeDirectoryOptions,
};
@@ -1,78 +0,0 @@
import { describe, expect, it } from "vitest";
import ActivityApiTemplate from "./routes/api/CodeTemplate.Routes.Activity.Api";
import EditApiTemplate from "./routes/api/CodeTemplate.Routes.Edit.Api";
import ShareApiTemplate from "./routes/api/CodeTemplate.Routes.Share.Api";
import TagsApiTemplate from "./routes/api/CodeTemplate.Routes.Tags.Api";
import ServiceTemplate from "./services/CodeTemplate.Service";
import type { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
const entity = {
name: "tickets",
title: "Tickets",
titlePlural: "Tickets",
prefix: "TCK",
hasTasks: true,
properties: [],
} as unknown as EntityWithDetails;
describe("generated entity route tenant scope", () => {
it("generates edit actions through scoped services and validates task row ownership", () => {
const source = EditApiTemplate.generate({ entity });
expect(source).not.toContain('import { getRowById } from "~/utils/db/entities/rows.db.server"');
expect(source).toContain("const item = await TicketsService.get(params.id!, {");
expect(source).toContain("tenantId,");
expect(source).toContain("userId,");
expect(source).toContain("getRowTaskInRow({ id: taskId, rowId: item.row.id })");
expect(source).toContain("updateRowTaskInRow({ id: taskId, rowId: item.row.id }");
expect(source).toContain("deleteRowTaskInRow({ id: taskId, rowId: item.row.id })");
expect(source).toContain("if (!task)");
expect(source).not.toContain("getRowTask(taskId)");
expect(source).toContain("to: item.row.createdByUser");
expect(source).toContain("tenantId,");
expect(source.match(/if \(!rowPermissions\.canUpdate\)/g)).toHaveLength(3);
expect(source).toContain('return Response.json({ error: t("shared.unauthorized") }, { status: 403 });');
expect(source).not.toContain('Response.json({ error: t("shared.notFound"), status: 404 })');
expect(source).not.toContain('Response.json({ error: t("shared.unauthorized"), status: 404 })');
});
it("generates update services through RowsApi tenant and permission checks", () => {
const source = ServiceTemplate.generate({ entity });
expect(source).not.toContain("getRowById");
expect(source).toContain("const { item: row, rowPermissions } = await RowsApi.get(id, {");
expect(source).toContain("tenantId: session.tenantId");
expect(source).toContain("userId: session.userId");
expect(source).toContain("if (!row || !rowPermissions.canUpdate)");
});
it("generates activity comment mutations with row-scoped lookups", () => {
const source = ActivityApiTemplate.generate({ entity });
expect(source).toContain("tenantId,");
expect(source).toContain("getRowCommentInRow({ id: rowCommentId, rowId: rowData.item.id })");
expect(source).toContain("updateRowCommentInRow({ id: rowCommentId, rowId: rowData.item.id }");
expect(source).toContain('t("models.row.activity.errors.commentForbidden")');
expect(source).toContain('t("models.row.activity.errors.updateCommentForbidden")');
expect(source).toContain('t("models.row.activity.errors.deleteCommentForbidden")');
expect(source).toContain('t("notifications.messages.row.commented"');
expect(source).not.toContain("getRowComment(rowCommentId)");
expect(source).not.toContain("You don't have access");
expect(source).not.toContain("commented on");
});
it("generates missing-record responses with HTTP status init", () => {
const sources = [
EditApiTemplate.generate({ entity }),
TagsApiTemplate.generate({ entity }),
ShareApiTemplate.generate({ entity }),
ActivityApiTemplate.generate({ entity }),
];
for (const source of sources) {
expect(source).not.toContain('Response.json({ error: t("shared.notFound"), status: 404 })');
expect(source).not.toContain('Response.json({ error: t("shared.unauthorized"), status: 403 })');
}
});
});
@@ -1,114 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [];
imports.push(`import { useNavigation, useSubmit, Form } from "react-router";
import { useTranslation } from "react-i18next";
import { useRef } from "react";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import InputGroup from "~/components/ui/forms/InputGroup";
import ActionResultModal from "~/components/ui/modals/ActionResultModal";
import ConfirmModal, { RefConfirmModal } from "~/components/ui/modals/ConfirmModal";
import { useRootData } from "~/utils/data/useRootData";`);
imports.push(`import { ${capitalized}Dto } from "../dtos/${capitalized}Dto";`);
let template = `
export default function ${capitalized}Form({
item,
actionData,
isUpdating,
isCreating,
canUpdate,
canDelete,
onCancel,
}: {
item?: ${capitalized}Dto;
actionData: { success?: string; error?: string } | undefined;
isUpdating?: boolean;
isCreating?: boolean;
canUpdate?: boolean;
canDelete?: boolean;
onCancel?: () => void;
}) {
const { t } = useTranslation();
const navigation = useNavigation();
const submit = useSubmit();
const rootData = useRootData();
const confirmDelete = useRef<RefConfirmModal>(null);
function onDelete() {
confirmDelete.current?.show(t("shared.confirmDelete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
}
function onDeleteConfirmed() {
const form = new FormData();
form.set("action", "delete");
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
submit(form, {
method: "post",
});
}
function isDisabled() {
if (isUpdating && !canUpdate) {
return true;
}
if (!isUpdating && !isCreating) {
return true;
}
}
return (
<Form key={!isDisabled() ? "enabled" : "disabled"} method="post" className="space-y-4">
{item ? <input name="action" value="edit" hidden readOnly /> : <input name="action" value="create" hidden readOnly />}
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<InputGroup title={t("shared.details")}>
<div className="space-y-2">
{PROPERTIES_UI_CONTROLS}
</div>
</InputGroup>
{(isCreating || (isUpdating && canUpdate)) && (
<div className="flex justify-between space-x-2">
<div>
{canDelete && (
<ButtonSecondary disabled={navigation.state !== "idle"} destructive onClick={onDelete}>
{t("shared.delete")}
</ButtonSecondary>
)}
</div>
<div className="flex space-x-2">
{onCancel && <ButtonSecondary onClick={onCancel}>{t("shared.cancel")}</ButtonSecondary>}
<ButtonPrimary disabled={navigation.state !== "idle"} type="submit">
{item ? t("shared.save") : t("shared.create")}
</ButtonPrimary>
</div>
</div>
)}
<ConfirmModal ref={confirmDelete} onYes={onDeleteConfirmed} />
<ActionResultModal actionData={actionData} showSuccess={false} />
</Form>
);
}`;
const uiFormControls: string[] = [];
entity.properties
.filter((f) => !f.isDefault)
.forEach((property, index) => {
CodeGeneratorPropertiesHelper.uiForm({ code: uiFormControls, imports, property, index });
});
template = template.replace("{PROPERTIES_UI_CONTROLS}", uiFormControls.join("\n "));
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [];
const code: string[] = [];
code.push("");
code.push(`export type ${capitalized}CreateDto = {`);
entity.properties
.filter((f) => !f.isDefault && f.showInCreate && CodeGeneratorPropertiesHelper.isWritableProperty(f))
.forEach((property) => {
CodeGeneratorPropertiesHelper.type({ code, imports, property });
});
code.push("};");
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, ...code].join("\n");
}
export default {
generate,
};
@@ -1,29 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [];
const code: string[] = [];
imports.push(`import { RowWithDetails } from "~/utils/db/entities/rows.db.server";`);
code.push("");
code.push(`export type ${capitalized}Dto = {`);
code.push(` row: RowWithDetails;`);
code.push(` prefix: string;`);
code.push(` // Custom Row Properties:`);
entity.properties
.filter((f) => !f.isDefault)
.forEach((property) => {
CodeGeneratorPropertiesHelper.type({ code, imports, property });
});
code.push("};");
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, ...code].join("\n");
}
export default {
generate,
};
@@ -1,54 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [];
imports.push(`import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import { RowWithDetails } from "~/utils/db/entities/rows.db.server";
import FormHelper from "~/utils/helpers/FormHelper";
import RowValueHelper from "~/utils/helpers/RowValueHelper";`);
imports.push(`import { ${capitalized}Dto } from "../dtos/${capitalized}Dto";`);
// if (entity.properties.some((p) => p.type === PropertyType.MEDIA)) {
// imports.push(`import { MediaDto } from "~/application/dtos/entities/MediaDto";`);
// }
let template = `
function rowToDto({ entity, row }: { entity: EntityWithDetails; row: RowWithDetails }): ${capitalized}Dto {
return {
row,
prefix: entity.prefix,
{PROPERTIES_ROW_TO_DTO}
};
}
function formToDto(form: FormData): Partial<${capitalized}Dto> {
return {
{PROPERTIES_FORM_TO_DTO}
};
}
export default {
rowToDto,
formToDto,
};`;
const rowToDto: string[] = [];
const formToDto: string[] = [];
entity.properties
.filter((f) => !f.isDefault)
.forEach((property, index) => {
CodeGeneratorPropertiesHelper.rowToDto({ code: rowToDto, property });
CodeGeneratorPropertiesHelper.formToDto({ code: formToDto, property });
});
template = template.replace("{PROPERTIES_ROW_TO_DTO}", rowToDto.join("\n "));
template = template.replace("{PROPERTIES_FORM_TO_DTO}", formToDto.join("\n "));
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,126 +0,0 @@
/* eslint-disable no-template-curly-in-string */
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
let template = `import { LoaderFunctionArgs, ActionFunction } from "react-router";
import { RowPermissionsDto } from "~/application/dtos/entities/RowPermissionsDto";
import { getTranslations } from "~/locale/i18next.server";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import { RowCommentsApi } from "~/utils/api/.server/RowCommentsApi";
import { RowsApi } from "~/utils/api/.server/RowsApi";
import { getEntityByName } from "~/utils/db/entities/entities.db.server";
import { setRowCommentReaction } from "~/utils/db/entities/rowCommentReaction.db.server";
import { getRowCommentInRow, updateRowCommentInRow } from "~/utils/db/entities/rowComments.db.server";
import { LogWithDetails, getRowLogsById } from "~/utils/db/logs.db.server";
import { getUser } from "~/utils/db/users.db.server";
import RowHelper from "~/utils/helpers/RowHelper";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { requireAuth, validateCSRFToken } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
export namespace ${capitalized}RoutesActivityApi {
export type LoaderData = {
metatags: MetaTagsDto;
logs: LogWithDetails[];
permissions: RowPermissionsDto;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
const { t } = await getTranslations(request);
const entity = await getEntityByName({ tenantId, name: "${name}" });
const rowData = await RowsApi.get(params.id!, { entity, tenantId, userId });
const data: LoaderData = {
metatags: [{ title: t("shared.activity") + " | " + process.env.APP_NAME }],
logs: await getRowLogsById(rowData.item.id),
permissions: rowData.rowPermissions,
};
return data;
};
export type ActionData = {
success?: string;
error?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const { userId } = await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const user = await getUser(userId);
const entity = await getEntityByName({ tenantId, name: "${name}" });
const rowData = await RowsApi.get(params.id!, { entity, tenantId, userId });
if (action === "comment") {
let comment = form.get("comment")?.toString();
if (!comment) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
if (!rowData.rowPermissions.canComment) {
return Response.json({ error: t("models.row.activity.errors.commentForbidden") }, { status: 403 });
}
await RowCommentsApi.create(params.id!, {
comment,
tenantId,
userId,
});
const item = rowData.item;
if (item!.createdByUser) {
await NotificationService.send({
channel: "my-rows",
to: item!.createdByUser,
tenantId,
notification: {
from: { user },
message: t("notifications.messages.row.commented", { email: user?.email, row: RowHelper.getRowFolio(entity, item!) }),
// action: {
// title: t("shared.view"),
// url: "",
// },
},
});
}
return Response.json({ newComment: comment });
} else if (action === "comment-reaction") {
const rowCommentId = form.get("comment-id")?.toString();
const reaction = form.get("reaction")?.toString();
if (!rowCommentId || !reaction) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
const rowComment = await getRowCommentInRow({ id: rowCommentId, rowId: rowData.item.id });
if (!rowComment || !rowData.rowPermissions.canComment) {
return Response.json({ error: t("models.row.activity.errors.updateCommentForbidden") }, { status: 403 });
}
await setRowCommentReaction({
createdByUserId: userId,
rowCommentId,
reaction,
});
return Response.json({ newCommentReaction: reaction });
} else if (action === "comment-delete") {
const rowCommentId = form.get("comment-id")?.toString();
if (!rowCommentId) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
const rowComment = await getRowCommentInRow({ id: rowCommentId, rowId: rowData.item.id });
if (!rowComment || (!rowData.rowPermissions.canDelete && rowComment.createdByUserId !== userId)) {
return Response.json({ error: t("models.row.activity.errors.deleteCommentForbidden") }, { status: 403 });
}
await updateRowCommentInRow({ id: rowCommentId, rowId: rowData.item.id }, { isDeleted: true });
return Response.json({ deletedComment: rowCommentId });
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}
`;
return template;
}
export default {
generate,
};
@@ -1,225 +0,0 @@
/* eslint-disable no-template-curly-in-string */
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "~/modules/codeGenerator/utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [
`import { LoaderFunctionArgs, ActionFunction, redirect } from "react-router";
import { RowPermissionsDto } from "~/application/dtos/entities/RowPermissionsDto";
import { getTranslations } from "~/locale/i18next.server";
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
import UrlUtils from "~/utils/app/UrlUtils";
import { getEntityByName } from "~/utils/db/entities/entities.db.server";
import { getUser } from "~/utils/db/users.db.server";
import { getUserRowPermission } from "~/utils/helpers/.server/PermissionsService";
import RowHelper from "~/utils/helpers/RowHelper";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";`,
];
if (entity.hasTasks) {
imports.push(
`import { RowTaskWithDetails, getRowTasks, createRowTask, getRowTaskInRow, updateRowTaskInRow, deleteRowTaskInRow } from "~/utils/db/entities/rowTasks.db.server";`
);
}
imports.push(`import { ${capitalized}Dto } from "../../dtos/${capitalized}Dto";
import ${capitalized}Helpers from "../../helpers/${capitalized}Helpers";
import { ${capitalized}Service } from "../../services/${capitalized}Service";`);
let template = `
export namespace ${capitalized}RoutesEditApi {
export type LoaderData = {
metatags: MetaTagsDto;
item: ${capitalized}Dto;
permissions: RowPermissionsDto;
{TASKS_LOADER_INTERFACE}
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
const item = await ${capitalized}Service.get(params.id!, {
tenantId,
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
const permissions = await getUserRowPermission(item.row, tenantId, userId);
if (!permissions.canRead) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const data: LoaderData = {
metatags: [{ title: item.prefix + "-" + String(item.row.folio ?? 0).padStart(4, "0") + " | " + process.env.APP_NAME }],
item,
permissions,
{TASKS_LOADER_DATA}
};
return data;
};
export type ActionData = {
success?: string;
error?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const user = await getUser(userId);
const entity = await getEntityByName({ tenantId, name: "${name}" });
const item = await ${capitalized}Service.get(params.id!, {
tenantId,
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
if (action === "edit") {
try {
const { {PROPERTIES_UPDATE_NAMES} } = ${capitalized}Helpers.formToDto(form);
await ${capitalized}Service.update(
params.id!,
{ {PROPERTIES_UPDATE_NAMES} },
{ tenantId, userId }
);
if (item.row.createdByUser) {
await NotificationService.send({
channel: "my-rows",
to: item.row.createdByUser,
tenantId,
notification: {
from: { user },
message: ${"`${user?.email} updated ${RowHelper.getRowFolio(entity, item.row)}`"},
// action: {
// title: t("shared.view"),
// url: "",
// },
},
});
}
return Response.json({ success: t("shared.updated") });
} catch (error: any) {
return Response.json({ error: error.message }, { status: 400 });
}
} else if (action === "delete") {
try {
await ${capitalized}Service.del(params.id!, {
tenantId,
userId,
});
if (item.row.createdByUser) {
await NotificationService.send({
channel: "my-rows",
to: item.row.createdByUser,
tenantId,
notification: {
from: { user },
message: ${"`${user?.email} deleted ${RowHelper.getRowFolio(entity, item.row)}`"},
},
});
}
return redirect(UrlUtils.getParentRoute(new URL(request.url).pathname));
} catch (error: any) {
return Response.json({ error: error.message }, { status: 400 });
}
} {TASKS_ACTIONS}
else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}`;
const propertiesUpdateNames: string[] = [];
entity.properties
.filter((f) => f.showInCreate && !f.isDefault && CodeGeneratorPropertiesHelper.isWritableProperty(f))
.forEach((property) => {
propertiesUpdateNames.push(property.name);
});
template = template.split("{PROPERTIES_UPDATE_NAMES}").join(propertiesUpdateNames.join(", "));
const tasksLoaderInterface: string[] = [];
const tasksLoaderData: string[] = [];
if (entity.hasTasks) {
tasksLoaderInterface.push("tasks: RowTaskWithDetails[]");
tasksLoaderData.push(`tasks: await getRowTasks(params.id!),`);
}
template = template.split("{TASKS_LOADER_INTERFACE}").join(tasksLoaderInterface.join("\n "));
template = template.split("{TASKS_LOADER_DATA}").join(tasksLoaderData.join("\n "));
let tasksActions = "";
if (entity.hasTasks) {
tasksActions = `else if (action === "task-new") {
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const taskTitle = form.get("task-title")?.toString();
if (!taskTitle) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
const task = await createRowTask({
createdByUserId: userId,
rowId: item.row.id,
title: taskTitle,
});
return Response.json({ newTask: task });
} else if (action === "task-complete-toggle") {
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const taskId = form.get("task-id")?.toString() ?? "";
const task = await getRowTaskInRow({ id: taskId, rowId: item.row.id });
if (!task) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
if (task) {
if (task.completed) {
await updateRowTaskInRow({ id: taskId, rowId: item.row.id }, {
completed: false,
completedAt: null,
completedByUserId: null,
});
} else {
await updateRowTaskInRow({ id: taskId, rowId: item.row.id }, {
completed: true,
completedAt: new Date(),
completedByUserId: userId,
});
}
}
return Response.json({ completedTask: taskId });
} else if (action === "task-delete") {
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const taskId = form.get("task-id")?.toString() ?? "";
const task = await getRowTaskInRow({ id: taskId, rowId: item.row.id });
if (!task) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
if (task) {
await deleteRowTaskInRow({ id: taskId, rowId: item.row.id });
}
return Response.json({ deletedTask: taskId });
}`;
}
template = template.split("{TASKS_ACTIONS}").join(tasksActions);
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,62 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
const titleExpression = CodeGeneratorHelper.getEntityTitleExpression(entity);
const imports: string[] = [];
imports.push(`import { LoaderFunctionArgs } from "react-router";
import { FilterablePropertyDto } from "~/application/dtos/data/FilterablePropertyDto";
import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { getTranslations } from "~/locale/i18next.server";
import { getEntityByName } from "~/utils/db/entities/entities.db.server";
import EntityHelper from "~/utils/helpers/EntityHelper";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { requireAuth } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";`);
imports.push(`import { ${capitalized}Dto } from "../../dtos/${capitalized}Dto";
import { ${capitalized}Service } from "../../services/${capitalized}Service";`);
let template = `
export namespace ${capitalized}RoutesIndexApi {
export type LoaderData = {
metatags: MetaTagsDto;
items: ${capitalized}Dto[];
pagination: PaginationDto;
filterableProperties?: FilterablePropertyDto[];
overviewItem?: ${capitalized}Dto | null;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
const urlSearchParams = new URL(request.url).searchParams;
const { items, pagination } = await ${capitalized}Service.getAll({
tenantId,
userId,
urlSearchParams,
});
const data: LoaderData = {
metatags: [{ title: ${titleExpression} + " | " + process.env.APP_NAME }],
items,
pagination,
filterableProperties: EntityHelper.getFilters({ t, entity: await getEntityByName({ tenantId, name: "${name}" }) }),
};
const overviewId = urlSearchParams.get("overview") ?? "";
if (overviewId) {
data.overviewItem = await ${capitalized}Service.get(overviewId, {
tenantId,
userId,
});
}
return data;
};
}`;
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,88 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "~/modules/codeGenerator/utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
const titleExpression = CodeGeneratorHelper.getEntityTitleExpression(entity);
const imports: string[] = [];
imports.push(`import { LoaderFunctionArgs, ActionFunction, redirect } from "react-router";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { getTranslations } from "~/locale/i18next.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { requireAuth } from "~/utils/loaders.middleware";
import { getPlanFeatureUsage } from "~/utils/services/.server/subscriptionService";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";`);
imports.push(`import ${capitalized}Helpers from "../../helpers/${capitalized}Helpers";
import { ${capitalized}Service } from "../../services/${capitalized}Service";`);
let template = `
export namespace ${capitalized}RoutesNewApi {
export type LoaderData = {
metatags: MetaTagsDto;
featureUsage: PlanFeatureUsageDto | undefined;
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
const data: LoaderData = {
metatags: [{ title: t("shared.create") + " " + ${titleExpression} + " | " + process.env.APP_NAME }],
featureUsage: tenantId ? await getPlanFeatureUsage(tenantId, "${name}") : undefined,
};
return data;
};
export type ActionData = {
success?: string;
error?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const { userId } = await requireAuth({ request, params });
const tenantId = await getTenantIdOrNull({ request, params });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString();
if (action === "create") {
try {
const { {PROPERTIES_CREATE_NAMES} } = ${capitalized}Helpers.formToDto(form);
{PROPERTIES_CREATE_VALIDATION_REQUIRED}
const item = await ${capitalized}Service.create(
{ {PROPERTIES_CREATE_NAMES} },
{ userId, tenantId }
);
return redirect(UrlUtils.getParentRoute(new URL(request.url).pathname) + "/" + item.row.id);
} catch (error: any) {
return Response.json({ error: error.message }, { status: 400 });
}
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}`;
const propertiesCreateNames: string[] = [];
const propertiesCreateValidationRequired: string[] = [];
entity.properties
.filter((f) => !f.isDefault && f.showInCreate && CodeGeneratorPropertiesHelper.isWritableProperty(f))
.forEach((property) => {
propertiesCreateNames.push(property.name);
if (property.isRequired) {
propertiesCreateValidationRequired.push(
`if (${property.name} === undefined) throw new Error(${CodeGeneratorHelper.getPropertyTitleExpression(property)} + " is required");`
);
}
});
template = template.split("{PROPERTIES_CREATE_NAMES}").join(propertiesCreateNames.join(", "));
template = template.split("{PROPERTIES_CREATE_VALIDATION_REQUIRED}").join(propertiesCreateValidationRequired.join("\n "));
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,123 +0,0 @@
/* eslint-disable no-template-curly-in-string */
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
let template = `import { Tenant } from "@toolctrl/db/prisma-browser";
import { LoaderFunctionArgs, ActionFunction } from "react-router";
import { RowAccess } from "~/application/enums/entities/RowAccess";
import { getTranslations } from "~/locale/i18next.server";
import { RowPermissionsApi } from "~/utils/api/.server/RowPermissionsApi";
import { getUserRowPermission } from "~/utils/helpers/.server/PermissionsService";
import { getTenant, adminGetAllTenants } from "~/utils/db/tenants.db.server";
import { UserWithDetails, getUsersByTenant } from "~/utils/db/users.db.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
import { ${capitalized}Dto } from "../../dtos/${capitalized}Dto";
import { ${capitalized}Service } from "../../services/${capitalized}Service";
export namespace ${capitalized}RoutesShareApi {
export type LoaderData = {
metatags: MetaTagsDto;
item: ${capitalized}Dto;
tenants: Tenant[];
users: UserWithDetails[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
const item = await ${capitalized}Service.get(params.id!, {
tenantId,
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
let tenants: Tenant[] = [];
if (tenantId) {
tenants.push((await getTenant(tenantId))!);
} else {
tenants = await adminGetAllTenants();
}
const data: LoaderData = {
metatags: [{ title: t("shared.share") + " | " + process.env.APP_NAME }],
item,
tenants,
users: (await getUsersByTenant(tenantId)).filter((f) => f.id !== userId),
};
return data;
};
export type ActionData = {
success?: string;
error?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const { userId } = await requireAuth({ request, params });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const tenantId = await getTenantIdOrNull({ request, params });
const item = await ${capitalized}Service.get(params.id!, {
tenantId,
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
if (action === "share") {
const allowedShareTypes = ["tenant", "user", "role", "group"] as const;
type ShareType = (typeof allowedShareTypes)[number];
const maybeType = form.get("type")?.toString();
const type = allowedShareTypes.includes(maybeType as ShareType) ? (maybeType as ShareType) : null;
if (!type) {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
const id = form.get("id")?.toString() ?? "";
const access = form.get("access")?.toString() as RowAccess;
try {
await RowPermissionsApi.share(item.row, {
type,
id,
access,
}, { currentTenantId: tenantId });
return Response.json({ success: t("shared.saved") });
} catch (error: any) {
return Response.json({ error: error.message }, { status: 400 });
}
} else if (action === "set-access") {
const id = form.get("id")?.toString() ?? "";
const access = form.get("access")?.toString() as RowAccess;
await RowPermissionsApi.setAccessForRow(item.row.id, id, access);
return Response.json({ success: t("shared.saved") });
} else if (action === "remove") {
const id = form.get("id")?.toString() ?? "";
await RowPermissionsApi.delForRow(item.row.id, id);
return Response.json({ success: t("shared.deleted") });
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}
`;
return template;
}
export default {
generate,
};
@@ -1,145 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
return `import { EntityTag } from "@toolctrl/db/prisma-browser";
import { LoaderFunctionArgs, ActionFunction } from "react-router";
import { Colors } from "~/application/enums/shared/Colors";
import { getTranslations } from "~/locale/i18next.server";
import { getEntityByName } from "~/utils/db/entities/entities.db.server";
import { getEntityTags, getEntityTag, createEntityTag, updateEntityTag, deleteEntityTag, getEntityTagById } from "~/utils/db/entities/entityTags.db.server";
import { getRowTag, createRowTag, deleteRowTags } from "~/utils/db/entities/rowTags.db.server";
import { getUserRowPermission } from "~/utils/helpers/.server/PermissionsService";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdOrNull } from "~/utils/services/.server/urlService";
import { validateCSRFToken } from "~/utils/session.server";
import { MetaTagsDto } from "~/application/dtos/seo/MetaTagsDto";
import { ${capitalized}Dto } from "../../dtos/${capitalized}Dto";
import { ${capitalized}Service } from "../../services/${capitalized}Service";
export namespace ${capitalized}RoutesTagsApi {
export type LoaderData = {
metatags: MetaTagsDto;
item: ${capitalized}Dto;
tags: EntityTag[];
};
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
const entity = await getEntityByName({ tenantId, name: "${name}" });
const item = await ${capitalized}Service.get(params.id!, {
tenantId,
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
const data: LoaderData = {
metatags: [{ title: t("models.row.tags") + " | " + process.env.APP_NAME }],
item,
tags: await getEntityTags(entity.id),
};
return data;
};
export type ActionData = {
success?: string;
error?: string;
};
export const action: ActionFunction = async ({ request, params }) => {
const { t } = await getTranslations(request);
const tenantId = await getTenantIdOrNull({ request, params });
const { userId } = await requireAuth({ request, params });
await validateCSRFToken(request);
const form = await request.formData();
const action = form.get("action")?.toString() ?? "";
const entity = await getEntityByName({ tenantId, name: "${name}" });
const item = await ${capitalized}Service.get(params.id!, {
tenantId: await getTenantIdOrNull({ request, params }),
userId,
});
if (!item) {
return Response.json({ error: t("shared.notFound") }, { status: 404 });
}
const rowPermissions = await getUserRowPermission(item.row, tenantId, userId);
if (!rowPermissions.canUpdate) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const canMutateTagCatalog = !tenantId;
if (action === "new-tag") {
const value = form.get("tag-name")?.toString() ?? "";
const color = Number(form.get("tag-color") ?? Colors.INDIGO);
let tag = await getEntityTag(entity.id, value);
if (!tag) {
if (!canMutateTagCatalog) {
return Response.json({ error: t("shared.notFound") }, { status: 400 });
}
tag = await createEntityTag({
entityId: entity.id,
value,
color,
});
}
const existingTag = await getRowTag(params.id!, value);
if (tag && !existingTag) {
await createRowTag({
rowId: params.id!,
tagId: tag.id,
});
}
return Response.json({});
} else if (action === "edit-tag") {
if (!canMutateTagCatalog) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const id = form.get("tag-id")?.toString() ?? "";
const value = form.get("tag-name")?.toString() ?? "";
const color = Number(form.get("tag-color"));
const tag = await getEntityTagById(id, entity.id);
if (!tag) {
return Response.json({ error: t("shared.notFound") }, { status: 400 });
}
await updateEntityTag({ id: tag.id, entityId: entity.id }, {
value,
color,
});
return Response.json({});
} else if (action === "set-tag") {
const id = form.get("tag-id")?.toString() ?? "";
const tagAction = form.get("tag-action")?.toString() ?? "";
const tag = await getEntityTagById(id, entity.id);
if (!tag) {
return Response.json({ error: t("shared.notFound") }, { status: 400 });
}
if (tagAction === "add") {
await createRowTag({
rowId: params.id!,
tagId: tag.id,
});
} else {
await deleteRowTags(params.id!, tag.id);
}
return Response.json({});
} else if (action === "delete-tag") {
if (!canMutateTagCatalog) {
return Response.json({ error: t("shared.unauthorized") }, { status: 403 });
}
const id = form.get("tag-id")?.toString() ?? "";
const tag = await getEntityTagById(id, entity.id);
if (tag) {
await deleteEntityTag({ id: tag.id, entityId: entity.id });
}
return Response.json({});
} else {
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
}
};
}
`;
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs, ActionFunction } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesActivityApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.Activity.Api";
import ${capitalized}RoutesActivityView from "~/${moduleLocation}/routes/views/${capitalized}Routes.Activity.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesActivityApi.loader(args);
export const action: ActionFunction = (args) => ${capitalized}RoutesActivityApi.action(args);
export default () => <${capitalized}RoutesActivityView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs, ActionFunction } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesEditApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.Edit.Api";
import ${capitalized}RoutesEditView from "~/${moduleLocation}/routes/views/${capitalized}Routes.Edit.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesEditApi.loader(args);
export const action: ActionFunction = (args) => ${capitalized}RoutesEditApi.action(args);
export default () => <${capitalized}RoutesEditView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,24 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesIndexApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.Index.Api";
import ${capitalized}RoutesIndexView from "~/${moduleLocation}/routes/views/${capitalized}Routes.Index.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesIndexApi.loader(args);
export default () => <${capitalized}RoutesIndexView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs, ActionFunction } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesNewApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.New.Api";
import ${capitalized}RoutesNewView from "~/${moduleLocation}/routes/views/${capitalized}Routes.New.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesNewApi.loader(args);
export const action: ActionFunction = (args) => ${capitalized}RoutesNewApi.action(args);
export default () => <${capitalized}RoutesNewView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs, ActionFunction } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesShareApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.Share.Api";
import ${capitalized}RoutesShareView from "~/${moduleLocation}/routes/views/${capitalized}Routes.Share.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesShareApi.loader(args);
export const action: ActionFunction = (args) => ${capitalized}RoutesShareApi.action(args);
export default () => <${capitalized}RoutesShareView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,25 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity, moduleLocation }: { entity: EntityWithDetails; moduleLocation: string }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import { MetaFunction, LoaderFunctionArgs, ActionFunction } from "react-router";
import ServerError from "~/components/ui/errors/ServerError";
import { ${capitalized}RoutesTagsApi } from "~/${moduleLocation}/routes/api/${capitalized}Routes.Tags.Api";
import ${capitalized}RoutesTagsView from "~/${moduleLocation}/routes/views/${capitalized}Routes.Tags.View";
export const meta: MetaFunction<typeof loader> = ({ data }) => (data && "metatags" in data ? data.metatags : []);
export const loader = (args: LoaderFunctionArgs) => ${capitalized}RoutesTagsApi.loader(args);
export const action: ActionFunction = (args) => ${capitalized}RoutesTagsApi.action(args);
export default () => <${capitalized}RoutesTagsView />;
export function ErrorBoundary() {
return <ServerError />;
}
`;
}
export default {
generate,
};
@@ -1,19 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import RowActivity from "~/components/entities/rows/RowActivity";
import { ${capitalized}RoutesActivityApi } from "../api/${capitalized}Routes.Activity.Api";
import { useLoaderData } from "react-router";
export default function ${capitalized}RoutesActivityView() {
const data = useLoaderData<${capitalized}RoutesActivityApi.LoaderData>();
return <RowActivity items={data.logs} withTitle={false} hasActivity={true} hasComments={data.permissions.canComment} />;
}
`;
}
export default {
generate,
};
@@ -1,149 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const titleExpression = CodeGeneratorHelper.getEntityTitleExpression(entity);
const pluralExpression = CodeGeneratorHelper.getEntityPluralExpression(entity);
const imports: string[] = [
`import { useActionData, useLoaderData, useOutlet, useNavigate, useLocation, useSearchParams, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import RowSettingsTabs from "~/components/entities/rows/RowSettingsTabs";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import EditPageLayout from "~/components/ui/layouts/EditPageLayout";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import UrlUtils from "~/utils/app/UrlUtils";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import ShareIcon from "~/components/ui/icons/ShareIcon";
import ClockIcon from "~/components/ui/icons/ClockIcon";
import PencilIcon from "~/components/ui/icons/PencilEmptyIcon";`,
];
if (entity.hasTasks) {
imports.push(`import RowTasks from "~/components/entities/rows/RowTasks";`);
}
if (entity.hasTags) {
imports.push(`import RowTags from "~/components/entities/rows/RowTags";`);
}
imports.push(`import ${capitalized}Form from "../../components/${capitalized}Form";
import { ${capitalized}RoutesEditApi } from "../api/${capitalized}Routes.Edit.Api";`);
let template = `
export default function ${capitalized}RoutesEditView() {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
const data = useLoaderData<${capitalized}RoutesEditApi.LoaderData>();
const actionData = useActionData<${capitalized}RoutesEditApi.ActionData>();
const outlet = useOutlet();
const navigate = useNavigate();
const location = useLocation();
const submit = useSubmit();
const [searchParams, setSearchParams] = useSearchParams();
function canUpdate() {
return data.permissions.canUpdate;
}
function canDelete() {
return data.permissions.canDelete;
}
return (
<EditPageLayout
title={t("shared.edit") + " " + ${titleExpression}}
menu={[
{
title: ${pluralExpression},
routePath: UrlUtils.getParentRoute(location?.pathname),
},
{
title: t("shared.edit"),
routePath: "",
},
]}
>
<div className="relative items-center justify-between space-y-2 border-b border-border pb-4 sm:flex sm:space-y-0">
<div className="flex items-center space-x-2">
<div className="text-xl font-bold uppercase">
{data.item.prefix}-{String(data.item.row.folio ?? 0).padStart(4, "0")}
</div>
</div>
<div className="flex space-x-2">
<ButtonSecondary to="activity">
<ClockIcon className="h-4 w-4 text-muted-foreground" />
</ButtonSecondary>
{data.permissions.isOwner && (
<ButtonSecondary to="share">
<ShareIcon className="h-4 w-4 text-muted-foreground" />
</ButtonSecondary>
)}
{canUpdate() && (
<ButtonSecondary
onClick={() => {
if (searchParams.get("view") === "edit") {
setSearchParams({});
} else {
searchParams.set("view", "edit");
setSearchParams(searchParams);
}
}}
>
<PencilIcon className="h-4 w-4 text-muted-foreground" />
</ButtonSecondary>
)}
</div>
</div>
{!data.item ? (
<div>{t("shared.loading")}...</div>
) : (
<div className="mx-auto space-y-2 pt-2 lg:flex lg:space-x-4 lg:space-y-0 pb-10">
<div className="space-y-4 lg:w-4/6">
<${capitalized}Form
item={data.item}
actionData={actionData}
canUpdate={canUpdate()}
canDelete={canDelete()}
isUpdating={searchParams.get("view") === "edit"}
onCancel={() => {
setSearchParams({});
}}
/>
</div>
<div className="space-y-4 lg:w-2/6">
${entity.hasTags ? `<RowTags items={data.item.row.tags} onSetTagsRoute={canUpdate() ? "tags" : undefined} />` : ""}
${entity.hasTasks ? `<RowTasks items={data.tasks} />` : ""}
</div>
</div>
)}
<SlideOverWideEmpty
withTitle={false}
withClose={false}
title={""}
open={!!outlet}
onClose={() => {
navigate(".", { replace: true });
}}
className="sm:max-w-sm"
overflowYScroll={true}
>
<div className="-mx-1 -mt-3">
<div className="space-y-4">
<RowSettingsTabs canUpdate={canUpdate()} isOwner={data.permissions.isOwner} hasTags={${entity.hasTags ? "true" : "false"}} />
{outlet}
</div>
</div>
</SlideOverWideEmpty>
</EditPageLayout>
);
}`;
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,134 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import CodeGeneratorPropertiesHelper from "~/modules/codeGenerator/utils/CodeGeneratorPropertiesHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const titleExpression = CodeGeneratorHelper.getEntityTitleExpression(entity);
const pluralExpression = CodeGeneratorHelper.getEntityPluralExpression(entity);
const imports: string[] = [];
imports.push(`import { useActionData, useLoaderData, useSearchParams, Link } from "react-router";
import { useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import RowCreatedByCell from "~/components/entities/rows/cells/RowCreatedByCell";
import RowFolioCell from "~/components/entities/rows/cells/RowFolioCell";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import DateCell from "~/components/ui/dates/DateCell";
import ExternalLinkEmptyIcon from "~/components/ui/icons/ExternalLinkEmptyIcon";
import InputFilters from "~/components/ui/input/InputFilters";
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
import SlideOverWideEmpty from "~/components/ui/slideOvers/SlideOverWideEmpty";
import TableSimple from "~/components/ui/tables/TableSimple";`);
imports.push(`import ${capitalized}Form from "../../components/${capitalized}Form";
import { ${capitalized}Dto } from "../../dtos/${capitalized}Dto";
import { ${capitalized}RoutesIndexApi } from "../api/${capitalized}Routes.Index.Api";`);
let template = `
export default function ${capitalized}RoutesIndexView() {
const { t } = useTranslation();
const data = useLoaderData<${capitalized}RoutesIndexApi.LoaderData>();
const actionData = useActionData<{ error?: string; success?: string }>();
const [searchParams, setSearchParams] = useSearchParams();
const [overviewItem, setOverviewItem] = useState<${capitalized}Dto>();
useEffect(() => {
setOverviewItem(data.overviewItem ?? undefined);
}, [data.overviewItem]);
return (
<IndexPageLayout
title={${pluralExpression}}
buttons={
<>
{!!data.filterableProperties?.length && <InputFilters filters={data.filterableProperties} />}
<ButtonPrimary to="new">{t("shared.new")}</ButtonPrimary>
</>
}
>
<TableSimple
items={data.items}
pagination={data.pagination}
actions={[
{
title: t("shared.overview"),
onClick: (_, item) => {
searchParams.set("overview", item.row.id);
setSearchParams(searchParams);
},
},
{
title: t("shared.edit"),
onClickRoute: (_, item) => item.row.id,
},
]}
headers={[
{
name: "folio",
title: t("models.row.folio"),
value: (item) => <RowFolioCell prefix={item.prefix} folio={item.row.folio} href={item.row.id} />,
},
{PROPERTIES_UI_CELLS}
{
name: "createdAt",
title: t("shared.createdAt"),
value: (item) => <DateCell date={item.row.createdAt} />,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
},
{
name: "createdByUser",
title: t("shared.createdBy"),
value: (item) => <RowCreatedByCell user={item.row.createdByUser} apiKey={item.row.createdByApiKey} />,
className: "text-muted-foreground text-xs",
breakpoint: "sm",
},
]}
/>
<SlideOverWideEmpty
withTitle={false}
withClose={false}
title={${titleExpression}}
open={!!searchParams.get("overview")?.toString()}
onClose={() => {
searchParams.delete("overview");
setSearchParams(searchParams);
setTimeout(() => {
setOverviewItem(undefined);
}, 100);
}}
className="sm:max-w-md"
buttons={
<>
<Link
to={overviewItem?.row.id ?? ""}
className="rounded-md bg-background text-muted-foreground hover:text-muted-foreground focus:outline-hidden focus:ring-2 focus:ring-gray-500 focus:ring-offset-2"
>
<span className="sr-only">{t("shared.openDetails")}</span>
<ExternalLinkEmptyIcon className="h-6 w-6" aria-hidden="true" />
</Link>
</>
}
>
{!overviewItem ? <div>{t("shared.loading")}...</div> : <${capitalized}Form item={overviewItem} actionData={actionData} />}
</SlideOverWideEmpty>
</IndexPageLayout>
);
}
`;
const uiCellControls: string[] = [];
entity.properties
.filter((f) => !f.isDefault)
.forEach((property) => {
CodeGeneratorPropertiesHelper.uiCell({ code: uiCellControls, imports, property });
});
template = template.replace("{PROPERTIES_UI_CELLS}", uiCellControls.join("\n "));
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,48 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
const titleExpression = CodeGeneratorHelper.getEntityTitleExpression(entity);
const pluralExpression = CodeGeneratorHelper.getEntityPluralExpression(entity);
return `import { useActionData, useLoaderData, useLocation } from "react-router";
import { useTranslation } from "react-i18next";
import CheckPlanFeatureLimit from "~/components/core/settings/subscription/CheckPlanFeatureLimit";
import NewPageLayout from "~/components/ui/layouts/NewPageLayout";
import UrlUtils from "~/utils/app/UrlUtils";
import ${capitalized}Form from "../../components/${capitalized}Form";
import { ${capitalized}RoutesNewApi } from "../api/${capitalized}Routes.New.Api";
export default function ${capitalized}RoutesNewView() {
const { t } = useTranslation();
const data = useLoaderData<${capitalized}RoutesNewApi.LoaderData>();
const actionData = useActionData<${capitalized}RoutesNewApi.ActionData>();
const location = useLocation();
return (
<NewPageLayout
title={t("shared.create") + " " + ${titleExpression}}
menu={[
{
title: ${pluralExpression},
routePath: UrlUtils.getParentRoute(location.pathname),
},
{
title: t("shared.create"),
routePath: "",
},
]}
>
<div className="mx-auto max-w-2xl">
<CheckPlanFeatureLimit item={data.featureUsage}>
<${capitalized}Form isCreating={true} actionData={actionData} />
</CheckPlanFeatureLimit>
</div>
</NewPageLayout>
);
}
`;
}
export default {
generate,
};
@@ -1,19 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import RowSettingsPermissions from "~/components/entities/rows/RowSettingsPermissions";
import { ${capitalized}RoutesShareApi } from "../api/${capitalized}Routes.Share.Api";
import { useLoaderData } from "react-router";
export default function ${capitalized}RoutesShareView() {
const data = useLoaderData<${capitalized}RoutesShareApi.LoaderData>();
return <RowSettingsPermissions item={data.item.row} items={data.item.row.permissions} tenants={data.tenants} users={data.users} />;
}
`;
}
export default {
generate,
};
@@ -1,19 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized } = CodeGeneratorHelper.getNames(entity);
return `import RowSettingsTags from "~/components/entities/rows/RowSettingsTags";
import { ${capitalized}RoutesTagsApi } from "../api/${capitalized}Routes.Tags.Api";
import { useLoaderData } from "react-router";
export default function ${capitalized}RoutesTagsView() {
const data = useLoaderData<${capitalized}RoutesTagsApi.LoaderData>();
return <RowSettingsTags item={data.item.row} tags={data.tags} />;
}
`;
}
export default {
generate,
};
@@ -1,35 +0,0 @@
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
const code: string[] = [
`model ${capitalized} {
id String @id @unique
row Row @relation(fields: [id], references: [id], onDelete: Cascade)`,
];
entity.properties
.filter((f) => !f.isDefault)
.forEach((property) => {
CodeGeneratorPropertiesHelper.schema({ code, property });
});
code.push("}");
code.push("");
code.push(`// Add at the end of the Row model
model Row {
// ...
${name} ${capitalized}?
}`);
return [...code].join("\n");
}
export default {
generate,
};
@@ -1,131 +0,0 @@
import { PropertyType } from "~/application/enums/entities/PropertyType";
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "../../utils/CodeGeneratorPropertiesHelper";
function generate({ entity }: { entity: EntityWithDetails }): string {
const { capitalized, name } = CodeGeneratorHelper.getNames(entity);
const imports: string[] = [];
imports.push(`import { PaginationDto } from "~/application/dtos/data/PaginationDto";
import { RowsApi } from "~/utils/api/.server/RowsApi";
import { getEntityByName } from "~/utils/db/entities/entities.db.server";
import RowHelper from "~/utils/helpers/RowHelper";
import RowValueService, { RowValueUpdateDto } from "~/utils/helpers/.server/RowValueService";`);
if (entity.properties.some((p) => p.type === PropertyType.MEDIA)) {
imports.push(`import { RowMedia } from "@toolctrl/db/prisma-browser";`);
}
imports.push(`import { ${capitalized}Dto } from "../dtos/${capitalized}Dto";
import { ${capitalized}CreateDto } from "../dtos/${capitalized}CreateDto";
import ${capitalized}Helpers from "../helpers/${capitalized}Helpers";`);
let template = `
export namespace ${capitalized}Service {
async function getEntity(tenantId: string | null) {
let entityName = "${name}";
const entity = await getEntityByName({ tenantId, name: entityName });
if (!entity) {
throw Error("Entity not found: " + entityName);
}
return entity;
}
export async function getAll({
tenantId,
userId,
urlSearchParams,
}: {
tenantId: string | null;
userId?: string;
urlSearchParams?: URLSearchParams;
}): Promise<{ items: ${capitalized}Dto[]; pagination: PaginationDto }> {
const entity = await getEntity(tenantId);
const data = await RowsApi.getAll({
entity,
tenantId,
userId,
urlSearchParams,
});
return {
items: data.items.map((row) => ${capitalized}Helpers.rowToDto({ entity, row })),
pagination: data.pagination,
};
}
export async function get(id: string, session: { tenantId: string | null; userId?: string }): Promise<${capitalized}Dto | null> {
const entity = await getEntity(session.tenantId);
const { item, rowPermissions } = await RowsApi.get(id, {
tenantId: session.tenantId,
userId: session.userId,
entity,
});
if (!rowPermissions.canRead) {
return null;
}
return ${capitalized}Helpers.rowToDto({ entity, row: item });
}
export async function create(data: ${capitalized}CreateDto, session: { tenantId: string | null; userId?: string }): Promise<${capitalized}Dto> {
const entity = await getEntity(session.tenantId);
const rowValues = RowHelper.getRowPropertiesFromForm({
entity,
values: [
{PROPERTIES_CREATE_VALUES}
],
});
const item = await RowsApi.create({
tenantId: session.tenantId,
userId: session.userId,
entity,
rowValues,
});
return ${capitalized}Helpers.rowToDto({ entity, row: item });
}
export async function update(id: string, data: Partial<${capitalized}Dto>, session: { tenantId: string | null; userId?: string }): Promise<${capitalized}Dto> {
const entity = await getEntity(session.tenantId);
const { item: row, rowPermissions } = await RowsApi.get(id, {
tenantId: session.tenantId,
userId: session.userId,
entity,
});
if (!row || !rowPermissions.canUpdate) {
throw Error("Not found");
}
const values: RowValueUpdateDto[] = [];
{PROPERTIES_UPDATE_VALUES}
const item = await RowValueService.update({
entity,
row,
values,
session,
});
return ${capitalized}Helpers.rowToDto({ entity, row: item });
}
export async function del(id: string, session: { tenantId: string | null; userId?: string }): Promise<void> {
const entity = await getEntity(session.tenantId);
await RowsApi.del(id, {
entity,
tenantId: session.tenantId,
userId: session.userId,
});
}
}`;
const createValues: string[] = [];
const updateValues: string[] = [];
entity.properties
.filter((f) => !f.isDefault)
.forEach((property) => {
if (property.showInCreate) {
CodeGeneratorPropertiesHelper.createDtoToRow({ code: createValues, property });
}
CodeGeneratorPropertiesHelper.updateDtoToRow({ code: updateValues, property });
});
template = template.replace("{PROPERTIES_CREATE_VALUES}", createValues.join("\n "));
template = template.replace("{PROPERTIES_UPDATE_VALUES}", updateValues.join("\n "));
const uniqueImports = [...new Set(imports)];
return [...uniqueImports, template].join("\n");
}
export default {
generate,
};
@@ -1,67 +0,0 @@
import { EntityWithDetails } from "~/utils/db/entities/entities.db.server";
const TRANSLATION_KEY_PATTERN = /^[a-z0-9]+(?:\.[A-Za-z0-9_-]+)+$/;
function isTranslationKey(value: string) {
return TRANSLATION_KEY_PATTERN.test(value);
}
function toGeneratedString(value: string) {
return JSON.stringify(value);
}
function getTranslationExpression(value: string, fallbackKey: string) {
if (isTranslationKey(value)) {
return `t(${toGeneratedString(value)})`;
}
return `t(${toGeneratedString(fallbackKey)}, { defaultValue: ${toGeneratedString(value)} })`;
}
function getEntityTitleExpression(entity: EntityWithDetails) {
return getTranslationExpression(entity.title, `generated.entities.${entity.name}.title`);
}
function getEntityPluralExpression(entity: EntityWithDetails) {
return getTranslationExpression(entity.titlePlural, `generated.entities.${entity.name}.titlePlural`);
}
function getPropertyTitleExpression(property: { name: string; title: string }) {
return getTranslationExpression(property.title, `generated.fields.${property.name}`);
}
function formatRawLabel(value: string) {
return value.replace(/\s+/g, " ").trim();
}
function getRawLabelWarnings(entity: EntityWithDetails) {
const rawLabels = [
!isTranslationKey(entity.title) ? `entity title "${formatRawLabel(entity.title)}"` : undefined,
!isTranslationKey(entity.titlePlural) ? `entity plural "${formatRawLabel(entity.titlePlural)}"` : undefined,
...entity.properties.map((property) => (!isTranslationKey(property.title) ? `property ${property.name} title "${formatRawLabel(property.title)}"` : undefined)),
].filter((label): label is string => Boolean(label));
if (rawLabels.length === 0) {
return [];
}
return [`Generator warning: raw labels are emitted with stable fallback i18n keys; add locale keys for ${rawLabels.join(", ")}.`];
}
function getNames(entity: EntityWithDetails) {
return {
capitalized: entity.name.charAt(0).toUpperCase() + entity.name.slice(1),
name: entity.name,
title: entity.title,
plural: entity.titlePlural,
slug: entity.slug,
};
}
export default {
getNames,
getEntityTitleExpression,
getEntityPluralExpression,
getPropertyTitleExpression,
getRawLabelWarnings,
getTranslationExpression,
isTranslationKey,
};
@@ -1,161 +0,0 @@
import { describe, expect, it } from "vitest";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import type { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
import CodeGeneratorPropertiesHelper from "./CodeGeneratorPropertiesHelper";
function createProperty(type: PropertyType, patch: Partial<PropertyWithDetails> = {}): PropertyWithDetails {
return {
name: `field${type}`,
title: `entities.fields.field${type}`,
type,
subtype: null,
isDefault: false,
isRequired: false,
showInCreate: true,
attributes: [],
options: [],
formula: null,
...patch,
} as unknown as PropertyWithDetails;
}
describe("CodeGeneratorPropertiesHelper", () => {
it("does not emit unresolved placeholder markers for any declared property type", () => {
const propertyTypes = Object.values(PropertyType).filter((value): value is PropertyType => typeof value === "number");
for (const propertyType of propertyTypes) {
const property = createProperty(propertyType);
const imports: string[] = [];
const code: string[] = [];
CodeGeneratorPropertiesHelper.type({ code, imports, property });
CodeGeneratorPropertiesHelper.rowToDto({ code, property });
CodeGeneratorPropertiesHelper.formToDto({ code, property });
CodeGeneratorPropertiesHelper.createDtoToRow({ code, property });
CodeGeneratorPropertiesHelper.updateDtoToRow({ code, property });
CodeGeneratorPropertiesHelper.uiForm({ code, imports, property, index: 0 });
CodeGeneratorPropertiesHelper.uiCell({ code, imports, property });
CodeGeneratorPropertiesHelper.schema({ code, property });
const generated = code.join("\n");
expect(generated).not.toContain("TODO");
expect(generated).not.toContain("not implemented");
expect(generated.trim()).not.toHaveLength(0);
}
});
it("maps complex generated schema properties to valid Prisma scalar types", () => {
const complexTypes = [
PropertyType.MEDIA,
PropertyType.MULTI_SELECT,
PropertyType.MULTI_TEXT,
PropertyType.RANGE_NUMBER,
PropertyType.RANGE_DATE,
];
for (const propertyType of complexTypes) {
const code: string[] = [];
CodeGeneratorPropertiesHelper.schema({ code, property: createProperty(propertyType) });
expect(code.join("\n")).toContain(" Json?");
expect(code.join("\n")).not.toContain("TODO");
}
});
it("does not treat raw English labels as direct i18n keys", () => {
const property = createProperty(PropertyType.TEXT, {
name: "firstName",
title: "First Name",
});
const imports: string[] = [];
const formCode: string[] = [];
const cellCode: string[] = [];
CodeGeneratorPropertiesHelper.uiForm({ code: formCode, imports, property, index: 0 });
CodeGeneratorPropertiesHelper.uiCell({ code: cellCode, imports, property });
expect(formCode.join("\n")).toContain('t("generated.fields.firstName", { defaultValue: "First Name" })');
expect(cellCode.join("\n")).toContain('t("generated.fields.firstName", { defaultValue: "First Name" })');
expect(formCode.join("\n")).not.toContain('t("First Name")');
expect(cellCode.join("\n")).not.toContain('t("First Name")');
});
it("keeps explicit i18n keys as translation keys", () => {
const property = createProperty(PropertyType.TEXT, {
name: "firstName",
title: "models.employee.firstName",
});
const imports: string[] = [];
const formCode: string[] = [];
CodeGeneratorPropertiesHelper.uiForm({ code: formCode, imports, property, index: 0 });
expect(formCode.join("\n")).toContain('t("models.employee.firstName")');
expect(formCode.join("\n")).not.toContain("{ defaultValue:");
});
it("treats formula as a read-only computed field in generated surfaces", () => {
const property = createProperty(PropertyType.FORMULA, {
name: "computedScore",
title: "entities.fields.computedScore",
formula: { name: "Score", resultAs: "number", calculationTrigger: "manual" },
});
const imports: string[] = [];
const typeCode: string[] = [];
const rowCode: string[] = [];
const formCode: string[] = [];
const createCode: string[] = [];
const updateCode: string[] = [];
const formUiCode: string[] = [];
const cellCode: string[] = [];
const schemaCode: string[] = [];
CodeGeneratorPropertiesHelper.type({ code: typeCode, imports, property });
CodeGeneratorPropertiesHelper.rowToDto({ code: rowCode, property });
CodeGeneratorPropertiesHelper.formToDto({ code: formCode, property });
CodeGeneratorPropertiesHelper.createDtoToRow({ code: createCode, property });
CodeGeneratorPropertiesHelper.updateDtoToRow({ code: updateCode, property });
CodeGeneratorPropertiesHelper.uiForm({ code: formUiCode, imports, property, index: 0 });
CodeGeneratorPropertiesHelper.uiCell({ code: cellCode, imports, property });
CodeGeneratorPropertiesHelper.schema({ code: schemaCode, property });
expect(typeCode.join("\n")).toContain("computedScore: number | undefined");
expect(rowCode.join("\n")).toContain('RowValueHelper.getNumber({ entity, row, name: "computedScore" })');
expect(formCode).toEqual([]);
expect(createCode).toEqual([]);
expect(updateCode).toEqual([]);
expect(formUiCode.join("\n")).not.toContain('name="computedScore"');
expect(cellCode.join("\n")).toContain("RowNumberCell");
expect(schemaCode.join("\n")).toContain("computed Formula field");
expect(schemaCode.join("\n")).not.toContain("Json?");
});
it("maps formula resultAs variants to stable DTO display types", () => {
const cases = [
["number", "number | undefined", "getNumber", "RowNumberCell"],
["string", "string | undefined", "getText", "truncate"],
["date", "Date | undefined", "getDate", "RowDateCell"],
["boolean", "boolean | undefined", "getBoolean", "RowBooleanCell"],
] as const;
for (const [resultAs, dtoType, rowHelper, cellMarker] of cases) {
const property = createProperty(PropertyType.FORMULA, {
name: `computed${resultAs}`,
formula: { name: resultAs, resultAs, calculationTrigger: "manual" },
});
const imports: string[] = [];
const typeCode: string[] = [];
const rowCode: string[] = [];
const cellCode: string[] = [];
CodeGeneratorPropertiesHelper.type({ code: typeCode, imports, property });
CodeGeneratorPropertiesHelper.rowToDto({ code: rowCode, property });
CodeGeneratorPropertiesHelper.uiCell({ code: cellCode, imports, property });
expect(typeCode.join("\n")).toContain(dtoType);
expect(rowCode.join("\n")).toContain(`RowValueHelper.${rowHelper}`);
expect(cellCode.join("\n")).toContain(cellMarker);
}
});
});
@@ -1,689 +0,0 @@
import { PropertyAttributeName } from "~/application/enums/entities/PropertyAttributeName";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import { Colors } from "~/application/enums/shared/Colors";
import CodeGeneratorHelper from "~/modules/codeGenerator/utils/CodeGeneratorHelper";
import { PropertyWithDetails } from "~/utils/db/entities/entities.db.server";
import PropertyAttributeHelper from "~/utils/helpers/PropertyAttributeHelper";
import { SelectOptionsDisplay } from "~/utils/shared/SelectOptionsUtils";
function getPropertyTypeLabel(property: PropertyWithDetails) {
return PropertyType[property.type] ?? `UNKNOWN_${property.type}`;
}
function unsupportedGeneratedComment(property: PropertyWithDetails, surface: string) {
return `Unsupported generated ${surface} for ${property.name} (${getPropertyTypeLabel(property)})`;
}
function isWritableProperty(property: PropertyWithDetails) {
return property.type !== PropertyType.FORMULA;
}
function getFormulaResultAs(property: PropertyWithDetails) {
const resultAs = property.formula?.resultAs;
if (resultAs === "number" || resultAs === "string" || resultAs === "date" || resultAs === "boolean") {
return resultAs;
}
return "unknown";
}
function getFormulaType(property: PropertyWithDetails) {
const resultAs = getFormulaResultAs(property);
if (resultAs === "number") {
return "number";
}
if (resultAs === "string") {
return "string";
}
if (resultAs === "date") {
return "Date";
}
if (resultAs === "boolean") {
return "boolean";
}
return "unknown";
}
function type({ code, imports, property }: { code: string[]; imports: string[]; property: PropertyWithDetails }) {
let type = "";
if (property.type === PropertyType.TEXT) {
type = property.isRequired ? "string" : "string | undefined";
} else if (property.type === PropertyType.NUMBER) {
type = property.isRequired ? "number" : "number | undefined";
} else if (property.type === PropertyType.DATE) {
type = property.isRequired ? "Date" : "Date | undefined";
} else if (property.type === PropertyType.SELECT) {
type = property.isRequired ? "string" : "string | undefined";
} else if (property.type === PropertyType.BOOLEAN) {
type = property.isRequired ? "boolean" : "boolean | undefined";
} else if (property.type === PropertyType.MEDIA) {
imports.push(`import { MediaDto } from "~/application/dtos/entities/MediaDto";`);
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
type = property.isRequired ? "MediaDto" : "MediaDto | undefined";
} else {
type = property.isRequired ? "MediaDto[]" : "MediaDto[] | undefined";
}
} else if (property.type === PropertyType.MULTI_SELECT) {
imports.push(`import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";`);
type = "RowValueMultipleDto[]";
} else if (property.type === PropertyType.RANGE_NUMBER) {
imports.push(`import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";`);
type = property.isRequired ? "RowValueRangeDto" : "RowValueRangeDto | undefined";
} else if (property.type === PropertyType.RANGE_DATE) {
imports.push(`import { RowValueRangeDto } from "~/application/dtos/entities/RowValueRangeDto";`);
type = property.isRequired ? "RowValueRangeDto" : "RowValueRangeDto | undefined";
} else if (property.type === PropertyType.MULTI_TEXT) {
imports.push(`import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";`);
type = "RowValueMultipleDto[]";
} else if (property.type === PropertyType.FORMULA) {
const formulaType = getFormulaType(property);
type = property.isRequired ? formulaType : `${formulaType} | undefined`;
} else {
type = "unknown";
}
let comments: string[] = [];
comments.push(property.isRequired ? "required" : "optional");
property.attributes
.filter((f) => f.value)
.forEach((attribute) => {
comments.push(`${attribute.name}: ${attribute.value}`);
});
code.push(` ${property.name}: ${type}; // ${comments.join(", ")}`);
}
function rowToDto({ code, property }: { code: string[]; property: PropertyWithDetails }) {
let propertyCode = "";
let comments: string[] = [];
comments.push(property.isRequired ? "required" : "optional");
if (property.type === PropertyType.TEXT) {
let fallbackValue = property.isRequired ? ` ?? ""` : ``;
propertyCode = `${property.name}: RowValueHelper.getText({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (property.type === PropertyType.NUMBER) {
let fallbackValue = property.isRequired ? ` ?? 0` : ``;
propertyCode = `${property.name}: RowValueHelper.getNumber({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (property.type === PropertyType.DATE) {
let fallbackValue = property.isRequired ? ` ?? new Date()` : ``;
propertyCode = `${property.name}: RowValueHelper.getDate({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (property.type === PropertyType.SELECT) {
let fallbackValue = property.isRequired ? ` ?? ""` : ``;
propertyCode = `${property.name}: RowValueHelper.getText({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (property.type === PropertyType.BOOLEAN) {
propertyCode = `${property.name}: RowValueHelper.getBoolean({ entity, row, name: "${property.name}" }) ?? false,`;
} else if (property.type === PropertyType.MEDIA) {
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
if (property.isRequired) {
propertyCode = `${property.name}: RowValueHelper.getFirstMedia({ entity, row, name: "${property.name}" }) as MediaDto,`;
} else {
propertyCode = `${property.name}: RowValueHelper.getFirstMedia({ entity, row, name: "${property.name}" }),`;
}
} else {
propertyCode = `${property.name}: RowValueHelper.getMedia({ entity, row, name: "${property.name}" }),`;
}
} else if (property.type === PropertyType.MULTI_SELECT) {
propertyCode = `${property.name}: RowValueHelper.getMultiple({ entity, row, name: "${property.name}" }),`;
} else if (property.type === PropertyType.MULTI_TEXT) {
propertyCode = `${property.name}: RowValueHelper.getMultiple({ entity, row, name: "${property.name}" }),`;
} else if (property.type === PropertyType.RANGE_NUMBER) {
propertyCode = `${property.name}: RowValueHelper.getNumberRange({ entity, row, name: "${property.name}" }),`;
} else if (property.type === PropertyType.RANGE_DATE) {
propertyCode = `${property.name}: RowValueHelper.getDateRange({ entity, row, name: "${property.name}" }),`;
} else if (property.type === PropertyType.FORMULA) {
const resultAs = getFormulaResultAs(property);
if (resultAs === "number") {
let fallbackValue = property.isRequired ? ` ?? 0` : ``;
propertyCode = `${property.name}: RowValueHelper.getNumber({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (resultAs === "string") {
let fallbackValue = property.isRequired ? ` ?? ""` : ``;
propertyCode = `${property.name}: RowValueHelper.getText({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (resultAs === "date") {
let fallbackValue = property.isRequired ? ` ?? new Date()` : ``;
propertyCode = `${property.name}: RowValueHelper.getDate({ entity, row, name: "${property.name}" })${fallbackValue},`;
} else if (resultAs === "boolean") {
propertyCode = `${property.name}: RowValueHelper.getBoolean({ entity, row, name: "${property.name}" }) ?? false,`;
} else {
propertyCode = `${property.name}: undefined, // ${unsupportedGeneratedComment(property, "formula row mapping")}`;
}
} else {
propertyCode = `${property.name}: undefined, // ${unsupportedGeneratedComment(property, "row mapping")}`;
}
if (comments.length > 0) {
propertyCode = propertyCode + ` // ${comments.join(", ")}`;
}
code.push(propertyCode);
}
function formToDto({ code, property }: { code: string[]; property: PropertyWithDetails }) {
if (!isWritableProperty(property)) {
return;
}
let propertyCode = "";
let comments: string[] = [];
comments.push(property.isRequired ? "required" : "optional");
if (property.type === PropertyType.TEXT) {
propertyCode = `${property.name}: FormHelper.getText(form, "${property.name}"),`;
} else if (property.type === PropertyType.NUMBER) {
propertyCode = `${property.name}: FormHelper.getNumber(form, "${property.name}"),`;
} else if (property.type === PropertyType.DATE) {
propertyCode = `${property.name}: FormHelper.getDate(form, "${property.name}"),`;
} else if (property.type === PropertyType.SELECT) {
propertyCode = `${property.name}: FormHelper.getText(form, "${property.name}"),`;
} else if (property.type === PropertyType.BOOLEAN) {
propertyCode = `${property.name}: FormHelper.getBoolean(form, "${property.name}"),`;
} else if (property.type === PropertyType.MEDIA) {
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
propertyCode = `${property.name}: FormHelper.getFormFirstMedia(form, "${property.name}"),`;
} else {
propertyCode = `${property.name}: FormHelper.getFormMedia(form, "${property.name}"),`;
}
} else if (property.type === PropertyType.MULTI_SELECT) {
propertyCode = `${property.name}: FormHelper.getMultiple(form, "${property.name}"),`;
} else if (property.type === PropertyType.RANGE_NUMBER) {
propertyCode = `${property.name}: FormHelper.getNumberRange(form, "${property.name}"),`;
} else if (property.type === PropertyType.RANGE_DATE) {
propertyCode = `${property.name}: FormHelper.getDateRange(form, "${property.name}"),`;
} else if (property.type === PropertyType.MULTI_TEXT) {
propertyCode = `${property.name}: FormHelper.getMultiple(form, "${property.name}"),`;
} else {
propertyCode = `${property.name}: undefined, // ${unsupportedGeneratedComment(property, "form mapping")}`;
}
if (comments.length > 0) {
propertyCode = propertyCode + ` // ${comments.join(", ")}`;
}
code.push(propertyCode);
}
function createDtoToRow({ code, property }: { code: string[]; property: PropertyWithDetails }) {
if (!isWritableProperty(property)) {
return;
}
const optionalChaining = property.isRequired ? "" : "?";
let propertyCode = ``;
if (property.type === PropertyType.TEXT) {
propertyCode = `{ name: "${property.name}", value: data.${property.name} },`;
} else if (property.type === PropertyType.NUMBER) {
propertyCode = `{ name: "${property.name}", value: data.${property.name}${optionalChaining}.toString() },`;
} else if (property.type === PropertyType.DATE) {
propertyCode = `{ name: "${property.name}", value: data.${property.name}${optionalChaining}.toISOString() },`;
} else if (property.type === PropertyType.SELECT) {
propertyCode = `{ name: "${property.name}", value: data.${property.name} },`;
} else if (property.type === PropertyType.BOOLEAN) {
propertyCode = `{ name: "${property.name}", value: data.${property.name}${optionalChaining}.toString() },`;
} else if (property.type === PropertyType.MEDIA) {
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
propertyCode = `{ name: "${property.name}", media: data.${property.name} ? [data.${property.name}] : [] },`;
} else {
propertyCode = `{ name: "${property.name}", media: data.${property.name} },`;
}
} else if (property.type === PropertyType.MULTI_SELECT) {
propertyCode = `{ name: "${property.name}", multiple: data.${property.name} },`;
} else if (property.type === PropertyType.RANGE_NUMBER) {
propertyCode = `{ name: "${property.name}", range: data.${property.name} },`;
} else if (property.type === PropertyType.RANGE_DATE) {
propertyCode = `{ name: "${property.name}", range: data.${property.name} },`;
} else if (property.type === PropertyType.MULTI_TEXT) {
propertyCode = `{ name: "${property.name}", multiple: data.${property.name} },`;
} else {
propertyCode = `// ${unsupportedGeneratedComment(property, "create mapping")}`;
}
code.push(propertyCode);
}
function updateDtoToRow({ code, property }: { code: string[]; property: PropertyWithDetails }) {
if (!isWritableProperty(property)) {
return;
}
let propertyCode = `if (data.${property.name} !== undefined) {\n`;
if (property.type === PropertyType.TEXT) {
propertyCode += `values.push({ name: "${property.name}", textValue: data.${property.name} });`;
} else if (property.type === PropertyType.NUMBER) {
propertyCode += `values.push({ name: "${property.name}", numberValue: data.${property.name} });`;
} else if (property.type === PropertyType.DATE) {
propertyCode += `values.push({ name: "${property.name}", dateValue: data.${property.name} });`;
} else if (property.type === PropertyType.SELECT) {
propertyCode += `values.push({ name: "${property.name}", textValue: data.${property.name} });`;
} else if (property.type === PropertyType.BOOLEAN) {
propertyCode += `values.push({ name: "${property.name}", booleanValue: data.${property.name} });`;
} else if (property.type === PropertyType.MEDIA) {
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
propertyCode += `values.push({ name: "${property.name}", media: data.${property.name} ? [data.${property.name} as RowMedia] : [] });`;
} else {
propertyCode += `values.push({ name: "${property.name}", media: data.${property.name} ? data.${property.name} as RowMedia[] : [] });`;
}
} else if (property.type === PropertyType.MULTI_SELECT) {
propertyCode += `values.push({ name: "${property.name}", multiple: data.${property.name} });`;
} else if (property.type === PropertyType.RANGE_NUMBER) {
propertyCode += `values.push({ name: "${property.name}", range: data.${property.name} });`;
} else if (property.type === PropertyType.RANGE_DATE) {
propertyCode += `values.push({ name: "${property.name}", range: data.${property.name} });`;
} else if (property.type === PropertyType.MULTI_TEXT) {
propertyCode += `values.push({ name: "${property.name}", multiple: data.${property.name} });`;
} else {
propertyCode += `// ${unsupportedGeneratedComment(property, "update mapping")}`;
}
propertyCode = propertyCode + `\n}`;
code.push(propertyCode);
}
function getColor(color: number) {
return "Colors." + Colors[color];
}
function uiForm({ code, imports, property, index }: { code: string[]; imports: string[]; property: PropertyWithDetails; index: number }) {
const titleExpression = CodeGeneratorHelper.getPropertyTitleExpression(property);
if (property.type === PropertyType.FORMULA) {
code.push(`{item && (
<div className="space-y-1">
<div className="text-xs font-medium text-muted-foreground">{${titleExpression}}</div>
<div className="rounded-md border bg-muted/40 px-3 py-2 text-sm">{item.${property.name}?.toString() ?? ""}</div>
</div>
)}`);
return;
}
if (!property.showInCreate) {
// render if row exists only
code.push(`{item && (`);
}
const props: string[] = [];
if (property.isRequired) {
props.push(`required`);
}
if (index === 0) {
props.push(`autoFocus`);
}
props.push("disabled={isDisabled()}");
let min = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Min) ?? 0;
let max = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) ?? 0;
if (property.type === PropertyType.TEXT) {
let defaultValue = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
let value = `item?.${property.name}`;
if (defaultValue) {
value = `item?.${property.name} ?? (!item ? "${defaultValue}" : undefined)`;
}
props.push(`defaultValue={${value}}`);
let placeholder = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Placeholder);
if (placeholder) {
props.push(`placeholder="${placeholder}"`);
}
if (min > 0) {
props.push(`minLength={${min}}`);
}
if (max > 0) {
props.push(`maxLength={${max}}`);
}
let rows = property.attributes.find((f) => f.name === PropertyAttributeName.Rows);
if (rows) {
props.push(`rows={${PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Rows)}}`);
}
let pattern = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Pattern);
if (pattern) {
props.push(`pattern="${pattern}"`);
}
let editor = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Editor);
if (editor === "monaco") {
props.push(`editor="monaco" editorLanguage="markdown"`);
} else if (editor === "wysiwyg") {
props.push(`editor="wysiwyg" autoFocus={${index === 0}}`);
}
if (!property.subtype || property.subtype === "singleLine") {
imports.push(`import InputText from "~/components/ui/input/InputText";`);
code.push(`<InputText name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else {
imports.push(`import InputTextSubtype from "~/components/ui/input/subtypes/InputTextSubtype";`);
code.push(`<InputTextSubtype subtype="${property.subtype}" name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
}
} else if (property.type === PropertyType.NUMBER) {
imports.push(`import InputNumber from "~/components/ui/input/InputNumber";`);
let defaultValue = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.DefaultValue);
let value = `item?.${property.name}`;
if (defaultValue) {
value = `item?.${property.name} ?? (!item ? ${defaultValue} : undefined)`;
}
props.push(`defaultValue={${value}}`);
if (min > 0) {
props.push(`min={${min}}`);
}
if (max > 0) {
props.push(`max={${max}}`);
}
let step = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Step);
if (step) {
props.push(`step="${step}"`);
}
code.push(`<InputNumber name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else if (property.type === PropertyType.DATE) {
imports.push(`import InputDate from "~/components/ui/input/InputDate";`);
code.push(`<InputDate name="${property.name}" title={${titleExpression}} defaultValue={item?.${property.name}} ${props.join(" ")} />`);
} else if (property.type === PropertyType.SELECT) {
let defaultValue = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.DefaultValue);
let value = `item?.${property.name}`;
if (defaultValue) {
value = `item?.${property.name} ?? (!item ? "${defaultValue}" : undefined)`;
}
props.push(`defaultValue={${value}}`);
const withColors = property.options.filter((f) => f.color).length > 0;
imports.push(`import { Colors } from "~/application/enums/shared/Colors";`);
props.push(
`options={[${property.options.map((option) => {
return `{ name: ${option.name === null ? `"${option.value}"` : `"${option.name}"`}, value: "${option.value}", color: ${getColor(option.color)} }`;
})}]}`
);
if (!property.subtype || property.subtype === "dropdown") {
// props.push(`withSearch={false}`);
props.push(`withColors={${withColors ? "true" : "false"}}`);
imports.push(`import InputSelect from "~/components/ui/input/InputSelect";`);
code.push(`<InputSelect name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else if (property.subtype === "radioGroupCards") {
imports.push(`import InputRadioGroupCards from "~/components/ui/input/InputRadioGroupCards";`);
code.push(`<InputRadioGroupCards name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
}
} else if (property.type === PropertyType.BOOLEAN) {
imports.push(`import InputCheckbox from "~/components/ui/input/InputCheckbox";`);
let defaultValue = PropertyAttributeHelper.getPropertyAttributeValue_Boolean(property, PropertyAttributeName.DefaultValue);
let value = `item?.${property.name}`;
if (defaultValue) {
value = `item?.${property.name} ?? (!item ? ${defaultValue} : undefined)`;
}
props.push(`value={${value}}`);
code.push(`<InputCheckbox name="${property.name}" title={${titleExpression}} asToggle ${props.join(" ")} />`);
} else if (property.type === PropertyType.MEDIA) {
imports.push(`import InputMedia from "~/components/ui/input/InputMedia";`);
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
props.push(`initialMedia={item?.${property.name} ? [item?.${property.name}] : []}`);
} else {
props.push(`initialMedia={item?.${property.name}}`);
}
let acceptFileTypes = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.AcceptFileTypes);
if (min > 0) {
props.push(`min={${min}}`);
}
if (max > 0) {
props.push(`max={${max}}`);
}
if (acceptFileTypes) {
props.push(`accept="${acceptFileTypes}"`);
}
let maxSize = PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.MaxSize) ?? 0;
if (maxSize > 0) {
props.push(`maxSize={${maxSize}}`);
}
code.push(`<InputMedia name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else if (property.type === PropertyType.MULTI_SELECT) {
props.push(`value={item?.${property.name}}`);
imports.push(`import { Colors } from "~/application/enums/shared/Colors";`);
props.push(
`options={[${property.options.map((option) => {
return `{ name: ${option.name === null ? `"${option.value}"` : `"${option.name}"`}, value: "${option.value}", color: ${getColor(option.color)} }`;
})}]}`
);
if (!property.subtype || property.subtype === "combobox") {
// imports.push(`import InputCombobox from "~/components/ui/input/InputCombobox";`);
imports.push(`import PropertyMultiSelector from "~/components/entities/properties/PropertyMultiSelector";`);
code.push(`<PropertyMultiSelector name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else if (property.subtype === "checkboxCards") {
imports.push(`import PropertyMultiSelector from "~/components/entities/properties/PropertyMultiSelector";`);
code.push(`<PropertyMultiSelector subtype="checkboxCards" name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
}
} else if (property.type === PropertyType.RANGE_NUMBER) {
imports.push(`import InputRangeNumber from "~/components/ui/input/ranges/InputRangeNumber";`);
code.push(
`<InputRangeNumber name="${property.name}" title={${titleExpression}} ${props.join(" ")} defaultValueMin={item?.${
property.name
}?.numberMin ? Number(item.${property.name}.numberMin) : undefined} defaultValueMax={item?.${property.name}?.numberMax ? Number(item.${
property.name
}.numberMax) : undefined} />`
);
} else if (property.type === PropertyType.RANGE_DATE) {
imports.push(`import InputRangeDate from "~/components/ui/input/ranges/InputRangeDate";`);
code.push(
`<InputRangeDate name="${property.name}" title={${titleExpression}} ${props.join(" ")} defaultValueMin={item?.${
property.name
}?.dateMin} defaultValueMax={item?.${property.name}?.dateMax} />`
);
} else if (property.type === PropertyType.MULTI_TEXT) {
imports.push(`import InputMultiText from "~/components/ui/input/InputMultiText";`);
let separator = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.Separator);
if (separator) {
props.push(`separator="${separator}"`);
}
props.push(`value={item?.${property.name}}`);
code.push(`<InputMultiText name="${property.name}" title={${titleExpression}} ${props.join(" ")} />`);
} else {
code.push(`{/* ${unsupportedGeneratedComment(property, "input")} */}`);
}
if (!property.showInCreate) {
// render if row exists only
code.push(`)}`);
}
}
function uiCell({ code, imports, property }: { code: string[]; imports: string[]; property: PropertyWithDetails }) {
const titleExpression = CodeGeneratorHelper.getPropertyTitleExpression(property);
const props: string[] = [];
if (property.type === PropertyType.TEXT) {
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <div className="max-w-sm truncate">{item.${property.name}}</div>,
},`);
} else if (property.type === PropertyType.NUMBER) {
imports.push(`import RowNumberCell from "~/components/entities/rows/cells/RowNumberCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatNumber);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowNumberCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.DATE) {
imports.push(`import RowDateCell from "~/components/entities/rows/cells/RowDateCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatDate);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowDateCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.SELECT) {
imports.push(`import RowSelectedOptionCell from "~/components/entities/rows/cells/RowSelectedOptionCell";`);
// const withColors = property.options.filter((f) => f.color).length > 0;
// if (withColors) {
imports.push(`import { Colors } from "~/application/enums/shared/Colors";`);
// }
props.push(
`options={[${property.options.map((option) => {
return `{ name: ${option.name === null ? "null" : `"${option.name}"`}, value: "${option.value}", color: ${getColor(option.color)} }`;
})}]}`
);
let display: SelectOptionsDisplay = "Value";
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.SelectOptions);
if (format) {
display = format as SelectOptionsDisplay;
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowSelectedOptionCell value={item?.${property.name}} display="${display}" ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.BOOLEAN) {
imports.push(`import RowBooleanCell from "~/components/entities/rows/cells/RowBooleanCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatBoolean);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowBooleanCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.MEDIA) {
imports.push(`import RowMediaCell from "~/components/entities/rows/cells/RowMediaCell";`);
if (PropertyAttributeHelper.getPropertyAttributeValue_Number(property, PropertyAttributeName.Max) === 1) {
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowMediaCell media={item.${property.name} ? [item.${property.name}] : []} ${props.join(" ")} />,
},`);
} else {
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowMediaCell media={item.${property.name}} ${props.join(" ")} />,
},`);
}
} else if (property.type === PropertyType.MULTI_SELECT) {
imports.push(`import PropertyMultipleValueBadge from "~/components/entities/properties/PropertyMultipleValueBadge";`);
props.push(
`options={[${property.options.map((option) => {
return `{ name: ${option.name === null ? "null" : `"${option.name}"`}, value: "${option.value}" }`;
})}]}`
);
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <PropertyMultipleValueBadge values={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.RANGE_NUMBER) {
imports.push(`import RowRangeNumberCell from "~/components/entities/rows/cells/RowRangeNumberCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatNumber);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowRangeNumberCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.RANGE_DATE) {
imports.push(`import RowRangeDateCell from "~/components/entities/rows/cells/RowRangeDateCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatNumber);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowRangeDateCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.MULTI_TEXT) {
imports.push(`import PropertyMultipleValueBadge from "~/components/entities/properties/PropertyMultipleValueBadge";`);
props.push(
`options={[${property.options.map((option) => {
return `{ name: ${option.name === null ? "null" : `"${option.name}"`}, value: "${option.value}" }`;
})}]}`
);
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <PropertyMultipleValueBadge values={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (property.type === PropertyType.FORMULA) {
const resultAs = getFormulaResultAs(property);
if (resultAs === "number") {
imports.push(`import RowNumberCell from "~/components/entities/rows/cells/RowNumberCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatNumber);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowNumberCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (resultAs === "date") {
imports.push(`import RowDateCell from "~/components/entities/rows/cells/RowDateCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatDate);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowDateCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else if (resultAs === "boolean") {
imports.push(`import RowBooleanCell from "~/components/entities/rows/cells/RowBooleanCell";`);
let format = PropertyAttributeHelper.getPropertyAttributeValue_String(property, PropertyAttributeName.FormatBoolean);
if (format) {
props.push(`format="${format}"`);
}
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <RowBooleanCell value={item.${property.name}} ${props.join(" ")} />,
},`);
} else {
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: (item) => <div className="max-w-sm truncate">{item.${property.name}}</div>,
},`);
}
} else {
code.push(`{
name: "${property.name}",
title: ${titleExpression},
value: () => null,
},`);
}
}
function schema({ code, property }: { code: string[]; property: PropertyWithDetails }) {
const typeMap: Record<PropertyType, string> = {
[PropertyType.TEXT]: "String",
[PropertyType.NUMBER]: "Decimal",
[PropertyType.DATE]: "DateTime",
[PropertyType.SELECT]: "String",
[PropertyType.BOOLEAN]: "Boolean",
[PropertyType.MEDIA]: "Json",
[PropertyType.MULTI_SELECT]: "Json",
[PropertyType.MULTI_TEXT]: "Json",
[PropertyType.RANGE_NUMBER]: "Json",
[PropertyType.RANGE_DATE]: "Json",
[PropertyType.FORMULA]: "",
};
const type = typeMap[property.type as PropertyType];
if (type === undefined) {
return;
}
if (property.type === PropertyType.FORMULA) {
code.push(` // ${property.name} is a computed Formula field; no editable Prisma column is generated by default.`);
return;
}
const suffix = property.isRequired ? "" : "?";
const schemaString = ` ${property.name} ${type}${suffix}`;
code.push(schemaString);
}
export default {
type,
rowToDto,
formToDto,
createDtoToRow,
updateDtoToRow,
uiForm,
uiCell,
schema,
isWritableProperty,
};
@@ -1,17 +0,0 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import path from "node:path";
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "CrmService.ts"), "utf8");
describe("CrmService env boundary", () => {
test("uses typed web config for Formspree and stays free of US newsletter providers", () => {
expect(source).toContain("loadWebConfig().config.contactFormspreeEndpoint");
expect(source).not.toContain("process.env.INTEGRATIONS_CONTACT_FORMSPREE");
// EU-Sterilisation (R-P1a): ConvertKit-Provider vollständig entfernt.
expect(source).not.toContain("process.env.CONVERTKIT_");
expect(source).not.toContain("api.convertkit.com");
});
});
@@ -1,68 +0,0 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
/**
* PII-protection regression test for CrmService.
*
* Newsletter + ConvertKit code paths historically logged raw `response`
* objects (containing subscriber email) and raw exceptions. We tightened
* those to log only the operation tag, an ok-boolean, and a sanitised
* `err`. Never log: email, firstName, lastName, phone, response body,
* api key, contact object.
*/
describe("CrmService PII discipline", () => {
const SOURCE = readFileSync(resolve(__dirname, "CrmService.ts"), "utf8");
it("contains no live console.* call sites", () => {
const live = SOURCE.split("\n").filter((line, idx, all) => {
if (!/console\.(log|error|warn|info|debug)\s*\(/.test(line)) return false;
const trimmed = line.trimStart();
if (trimmed.startsWith("//") || trimmed.startsWith("*")) return false;
const prev = idx > 0 ? all[idx - 1].trim() : "";
if (/eslint-disable-next-line[^\n]*no-console/.test(prev)) return false;
return true;
});
expect(live).toEqual([]);
});
it("never passes contact PII keys as own crmLogger fields", () => {
const pattern = /crmLogger\.(info|warn|error|debug)\s*\(\s*\{([\s\S]*?)\}/g;
const forbiddenKeys = [
"email",
"firstName",
"lastName",
"phone",
"contact",
"response",
"responseBody",
"apiKey",
"API_KEY",
"api_key",
"api_secret",
];
const offenders: string[] = [];
let match: RegExpExecArray | null;
while ((match = pattern.exec(SOURCE)) !== null) {
const objContent = match[2];
for (const key of forbiddenKeys) {
const keyRe = new RegExp(`(^|[\\s,{])${key}\\s*:`, "m");
if (keyRe.test(objContent)) offenders.push(`key "${key}" in ${match[0].slice(0, 80)}...`);
}
}
expect(offenders, `crmLogger must not log PII / secret fields: ${offenders.join("; ")}`).toEqual([]);
});
it("uses createScopedLogger('crm')", () => {
expect(SOURCE).toMatch(/createScopedLogger\(\s*["']crm["']\s*\)/);
});
it("does not expose CRM template or entity details in configuration errors", () => {
expect(SOURCE).toContain("class CrmConfigurationError");
expect(SOURCE).not.toContain("CRM is not configured:");
expect(SOURCE).not.toContain('Entity "');
expect(SOURCE).not.toContain("load the template");
expect(SOURCE).not.toContain('must be "All" or');
expect(SOURCE).not.toContain("ConvertKit error:");
});
});
@@ -1,550 +0,0 @@
import { loadWebConfig } from "@toolctrl/config";
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { Colors } from "~/application/enums/shared/Colors";
import { RowRelationshipsApi } from "~/utils/api/.server/RowRelationshipsApi";
import { RowsApi } from "~/utils/api/.server/RowsApi";
import { dbRead } from "~/utils/db.server";
import { EntityWithDetails, findEntityByName, getEntitiesByName, getEntityByName } from "~/utils/db/entities/entities.db.server";
import { RowWithDetails, countRows, getRowById, getRows, getRowsInIds } from "~/utils/db/entities/rows.db.server";
import RowValueService, { RowValueUpdateDto } from "~/utils/helpers/.server/RowValueService";
import RowHelper from "~/utils/helpers/RowHelper";
import RowValueHelper from "~/utils/helpers/RowValueHelper";
import { t as i18nT } from "i18next";
import { createScopedLogger } from "~/utils/logger.server";
import { ensureProductCoreCrmEntities } from "./ProductCoreCrmEntities.server";
// EU-Sterilisation (R-P1a): ConvertKit (US-Newsletter-Provider) entfernt. Das CRM bleibt
// (Contacts/Companies/Opportunities/Submissions); Newsletter laufen ausschließlich über das
// eigene CRM. ConvertKit-Subscriber-Sync, -Fetch und -Config sind gestrichen.
const crmLogger = createScopedLogger("crm");
export class CrmConfigurationError extends Error {
readonly code = "CRM_CONFIGURATION_INVALID";
constructor() {
super("CRM_CONFIGURATION_INVALID");
this.name = "CrmConfigurationError";
}
}
export class CrmProviderError extends Error {
readonly code = "CRM_PROVIDER_UNAVAILABLE";
constructor() {
super("CRM_PROVIDER_UNAVAILABLE");
this.name = "CrmProviderError";
}
}
async function validate(tenantId: string | null = null) {
if (tenantId !== null) {
await ensureProductCoreCrmEntities();
}
const crmEntities = ["company", "opportunity", "contact"];
if (tenantId === null) {
crmEntities.push("submission");
}
const entities = await getEntitiesByName(crmEntities);
await Promise.all(
crmEntities.map(async (crmEntity) => {
const entity = entities.find((i) => i.name === crmEntity);
if (!entity) {
throw new CrmConfigurationError();
}
if (tenantId === null && ![DefaultEntityTypes.All, DefaultEntityTypes.AdminOnly].find((f) => f.toString() === entity.type)) {
throw new CrmConfigurationError();
} else if (tenantId !== null && ![DefaultEntityTypes.All, DefaultEntityTypes.AppOnly].find((f) => f.toString() === entity.type)) {
throw new CrmConfigurationError();
}
})
);
}
async function getContactsInRowIds(rowIds: string[], tenantId: string | null): Promise<ContactDto[]> {
const contactsEntity = await getEntityByName({ tenantId, name: "contact" });
const rows = await getRowsInIds(rowIds, tenantId);
return await Promise.all(
rowIds
.filter((f) => f)
.map(async (rowId) => {
const row = rows.find((i) => i.id === rowId);
if (!row) {
throw new Error("Contact not found: " + rowId);
}
const email = RowValueHelper.getText({ entity: contactsEntity, row, name: "email" }) ?? "";
const firstName = RowValueHelper.getText({ entity: contactsEntity, row, name: "firstName" }) ?? "";
const lastName = RowValueHelper.getText({ entity: contactsEntity, row, name: "lastName" }) ?? "";
const jobTitle = RowValueHelper.getText({ entity: contactsEntity, row, name: "jobTitle" }) ?? "";
const marketingSubscriber = RowValueHelper.getBoolean({ entity: contactsEntity, row, name: "marketingSubscriber" }) ?? false;
const contact: ContactDto = {
id: row.id,
email,
firstName,
lastName,
jobTitle,
marketingSubscriber,
};
return contact;
})
);
}
export type ContactDto = {
id: string;
email: string;
firstName: string;
lastName: string;
jobTitle: string;
marketingSubscriber: boolean;
company?: {
name: string;
};
};
async function getContact(rowId: string, tenantId: string | null): Promise<ContactDto | null> {
const contactsEntity = await getEntityByName({ tenantId, name: "contact" });
const row = await getRowById(rowId, { entityId: contactsEntity.id, tenantId });
if (!row) {
return null;
}
return rowToContact({ row, entity: contactsEntity });
}
async function getContacts(tenantId: string | null): Promise<ContactDto[]> {
const contactsEntity = await getEntityByName({ tenantId, name: "contact" });
const rows = await getRows({ entityName: "contact", tenantId });
return rows.map((row) => rowToContact({ row, entity: contactsEntity }));
}
export type ContactFormSettings = { crm: boolean; actionUrl?: string; error?: string };
async function getContactFormSettings() {
const settings: ContactFormSettings = {
crm: false,
actionUrl: undefined,
error: undefined,
};
try {
await validate();
settings.crm = true;
} catch {
const formspreeEndpoint = loadWebConfig().config.contactFormspreeEndpoint;
if (formspreeEndpoint) {
settings.actionUrl = formspreeEndpoint;
} else {
settings.error = i18nT("crm.contact.errors.formNotConfigured");
}
}
return settings;
}
export type NewsletterFormSettings = {
crm: boolean;
error?: string;
};
async function getNewsletterFormSettings() {
const settings: NewsletterFormSettings = {
crm: false,
error: undefined,
};
try {
await validate();
settings.crm = true;
} catch {
//
}
if (!settings.crm) {
settings.error = i18nT("crm.newsletter.errors.formNotConfigured");
}
return settings;
}
export type CrmSummaryDto = {
companies: number;
contacts: number;
opportunities: { value: number; count: number };
submissions: number;
data: {
openOpportunities: RowWithDetails[];
submissions: RowWithDetails[];
};
};
async function getSummary(tenantId: string | null): Promise<CrmSummaryDto> {
const openOpportunities = await getRows({
tenantId,
entityName: "opportunity",
});
const opportunities = { value: 0, count: 0 };
const opportunitiesEntity = await getEntityByName({ tenantId, name: "opportunity" });
openOpportunities.forEach((row) => {
const value = RowValueHelper.getNumber({ entity: opportunitiesEntity, row, name: "value" });
opportunities.value += value ?? 0;
if ((value ?? 0) > 0) {
opportunities.count++;
}
});
const submissionsEntity = await findEntityByName({ name: "submission", tenantId });
const submissions = submissionsEntity ? await getRows({ entityName: "submission", tenantId }) : [];
return {
companies: await countRows({ entityName: "company", tenantId }),
contacts: await countRows({ entityName: "contact", tenantId }),
opportunities,
submissions: submissions.length,
data: {
openOpportunities,
submissions,
},
};
}
async function createCompany({ tenantId, name, request }: { tenantId: string | null; name: string; request: Request }) {
const entity = await getEntityByName({ tenantId, name: "company" });
const rowValues = RowHelper.getRowPropertiesFromForm({
entity,
values: [{ name: "name", value: name }],
});
const row = await RowsApi.create({
entity,
tenantId,
rowValues,
request,
});
return row;
}
async function createContact({
tenantId,
firstName,
lastName,
email,
jobTitle,
status,
marketingSubscriber,
options,
request,
}: {
tenantId: string | null;
firstName: string;
lastName: string;
email: string;
jobTitle?: string;
status: string;
marketingSubscriber: boolean;
options?: {
checkUsage: boolean;
createLog: boolean;
createEvent: boolean;
storeMedia: boolean;
reportUsage: boolean;
};
request: Request;
}) {
const entity = await getEntityByName({ tenantId, name: "contact" });
const rowValues = RowHelper.getRowPropertiesFromForm({
entity,
values: [
{ name: "firstName", value: firstName },
{ name: "lastName", value: lastName },
{ name: "email", value: email },
{ name: "jobTitle", value: jobTitle ?? "" },
{ name: "status", value: status },
{ name: "marketingSubscriber", value: marketingSubscriber ? "true" : "false" },
],
options: {
skipValidation: true,
},
});
return await RowsApi.create({
entity,
tenantId,
rowValues,
options,
request,
});
}
async function createSubmission({ tenantId, users, message, request }: { tenantId: string | null; users: string; message: string; request: Request }) {
const entity = await getEntityByName({ tenantId, name: "submission" });
const rowValues = RowHelper.getRowPropertiesFromForm({
entity,
values: [
{ name: "users", value: users },
{ name: "message", value: message },
],
});
const row = await RowsApi.create({
entity,
tenantId,
rowValues,
request,
});
return row;
}
async function createContactSubmission(
submission: {
firstName: string;
lastName: string;
email: string;
jobTitle?: string;
company?: string;
users: string;
message: string;
},
request: Request
) {
let contact = await RowsApi.find({
entity: { name: "contact" },
tenantId: null,
properties: [{ name: "email", value: submission.email }],
});
if (!contact) {
contact = await createContact({
tenantId: null,
firstName: submission.firstName,
lastName: submission.lastName,
email: submission.email,
jobTitle: submission.jobTitle,
status: "contact",
marketingSubscriber: false,
request,
});
await RowsApi.addTag({ row: contact, tag: { value: "form", color: Colors.BLUE } });
}
const companyEntity = await getEntityByName({ tenantId: null, name: "company" });
const companies = contact.parentRows.filter((f) => f.parent.entityId === companyEntity.id);
if (companies.length === 0 && submission.company) {
const company = await createCompany({
tenantId: null,
name: submission.company,
request,
});
await RowRelationshipsApi.createRelationship({
parent: company,
child: contact,
tenantId: null,
});
}
const newSubmission = await createSubmission({
tenantId: null,
users: submission.users,
message: submission.message,
request,
});
await RowRelationshipsApi.createRelationship({
parent: contact,
child: newSubmission,
tenantId: null,
});
return contact;
}
async function updateContact(
rowId: string,
data: {
marketingSubscriber?: boolean;
firstName?: string;
lastName?: string;
jobTitle?: string;
},
options?: {
createEvent?: boolean;
tenantId?: string | null;
}
) {
const tenantId = options?.tenantId ?? null;
const contactsEntity = await getEntityByName({ tenantId, name: "contact" });
const row = await getRowById(rowId, { entityId: contactsEntity.id, tenantId });
if (!row) {
return null;
}
const contact = rowToContact({ row, entity: contactsEntity });
let changes: RowValueUpdateDto[] = [];
if (data.firstName !== undefined && data.firstName !== contact.firstName) {
changes.push({ name: "firstName", textValue: data.firstName });
} else if (data.lastName !== undefined && data.lastName !== contact.lastName) {
changes.push({ name: "lastName", textValue: data.lastName });
} else if (data.jobTitle !== undefined && data.jobTitle !== contact.jobTitle) {
changes.push({ name: "jobTitle", textValue: data.jobTitle });
} else if (data.marketingSubscriber !== undefined && data.marketingSubscriber !== contact.marketingSubscriber) {
changes.push({ name: "marketingSubscriber", booleanValue: data.marketingSubscriber });
}
if (changes.length === 0) {
return [];
}
await RowValueService.update({
entity: contactsEntity,
row,
values: changes,
session: { tenantId: row.tenantId },
checkPermissions: false,
options: {
createEvent: options?.createEvent,
},
});
return changes;
}
async function subscribeToNewsletter({
firstName,
lastName,
email,
source,
request,
}: {
firstName: string;
lastName: string;
email: string;
source?: string;
request: Request;
}) {
const settings = await getNewsletterFormSettings();
if (!settings.crm) {
return { error: i18nT("crm.newsletter.errors.integrationMissing") };
}
if (settings.crm) {
// Note: never log raw email/firstName/lastName here — those are PII.
crmLogger.info({ op: "newsletter.createContact", hasSource: Boolean(source) }, "Creating newsletter contact in CRM");
let contact = await RowsApi.find({
entity: { name: "contact" },
tenantId: null,
properties: [{ name: "email", value: email }],
});
if (!contact) {
contact = await createContact({
tenantId: null,
firstName,
lastName,
email: email,
jobTitle: "",
status: "contact",
marketingSubscriber: true,
request,
});
if (source) {
await RowsApi.addTag({ row: contact, tag: { value: source, color: Colors.ORANGE } });
} else {
await RowsApi.addTag({ row: contact, tag: { value: "newsletter", color: Colors.ORANGE } });
}
} else {
await updateContact(contact.id, { marketingSubscriber: true });
}
}
return { success: i18nT("crm.newsletter.subscribed") };
}
function rowToContact({ row, entity }: { row: RowWithDetails; entity: EntityWithDetails }) {
const email = RowValueHelper.getText({ entity, row, name: "email" }) ?? "";
const firstName = RowValueHelper.getText({ entity, row, name: "firstName" }) ?? "";
const lastName = RowValueHelper.getText({ entity, row, name: "lastName" }) ?? "";
const jobTitle = RowValueHelper.getText({ entity, row, name: "jobTitle" }) ?? "";
const marketingSubscriber = RowValueHelper.getBoolean({ entity, row, name: "marketingSubscriber" }) ?? false;
const companyRow = row.parentRows.find((f) => f.parent.entityId === entity.id)?.parent;
let company: { name: string } | undefined = undefined;
if (companyRow) {
company = {
name: RowValueHelper.getText({ entity, row: companyRow, name: "name" }) ?? "",
};
}
return {
id: row.id,
email,
firstName,
lastName,
jobTitle,
marketingSubscriber,
company,
};
}
export type UserInCrmDto = {
status: "synced" | "to-create" | "to-update";
email: string;
source: "user";
id: string;
firstName: string;
lastName: string;
isContact: boolean;
contact: ContactDto | null;
updatedAt: Date | null;
};
// EU-Sterilisation (R-P1a): invalidateCache wurde nur vom ConvertKit-Sync genutzt und bleibt als
// no-op-Parameter in der Signatur, damit Aufrufer (Admin-CRM-Sync) unverändert funktionieren.
async function getUsersInCrm(_options: { invalidateCache?: boolean } = {}): Promise<UserInCrmDto[]> {
const contacts = await getContacts(null);
let usersInCrm: UserInCrmDto[] = [];
usersInCrm.push(...(await loadFromUsers({ contacts })));
// filter by not contacts first, then by updated date desc
usersInCrm = usersInCrm.sort((a, b) => {
if (a.isContact && !b.isContact) {
return 1;
} else if (!a.isContact && b.isContact) {
return -1;
} else if (a.updatedAt && b.updatedAt) {
return b.updatedAt.getTime() - a.updatedAt.getTime();
} else if (a.updatedAt) {
return -1;
} else if (b.updatedAt) {
return 1;
}
return 0;
});
return usersInCrm;
}
async function loadFromUsers({ contacts }: { contacts: ContactDto[] }) {
let usersInCrm: UserInCrmDto[] = [];
// Read-only enumeration of users for CRM sync display — eventually-consistent
// is fine here. The sync action itself runs in a separate request that uses
// the write client.
const users = await dbRead.user.findMany({});
users.forEach((user) => {
const contact = contacts.find((f) => f.email === user.email) ?? null;
let status: "synced" | "to-create" | "to-update" = "synced";
if (!contact) {
status = "to-create";
} else if (contact.firstName !== user.firstName || contact.lastName !== user.lastName) {
status = "to-update";
}
const userInCrm: UserInCrmDto = {
status,
email: user.email,
source: "user",
id: user.id,
firstName: user.firstName,
lastName: user.lastName,
updatedAt: user.updatedAt,
isContact: !!contact,
contact,
};
usersInCrm.push(userInCrm);
});
return usersInCrm;
}
export default {
validate,
getContactsInRowIds,
getContact,
getContacts,
getContactFormSettings,
getNewsletterFormSettings,
getSummary,
createCompany,
createContact,
createSubmission,
createContactSubmission,
updateContact,
subscribeToNewsletter,
getUsersInCrm,
};
@@ -1,280 +0,0 @@
import { DefaultEntityTypes } from "~/application/dtos/shared/DefaultEntityTypes";
import { PropertyType } from "~/application/enums/entities/PropertyType";
import type { TemplateEntityPropertyTypeDto } from "~/modules/templates/EntityTemplateDto";
import { CRM_ENTITIES_TEMPLATE } from "~/modules/templates/defaultEntityTemplates";
import { db } from "~/utils/db.server";
import { createEntity } from "~/utils/db/entities/entities.db.server";
import { createProperties, type CreatePropertyDto } from "~/utils/db/entities/properties.db.server";
import { DefaultAdminRoles } from "~/application/dtos/shared/DefaultAdminRoles";
import { DefaultAppRoles } from "~/application/dtos/shared/DefaultAppRoles";
import { DefaultPermission } from "~/application/dtos/shared/DefaultPermissions";
import { getEntityPermissions } from "~/utils/helpers/PermissionsHelper";
export const productCoreCrmEntityNames = ["company", "contact", "opportunity"] as const;
export async function ensureProductCoreCrmEntities(options: { ensurePermissions?: boolean; ensureViews?: boolean } = {}) {
assertProductCoreCrmTemplateLanguage();
const ensurePermissions = options.ensurePermissions ?? false;
const ensureViews = options.ensureViews ?? false;
const existingEntities = await db.entity.findMany({
where: { name: { in: [...productCoreCrmEntityNames] } },
select: { id: true, name: true, type: true },
});
const existingNames = new Set(existingEntities.map((entity) => entity.name));
const missingNames = productCoreCrmEntityNames.filter((name) => !existingNames.has(name));
if (missingNames.length > 0) {
for (const entityTemplate of CRM_ENTITIES_TEMPLATE.entities.filter((entity) => missingNames.includes(entity.name as (typeof productCoreCrmEntityNames)[number]))) {
const entity = await createEntity({
name: entityTemplate.name,
slug: entityTemplate.slug,
prefix: entityTemplate.prefix,
title: entityTemplate.title,
titlePlural: entityTemplate.titlePlural,
isAutogenerated: entityTemplate.isAutogenerated ?? true,
hasApi: entityTemplate.hasApi ?? true,
icon: entityTemplate.icon ?? "",
active: entityTemplate.active ?? true,
type: DefaultEntityTypes.All,
showInSidebar: false,
hasTags: entityTemplate.hasTags ?? true,
hasComments: entityTemplate.hasComments ?? true,
hasTasks: entityTemplate.hasTasks ?? false,
hasActivity: entityTemplate.hasActivity ?? true,
hasBulkDelete: entityTemplate.hasBulkDelete ?? false,
hasViews: entityTemplate.hasViews ?? true,
defaultVisibility: entityTemplate.defaultVisibility ?? "tenant",
onCreated: entityTemplate.onCreated ?? "redirectToOverview",
onEdit: entityTemplate.onEdit ?? "editRoute",
});
await createProperties(
entity.id,
entityTemplate.properties.map((property): CreatePropertyDto => ({
name: property.name,
title: property.title,
type: toProductCorePropertyType(property.type),
subtype: property.subtype ?? null,
isRequired: property.isRequired,
isDisplay: property.isDisplay,
isReadOnly: property.isReadOnly,
canUpdate: property.canUpdate,
showInCreate: property.showInCreate,
tenantId: property.tenantId ?? null,
options: property.options?.map((option, index) => ({
order: index + 1,
value: option.value,
name: option.name,
color: option.color,
})),
attributes: property.attributes,
}))
);
}
}
await db.entity.updateMany({
where: { name: { in: [...productCoreCrmEntityNames] }, type: DefaultEntityTypes.AdminOnly },
data: {
type: DefaultEntityTypes.All,
active: true,
showInSidebar: false,
},
});
if (ensureViews) {
await ensureProductCoreCrmViewsAndRelationships();
}
if (ensurePermissions) {
await ensureProductCoreCrmPermissions();
}
}
function assertProductCoreCrmTemplateLanguage() {
if (CRM_ENTITIES_TEMPLATE.defaultLanguage !== "en" || !CRM_ENTITIES_TEMPLATE.languages.includes("en")) {
throw new Error("Product core CRM defaults are language-scoped English seed data.");
}
}
async function ensureProductCoreCrmViewsAndRelationships() {
const entities = await db.entity.findMany({
where: { name: { in: [...productCoreCrmEntityNames] }, active: true },
include: {
properties: true,
views: {
where: { tenantId: null, userId: null },
include: { properties: true },
orderBy: { order: "asc" },
},
},
});
const entityByName = new Map(entities.map((entity) => [entity.name, entity]));
for (const entity of entities) {
const entityTemplate = CRM_ENTITIES_TEMPLATE.entities.find((template) => template.name === entity.name);
if (!entityTemplate) {
continue;
}
const existingViewNames = new Set(entity.views.map((view) => view.name));
const hasDefaultView = entity.views.some((view) => view.isDefault);
const viewTemplates =
entityTemplate.views && entityTemplate.views.length > 0
? entityTemplate.views
: [
{
layout: "table" as const,
name: "all",
title: entity.titlePlural,
isDefault: true,
properties: getDefaultViewPropertyNames(entityTemplate),
},
];
let nextOrder = entity.views.length + 1;
for (const [index, viewTemplate] of viewTemplates.entries()) {
if (existingViewNames.has(viewTemplate.name)) {
continue;
}
const groupByPropertyId = viewTemplate.groupByProperty
? (entity.properties.find((property) => property.name === viewTemplate.groupByProperty)?.id ?? null)
: null;
const view = await db.entityView.create({
data: {
entityId: entity.id,
tenantId: null,
userId: null,
createdByUserId: null,
layout: viewTemplate.layout,
order: viewTemplate.order ?? nextOrder++,
name: viewTemplate.name,
title: viewTemplate.title,
isDefault: viewTemplate.isDefault ?? (!hasDefaultView && index === 0),
isSystem: viewTemplate.isSystem ?? false,
pageSize: viewTemplate.pageSize ?? 100,
groupByPropertyId,
},
});
await Promise.all(
viewTemplate.properties.map((propertyName, propertyIndex) =>
db.entityViewProperty.create({
data: {
entityViewId: view.id,
propertyId: entity.properties.find((property) => property.name === propertyName)?.id ?? null,
name: propertyName,
order: propertyIndex + 1,
},
})
)
);
await Promise.all(
(viewTemplate.filters ?? []).map((filter) =>
db.entityViewFilter.create({
data: {
entityViewId: view.id,
name: filter.name,
condition: filter.condition,
value: filter.value,
match: filter.match ?? "and",
},
})
)
);
await Promise.all(
(viewTemplate.sort ?? []).map((sort, sortIndex) =>
db.entityViewSort.create({
data: {
entityViewId: view.id,
name: sort.name,
asc: sort.asc,
order: sortIndex + 1,
},
})
)
);
}
}
for (const relationship of CRM_ENTITIES_TEMPLATE.relationships) {
const parent = entityByName.get(relationship.parent);
const child = entityByName.get(relationship.child);
if (!parent || !child) {
continue;
}
const existing = await db.entityRelationship.findFirst({
where: { parentId: parent.id, childId: child.id, title: relationship.title ?? null },
select: { id: true },
});
if (existing) {
continue;
}
await db.entityRelationship.create({
data: {
parentId: parent.id,
childId: child.id,
order: relationship.order,
title: relationship.title ?? null,
type: relationship.type,
required: relationship.required,
cascade: relationship.cascade ?? false,
readOnly: relationship.readOnly ?? false,
hiddenIfEmpty: relationship.hiddenIfEmpty ?? false,
},
});
}
}
function getDefaultViewPropertyNames(entityTemplate: (typeof CRM_ENTITIES_TEMPLATE.entities)[number]) {
const displayProperties = entityTemplate.properties.filter((property) => property.isDisplay).map((property) => property.name);
if (displayProperties.length > 0) {
return displayProperties;
}
return entityTemplate.properties.slice(0, 4).map((property) => property.name);
}
async function ensureProductCoreCrmPermissions() {
const { createPermissions } = await import("~/utils/db/permissions/permissions.db.server");
const entities = await db.entity.findMany({
where: { name: { in: [...productCoreCrmEntityNames] }, active: true },
});
let order = 0;
for (const entity of entities) {
const entityPermissions = getEntityPermissions(entity);
await createPermissions(
entityPermissions.map((permission) => ({
inRoles: [DefaultAdminRoles.SuperAdmin, DefaultAppRoles.SuperUser, DefaultAppRoles.Admin, DefaultAppRoles.User].map((role) => role.toString()),
name: permission.name as DefaultPermission,
description: permission.description,
type: entity.type,
})),
order
);
order += entityPermissions.length;
}
}
function toProductCorePropertyType(type: TemplateEntityPropertyTypeDto): PropertyType {
switch (type) {
case "string":
return PropertyType.TEXT;
case "number":
return PropertyType.NUMBER;
case "boolean":
return PropertyType.BOOLEAN;
case "date":
return PropertyType.DATE;
case "media":
return PropertyType.MEDIA;
case "select":
return PropertyType.SELECT;
case "multiSelect":
return PropertyType.MULTI_SELECT;
case "multiText":
return PropertyType.MULTI_TEXT;
case "rangeNumber":
return PropertyType.RANGE_NUMBER;
case "rangeDate":
return PropertyType.RANGE_DATE;
case "formula":
return PropertyType.FORMULA;
}
}
@@ -1,163 +0,0 @@
/**
* CRM-contacts public search — hot-path migration to Meilisearch.
*
* Wraps `searchWithFallback({ index: 'crm-contacts', tenantId, query,
* fallback })` so consumers of the contact list / contact filter can
* adopt the typed client without further refactors. When MEILI_URL is
* unset, or SEARCH_BACKEND=sql is forced, or Meilisearch raises a
* connectivity error, the helper transparently falls back to a
* SQL ILIKE-against-RowValue scan over the contact entity.
*
* Contacts are stored as rows with `entityName = "contact"`; the SQL
* fallback therefore reuses the legacy row-search code-path so the
* shape returned from both backends is the same set of `Row` IDs that
* the caller can hydrate via the existing rows.db.server helpers.
*/
import {
createSearchClient,
crmContactsIndex,
searchWithFallback,
type SearchClient,
type SearchFallback,
type SearchHits,
} from "@toolctrl/search";
import { db } from "~/utils/db.server";
let cachedClient: SearchClient | undefined;
let cachedUrl: string | undefined;
function getSearchClient(): SearchClient | undefined {
const url = process.env.MEILI_URL;
if (!url || process.env.SEARCH_BACKEND === "sql") return undefined;
if (cachedClient && cachedUrl === url) return cachedClient;
cachedClient = createSearchClient({ url, apiKey: process.env.MEILI_API_KEY ?? undefined });
cachedUrl = url;
return cachedClient;
}
export interface SearchCrmContactsInput {
/** Tenant scope — REQUIRED for the Meilisearch path. The SQL
* fallback also scopes by tenantId. */
readonly tenantId: string;
/** User-supplied query string. Empty string returns the first page. */
readonly query: string;
/** Optional cap on result count. Defaults to 50. */
readonly limit?: number;
}
export interface CrmContactSearchHit {
readonly id: string;
readonly firstName: string;
readonly lastName: string;
readonly email: string;
readonly company: string;
readonly jobTitle: string;
}
export interface CrmContactSearchResult {
readonly hits: readonly CrmContactSearchHit[];
readonly total: number;
readonly fellBack: boolean;
}
/**
* SQL fallback — uses RowValue text-search joined to the `contact`
* entity. Returns the same hit-shape Meilisearch returns so the caller
* doesn't have to branch.
*/
async function sqlFallback(input: SearchCrmContactsInput): Promise<SearchHits> {
const limit = input.limit ?? 50;
const q = input.query.trim();
const where: Record<string, unknown> = {
tenantId: input.tenantId,
deletedAt: null,
entity: { name: "contact" },
};
if (q.length > 0) {
where.values = {
some: {
textValue: { contains: q, mode: "insensitive" },
},
};
}
const rows = await db.row.findMany({
where: where as never,
take: limit,
orderBy: [{ createdAt: "desc" }],
select: {
id: true,
values: {
select: {
textValue: true,
property: { select: { name: true } },
},
},
},
});
return {
hits: rows.map((row) => {
const get = (name: string): string => {
const v = row.values.find((vv) => vv.property?.name === name);
return v?.textValue ?? "";
};
return {
document: {
id: row.id,
tenantId: input.tenantId,
firstName: get("firstName"),
lastName: get("lastName"),
email: get("email"),
company: get("company"),
jobTitle: get("jobTitle"),
} as Record<string, unknown> & { id: string; tenantId: string },
};
}),
estimatedTotalHits: rows.length,
processingTimeMs: 0,
};
}
export async function searchCrmContacts(input: SearchCrmContactsInput): Promise<CrmContactSearchResult> {
const fallback: SearchFallback = async () => sqlFallback(input);
const client = getSearchClient();
if (!client) {
const sql = await sqlFallback(input);
return {
hits: sql.hits.map((hit) => toContactHit(hit.document)),
total: sql.estimatedTotalHits ?? sql.hits.length,
fellBack: true,
};
}
let fellBack = false;
const hits = await searchWithFallback({
client,
schema: crmContactsIndex,
tenantId: input.tenantId,
query: input.query,
fallback,
onFallback: () => {
fellBack = true;
},
options: { limit: input.limit ?? 50 },
});
return {
hits: hits.hits.map((hit) => toContactHit(hit.document)),
total: hits.estimatedTotalHits ?? hits.hits.length,
fellBack,
};
}
function toContactHit(document: Record<string, unknown>): CrmContactSearchHit {
return {
id: String(document.id ?? ""),
firstName: typeof document.firstName === "string" ? document.firstName : "",
lastName: typeof document.lastName === "string" ? document.lastName : "",
email: typeof document.email === "string" ? document.email : "",
company: typeof document.company === "string" ? document.company : "",
jobTitle: typeof document.jobTitle === "string" ? document.jobTitle : "",
};
}
@@ -1,112 +0,0 @@
/**
* Unit tests for searchCrmContacts — the public CRM-contacts search
* entry-point. These tests cover the SQL-fallback path (when MEILI_URL
* is unset) so the legacy SQL contract is exercised without requiring
* a live Meilisearch container.
*/
import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("~/utils/db.server", () => ({
db: {
row: {
findMany: vi.fn(),
},
},
}));
import { db } from "~/utils/db.server";
import { searchCrmContacts } from "./crmContactSearch.server";
const dbMock = db as unknown as {
row: {
findMany: ReturnType<typeof vi.fn>;
};
};
describe("searchCrmContacts (sql fallback)", () => {
const originalMeili = process.env.MEILI_URL;
const originalBackend = process.env.SEARCH_BACKEND;
beforeEach(() => {
delete process.env.MEILI_URL;
delete process.env.SEARCH_BACKEND;
dbMock.row.findMany.mockReset();
});
afterEachRestore(originalMeili, originalBackend);
it("scopes by tenant + entity=contact and maps row values to contact-hit fields", async () => {
dbMock.row.findMany.mockResolvedValueOnce([
{
id: "row-1",
values: [
{ textValue: "Alice", property: { name: "firstName" } },
{ textValue: "Anderson", property: { name: "lastName" } },
{ textValue: "alice@example.com", property: { name: "email" } },
{ textValue: "Acme", property: { name: "company" } },
{ textValue: "CTO", property: { name: "jobTitle" } },
],
},
]);
const result = await searchCrmContacts({ tenantId: "tenant-1", query: "alice" });
expect(dbMock.row.findMany).toHaveBeenCalledTimes(1);
const where = dbMock.row.findMany.mock.calls[0][0].where as Record<string, unknown>;
expect(where.tenantId).toBe("tenant-1");
expect((where.entity as { name: string }).name).toBe("contact");
expect(where.deletedAt).toBeNull();
expect(where.values).toBeDefined();
expect(result.fellBack).toBe(true);
expect(result.hits).toHaveLength(1);
expect(result.hits[0]).toEqual({
id: "row-1",
firstName: "Alice",
lastName: "Anderson",
email: "alice@example.com",
company: "Acme",
jobTitle: "CTO",
});
});
it("omits the value-text predicate when the query is empty", async () => {
dbMock.row.findMany.mockResolvedValueOnce([]);
await searchCrmContacts({ tenantId: "tenant-1", query: "" });
const where = dbMock.row.findMany.mock.calls[0][0].where as Record<string, unknown>;
expect(where.values).toBeUndefined();
});
it("honours the limit option", async () => {
dbMock.row.findMany.mockResolvedValueOnce([]);
await searchCrmContacts({ tenantId: "tenant-1", query: "x", limit: 5 });
expect(dbMock.row.findMany.mock.calls[0][0].take).toBe(5);
});
it("returns total = number of fallback hits when Meilisearch is unavailable", async () => {
dbMock.row.findMany.mockResolvedValueOnce([
{ id: "r1", values: [] },
{ id: "r2", values: [] },
{ id: "r3", values: [] },
]);
const result = await searchCrmContacts({ tenantId: "tenant-1", query: "" });
expect(result.total).toBe(3);
expect(result.hits).toHaveLength(3);
});
});
function afterEachRestore(originalMeili: string | undefined, originalBackend: string | undefined) {
// restore env vars after the file completes (vitest doesn't gather them
// via beforeEach, so we centralize the cleanup here)
if (typeof afterAll === "function") {
afterAll(() => {
if (originalMeili === undefined) delete process.env.MEILI_URL;
else process.env.MEILI_URL = originalMeili;
if (originalBackend === undefined) delete process.env.SEARCH_BACKEND;
else process.env.SEARCH_BACKEND = originalBackend;
});
}
}
@@ -1,4 +1,4 @@
import { loadWebConfig } from "@toolctrl/config";
import { loadWebConfig } from "@hivegrid/config";
import { AppConfiguration, getAppConfiguration } from "~/utils/db/appConfiguration.db.server";
import FlyDomainsServer from "./FlyDomains.server";
import { GetCertDto } from "../dtos/GetCertDto";
@@ -0,0 +1,379 @@
// VA-P23 · email-inbox DB access (thin Prisma wrappers). Reads are tenant-scoped
// and — for read_own callers — owner-scoped (M09 Block I). Token ciphertext
// columns are NEVER selected into these read shapes; only the connect/refresh
// services touch them. The two webhook lookups at the bottom are the DOCUMENTED
// cross-tenant exceptions (provider pushes carry no tenant context) — mirrors
// calendar.db.server.findConnectionByWebhookSubscription.
import { db } from "~/utils/db.server";
/** Mailbox fields safe to surface (no token ciphertext, no clientState). */
export type EmailMailboxListRow = {
id: string;
ownerUserId: string;
provider: "gmail" | "microsoft";
emailAddress: string;
displayName: string | null;
isDefaultForUser: boolean;
status: "connecting" | "active" | "paused" | "error" | "revoked";
lastSyncAt: Date | null;
lastErrorText: string | null;
webhookSubscriptionExpiresAt: Date | null;
};
const MAILBOX_SAFE_SELECT = {
id: true,
ownerUserId: true,
provider: true,
emailAddress: true,
displayName: true,
isDefaultForUser: true,
status: true,
lastSyncAt: true,
lastErrorText: true,
webhookSubscriptionExpiresAt: true,
} as const;
/** The current user's own mailboxes (newest first). */
export async function listMailboxesForUser(tenantId: string, ownerUserId: string): Promise<EmailMailboxListRow[]> {
return db.emailIntegrationMailbox.findMany({
where: { tenantId, ownerUserId, archivedAt: null },
select: MAILBOX_SAFE_SELECT,
orderBy: { createdAt: "desc" },
}) as unknown as Promise<EmailMailboxListRow[]>;
}
/** Every tenant mailbox (read_all surface). */
export async function listMailboxesForTenant(tenantId: string): Promise<EmailMailboxListRow[]> {
return db.emailIntegrationMailbox.findMany({
where: { tenantId, archivedAt: null },
select: MAILBOX_SAFE_SELECT,
orderBy: { createdAt: "desc" },
}) as unknown as Promise<EmailMailboxListRow[]>;
}
/** One mailbox by id (tenant-scoped). Returns ownerUserId so the route owner-checks. */
export async function getMailboxForTenant(tenantId: string, mailboxId: string): Promise<EmailMailboxListRow | null> {
return db.emailIntegrationMailbox.findFirst({
where: { id: mailboxId, tenantId, archivedAt: null },
select: MAILBOX_SAFE_SELECT,
}) as unknown as Promise<EmailMailboxListRow | null>;
}
/** Initial-sync progress rows for the settings screen (per folder). */
export type EmailSyncCursorRow = {
mailboxId: string;
externalFolderId: string;
initialSyncStatus: "pending" | "running" | "completed" | "failed";
initialSyncProgress: unknown;
lastCursorAdvanceAt: Date | null;
errorText: string | null;
};
export async function listSyncCursorsForMailboxes(tenantId: string, mailboxIds: readonly string[]): Promise<EmailSyncCursorRow[]> {
if (mailboxIds.length === 0) {
return [];
}
return db.emailIntegrationSyncCursor.findMany({
where: { tenantId, mailboxId: { in: [...mailboxIds] } },
select: {
mailboxId: true,
externalFolderId: true,
initialSyncStatus: true,
initialSyncProgress: true,
lastCursorAdvanceAt: true,
errorText: true,
},
}) as unknown as Promise<EmailSyncCursorRow[]>;
}
/** List-row projection of a mirrored message (NO bodies — snippet only). */
export type EmailMessageListRow = {
id: string;
mailboxId: string;
direction: "inbound" | "outbound";
fromAddress: string;
fromName: string | null;
subject: string | null;
snippet: string | null;
sentAt: Date;
isRead: boolean;
hasAttachments: boolean;
isNewsletter: boolean;
matchedKontaktId: string | null;
matchedLeadId: string | null;
matchedProjektId: string | null;
};
export interface ListMessagesFilter {
mailboxIds: readonly string[];
onlyMailboxId?: string | null;
direction?: "inbound" | "outbound" | null;
linked?: "linked" | "unlinked" | null;
read?: "read" | "unread" | null;
q?: string | null;
showArchived?: boolean;
/** Keyset cursor: rows strictly older than (sentAt, id). */
cursor?: { sentAt: Date; id: string } | null;
take: number;
}
/**
* Server-side inbox list (M09 Block F): filters + trigram-ish search (ILIKE on
* subject/from/bodyText — v1) + keyset pagination on (sentAt DESC, id DESC).
* `mailboxIds` is the caller's VISIBILITY set (read_own → own mailboxes only).
*/
export async function listMessagesForMailboxes(tenantId: string, filter: ListMessagesFilter): Promise<EmailMessageListRow[]> {
if (filter.mailboxIds.length === 0) {
return [];
}
const mailboxScope = filter.onlyMailboxId && filter.mailboxIds.includes(filter.onlyMailboxId) ? [filter.onlyMailboxId] : [...filter.mailboxIds];
const where: Record<string, unknown> = {
tenantId,
mailboxId: { in: mailboxScope },
...(filter.showArchived ? {} : { archivedAt: null }),
...(filter.direction ? { direction: filter.direction } : {}),
...(filter.read ? { isRead: filter.read === "read" } : {}),
};
if (filter.linked === "linked") {
where.OR = [{ matchedKontaktId: { not: null } }, { matchedLeadId: { not: null } }, { matchedProjektId: { not: null } }];
} else if (filter.linked === "unlinked") {
where.AND = [{ matchedKontaktId: null }, { matchedLeadId: null }, { matchedProjektId: null }];
}
if (filter.q) {
const q = filter.q;
where.OR = [
...((where.OR as unknown[] | undefined) ?? []),
{ subject: { contains: q, mode: "insensitive" } },
{ fromAddress: { contains: q, mode: "insensitive" } },
{ fromName: { contains: q, mode: "insensitive" } },
{ bodyText: { contains: q, mode: "insensitive" } },
];
}
if (filter.cursor) {
where.AND = [
...((where.AND as unknown[] | undefined) ?? []),
{
OR: [{ sentAt: { lt: filter.cursor.sentAt } }, { sentAt: filter.cursor.sentAt, id: { lt: filter.cursor.id } }],
},
];
}
return db.emailIntegrationMessage.findMany({
where: where as never,
select: {
id: true,
mailboxId: true,
direction: true,
fromAddress: true,
fromName: true,
subject: true,
snippet: true,
sentAt: true,
isRead: true,
hasAttachments: true,
isNewsletter: true,
matchedKontaktId: true,
matchedLeadId: true,
matchedProjektId: true,
},
orderBy: [{ sentAt: "desc" }, { id: "desc" }],
take: filter.take,
}) as unknown as Promise<EmailMessageListRow[]>;
}
/** Full detail projection of one mirrored message (bodies included). */
export type EmailMessageDetailRow = EmailMessageListRow & {
providerMessageId: string;
providerThreadId: string | null;
internetMessageId: string | null;
toAddresses: unknown;
ccAddresses: unknown;
bodyHtml: string | null;
bodyText: string | null;
receivedAt: Date | null;
matchConfidence: "high" | "medium" | "low" | "manual" | "none";
manualOverrideAt: Date | null;
manualOverrideUserId: string | null;
archivedAt: Date | null;
};
const MESSAGE_DETAIL_SELECT = {
id: true,
mailboxId: true,
providerMessageId: true,
providerThreadId: true,
internetMessageId: true,
direction: true,
fromAddress: true,
fromName: true,
toAddresses: true,
ccAddresses: true,
subject: true,
snippet: true,
bodyHtml: true,
bodyText: true,
sentAt: true,
receivedAt: true,
isRead: true,
hasAttachments: true,
isNewsletter: true,
matchedKontaktId: true,
matchedLeadId: true,
matchedProjektId: true,
matchConfidence: true,
manualOverrideAt: true,
manualOverrideUserId: true,
archivedAt: true,
} as const;
/** One message (tenant + visibility scoped by the caller's mailbox set). */
export async function getMessageForMailboxes(tenantId: string, mailboxIds: readonly string[], messageId: string): Promise<EmailMessageDetailRow | null> {
if (mailboxIds.length === 0) {
return null;
}
return db.emailIntegrationMessage.findFirst({
where: { id: messageId, tenantId, mailboxId: { in: [...mailboxIds] } },
select: MESSAGE_DETAIL_SELECT,
}) as unknown as Promise<EmailMessageDetailRow | null>;
}
/** All messages of the thread, chronological (M09 Block F detail). */
export async function listThreadMessages(
tenantId: string,
mailboxIds: readonly string[],
providerThreadId: string,
): Promise<EmailMessageDetailRow[]> {
if (mailboxIds.length === 0) {
return [];
}
return db.emailIntegrationMessage.findMany({
where: { tenantId, mailboxId: { in: [...mailboxIds] }, providerThreadId },
select: MESSAGE_DETAIL_SELECT,
orderBy: [{ sentAt: "asc" }, { id: "asc" }],
}) as unknown as Promise<EmailMessageDetailRow[]>;
}
/**
* Manual link override (M09 Block E): the user's assignment wins and blocks any
* re-match. Passing all-null targets CLEARS the link (still an override).
*/
export async function setMessageMatchOverride(
tenantId: string,
mailboxIds: readonly string[],
messageId: string,
byUserId: string,
targets: { kontaktId: string | null; leadId: string | null; projektId: string | null },
): Promise<{ count: number }> {
return db.emailIntegrationMessage.updateMany({
where: { id: messageId, tenantId, mailboxId: { in: [...mailboxIds] } },
data: {
matchedKontaktId: targets.kontaktId,
matchedLeadId: targets.leadId,
matchedProjektId: targets.projektId,
matchConfidence: "manual",
manualOverrideAt: new Date(),
manualOverrideUserId: byUserId,
},
});
}
/** Files already imported for a message (FileEntityLink entityType email_message). */
export async function listImportedAttachmentFiles(
tenantId: string,
messageId: string,
): Promise<Array<{ fileId: string; displayName: string; sizeBytes: number; mimeType: string }>> {
const links = await db.fileEntityLink.findMany({
where: { tenantId, entityType: "email_message", entityId: messageId },
select: { fileId: true },
});
if (links.length === 0) {
return [];
}
const files = await db.file.findMany({
where: { tenantId, id: { in: links.map((l) => l.fileId) }, archivedAt: null },
select: { id: true, displayName: true, sizeBytes: true, mimeType: true },
});
return files.map((f) => ({ fileId: f.id, displayName: f.displayName, sizeBytes: Number(f.sizeBytes), mimeType: f.mimeType }));
}
/** Bulk read/unread + HiveGrid-side archive (provider untouched by archive). */
export async function bulkUpdateMessages(
tenantId: string,
mailboxIds: readonly string[],
messageIds: readonly string[],
patch: { isRead?: boolean; archived?: boolean },
): Promise<{ count: number }> {
if (messageIds.length === 0 || mailboxIds.length === 0) {
return { count: 0 };
}
return db.emailIntegrationMessage.updateMany({
where: { tenantId, mailboxId: { in: [...mailboxIds] }, id: { in: [...messageIds] } },
data: {
...(patch.isRead !== undefined ? { isRead: patch.isRead } : {}),
...(patch.archived !== undefined ? { archivedAt: patch.archived ? new Date() : null } : {}),
},
});
}
/** Provider ids of messages (for the read-state write-back to the provider). */
export async function getProviderMessageRefs(
tenantId: string,
mailboxIds: readonly string[],
messageIds: readonly string[],
): Promise<Array<{ id: string; mailboxId: string; providerMessageId: string }>> {
if (messageIds.length === 0) {
return [];
}
return db.emailIntegrationMessage.findMany({
where: { tenantId, mailboxId: { in: [...mailboxIds] }, id: { in: [...messageIds] } },
select: { id: true, mailboxId: true, providerMessageId: true },
});
}
/**
* Resolve the mailbox a Microsoft Graph notification belongs to. The webhook
* entrypoint has NO tenant context (Microsoft calls a fixed URL), so this is a
* deliberate cross-tenant lookup by the stored subscription id; the caller then
* scopes every follow-up to the returned tenantId and MUST verify clientState.
*/
export async function findMailboxByWebhookSubscription(
subscriptionId: string,
): Promise<{ id: string; tenantId: string; ownerUserId: string; webhookClientState: string | null } | null> {
return db.emailIntegrationMailbox.findFirst({
where: { webhookSubscriptionId: subscriptionId, archivedAt: null },
select: { id: true, tenantId: true, ownerUserId: true, webhookClientState: true },
});
}
/**
* Resolve the mailbox a Gmail Pub/Sub push belongs to. Gmail pushes carry only
* `{emailAddress, historyId}` — a deliberate cross-tenant lookup by address
* (mirrors the calendar webhook exception; endpoint auth = shared token).
*/
export async function findMailboxByEmailAddress(
provider: "gmail" | "microsoft",
emailAddress: string,
): Promise<{ id: string; tenantId: string; ownerUserId: string } | null> {
return db.emailIntegrationMailbox.findFirst({
where: { provider, emailAddress: emailAddress.toLowerCase(), archivedAt: null },
select: { id: true, tenantId: true, ownerUserId: true },
});
}
/** Persist an inbound provider push as pending (idempotency + retry). */
export async function recordEmailWebhookEvent(input: {
tenantId: string;
mailboxId: string;
provider: "gmail" | "microsoft";
notificationPayload: Record<string, unknown>;
}): Promise<void> {
await db.emailIntegrationWebhookEvent.create({
data: {
tenantId: input.tenantId,
mailboxId: input.mailboxId,
provider: input.provider,
notificationPayload: input.notificationPayload as never,
processingStatus: "pending",
},
});
}
@@ -0,0 +1,103 @@
// VA-P23 · shared loader/action guard for the email-inbox module (mirrors
// calendarAccess). The MODULE gate is the plan-gated `email-inbox` feature
// (tenantHasModule). Visibility (M09 Block I): `email.read_own` sees only
// mailboxes with ownerUserId = self, `email.read_all` sees every tenant mailbox,
// `email.write` composes/sends over the own mailbox. Module-off renders a locked
// empty VM on GET and 404s on write (Bauprinzip A.5.3); a permission miss is
// also a 404, never a 403.
import { CatalogError, foundationErrors } from "@hivegrid/foundation";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo } from "~/utils/session.server";
import { tenantHasModule } from "~/utils/connector/tenantConnector.server";
import { getPermissionsByUser } from "~/utils/db/permissions/userRoles.db.server";
import { EMAIL_INBOX_MODULE_KEY } from "./emailInboxRoutePaths";
/** Email-inbox atomic permissions (M09 Block I). */
export const EMAIL_PERMISSIONS = {
/** See mails of the user's OWN connected mailboxes (default tenant-user capability). */
readOwn: "email.read_own",
/** See every tenant mailbox's mails (tenant administration). */
readAll: "email.read_all",
/** Compose/send over the user's own connected mailbox. */
write: "email.write",
} as const;
export type EmailInboxRouteContext = {
tenantId: string;
userId: string;
permissions: readonly string[];
hasModule: boolean;
};
/**
* Resolve the email-inbox route context: auth + tenant + the email-inbox module
* gate + the user's permissions. With `requireModule` a module-off tenant 404s
* (write paths); GET paths can render a locked empty VM from `hasModule === false`.
*/
export async function loadEmailInboxContext({
request,
params,
requireModule = false,
}: {
request: Request;
params: Record<string, string | undefined>;
requireModule?: boolean;
}): Promise<EmailInboxRouteContext> {
await requireAuth({ request, params });
const [tenantId, userInfo] = await Promise.all([getTenantIdFromUrl(params), getUserInfo(request)]);
if (!tenantId || !userInfo.userId) {
throw new CatalogError(foundationErrors.notFound);
}
const [hasModule, permissions] = await Promise.all([
tenantHasModule({ tenantId, userId: userInfo.userId, moduleKey: EMAIL_INBOX_MODULE_KEY }),
getPermissionsByUser(userInfo.userId, tenantId),
]);
if (requireModule && !hasModule) {
throw new CatalogError(foundationErrors.notFound, { module: EMAIL_INBOX_MODULE_KEY });
}
return { tenantId, userId: userInfo.userId, permissions, hasModule };
}
/** True when the user may see EVERY tenant mailbox (read_all bundle). */
export function canReadAllMailboxes(ctx: EmailInboxRouteContext): boolean {
return ctx.permissions.includes(EMAIL_PERMISSIONS.readAll);
}
/** True when the user may see at least their own mailboxes. */
export function canReadOwnMailboxes(ctx: EmailInboxRouteContext): boolean {
return ctx.permissions.includes(EMAIL_PERMISSIONS.readOwn) || canReadAllMailboxes(ctx);
}
/** True when the user may compose/send over their own mailbox. */
export function canWriteEmail(ctx: EmailInboxRouteContext): boolean {
return ctx.permissions.includes(EMAIL_PERMISSIONS.write);
}
/** Require any read capability; 404 if missing (A.5.3). */
export function requireEmailRead(ctx: EmailInboxRouteContext): EmailInboxRouteContext {
if (!canReadOwnMailboxes(ctx)) {
throw new CatalogError(foundationErrors.notFound, { permission: EMAIL_PERMISSIONS.readOwn });
}
return ctx;
}
/** Require the write capability; 404 if missing (A.5.3). */
export function requireEmailWrite(ctx: EmailInboxRouteContext): EmailInboxRouteContext {
if (!canWriteEmail(ctx)) {
throw new CatalogError(foundationErrors.notFound, { permission: EMAIL_PERMISSIONS.write });
}
return ctx;
}
/**
* Owner-check for mailbox-scoped resources (M09 Block I): with only read_own the
* caller must own the mailbox; read_all lifts the restriction. Miss = 404.
*/
export function requireMailboxVisibility(ctx: EmailInboxRouteContext, mailboxOwnerUserId: string): EmailInboxRouteContext {
if (ctx.userId === mailboxOwnerUserId || canReadAllMailboxes(ctx)) {
return ctx;
}
throw new CatalogError(foundationErrors.notFound, { owner: "mismatch" });
}
@@ -0,0 +1,40 @@
// VA-P23 · pure client-safe route-path builders for the email-inbox module.
// Loaders build these and pass them into the VMs so the VMs stay routing-agnostic
// (mirrors calendarRoutePaths). Unlike calendar, the email inbox has its OWN
// plan-gated feature key (`email-inbox` in packages/entitlements) — the ticket
// names the connector gate tenantHasModule('email_inbox'); the canonical key is
// kebab-case per repo convention (documented deviation, VA-P23).
export const EMAIL_INBOX_MODULE_KEY = "email-inbox";
/** The inbox list. */
export function emailInboxPath(tenantSlug: string): string {
return `/${tenantSlug}/emails`;
}
/** A single message's thread detail. */
export function emailMessagePath(tenantSlug: string, messageId: string): string {
return `/${tenantSlug}/emails/${messageId}`;
}
/** The compose surface (new mail / reply / forward via query params). */
export function emailComposePath(tenantSlug: string): string {
return `/${tenantSlug}/emails/new`;
}
/** The mailbox connect settings. */
export function emailSettingsPath(tenantSlug: string): string {
return `/${tenantSlug}/settings/integrations/email`;
}
/**
* The OAuth callback URIs. NOT tenant-scoped (providers redirect to fixed URIs);
* the signed `state` carries the tenant + user + provider.
*/
export const GMAIL_OAUTH_CALLBACK_PATH = "/integrations/email/google/oauth/callback";
export const MICROSOFT_OAUTH_CALLBACK_PATH = "/integrations/email/microsoft/oauth/callback";
/** 404 helper (Bauprinzip A.5.3 — permission/owner miss renders 404, not 403). */
export function notFoundResponse(): Response {
return new Response("Not Found", { status: 404 });
}
@@ -0,0 +1,121 @@
// VA-P23 · attachment import (M09: "Anhänge landen in v1-Files", DoD 5).
//
// Attachments are imported LAZILY on user action (not eagerly during sync —
// Gmail base64 bodies are expensive and Graph >3 MB needs a $value stream):
// adapter download → private bucket via putBufferAsFile → `File` row (source
// `email_attachment`) + polymorphic FileEntityLink (entityType `email_message`).
// Delivery then runs through the normal Files auth-proxy. v1 size cap: 15 MB.
import { randomUUID } from "node:crypto";
import { buildFileStorageKeys } from "@hivegrid/storage";
import { putBufferAsFile, resolveStorageBucket } from "~/utils/integrations/storageService";
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
import { adapterForProvider, ensureFreshMailboxCreds, loadMailboxCreds } from "./MailboxConnectionService.server";
import type { EmailOAuthProvider } from "./oauthState.server";
export const EMAIL_ATTACHMENT_MAX_BYTES = 15 * 1024 * 1024;
export class EmailAttachmentError extends Error {
readonly code: "not_found" | "too_large" | "not_connected" | "provider_failed";
constructor(code: EmailAttachmentError["code"]) {
super(code);
this.name = "EmailAttachmentError";
this.code = code;
}
}
/** Provider-side attachment metadata for the detail view. */
export async function listProviderAttachments(input: {
tenantId: string;
mailboxId: string;
provider: EmailOAuthProvider;
providerMessageId: string;
}): Promise<Array<{ attachmentId: string; filename: string; mimeType: string | null; sizeBytes: number }>> {
const creds = await loadMailboxCreds(input.tenantId, input.mailboxId);
if (!creds) {
return [];
}
try {
const fresh = await ensureFreshMailboxCreds(input.tenantId, input.mailboxId, input.provider, creds);
return await adapterForProvider(input.provider).listAttachments(fresh, input.providerMessageId);
} catch {
return [];
}
}
/**
* Import ONE provider attachment into v1-Files and link it to the message.
* Idempotence: linkRole carries the provider attachment id — an existing link
* short-circuits to the already-imported file.
*/
export async function importAttachmentToFiles(input: {
tenantId: string;
userId: string;
mailboxId: string;
provider: EmailOAuthProvider;
messageId: string;
providerMessageId: string;
attachmentId: string;
}): Promise<{ fileId: string }> {
const existing = await withTenantRLS(input.tenantId, async (tx) => {
return tx.fileEntityLink.findFirst({
where: { tenantId: input.tenantId, entityType: "email_message", entityId: input.messageId, linkRole: `attachment:${input.attachmentId}` },
select: { fileId: true },
});
});
if (existing) {
return { fileId: existing.fileId };
}
const creds = await loadMailboxCreds(input.tenantId, input.mailboxId);
if (!creds) {
throw new EmailAttachmentError("not_connected");
}
const fresh = await ensureFreshMailboxCreds(input.tenantId, input.mailboxId, input.provider, creds);
const attachment = await adapterForProvider(input.provider)
.downloadAttachment(fresh, input.providerMessageId, input.attachmentId)
.catch(() => null);
if (!attachment) {
throw new EmailAttachmentError("not_found");
}
const body = Buffer.from(attachment.contentBase64, "base64");
if (body.byteLength > EMAIL_ATTACHMENT_MAX_BYTES) {
throw new EmailAttachmentError("too_large");
}
const fileId = `file_${randomUUID()}`;
const { original: storageKey } = buildFileStorageKeys(input.tenantId, fileId);
await putBufferAsFile({
bucket: resolveStorageBucket(),
key: storageKey,
body,
contentType: attachment.mimeType ?? "application/octet-stream",
});
await withTenantRLS(input.tenantId, async (tx) => {
await tx.file.create({
data: {
id: fileId,
tenantId: input.tenantId,
createdByUserId: input.userId,
displayName: attachment.filename.slice(0, 255),
mimeType: attachment.mimeType ?? "application/octet-stream",
sizeBytes: body.byteLength,
storageKey,
source: "email_attachment",
scanStatus: "pending",
previewStatus: "pending",
},
});
await tx.fileEntityLink.create({
data: {
tenantId: input.tenantId,
createdByUserId: input.userId,
fileId,
entityType: "email_message",
entityId: input.messageId,
linkRole: `attachment:${input.attachmentId}`,
},
});
});
return { fileId };
}
@@ -0,0 +1,173 @@
// VA-P23 · outbound send over the user's OWN mailbox (M09 Block G, DoD 4c).
//
// The send path goes through the provider adapter (Gmail messages.send with
// threadId + In-Reply-To/References; Graph sendMail → 202 without an id). After
// a successful send the message is mirrored locally as direction=outbound —
// for Graph the sent-items delta later collapses onto this mirror via
// internetMessageId. Provider errors surface as Klartext codes (M002).
import { randomUUID } from "node:crypto";
import { GmailError, GraphMailError, type MappedEmailMessage } from "@hivegrid/integrations";
import { logActivity } from "@hivegrid/activity";
import { db } from "~/utils/db.server";
import { adapterForProvider, ensureFreshMailboxCreds, loadMailboxCreds } from "./MailboxConnectionService.server";
import type { EmailOAuthProvider } from "./oauthState.server";
import type { NeutralAddress } from "./adapters/EmailProviderAdapter";
export class EmailSendError extends Error {
readonly code: "no_mailbox" | "not_connected" | "quota_exceeded" | "token_expired" | "provider_failed" | "no_recipients";
constructor(code: EmailSendError["code"]) {
super(code);
this.name = "EmailSendError";
this.code = code;
}
}
export interface SendEmailInput {
tenantId: string;
userId: string;
mailboxId: string;
to: readonly NeutralAddress[];
cc?: readonly NeutralAddress[];
bcc?: readonly NeutralAddress[];
subject: string;
bodyHtml: string;
/** Reply context: the mirrored message being answered (threading headers). */
replyToMessageId?: string | null;
attachments?: ReadonlyArray<{ filename: string; mimeType: string; contentBase64: string }>;
}
function mapProviderError(error: unknown): EmailSendError {
if (error instanceof GmailError) {
if (error.code === "quota_exceeded" || (error.code === "auth_scope_missing" && error.httpStatus === 403)) {
return new EmailSendError("quota_exceeded");
}
if (error.code === "auth_token_expired") {
return new EmailSendError("token_expired");
}
}
if (error instanceof GraphMailError && error.code === "auth_token_expired") {
return new EmailSendError("token_expired");
}
return new EmailSendError("provider_failed");
}
/** Send + mirror. Returns the local mirror message id (detail redirect). */
export async function sendEmail(input: SendEmailInput): Promise<{ messageId: string }> {
if (input.to.length === 0) {
throw new EmailSendError("no_recipients");
}
const mailbox = await db.emailIntegrationMailbox.findFirst({
where: { id: input.mailboxId, tenantId: input.tenantId, ownerUserId: input.userId, archivedAt: null, status: { in: ["active", "connecting", "error"] } },
select: { id: true, provider: true, emailAddress: true, displayName: true },
});
if (!mailbox) {
throw new EmailSendError("no_mailbox");
}
const provider = mailbox.provider as EmailOAuthProvider;
const creds = await loadMailboxCreds(input.tenantId, input.mailboxId);
if (!creds) {
throw new EmailSendError("not_connected");
}
// Reply threading context from the mirrored original (M09 Block G).
const replyTo = input.replyToMessageId
? await db.emailIntegrationMessage.findFirst({
where: { id: input.replyToMessageId, tenantId: input.tenantId },
select: { providerThreadId: true, internetMessageId: true },
})
: null;
let result: { providerMessageId: string | null; providerThreadId: string | null };
try {
const fresh = await ensureFreshMailboxCreds(input.tenantId, input.mailboxId, provider, creds);
result = await adapterForProvider(provider).sendMessage(fresh, {
to: input.to,
cc: input.cc,
bcc: input.bcc,
subject: input.subject,
bodyHtml: input.bodyHtml,
attachments: input.attachments,
providerThreadId: replyTo?.providerThreadId ?? null,
inReplyToInternetMessageId: replyTo?.internetMessageId ?? null,
referencesInternetMessageIds: replyTo?.internetMessageId ? [replyTo.internetMessageId] : undefined,
});
} catch (error) {
throw mapProviderError(error);
}
// Local outbound mirror. Graph returns no id (202) → provisional local id;
// the sent-items delta adopts the provider ids via internetMessageId later.
const now = new Date();
const mirror = await db.emailIntegrationMessage.create({
data: {
tenantId: input.tenantId,
mailboxId: input.mailboxId,
providerMessageId: result.providerMessageId ?? `local_${randomUUID()}`,
providerThreadId: result.providerThreadId ?? replyTo?.providerThreadId ?? null,
internetMessageId: null,
direction: "outbound",
fromAddress: mailbox.emailAddress,
fromName: mailbox.displayName,
toAddresses: input.to as never,
ccAddresses: (input.cc ?? []) as never,
bccAddresses: (input.bcc ?? []) as never,
subject: input.subject,
snippet: input.bodyHtml.replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim().slice(0, 140),
bodyHtml: input.bodyHtml,
sentAt: now,
isRead: true,
hasAttachments: (input.attachments?.length ?? 0) > 0,
},
select: { id: true },
});
// Activity at the reply-context entities (auto-match hook covers synced
// inbound mail; the outbound mirror logs directly, actor = the sender).
if (input.replyToMessageId) {
const original = await db.emailIntegrationMessage.findFirst({
where: { id: input.replyToMessageId, tenantId: input.tenantId },
select: { matchedKontaktId: true, matchedLeadId: true, matchedProjektId: true },
});
const subject = original?.matchedKontaktId
? { subjectType: "contact" as const, subjectId: original.matchedKontaktId }
: original?.matchedLeadId
? { subjectType: "lead" as const, subjectId: original.matchedLeadId }
: original?.matchedProjektId
? { subjectType: "project" as const, subjectId: original.matchedProjektId }
: null;
if (subject) {
// The reply inherits the original's match so it shows on the same timeline.
await db.emailIntegrationMessage.update({
where: { id: mirror.id },
data: {
matchedKontaktId: original?.matchedKontaktId ?? null,
matchedLeadId: original?.matchedLeadId ?? null,
matchedProjektId: original?.matchedProjektId ?? null,
matchConfidence: "high",
},
});
await logActivity({
tenantId: input.tenantId,
actorUserId: input.userId,
actorKind: "user",
activityType: "email_sent",
subjectType: subject.subjectType,
subjectId: subject.subjectId,
summaryText: `Ausgehende E-Mail an ${input.to[0]?.name ?? input.to[0]?.address}: ${input.subject.trim() ? `„${input.subject.trim()}“` : "(ohne Betreff)"}`,
metadata: { emailMessageId: mirror.id, mailboxId: input.mailboxId },
}).catch(() => undefined);
}
}
return { messageId: mirror.id };
}
/** Active templates for the compose dropdown (M098 — v1-EmailTemplate reuse). */
export async function listEmailTemplates(tenantId: string): Promise<Array<{ id: string; name: string; subject: string; htmlBody: string }>> {
return db.emailTemplate.findMany({
where: { tenantId, archivedAt: null },
select: { id: true, name: true, subject: true, htmlBody: true },
orderBy: [{ isDefault: "desc" }, { name: "asc" }],
});
}
Loaded 100 of 3781 files, more files were not shown because too many files have changed in this diff. Show more