Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+139
@@ -0,0 +1,139 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import {
|
||||
applyAdminFeatureFlagBulkOverride,
|
||||
getAdminFeatureFlagRolloutView,
|
||||
} from "~/services/admin/feature-flag-rollout.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
|
||||
import { action, loader } from "./$key.bulk";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({ t: (key: string) => key })),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/admin-identity.server", () => ({
|
||||
runAsAdminIdentity: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/admin/feature-flag-rollout.server", async () => {
|
||||
const actual = await vi.importActual<typeof import("~/services/admin/feature-flag-rollout.server")>(
|
||||
"~/services/admin/feature-flag-rollout.server"
|
||||
);
|
||||
return {
|
||||
...actual,
|
||||
applyAdminFeatureFlagBulkOverride: vi.fn(),
|
||||
getAdminFeatureFlagRolloutView: vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: vi.fn(),
|
||||
}));
|
||||
|
||||
const runAsAdminIdentityMock = vi.mocked(runAsAdminIdentity);
|
||||
const getRolloutViewMock = vi.mocked(getAdminFeatureFlagRolloutView);
|
||||
const applyBulkOverrideMock = vi.mocked(applyAdminFeatureFlagBulkOverride);
|
||||
|
||||
describe("admin feature flag bulk route", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
runAsAdminIdentityMock.mockImplementation(async (_request, _permission, operation) =>
|
||||
operation({
|
||||
adminUserId: "admin-raffael",
|
||||
sessionId: "session-1",
|
||||
assurance: "mfa",
|
||||
} as never)
|
||||
);
|
||||
});
|
||||
|
||||
it("builds the effective rollout VM behind the read permission", async () => {
|
||||
getRolloutViewMock.mockResolvedValue({
|
||||
flag: {
|
||||
id: "flag-1",
|
||||
key: "sales_workspace",
|
||||
label: "Sales Workspace",
|
||||
defaultValue: false,
|
||||
lifecycleStage: "rollout",
|
||||
},
|
||||
tenants: [
|
||||
{
|
||||
id: "tenant-1",
|
||||
name: "Muster SHK",
|
||||
slug: "muster",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
size: "11-25",
|
||||
industry: "shk",
|
||||
status: "active",
|
||||
subscriptionProductIds: [],
|
||||
},
|
||||
],
|
||||
preview: {
|
||||
enabled: 1,
|
||||
disabled: 0,
|
||||
overrides: 1,
|
||||
filtered: 0,
|
||||
defaulted: 0,
|
||||
rows: [{ tenantId: "tenant-1", decision: { value: true, source: "override", filterId: null } }],
|
||||
},
|
||||
});
|
||||
|
||||
const response = await loader({
|
||||
request: new Request("https://admin.hivegrid.de/feature-flags/sales_workspace/bulk"),
|
||||
params: { key: "sales_workspace" },
|
||||
context: {},
|
||||
} as never);
|
||||
const body = await response.json();
|
||||
|
||||
expect(runAsAdminIdentityMock).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin.featureFlags.view",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(body.vm.tenants[0]).toMatchObject({
|
||||
id: "tenant-1",
|
||||
effectiveValue: true,
|
||||
source: "override",
|
||||
});
|
||||
});
|
||||
|
||||
it("validates CSRF and uses the smallest manage permission for a bulk override", async () => {
|
||||
applyBulkOverrideMock.mockResolvedValue({ updated: 2 });
|
||||
const form = new FormData();
|
||||
form.set("action", "bulk-override");
|
||||
form.set("value", "true");
|
||||
form.set("reason", "Pilotgruppe freigegeben");
|
||||
form.append("tenantId", "tenant-1");
|
||||
form.append("tenantId", "tenant-2");
|
||||
|
||||
const body = new URLSearchParams();
|
||||
for (const [key, value] of form.entries()) {
|
||||
if (typeof value === "string") body.append(key, value);
|
||||
}
|
||||
const response = await action({
|
||||
request: new Request("https://admin.hivegrid.de/feature-flags/sales_workspace/bulk", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
}),
|
||||
params: { key: "sales_workspace" },
|
||||
context: {},
|
||||
} as never);
|
||||
|
||||
expect(validateCSRFToken).toHaveBeenCalledOnce();
|
||||
expect(runAsAdminIdentityMock).toHaveBeenCalledWith(
|
||||
expect.any(Request),
|
||||
"admin.featureFlags.manage",
|
||||
expect.any(Function)
|
||||
);
|
||||
expect(applyBulkOverrideMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
flagKey: "sales_workspace",
|
||||
tenantIds: ["tenant-1", "tenant-2"],
|
||||
actorAdminUserId: "admin-raffael",
|
||||
})
|
||||
);
|
||||
expect(response.status).toBe(303);
|
||||
});
|
||||
});
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { useActionData, useLoaderData, useSubmit } from "react-router";
|
||||
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
|
||||
import { buildAdminFeatureFlagRolloutVM } from "@hivegrid/view-models";
|
||||
|
||||
import { AdminFeatureFlagBulkPage } from "~/components/screens/admin/sales/feature-flags/AdminFeatureFlagBulkPage";
|
||||
import { runAsAdminIdentity } from "~/services/admin/admin-identity.server";
|
||||
import {
|
||||
AdminFeatureFlagRolloutError,
|
||||
applyAdminFeatureFlagBulkOverride,
|
||||
getAdminFeatureFlagRolloutView,
|
||||
} from "~/services/admin/feature-flag-rollout.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { NOT_FOUND_ENVELOPE } from "~/utils/errors.server";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = { errorKey?: string };
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const flagKey = params.key ?? "";
|
||||
const view = await runAsAdminIdentity(request, "admin.featureFlags.view", () => getAdminFeatureFlagRolloutView(flagKey));
|
||||
if (!view) throw Response.json(NOT_FOUND_ENVELOPE, { status: 404 });
|
||||
const updatedValue = Number(new URL(request.url).searchParams.get("updated"));
|
||||
const updatedCount = Number.isSafeInteger(updatedValue) && updatedValue > 0 ? updatedValue : null;
|
||||
const vm = buildAdminFeatureFlagRolloutVM({ ...view, updatedCount });
|
||||
if (vm.status !== "ready") throw new Error("Feature flag rollout view model is not ready.");
|
||||
return Response.json({ vm: vm.data });
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const actionName = form.get("action");
|
||||
if (actionName !== "bulk-override") {
|
||||
return Response.json({ errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const value = form.get("value");
|
||||
if (value !== "true" && value !== "false") {
|
||||
return Response.json({ errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runAsAdminIdentity(request, "admin.featureFlags.manage", (session) =>
|
||||
applyAdminFeatureFlagBulkOverride({
|
||||
flagKey: params.key ?? "",
|
||||
tenantIds: form.getAll("tenantId").map(String),
|
||||
value: value === "true",
|
||||
reason: String(form.get("reason") ?? ""),
|
||||
note: String(form.get("note") ?? ""),
|
||||
expiresAt: parseOptionalDate(form.get("expiresAt")),
|
||||
actorAdminUserId: session.adminUserId,
|
||||
request,
|
||||
})
|
||||
);
|
||||
return Response.redirect(
|
||||
new URL(adminPath(`feature-flags/${encodeURIComponent(params.key ?? "")}/bulk`, { mode: "host-aware" }) + `?updated=${result.updated}`, request.url),
|
||||
303
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof AdminFeatureFlagRolloutError) {
|
||||
return Response.json({ errorKey: `featureFlags.rollout.errors.${error.code}` } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export default function AdminFeatureFlagBulkRoute() {
|
||||
const { vm } = useLoaderData<typeof loader>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<AdminFeatureFlagBulkPage
|
||||
vm={vm}
|
||||
actions={{
|
||||
onApplyOverride(input) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "bulk-override");
|
||||
form.set("value", String(input.value));
|
||||
form.set("reason", input.reason);
|
||||
form.set("note", input.note);
|
||||
form.set("expiresAt", input.expiresAt);
|
||||
input.tenantIds.forEach((tenantId) => form.append("tenantId", tenantId));
|
||||
submit(form, { method: "post" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function parseOptionalDate(value: FormDataEntryValue | null): Date | null {
|
||||
const text = typeof value === "string" ? value.trim() : "";
|
||||
if (!text) return null;
|
||||
const date = new Date(text);
|
||||
if (!Number.isFinite(date.getTime())) throw new AdminFeatureFlagRolloutError("INVALID_INPUT");
|
||||
return date;
|
||||
}
|
||||
+34
-23
@@ -18,8 +18,8 @@ import { validateCSRFToken, getUserInfo } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { evaluateRule, type TargetingRule } from "@hivegrid/feature-flags";
|
||||
import { invalidateFlagCache } from "~/utils/services/.server/featureFlagEvaluator.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type V2Flag = {
|
||||
id: string;
|
||||
@@ -47,6 +47,14 @@ type LoaderData = {
|
||||
audits: AuditRow[];
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
intent: string;
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
errorValues?: Record<string, string | number>;
|
||||
};
|
||||
|
||||
type RuleValidationError = {
|
||||
key: string;
|
||||
options?: Record<string, string | number>;
|
||||
@@ -168,7 +176,6 @@ export const loader: LoaderFunction = async ({ request }) => {
|
||||
export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
await validateCSRFToken(request);
|
||||
const { t } = await getTranslations(request);
|
||||
const form = await request.formData();
|
||||
const intent = form.get("intent")?.toString() ?? "";
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
@@ -176,13 +183,13 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const actorUserId = userInfo.userId || null;
|
||||
|
||||
const existing = await db.featureFlag.findUnique({ where: { id } });
|
||||
if (!existing) return Response.json({ error: t("featureFlags.engine.errors.notFound") }, { status: 404 });
|
||||
if (!existing) return Response.json({ intent, errorKey: "featureFlags.engine.errors.notFound" } satisfies ActionData, { status: 404 });
|
||||
|
||||
if (intent === "toggle") {
|
||||
const newEnabled = !existing.enabled;
|
||||
await db.$transaction([
|
||||
db.featureFlag.update({ where: { id }, data: { enabled: newEnabled } }),
|
||||
db.featureFlagAudit.create({
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.featureFlag.update({ where: { id }, data: { enabled: newEnabled } });
|
||||
await tx.featureFlagAudit.create({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
@@ -190,10 +197,10 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
oldValue: { enabled: existing.enabled },
|
||||
newValue: { enabled: newEnabled },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
await invalidateFlagCache(existing.name);
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ intent } satisfies ActionData);
|
||||
}
|
||||
|
||||
if (intent === "save-rules") {
|
||||
@@ -203,11 +210,14 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const value = JSON.parse(rulesRaw);
|
||||
parsed = value === null ? null : (value as TargetingRule);
|
||||
} catch {
|
||||
return Response.json({ error: t("featureFlags.engine.errors.invalidRulesJson") }, { status: 400 });
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.invalidRulesJson" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
const validationError = parsed ? validateTargetingRuleShape(parsed) : null;
|
||||
if (validationError) {
|
||||
return Response.json({ error: t(validationError.key, validationError.options) }, { status: 400 });
|
||||
return Response.json(
|
||||
{ intent, errorKey: validationError.key, errorValues: validationError.options } satisfies ActionData,
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
// Validation: evaluate against a representative context to ensure
|
||||
// the rule does not throw (it never does — see evaluator.ts — but
|
||||
@@ -216,9 +226,8 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
if (parsed) {
|
||||
try {
|
||||
evaluateRule(parsed, { flagName: existing.name, tenantId: "ctx_probe", userId: "ctx_probe" });
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t("featureFlags.engine.errors.invalidRule");
|
||||
return Response.json({ error: message }, { status: 400 });
|
||||
} catch {
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.invalidRule" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
}
|
||||
// Prisma's JsonValue type rejects our typed TargetingRule narrowing — cast
|
||||
@@ -227,9 +236,9 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
const rulesForDb = (parsed ?? null) as unknown as never;
|
||||
const auditOldRules = (existing.rules ?? null) as unknown as never;
|
||||
const auditNewRules = (parsed ?? null) as unknown as never;
|
||||
await db.$transaction([
|
||||
db.featureFlag.update({ where: { id }, data: { rules: rulesForDb } }),
|
||||
db.featureFlagAudit.create({
|
||||
await db.$transaction(async (tx) => {
|
||||
await tx.featureFlag.update({ where: { id }, data: { rules: rulesForDb } });
|
||||
await tx.featureFlagAudit.create({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
@@ -237,21 +246,23 @@ export const action = async ({ request }: ActionFunctionArgs) => {
|
||||
oldValue: { rules: auditOldRules } as unknown as never,
|
||||
newValue: { rules: auditNewRules } as unknown as never,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
});
|
||||
});
|
||||
await invalidateFlagCache(existing.name);
|
||||
return Response.json({ ok: true });
|
||||
return Response.json({ intent, ok: true, messageKey: "featureFlags.engine.toast.rulesSaved" } satisfies ActionData);
|
||||
}
|
||||
|
||||
return Response.json({ error: t("featureFlags.engine.errors.unknownIntent") }, { status: 400 });
|
||||
return Response.json({ intent, errorKey: "featureFlags.engine.errors.unknownIntent" } satisfies ActionData, { status: 400 });
|
||||
};
|
||||
|
||||
export default function FeatureFlagsEngineRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher();
|
||||
const fetcher = useFetcher<ActionData>();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
useSaveToast(fetcher.data);
|
||||
|
||||
function submitToggle(flagId: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
@@ -270,7 +281,7 @@ export default function FeatureFlagsEngineRoute() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="mb-12 w-full space-y-5 px-6 py-6 mobile:px-4">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-lg leading-6 font-medium">{t("featureFlags.engine.title")}</h3>
|
||||
<p className="text-muted-foreground text-sm">{t("featureFlags.engine.description")}</p>
|
||||
|
||||
+5
-1
@@ -85,7 +85,11 @@ describe("admin feature flag engine rule validation", () => {
|
||||
})) as Response;
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "rule.op must be AND, OR, or NOT." });
|
||||
await expect(response.json()).resolves.toEqual({
|
||||
intent: "save-rules",
|
||||
errorKey: "featureFlags.engine.errors.invalidCompositeOperator",
|
||||
errorValues: { path: "rule" },
|
||||
});
|
||||
expect(mocks.transaction).not.toHaveBeenCalled();
|
||||
expect(mocks.invalidateFlagCache).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
+11
@@ -7,6 +7,8 @@ const repoRoot = process.cwd();
|
||||
const sourceFiles = [
|
||||
"apps/web/app/routes/admin/feature-flags/index.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags/new.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/flags/$id.tsx",
|
||||
"apps/web/app/routes/admin/feature-flags/engine.tsx",
|
||||
"apps/web/app/modules/featureFlags/components/FeatureFlagForm.tsx",
|
||||
];
|
||||
@@ -30,6 +32,15 @@ describe("feature flags i18n", () => {
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
});
|
||||
|
||||
it("does not expose persistence errors to administrators", () => {
|
||||
const sources = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
|
||||
expect(sources).toContain("featureFlags.errors.createFailed");
|
||||
expect(sources).toContain("featureFlags.errors.updateFailed");
|
||||
expect(sources).toContain("featureFlags.errors.deleteFailed");
|
||||
expect(sources).not.toContain("error: e.message");
|
||||
});
|
||||
|
||||
it("does not keep raw visible admin labels in source", () => {
|
||||
const forbidden = [
|
||||
"`All ",
|
||||
|
||||
+47
-4
@@ -3,11 +3,44 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({ getTranslations: vi.fn(async () => ({ t: (key: string) => key })) }));
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({ verifyUserHasPermission: vi.fn(async () => undefined) }));
|
||||
vi.mock("~/modules/featureFlags/db/featureFlags.db.server", () => ({ getAllFeatureFlags: vi.fn(async () => [{ enabled: true }, { enabled: false }]) }));
|
||||
vi.mock("~/utils/db.server", () => ({ db: { analyticsEvent: { count: vi.fn(async () => 2) } } }));
|
||||
vi.mock("~/modules/featureFlags/db/featureFlags.db.server", () => ({
|
||||
getAllFeatureFlags: vi.fn(async () => [
|
||||
{
|
||||
id: "flag_1",
|
||||
name: "maintenance",
|
||||
description: "Maintenance",
|
||||
enabled: true,
|
||||
scope: "global",
|
||||
tenantId: null,
|
||||
userId: null,
|
||||
filters: [],
|
||||
_count: { events: 2 },
|
||||
rules: null,
|
||||
variants: [],
|
||||
parentFlagId: null,
|
||||
enabledFrom: null,
|
||||
enabledUntil: null,
|
||||
},
|
||||
{
|
||||
id: "flag_2",
|
||||
name: "tenant-api",
|
||||
description: "Tenant API",
|
||||
enabled: false,
|
||||
scope: "tenant",
|
||||
tenantId: "tenant_1",
|
||||
userId: null,
|
||||
filters: [{ id: "filter_1" }],
|
||||
_count: { events: 0 },
|
||||
rules: { type: "boolean", value: true },
|
||||
variants: [],
|
||||
parentFlagId: null,
|
||||
enabledFrom: null,
|
||||
enabledUntil: null,
|
||||
},
|
||||
]),
|
||||
}));
|
||||
|
||||
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
describe("admin feature flag route permissions", () => {
|
||||
@@ -37,6 +70,16 @@ describe("admin feature flag route permissions", () => {
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "admin.featureFlags.view");
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(getAllFeatureFlags).mock.invocationCallOrder[0]);
|
||||
expect(vi.mocked(verifyUserHasPermission).mock.invocationCallOrder[0]).toBeLessThan(vi.mocked(db.analyticsEvent.count).mock.invocationCallOrder[0]);
|
||||
});
|
||||
|
||||
it("returns the feature flag studio summary VM", async () => {
|
||||
const request = new Request("https://admin.example.com/feature-flags");
|
||||
const { loader } = await import("./index");
|
||||
|
||||
const response = await loader({ request, params: {}, context: {} } as never);
|
||||
const data = await response.json();
|
||||
|
||||
expect(data.vm.status).toBe("ready");
|
||||
expect(data.vm.data.summary).toMatchObject({ flagsTotal: 2, flagsEnabled: 1, triggersTotal: 2, highRiskFlags: 1 });
|
||||
});
|
||||
});
|
||||
+21
-13
@@ -1,10 +1,15 @@
|
||||
import { ActionFunctionArgs, LoaderFunction, MetaFunction, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, LoaderFunction, useActionData, useLoaderData } from "react-router";
|
||||
import { FeatureFlag } from "@hivegrid/db/prisma-browser";
|
||||
import { FeatureFlagWithEvents, getFeatureFlag, getFeatureFlagsWithEvents, updateFeatureFlag } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import {
|
||||
FeatureFlagWithEventCount,
|
||||
getFeatureFlag,
|
||||
getLegacyFeatureFlagsWithEventCounts,
|
||||
updateFeatureFlag,
|
||||
} from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import SimpleBadge from "~/components/ui/badges/SimpleBadge";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link, Outlet, useSearchParams, useSubmit } from "react-router";
|
||||
import { Outlet, useSearchParams, useSubmit } from "react-router";
|
||||
import TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
@@ -14,28 +19,28 @@ import InputCheckbox from "~/components/ui/input/InputCheckbox";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import DateCell from "~/components/ui/dates/DateCell";
|
||||
import { v2MetaFunction } from "~/utils/compat/v2MetaFunction";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: FeatureFlagWithEvents[];
|
||||
items: FeatureFlagWithEventCount[];
|
||||
};
|
||||
type ActionData = { intent: "toggle"; errorKey?: string };
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const { t } = await getTranslations(request);
|
||||
const data: LoaderData = {
|
||||
title: `${t("featureFlags.title")} | ${process.env.APP_NAME}`,
|
||||
items: await getFeatureFlagsWithEvents({ enabled: undefined }),
|
||||
items: await getLegacyFeatureFlagsWithEventCounts({ enabled: undefined }),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export const action = async ({ request, params: _params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action")?.toString();
|
||||
@@ -46,16 +51,16 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
const flag = await getFeatureFlag({ id });
|
||||
if (!flag) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 400 });
|
||||
return Response.json({ intent: "toggle", errorKey: "shared.notFound" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
|
||||
await updateFeatureFlag(id, {
|
||||
enabled,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.success") });
|
||||
return Response.json({ intent: "toggle" } satisfies ActionData);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
return Response.json({ intent: "toggle", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -64,8 +69,11 @@ export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.ti
|
||||
export default function CampaignsListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
useSaveToast(actionData);
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
function countStatus(enabled?: boolean) {
|
||||
@@ -94,7 +102,7 @@ export default function CampaignsListRoute() {
|
||||
return data.items;
|
||||
}
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="mb-12 w-full space-y-5 px-6 py-6 mobile:px-4">
|
||||
<div className="flex items-center justify-between space-x-2">
|
||||
<div className="flex-grow">
|
||||
<TabsWithIcons
|
||||
@@ -155,7 +163,7 @@ export default function CampaignsListRoute() {
|
||||
</div>
|
||||
<div className="text-muted-foreground flex items-center space-x-2 text-sm">
|
||||
<span className="lowercase">
|
||||
{i.events.length} {t("featureFlags.triggers")}
|
||||
{i._count.events} {t("featureFlags.triggers")}
|
||||
</span>
|
||||
<div>•</div>
|
||||
<div>
|
||||
|
||||
+26
-8
@@ -1,8 +1,9 @@
|
||||
import { FeatureFlag, FeatureFlagFilter, Role, Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { ActionFunctionArgs, Link, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
@@ -17,6 +18,11 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.feature-flags.edit");
|
||||
|
||||
type LoaderData = {
|
||||
item: FeatureFlag & { filters: FeatureFlagFilter[] };
|
||||
@@ -99,20 +105,27 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
try {
|
||||
await updateFeatureFlag(item.id, { name, description, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.update_failed", ...toSafeErrorLog(error) }, "Admin feature flag update failed");
|
||||
return Response.json({ error: t("featureFlags.errors.updateFailed") }, { status: 500 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.updated")}`);
|
||||
} else if (action === "delete") {
|
||||
await deleteFeatureFlag(item.id);
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
try {
|
||||
await deleteFeatureFlag(item.id);
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.delete_failed", ...toSafeErrorLog(error) }, "Admin feature flag deletion failed");
|
||||
return Response.json({ error: t("featureFlags.errors.deleteFailed") }, { status: 500 });
|
||||
}
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.deleted")}`);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
@@ -134,7 +147,12 @@ export default function () {
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<div className="space-y-4">
|
||||
<div className="flex justify-end">
|
||||
<Link to={adminPath(`feature-flags/${encodeURIComponent(data.item.key ?? data.item.name)}/bulk`, { mode: "host-aware" })}>
|
||||
<Button variant="tertiary">{t("featureFlags.rollout.openBulk")}</Button>
|
||||
</Link>
|
||||
</div>
|
||||
<FeatureFlagForm item={data.item} metadata={data.metadata} onDelete={onDelete} />
|
||||
</div>
|
||||
);
|
||||
|
||||
+11
-6
@@ -1,7 +1,7 @@
|
||||
import { Role, Tenant } from "@hivegrid/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { toast } from "sonner";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
@@ -15,6 +15,10 @@ import { UserSimple, adminGetAllUsers } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { createScopedLogger } from "~/utils/logger.server";
|
||||
import { toSafeErrorLog } from "~/utils/safeErrorLog.server";
|
||||
|
||||
const logger = createScopedLogger("admin.feature-flags.create");
|
||||
|
||||
type LoaderData = {
|
||||
metadata: {
|
||||
@@ -33,7 +37,7 @@ type LoaderData = {
|
||||
};
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
export const loader = async ({ request, params: _params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const metadata = {
|
||||
users: (await adminGetAllUsers()).items,
|
||||
@@ -60,7 +64,7 @@ type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
export const action = async ({ request, params: _params }: ActionFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
await validateCSRFToken(request);
|
||||
@@ -90,11 +94,12 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
|
||||
try {
|
||||
await createFeatureFlag({ name, description, enabled: false, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
} catch (error: unknown) {
|
||||
logger.error({ event: "admin.feature_flags.create_failed", ...toSafeErrorLog(error) }, "Admin feature flag creation failed");
|
||||
return Response.json({ error: t("featureFlags.errors.createFailed") }, { status: 500 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
return redirect(`${adminPath("feature-flags/flags", { mode: "host-aware" })}?toast=${encodeURIComponent("featureFlags.toast.created")}`);
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
|
||||
+188
-40
@@ -1,31 +1,43 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { Link, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { FeatherAlertTriangle, FeatherArrowRight, FeatherGitBranch, FeatherShieldCheck, FeatherToggleLeft, FeatherZap } from "@subframe/core";
|
||||
import { buildFeatureFlagStudioVM, type FeatureFlagStudioData, type FeatureFlagStudioFlag, type FeatureFlagStudioRisk } from "@hivegrid/view-models";
|
||||
import type React from "react";
|
||||
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
import { Button } from "~/ui/components/Button";
|
||||
import { Card } from "~/ui/components/Card";
|
||||
import { StatsCard } from "~/ui/components/StatsCard";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
summary: {
|
||||
flagsTotal: number;
|
||||
flagsEnabled: number;
|
||||
triggersTotal: number;
|
||||
};
|
||||
vm: ReturnType<typeof buildFeatureFlagStudioVM>;
|
||||
};
|
||||
export const loader = async ({ request }: { request: Request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const items = await getAllFeatureFlags();
|
||||
const triggersTotal = await db.analyticsEvent.count({
|
||||
where: { featureFlagId: { not: null } },
|
||||
});
|
||||
const data: LoaderData = {
|
||||
summary: {
|
||||
flagsTotal: items.length,
|
||||
flagsEnabled: items.filter((f) => f.enabled).length,
|
||||
triggersTotal,
|
||||
},
|
||||
vm: buildFeatureFlagStudioVM({
|
||||
flags: items.map((item) => ({
|
||||
id: item.id,
|
||||
name: item.name,
|
||||
description: item.description,
|
||||
enabled: item.enabled,
|
||||
scope: item.scope,
|
||||
tenantId: item.tenantId,
|
||||
userId: item.userId,
|
||||
filtersCount: item.filters.length,
|
||||
eventsCount: item._count.events,
|
||||
rulesConfigured: item.rules !== null,
|
||||
variantsCount: Array.isArray(item.variants) ? item.variants.length : 0,
|
||||
parentFlagId: item.parentFlagId,
|
||||
enabledFrom: item.enabledFrom?.toISOString() ?? null,
|
||||
enabledUntil: item.enabledUntil?.toISOString() ?? null,
|
||||
})),
|
||||
}),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
@@ -34,31 +46,167 @@ export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const vm = data.vm.status === "ready" ? data.vm.data : null;
|
||||
return (
|
||||
<div className="mx-auto mb-12 max-w-5xl space-y-5 px-4 py-4 sm:px-6 lg:px-8 xl:max-w-7xl">
|
||||
<div className="border-border border-b pb-5">
|
||||
<h3 className="text-lg font-medium leading-6">{t("shared.overview")}</h3>
|
||||
<div className="mobile:px-4 mb-12 w-full space-y-5 px-6 py-6">
|
||||
<div className="border-border-default flex flex-wrap items-start justify-between gap-3 border-b pb-5">
|
||||
<div className="flex flex-col items-start">
|
||||
<h3 className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.title")}</h3>
|
||||
<p className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("featureFlags.studio.description")}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Link to={adminPath("feature-flags/flags", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("featureFlags.studio.actions.openFlags")}
|
||||
</Button>
|
||||
</Link>
|
||||
<Link to={adminPath("feature-flags/engine", { mode: "host-aware" })}>
|
||||
<Button variant="tertiary" size="small" iconRight={<FeatherArrowRight />}>
|
||||
{t("featureFlags.studio.actions.openEngine")}
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="grid gap-2 sm:grid-cols-2">
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow ">
|
||||
<dt className="text-muted-foreground flex items-center space-x-2 truncate text-xs font-medium uppercase">
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<div>{t("featureFlags.plural")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 flex items-baseline space-x-1 truncate text-2xl font-semibold">
|
||||
<div>
|
||||
{formatters.number(data.summary.flagsEnabled)}/{formatters.number(data.summary.flagsTotal)}
|
||||
</div>
|
||||
<div className="text-muted-foreground text-xs font-normal lowercase">{t("featureFlags.enabled")}</div>
|
||||
</dd>
|
||||
</div>
|
||||
<div className="bg-background overflow-hidden rounded-lg px-4 py-3 shadow ">
|
||||
<dt className="text-muted-foreground truncate text-xs font-medium uppercase">
|
||||
<div>{t("featureFlags.triggers")}</div>
|
||||
</dt>
|
||||
<dd className="mt-1 truncate text-2xl font-semibold">{formatters.number(data.summary.triggersTotal)}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
{vm ? <FeatureFlagStudio data={vm} formatNumber={formatters.number} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FeatureFlagStudio({ data, formatNumber }: { data: FeatureFlagStudioData; formatNumber: (value: number) => string }) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<div className="space-y-5">
|
||||
<div className="mobile:grid-cols-1 grid gap-4 md:grid-cols-2 xl:grid-cols-4">
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.enabled")}
|
||||
value={`${formatNumber(data.summary.flagsEnabled)}/${formatNumber(data.summary.flagsTotal)}`}
|
||||
icon={<FeatherToggleLeft />}
|
||||
tone={data.summary.flagsEnabled > 0 ? "success" : "neutral"}
|
||||
/>
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.targeted")}
|
||||
value={formatNumber(data.summary.targetedFlags)}
|
||||
icon={<FeatherGitBranch />}
|
||||
tone={data.summary.targetedFlags > 0 ? "success" : "warning"}
|
||||
/>
|
||||
<StudioKpi title={t("featureFlags.studio.summary.triggers")} value={formatNumber(data.summary.triggersTotal)} icon={<FeatherZap />} tone="neutral" />
|
||||
<StudioKpi
|
||||
title={t("featureFlags.studio.summary.highRisk")}
|
||||
value={formatNumber(data.summary.highRiskFlags)}
|
||||
icon={<FeatherAlertTriangle />}
|
||||
tone={data.summary.highRiskFlags > 0 ? "danger" : "success"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{data.summary.highRiskFlags > 0 ? (
|
||||
<BannerAlert type="warning" fillContainer>
|
||||
{t("featureFlags.studio.riskBanner.title")} — {t("featureFlags.studio.riskBanner.body")}
|
||||
</BannerAlert>
|
||||
) : null}
|
||||
|
||||
<div className="grid gap-4 lg:grid-cols-[minmax(0,1fr)_minmax(320px,0.7fr)]">
|
||||
<TopFlagsCard flags={data.topFlags} />
|
||||
<RolloutReadinessCard data={data} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StudioKpi({ title, value, icon, tone }: { title: string; value: string; icon: React.ReactNode; tone: "success" | "warning" | "danger" | "neutral" }) {
|
||||
return (
|
||||
<StatsCard
|
||||
label={title}
|
||||
value={value}
|
||||
trend={tone === "success" ? "positive" : tone === "danger" || tone === "warning" ? "negative" : "neutral"}
|
||||
percentage=""
|
||||
comparisonText=""
|
||||
icon={icon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TopFlagsCard({ flags }: { flags: readonly FeatureFlagStudioFlag[] }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.topFlags.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.topFlags.description")}
|
||||
</span>
|
||||
</div>
|
||||
{flags.length === 0 ? (
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("featureFlags.empty.description")}</span>
|
||||
) : (
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{flags.map((flag) => (
|
||||
<div
|
||||
key={flag.id}
|
||||
className="border-border-default bg-surface-neutral-primary flex w-full flex-col items-start gap-2 rounded-md border border-solid px-4 py-3"
|
||||
>
|
||||
<div className="flex w-full flex-wrap items-start justify-between gap-2">
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary truncate">{flag.description}</span>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary truncate">{flag.name}</span>
|
||||
</div>
|
||||
<BadgeFeedback farbe={riskTone(flag.risk)} size="small">
|
||||
{t(flag.riskLabelKey)}
|
||||
</BadgeFeedback>
|
||||
</div>
|
||||
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.topFlags.meta", {
|
||||
triggers: flag.eventsCount,
|
||||
filters: flag.filtersCount,
|
||||
scope: flag.scope ?? "global",
|
||||
})}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function RolloutReadinessCard({ data }: { data: FeatureFlagStudioData }) {
|
||||
const { t } = useTranslation();
|
||||
const items = [
|
||||
{ label: t("featureFlags.studio.readiness.scoped"), value: data.summary.scopedFlags },
|
||||
{ label: t("featureFlags.studio.readiness.scheduled"), value: data.summary.scheduledFlags },
|
||||
{ label: t("featureFlags.studio.readiness.disabled"), value: data.summary.flagsDisabled },
|
||||
];
|
||||
return (
|
||||
<Card>
|
||||
<div className="flex w-full items-start gap-3">
|
||||
<span className="text-heading- font-heading- text-icon-neutral-tertiary">
|
||||
<FeatherShieldCheck />
|
||||
</span>
|
||||
<div className="flex min-w-0 flex-col items-start">
|
||||
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("featureFlags.studio.readiness.title")}</span>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
|
||||
{t("featureFlags.studio.readiness.description")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex w-full flex-col items-start gap-2">
|
||||
{items.map((item) => (
|
||||
<div
|
||||
key={item.label}
|
||||
className="border-border-default bg-surface-neutral-primary flex w-full items-center justify-between gap-3 rounded-md border border-solid px-4 py-2"
|
||||
>
|
||||
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{item.label}</span>
|
||||
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{item.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function riskTone(risk: FeatureFlagStudioRisk): "subtle-negative" | "subtle-warning" | "subtle-positive" {
|
||||
if (risk === "high") return "subtle-negative";
|
||||
if (risk === "medium") return "subtle-warning";
|
||||
return "subtle-positive";
|
||||
}
|
||||
+15
-25
@@ -4,33 +4,32 @@ import { useTranslation } from "react-i18next";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import IndexPageLayout from "~/components/ui/layouts/IndexPageLayout";
|
||||
import SettingSection from "~/components/ui/sections/SettingSection";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { deleteAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { useSaveToast } from "~/hooks/use-save-toast";
|
||||
|
||||
type ActionData = {
|
||||
deleteError?: string;
|
||||
deleteSuccess?: boolean;
|
||||
intent: "delete-all";
|
||||
ok?: true;
|
||||
messageKey?: string;
|
||||
errorKey?: string;
|
||||
};
|
||||
export const action: ActionFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.manage");
|
||||
const { t } = await getTranslations(request);
|
||||
|
||||
await validateCSRFToken(request);
|
||||
const form = await request.formData();
|
||||
const action = form.get("action");
|
||||
if (action === "delete-all") {
|
||||
await db.analyticsEvent.deleteMany({ where: { featureFlagId: { not: null } } });
|
||||
await db.featureFlag.deleteMany({});
|
||||
return Response.json({
|
||||
deleteSuccess: true,
|
||||
});
|
||||
try {
|
||||
await deleteAllFeatureFlags();
|
||||
return Response.json({ intent: "delete-all", ok: true, messageKey: "featureFlags.danger.toast.reset" } satisfies ActionData);
|
||||
} catch {
|
||||
return Response.json({ intent: "delete-all", errorKey: "featureFlags.danger.errors.resetFailed" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
} else {
|
||||
return Response.json({
|
||||
error: t("shared.invalidForm"),
|
||||
});
|
||||
return Response.json({ intent: "delete-all", errorKey: "shared.invalidForm" } satisfies ActionData, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -38,6 +37,8 @@ export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
useSaveToast(actionData);
|
||||
return (
|
||||
<>
|
||||
<IndexPageLayout>
|
||||
@@ -55,17 +56,6 @@ export default function AdminAnalyticsOverviewRoute() {
|
||||
{t("featureFlags.danger.reset.title")}
|
||||
</ButtonPrimary>
|
||||
|
||||
{actionData?.deleteSuccess ? (
|
||||
<p className="py-2 text-xs text-green-500" role="alert">
|
||||
{t("analytics.deleted")}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{actionData?.deleteError ? (
|
||||
<p className="py-2 text-xs text-rose-500" role="alert">
|
||||
{actionData.deleteError}
|
||||
</p>
|
||||
) : null}
|
||||
</Form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user