Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+146
@@ -0,0 +1,146 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useFetcher } from "react-router";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { Label } from "~/components/ui/label";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select";
|
||||
import { SiteTypeConfig, SiteServerConfig, SiteServerResolutionModes } from "../lib/types";
|
||||
import { buildSiteUrlFromServer } from "../lib/utils";
|
||||
import { Site } from "@toolctrl/db/prisma-browser";
|
||||
import { Badge } from "~/components/ui/badge";
|
||||
import ErrorBanner from "~/components/ui/banners/ErrorBanner";
|
||||
import { translateSiteTypeName } from "../site-types";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
|
||||
interface Props {
|
||||
type: string;
|
||||
siteType: SiteTypeConfig;
|
||||
servers: SiteServerConfig[];
|
||||
item?: Site;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
export default function SiteForm({ type, siteType, servers, item, onCancel }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
const isEditing = !!item;
|
||||
|
||||
const [siteId, setSiteId] = useState(item?.siteId || "");
|
||||
const [name, setName] = useState(item?.name || "");
|
||||
const [selectedServer, setSelectedServer] = useState<SiteServerConfig | null>(servers[0] || null);
|
||||
const siteTypeName = translateSiteTypeName(t, type, siteType);
|
||||
|
||||
useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
}, [fetcher.data]);
|
||||
|
||||
const mainInput = useRef<HTMLInputElement>(null);
|
||||
useEffect(() => {
|
||||
setTimeout(() => {
|
||||
mainInput.current?.focus();
|
||||
}, 100);
|
||||
}, []);
|
||||
|
||||
function handleNameChange(value: string) {
|
||||
setName(value);
|
||||
if (!isEditing) {
|
||||
setSiteId(UrlUtils.slugify(value));
|
||||
}
|
||||
}
|
||||
|
||||
function handleServerChange(serverName: string) {
|
||||
const server = servers.find((s) => s.name === serverName);
|
||||
if (server) {
|
||||
setSelectedServer(server);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<fetcher.Form method="post">
|
||||
<input type="hidden" name="action" value={isEditing ? "update" : "create"} readOnly hidden />
|
||||
<input type="hidden" name="type" value={type} readOnly hidden />
|
||||
{selectedServer && (
|
||||
<>
|
||||
<input type="hidden" name="serverName" value={selectedServer.name} readOnly hidden />
|
||||
<input type="hidden" name="serverHost" value={selectedServer.host} readOnly hidden />
|
||||
<input type="hidden" name="serverResolution" value={selectedServer.resolutionMode} readOnly hidden />
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<Label className="mb-1 block text-xs">
|
||||
{t("shared.name")} <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
ref={mainInput}
|
||||
name="name"
|
||||
value={name}
|
||||
onChange={(e) => handleNameChange(e.target.value)}
|
||||
placeholder={t("models.site.placeholders.name", { type: siteTypeName })}
|
||||
required
|
||||
className="bg-background"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="mb-1 block text-xs">
|
||||
{t("models.site.siteId")} <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
name="siteId"
|
||||
value={siteId}
|
||||
onChange={(e) => setSiteId(UrlUtils.slugify(e.target.value))}
|
||||
placeholder={t("models.site.placeholders.siteId")}
|
||||
required
|
||||
pattern="[a-z0-9-]+"
|
||||
className="bg-background"
|
||||
disabled={isEditing}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{servers.length === 0 && <ErrorBanner title={t("models.site.servers.emptyTitle")}>{t("models.site.servers.emptyDescription")}</ErrorBanner>}
|
||||
|
||||
{!isEditing && servers.length > 0 && (
|
||||
<div>
|
||||
<Label className="mb-1 block text-xs">
|
||||
{t("models.site.server")} <span className="text-red-500">*</span>
|
||||
</Label>
|
||||
<Select value={selectedServer?.name || ""} onValueChange={handleServerChange}>
|
||||
<SelectTrigger className="bg-background w-full">
|
||||
<SelectValue placeholder={t("models.site.servers.selectPlaceholder")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{servers.map((server) => (
|
||||
<SelectItem key={server.name} value={server.name} className="w-full">
|
||||
<div className="flex w-full items-center justify-between gap-2">
|
||||
<Badge variant="outline">{t(SiteServerResolutionModes.find((m) => m.value === server.resolutionMode)?.nameKey ?? "models.site.resolutionModes.unknown")}</Badge>
|
||||
<span className="truncate">{buildSiteUrlFromServer(server, siteId)}</span>
|
||||
</div>
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-end gap-2 pt-2">
|
||||
{onCancel && (
|
||||
<Button type="button" variant="ghost" size="sm" onClick={onCancel} disabled={fetcher.state === "submitting"}>
|
||||
{t("shared.cancel")}
|
||||
</Button>
|
||||
)}
|
||||
<Button type="submit" isLoading={fetcher.state === "submitting"}>
|
||||
{isEditing ? t("models.site.actions.deploy") : t("models.site.actions.create")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
);
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { Link } from "react-router";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { SiteTypeConfig, translateSiteTypeDescription, translateSiteTypeName } from "../site-types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
slug: string;
|
||||
config: SiteTypeConfig;
|
||||
sitesCount: number;
|
||||
createUrl: string;
|
||||
}
|
||||
|
||||
export default function SiteTypeCard({ slug, config, sitesCount, createUrl }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<Card className="flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>{translateSiteTypeName(t, slug, config)}</CardTitle>
|
||||
<CardDescription>{translateSiteTypeDescription(t, slug, config)}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-1 flex-col justify-between gap-4">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{sitesCount === 0 ? (
|
||||
<span>{t("models.site.emptyTitle")}</span>
|
||||
) : (
|
||||
<span>{t("models.site.countCreated", { count: sitesCount, formattedCount: formatters.number(sitesCount, { maximumFractionDigits: 0 }) })}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link to={createUrl}>{t("models.site.actions.create")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
import { Link } from "react-router";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { SiteTypeConfig, translateSiteTypeDescription, translateSiteTypeName } from "../site-types";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
interface Props {
|
||||
slug: string;
|
||||
config: SiteTypeConfig;
|
||||
sitesCount: number;
|
||||
createUrl: string;
|
||||
}
|
||||
|
||||
export default function SiteTypeCard({ slug, config, sitesCount, createUrl }: Props) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
return (
|
||||
<Card className="flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle>{translateSiteTypeName(t, slug, config)}</CardTitle>
|
||||
<CardDescription>{translateSiteTypeDescription(t, slug, config)}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-1 flex-col justify-between gap-4">
|
||||
<div className="text-muted-foreground text-sm">
|
||||
{sitesCount === 0 ? (
|
||||
<span>{t("models.site.emptyTitle")}</span>
|
||||
) : (
|
||||
<span>{t("models.site.countCreated", { count: sitesCount, formattedCount: formatters.number(sitesCount, { maximumFractionDigits: 0 }) })}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button asChild variant="outline" size="sm">
|
||||
<Link to={createUrl}>{t("models.site.actions.create")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
import { Prisma, Site } from "@toolctrl/db/prisma-browser";
|
||||
import { db, dbRead } from "~/utils/db.server";
|
||||
|
||||
export async function getSite({ id, tenantId }: { id: string; tenantId: string }) {
|
||||
// Read-only site detail used by admin views and public renderers — replica-safe.
|
||||
return dbRead.site.findFirst({
|
||||
where: { id, tenantId },
|
||||
include: { tenant: true, createdByUser: true },
|
||||
});
|
||||
}
|
||||
|
||||
// Get site by type and siteId (for API authentication)
|
||||
export async function getSiteByTypeAndSiteId(type: string, siteId: string) {
|
||||
return db.site.findUnique({
|
||||
where: { type_siteId: { type, siteId } },
|
||||
include: { tenant: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function getSiteNameByTypeAndSiteId(type: string, siteId: string) {
|
||||
// Read-only public lookup (used by rendering, not auth). Replica-safe.
|
||||
return dbRead.site.findUnique({
|
||||
where: { type_siteId: { type, siteId } },
|
||||
include: { tenant: { select: { name: true, slug: true } } },
|
||||
// select: {
|
||||
// id: true,
|
||||
// tenantId: true,
|
||||
// name: true,
|
||||
// siteId: true,
|
||||
// isActive: true,
|
||||
// branding: true,
|
||||
// copy: true,
|
||||
// },
|
||||
});
|
||||
}
|
||||
|
||||
// Get all sites for a tenant
|
||||
export async function getSitesByTenantId(tenantId: string) {
|
||||
// Tenant site listing for admin/public rendering — read-only.
|
||||
return dbRead.site.findMany({
|
||||
where: { tenantId },
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: { createdByUser: { select: { email: true, firstName: true, lastName: true } } },
|
||||
});
|
||||
}
|
||||
|
||||
// Get sites by type for a tenant
|
||||
export async function getSitesByTenantIdAndType(tenantId: string, type: string) {
|
||||
// Tenant site listing filtered by type — read-only.
|
||||
return dbRead.site.findMany({
|
||||
where: { tenantId, type },
|
||||
orderBy: { createdAt: "desc" },
|
||||
});
|
||||
}
|
||||
|
||||
// Check if siteId is available for a type
|
||||
export async function isSiteIdAvailable(type: string, siteId: string): Promise<boolean> {
|
||||
const existing = await db.site.findUnique({
|
||||
where: { type_siteId: { type, siteId } },
|
||||
select: { id: true },
|
||||
});
|
||||
return !existing;
|
||||
}
|
||||
|
||||
// Create a new site
|
||||
export async function createSite(data: {
|
||||
tenantId: string;
|
||||
type: string;
|
||||
siteId: string;
|
||||
name: string;
|
||||
serverName: string;
|
||||
serverHost: string;
|
||||
isActive: boolean;
|
||||
serverResolution: string;
|
||||
createdByUserId?: string;
|
||||
branding?: string;
|
||||
copy?: string;
|
||||
}) {
|
||||
return db.site.create({
|
||||
data: {
|
||||
tenantId: data.tenantId,
|
||||
type: data.type,
|
||||
siteId: data.siteId,
|
||||
name: data.name,
|
||||
serverName: data.serverName,
|
||||
serverHost: data.serverHost,
|
||||
serverResolution: data.serverResolution,
|
||||
isActive: data.isActive,
|
||||
createdByUserId: data.createdByUserId,
|
||||
branding: data.branding ?? "{}",
|
||||
copy: data.copy ?? "{}",
|
||||
},
|
||||
include: { tenant: true },
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateSite(
|
||||
scope: { id: string; tenantId: string },
|
||||
data: {
|
||||
name?: string;
|
||||
siteId?: string;
|
||||
isActive?: boolean;
|
||||
branding?: string;
|
||||
copy?: string;
|
||||
}
|
||||
) {
|
||||
const result = await db.site.updateMany({
|
||||
where: scope,
|
||||
data,
|
||||
});
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Site not found for tenant scope.");
|
||||
}
|
||||
return db.site.findFirstOrThrow({
|
||||
where: scope,
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteSite(scope: { id: string; tenantId: string }) {
|
||||
const item = await db.site.findFirst({ where: scope });
|
||||
if (!item) {
|
||||
throw new Error("Site not found for tenant scope.");
|
||||
}
|
||||
const result = await db.site.deleteMany({ where: scope });
|
||||
if (result.count !== 1) {
|
||||
throw new Error("Site not found for tenant scope.");
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
// Get sites with pagination
|
||||
export async function getSitesWithPagination({
|
||||
tenantId,
|
||||
type,
|
||||
pagination,
|
||||
filters,
|
||||
}: {
|
||||
tenantId: string;
|
||||
type?: string;
|
||||
pagination?: { page: number; pageSize: number };
|
||||
filters?: { q?: string };
|
||||
}) {
|
||||
let where: Prisma.SiteWhereInput = { tenantId };
|
||||
|
||||
if (type) {
|
||||
where.type = type;
|
||||
}
|
||||
|
||||
if (filters?.q) {
|
||||
where = {
|
||||
...where,
|
||||
OR: [{ name: { contains: filters.q, mode: "insensitive" } }, { siteId: { contains: filters.q, mode: "insensitive" } }],
|
||||
};
|
||||
}
|
||||
|
||||
// Paginated listing for admin grid — read-only, replica-safe.
|
||||
const items = await dbRead.site.findMany({
|
||||
take: pagination?.pageSize,
|
||||
skip: pagination ? pagination.pageSize * (pagination.page - 1) : undefined,
|
||||
where,
|
||||
orderBy: { createdAt: "desc" },
|
||||
include: {
|
||||
createdByUser: { select: { email: true, firstName: true, lastName: true } },
|
||||
},
|
||||
});
|
||||
|
||||
if (!pagination) {
|
||||
return { items };
|
||||
}
|
||||
|
||||
const totalItems = await dbRead.site.count({ where });
|
||||
|
||||
return {
|
||||
items,
|
||||
pagination: {
|
||||
page: pagination.page,
|
||||
pageSize: pagination.pageSize,
|
||||
totalItems,
|
||||
totalPages: Math.ceil(totalItems / pagination.pageSize),
|
||||
},
|
||||
};
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// Sites Framework - Server Configuration
|
||||
// Environment-based server retrieval - do not modify
|
||||
|
||||
import { SITE_TYPE } from "../site-types";
|
||||
import { SiteServerConfig } from "./types";
|
||||
|
||||
export function getSiteServers(_type?: SITE_TYPE): SiteServerConfig[] {
|
||||
return [];
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SiteTypeConfig } from "../site-types";
|
||||
|
||||
const getSiteTypeMock = vi.hoisted(() => vi.fn());
|
||||
|
||||
vi.mock("../site-types", () => ({
|
||||
getSiteType: getSiteTypeMock,
|
||||
}));
|
||||
|
||||
import { buildCopyWithFallbacks, getSiteCopyFallbackKey } from "./site-settings-utils";
|
||||
|
||||
const siteTypeConfig: SiteTypeConfig = {
|
||||
enabled: true,
|
||||
name: "Portal",
|
||||
description: "Customer-facing portal",
|
||||
copyKeys: [
|
||||
{
|
||||
section: "Hero",
|
||||
name: "Title",
|
||||
key: "heroTitle",
|
||||
fallback: "Welcome",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
describe("site settings i18n fallbacks", () => {
|
||||
beforeEach(() => {
|
||||
getSiteTypeMock.mockReset();
|
||||
getSiteTypeMock.mockReturnValue(siteTypeConfig);
|
||||
});
|
||||
|
||||
it("derives stable copy fallback translation keys from the site type and copy key", () => {
|
||||
expect(getSiteCopyFallbackKey("customer-portal", "heroTitle")).toBe("models.site.types.customer-portal.copy.heroTitle.fallback");
|
||||
});
|
||||
|
||||
it("preserves saved tenant copy before resolving fallback translations", () => {
|
||||
const t = vi.fn((key: string) => `translated:${key}`);
|
||||
|
||||
expect(buildCopyWithFallbacks("portal", { heroTitle: "Tenant welcome" }, t)).toEqual({
|
||||
heroTitle: "Tenant welcome",
|
||||
});
|
||||
expect(t).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves missing copy through the i18n fallback key", () => {
|
||||
const t = vi.fn((key: string) => (key === "models.site.types.portal.copy.heroTitle.fallback" ? "Willkommen" : key));
|
||||
|
||||
expect(buildCopyWithFallbacks("portal", {}, t)).toEqual({
|
||||
heroTitle: "Willkommen",
|
||||
});
|
||||
expect(t).toHaveBeenCalledWith("models.site.types.portal.copy.heroTitle.fallback");
|
||||
});
|
||||
|
||||
it("keeps the config fallback as the last resort when an i18n key is missing", () => {
|
||||
const t = vi.fn((key: string) => key);
|
||||
|
||||
expect(buildCopyWithFallbacks("portal", {}, t)).toEqual({
|
||||
heroTitle: "Welcome",
|
||||
});
|
||||
});
|
||||
});
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
// ============================================
|
||||
// Site Settings Utilities
|
||||
// Helper functions for copy configuration
|
||||
// ============================================
|
||||
|
||||
import { getSiteType } from "../site-types";
|
||||
|
||||
type SiteCopyTranslator = (key: string) => string;
|
||||
|
||||
export function getSiteCopyFallbackKey(type: string, key: string): string {
|
||||
return `models.site.types.${type}.copy.${key}.fallback`;
|
||||
}
|
||||
|
||||
function resolveCopyFallback(type: string, key: string, fallback: string, t?: SiteCopyTranslator): string {
|
||||
if (!t) return fallback;
|
||||
|
||||
const fallbackKey = getSiteCopyFallbackKey(type, key);
|
||||
const translated = t(fallbackKey);
|
||||
return translated === fallbackKey ? fallback : translated;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build copy object with fallback values for missing keys
|
||||
*/
|
||||
export function buildCopyWithFallbacks(type: string, savedCopy: Record<string, string> | null, t?: SiteCopyTranslator): Record<string, string> {
|
||||
const siteType = getSiteType(type);
|
||||
if (!siteType) return {};
|
||||
|
||||
const result: Record<string, string> = {};
|
||||
for (const { key, fallback } of siteType.copyKeys) {
|
||||
result[key] = savedCopy?.[key] || resolveCopyFallback(type, key, fallback, t);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Sites Framework Types
|
||||
// These are the core type definitions - do not modify
|
||||
|
||||
export type SiteTypeConfig = {
|
||||
enabled: boolean;
|
||||
name: string;
|
||||
nameKey?: string;
|
||||
description: string;
|
||||
descriptionKey?: string;
|
||||
copyKeys: { section: string; name: string; key: string; fallback: string }[];
|
||||
};
|
||||
|
||||
export const SiteServerResolutionModes = [
|
||||
{
|
||||
nameKey: "models.site.resolutionModes.domain",
|
||||
value: "domain",
|
||||
description: "https://{siteId}",
|
||||
},
|
||||
{
|
||||
nameKey: "models.site.resolutionModes.path",
|
||||
value: "path",
|
||||
description: "https://example.com/{siteId}",
|
||||
},
|
||||
{
|
||||
nameKey: "models.site.resolutionModes.subdomain",
|
||||
value: "subdomain",
|
||||
description: "https://{siteId}.example.com",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export type SiteServerResolutionMode = (typeof SiteServerResolutionModes)[number]["value"];
|
||||
|
||||
export type SiteServerConfig = {
|
||||
name: string;
|
||||
description?: string;
|
||||
host: string; // e.g., "localhost:3001" or "booking.example.com"
|
||||
resolutionMode: SiteServerResolutionMode;
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
// Sites Framework Utilities
|
||||
// URL building utilities - do not modify
|
||||
|
||||
import { SiteServerConfig, SiteServerResolutionMode } from "./types";
|
||||
|
||||
export function buildSiteUrl(params: { serverHost: string; serverResolution: SiteServerResolutionMode | (string & {}); siteId: string }): string {
|
||||
return buildSiteUrlFromFields(params.serverHost, params.serverResolution, params.siteId);
|
||||
}
|
||||
|
||||
export function buildSiteUrlFromServer(server: SiteServerConfig, siteId: string): string {
|
||||
const protocol = server.host.startsWith("localhost") ? "http" : "https";
|
||||
switch (server.resolutionMode) {
|
||||
case "domain":
|
||||
return `${protocol}://${server.host}`;
|
||||
case "path":
|
||||
return `${protocol}://${server.host}/${siteId}`;
|
||||
case "subdomain":
|
||||
return `${protocol}://${siteId}.${server.host}`;
|
||||
default:
|
||||
return `${protocol}://${server.host}/${siteId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildSiteUrlFromFields(serverHost: string, serverResolution: SiteServerResolutionMode | (string & {}), siteId: string): string {
|
||||
const protocol = serverHost.startsWith("localhost") ? "http" : "https";
|
||||
switch (serverResolution) {
|
||||
case "domain":
|
||||
return `${protocol}://${serverHost}`;
|
||||
case "path":
|
||||
return `${protocol}://${serverHost}/${siteId}`;
|
||||
case "subdomain":
|
||||
return `${protocol}://${siteId}.${serverHost}`;
|
||||
default:
|
||||
return `${protocol}://${serverHost}/${siteId}`;
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getSiteTypeDescriptionKey,
|
||||
getSiteTypeNameKey,
|
||||
translateSiteTypeDescription,
|
||||
translateSiteTypeName,
|
||||
type SiteTypeConfig,
|
||||
} from "./site-types";
|
||||
|
||||
const siteTypeConfig: SiteTypeConfig = {
|
||||
enabled: true,
|
||||
name: "Portal",
|
||||
description: "Customer-facing portal",
|
||||
copyKeys: [],
|
||||
};
|
||||
|
||||
describe("site type i18n helpers", () => {
|
||||
it("derives stable translation keys from the site type slug", () => {
|
||||
expect(getSiteTypeNameKey("customer-portal")).toBe("models.site.types.customer-portal.name");
|
||||
expect(getSiteTypeDescriptionKey("customer-portal")).toBe("models.site.types.customer-portal.description");
|
||||
});
|
||||
|
||||
it("uses explicit translation keys when a site type config defines them", () => {
|
||||
expect(getSiteTypeNameKey("portal", { nameKey: "custom.site.name" })).toBe("custom.site.name");
|
||||
expect(getSiteTypeDescriptionKey("portal", { descriptionKey: "custom.site.description" })).toBe("custom.site.description");
|
||||
});
|
||||
|
||||
it("translates through i18n keys without English config default values", () => {
|
||||
const calls: Array<{ key: string; options: Record<string, unknown> | undefined }> = [];
|
||||
const t = (key: string, options?: Record<string, unknown>) => {
|
||||
calls.push({ key, options });
|
||||
return `translated:${key}`;
|
||||
};
|
||||
|
||||
expect(translateSiteTypeName(t, "portal", siteTypeConfig)).toBe("translated:models.site.types.portal.name");
|
||||
expect(translateSiteTypeDescription(t, "portal", siteTypeConfig)).toBe("translated:models.site.types.portal.description");
|
||||
expect(calls).toEqual([
|
||||
{ key: "models.site.types.portal.name", options: undefined },
|
||||
{ key: "models.site.types.portal.description", options: undefined },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
// Site Types - DEVELOPER CONFIG
|
||||
// Add your site types here. Each type becomes a separate nav item in the sidebar.
|
||||
|
||||
import { SiteTypeConfig } from "./lib/types";
|
||||
|
||||
// Re-export for convenience
|
||||
export type { SiteTypeConfig };
|
||||
|
||||
export type SITE_TYPE = keyof typeof SITE_TYPES;
|
||||
|
||||
export const SITE_TYPES: Record<string, SiteTypeConfig> = {
|
||||
// Add project-specific site types here.
|
||||
};
|
||||
|
||||
// Helper functions
|
||||
export function getSiteType(type: string): SiteTypeConfig | undefined {
|
||||
return SITE_TYPES[type];
|
||||
}
|
||||
|
||||
export function getEnabledSiteTypes() {
|
||||
return Object.entries(SITE_TYPES)
|
||||
.filter(([_, config]) => config.enabled)
|
||||
.map(([slug, config]) => ({ slug, ...config }));
|
||||
}
|
||||
|
||||
type SiteTypeTranslator = (key: string, options?: Record<string, unknown>) => string;
|
||||
|
||||
export function getSiteTypeNameKey(slug: string, config?: Pick<SiteTypeConfig, "nameKey">): string {
|
||||
return config?.nameKey ?? `models.site.types.${slug}.name`;
|
||||
}
|
||||
|
||||
export function getSiteTypeDescriptionKey(slug: string, config?: Pick<SiteTypeConfig, "descriptionKey">): string {
|
||||
return config?.descriptionKey ?? `models.site.types.${slug}.description`;
|
||||
}
|
||||
|
||||
export function translateSiteTypeName(t: SiteTypeTranslator, slug: string, config: Pick<SiteTypeConfig, "name" | "nameKey">): string {
|
||||
return t(getSiteTypeNameKey(slug, config));
|
||||
}
|
||||
|
||||
export function translateSiteTypeDescription(t: SiteTypeTranslator, slug: string, config: Pick<SiteTypeConfig, "description" | "descriptionKey">): string {
|
||||
return t(getSiteTypeDescriptionKey(slug, config));
|
||||
}
|
||||
|
||||
export function getSiteTypeKey(type: string): string {
|
||||
// Each site type has its own API key stored in env
|
||||
// e.g., SITE_KEY_COMMUNITY, SITE_KEY_BOOKING
|
||||
const envKey = `SITE_KEY_${type.replace("-", "_").toUpperCase()}`;
|
||||
return process.env[envKey] ?? "";
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const repoRoot = process.cwd();
|
||||
|
||||
function readSource(relativePath: string) {
|
||||
return fs.readFileSync(path.join(repoRoot, relativePath), "utf8");
|
||||
}
|
||||
|
||||
describe("site UI i18n", () => {
|
||||
it("uses semantic site action labels for visible create/deploy controls", () => {
|
||||
const sources = [
|
||||
"apps/web/app/modules/sites/components/site-form.tsx",
|
||||
"apps/web/app/routes/app.$tenant/sites/$type.tsx",
|
||||
"apps/web/app/routes/app.$tenant/sites/new.tsx",
|
||||
]
|
||||
.map(readSource)
|
||||
.join("\n");
|
||||
|
||||
expect(sources).toContain("models.site.actions.create");
|
||||
expect(sources).toContain("models.site.actions.createTyped");
|
||||
expect(sources).toContain("models.site.actions.deploy");
|
||||
expect(sources).not.toContain('t("shared.create")');
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("keeps German site deployment copy domain-specific", () => {
|
||||
const de = JSON.parse(readSource("apps/web/public/locales/de/translations.json"));
|
||||
|
||||
expect(de.models.site.actions.deploy).toBe("Bereitstellen");
|
||||
expect(de.models.site.servers.emptyDescription).toContain("Bereitstellungsserver");
|
||||
expect(de.models.site.servers.emptyDescription).not.toContain("Veröffentlichungsserver");
|
||||
});
|
||||
});
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
vi.mock("../site-types", () => ({
|
||||
getSiteType: vi.fn(),
|
||||
getSiteTypeKey: vi.fn(),
|
||||
}));
|
||||
vi.mock("../db/sites.db.server", () => ({
|
||||
getSiteNameByTypeAndSiteId: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/utils/db/apiKeys.db.server", () => ({
|
||||
createApiKeyLog: vi.fn(),
|
||||
}));
|
||||
vi.mock("@toolctrl/db/api-keys.server", () => ({
|
||||
setLegacyApiKeyLogStatus: vi.fn(),
|
||||
}));
|
||||
vi.mock("../lib/site-settings-utils", () => ({
|
||||
buildCopyWithFallbacks: vi.fn((_siteType: string, copy: Record<string, string>) => copy),
|
||||
}));
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string) => key,
|
||||
})),
|
||||
}));
|
||||
|
||||
import { setLegacyApiKeyLogStatus } from "@toolctrl/db/api-keys.server";
|
||||
import { getSiteNameByTypeAndSiteId } from "../db/sites.db.server";
|
||||
import { getSiteType, getSiteTypeKey } from "../site-types";
|
||||
import { createApiKeyLog } from "~/utils/db/apiKeys.db.server";
|
||||
import { withSiteAuthentication } from "./with-site-authentication";
|
||||
|
||||
describe("withSiteAuthentication", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(getSiteType).mockReturnValue({ name: "Booking", enabled: true } as never);
|
||||
vi.mocked(getSiteTypeKey).mockReturnValue("site-secret");
|
||||
vi.mocked(createApiKeyLog).mockResolvedValue({ id: "log_1" } as never);
|
||||
vi.mocked(getSiteNameByTypeAndSiteId).mockResolvedValue({
|
||||
id: "site_1",
|
||||
tenantId: "tenant_1",
|
||||
tenant: { name: "Acme", slug: "acme" },
|
||||
siteId: "booking",
|
||||
isActive: true,
|
||||
branding: "{}",
|
||||
copy: "{}",
|
||||
} as never);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("returns and stores generic diagnostics for handler failures", async () => {
|
||||
const response = await withSiteAuthentication({
|
||||
siteType: "booking" as never,
|
||||
request: new Request("https://app.example.test/sites/api?token=raw-token", {
|
||||
headers: { "X-Site-Key": "site-secret", "X-Site-Id": "booking" },
|
||||
}),
|
||||
params: {},
|
||||
handler: async () => {
|
||||
throw new Error("provider token=raw-token failed for tenant tenant_1");
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.status).toBe(500);
|
||||
await expect(response.json()).resolves.toEqual({ success: false, error: "models.site.auth.errors.internalFailure" });
|
||||
expect(setLegacyApiKeyLogStatus).toHaveBeenCalledWith(
|
||||
{ id: "log_1", tenantId: "tenant_1" },
|
||||
expect.objectContaining({
|
||||
status: 500,
|
||||
error: "models.site.auth.errors.internalFailure",
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
test("returns localized authentication errors", async () => {
|
||||
const response = await withSiteAuthentication({
|
||||
siteType: "booking" as never,
|
||||
request: new Request("https://app.example.test/sites/api", {
|
||||
headers: { "X-Site-Id": "booking" },
|
||||
}),
|
||||
params: {},
|
||||
handler: async () => Response.json({ ok: true }),
|
||||
});
|
||||
|
||||
expect(response.status).toBe(401);
|
||||
await expect(response.json()).resolves.toEqual({ error: "models.site.auth.errors.siteKeyRequired" });
|
||||
});
|
||||
});
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
import { setLegacyApiKeyLogStatus as setApiKeyLogStatus } from "@toolctrl/db/api-keys.server";
|
||||
import { Params } from "react-router";
|
||||
import { Site } from "@toolctrl/db/prisma-browser";
|
||||
import { getSiteNameByTypeAndSiteId } from "../db/sites.db.server";
|
||||
import { getSiteType, getSiteTypeKey, SITE_TYPE, SiteTypeConfig } from "../site-types";
|
||||
import { createApiKeyLog } from "~/utils/db/apiKeys.db.server";
|
||||
import { buildCopyWithFallbacks } from "../lib/site-settings-utils";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
/**
|
||||
* Context provided to site API handlers
|
||||
*/
|
||||
export type SiteAuthContext = {
|
||||
site: Site & {
|
||||
tenant: { name: string; slug: string };
|
||||
};
|
||||
siteType: SiteTypeConfig;
|
||||
branding: Record<string, unknown>;
|
||||
copy: Record<string, string>;
|
||||
};
|
||||
|
||||
type WithSiteAuthenticationParams = {
|
||||
siteType: SITE_TYPE;
|
||||
request: Request;
|
||||
params: Params;
|
||||
handler: (context: SiteAuthContext) => Promise<Response>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Authentication wrapper for site-specific API endpoints.
|
||||
*
|
||||
* ALL endpoints require:
|
||||
* - X-Site-Key header (site type API key)
|
||||
* - X-Site-Id header (site identification - slug, subdomain, or domain)
|
||||
*
|
||||
* @example
|
||||
* export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
* return withSiteAuthentication({
|
||||
* siteType: "booking",
|
||||
* request,
|
||||
* params,
|
||||
* handler: async ({ site, siteType, branding, copy }) => {
|
||||
* return Response.json({ branding, copy });
|
||||
* },
|
||||
* });
|
||||
* };
|
||||
*/
|
||||
export async function withSiteAuthentication({ siteType, request, handler }: WithSiteAuthenticationParams): Promise<Response> {
|
||||
const startTime = performance.now();
|
||||
let apiKeyLogId: string | undefined;
|
||||
let apiKeyLogTenantId: string | undefined;
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
try {
|
||||
// 1. Get site type config
|
||||
const siteTypeConfig = getSiteType(siteType);
|
||||
if (!siteTypeConfig) {
|
||||
return Response.json({ error: t("models.site.auth.errors.invalidType") }, { status: 400 });
|
||||
}
|
||||
|
||||
// 2. Validate X-Site-Key (required for all endpoints)
|
||||
const siteKey = request.headers.get("X-Site-Key");
|
||||
const expectedKey = getSiteTypeKey(siteType);
|
||||
|
||||
if (!siteKey) {
|
||||
return Response.json({ error: t("models.site.auth.errors.siteKeyRequired") }, { status: 401 });
|
||||
}
|
||||
|
||||
if (!expectedKey || siteKey !== expectedKey) {
|
||||
// Log failed attempt
|
||||
await createApiKeyLog(request, {
|
||||
apiKeyId: null,
|
||||
tenantId: null,
|
||||
endpoint: new URL(request.url).pathname,
|
||||
error: t("models.site.auth.errors.invalidKey"),
|
||||
status: 401,
|
||||
alias: `${siteType}: ${t("models.site.auth.logs.unknownSiteKey")}`,
|
||||
});
|
||||
return Response.json({ error: t("models.site.auth.errors.invalidKey") }, { status: 401 });
|
||||
}
|
||||
|
||||
// 3. Get site ID from X-Site-Id header
|
||||
const xSiteId = request.headers.get("X-Site-Id");
|
||||
if (!xSiteId) {
|
||||
return Response.json({ error: t("models.site.auth.errors.siteIdRequired") }, { status: 400 });
|
||||
}
|
||||
|
||||
// 4. Look up site by type + siteId
|
||||
const site = await getSiteNameByTypeAndSiteId(siteType, xSiteId);
|
||||
|
||||
if (!site) {
|
||||
return Response.json({ error: t("models.site.auth.errors.notFound") }, { status: 404 });
|
||||
}
|
||||
|
||||
if (!site.isActive) {
|
||||
return Response.json({ error: t("models.site.auth.errors.inactive") }, { status: 403 });
|
||||
}
|
||||
|
||||
// 5. Create API log entry
|
||||
const apiKeyLog = await createApiKeyLog(request, {
|
||||
tenantId: site.tenantId,
|
||||
apiKeyId: null,
|
||||
endpoint: new URL(request.url).pathname,
|
||||
alias: `${siteType}: ${site.siteId}`,
|
||||
});
|
||||
apiKeyLogId = apiKeyLog.id;
|
||||
apiKeyLogTenantId = site.tenantId;
|
||||
|
||||
// 6. Parse site configuration (branding/copy stored as JSON strings)
|
||||
const branding = JSON.parse(site.branding || "{}");
|
||||
const copy = JSON.parse(site.copy || "{}");
|
||||
|
||||
// 7. Call handler
|
||||
const fullCopy = buildCopyWithFallbacks(siteType, copy, t);
|
||||
const response = await handler({
|
||||
site,
|
||||
siteType: siteTypeConfig,
|
||||
branding,
|
||||
// copy,
|
||||
copy: fullCopy,
|
||||
});
|
||||
|
||||
// 8. Log success
|
||||
await setApiKeyLogStatus({ id: apiKeyLogId, tenantId: site.tenantId }, {
|
||||
status: response.status,
|
||||
startTime,
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error: unknown) {
|
||||
void error;
|
||||
const errorMessage = t("models.site.auth.errors.internalFailure");
|
||||
|
||||
// Log error
|
||||
if (apiKeyLogId && apiKeyLogTenantId) {
|
||||
await setApiKeyLogStatus({ id: apiKeyLogId, tenantId: apiKeyLogTenantId }, {
|
||||
status: 500,
|
||||
startTime,
|
||||
error: errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
return Response.json({ success: false, error: errorMessage }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user