Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,341 @@
|
||||
/**
|
||||
* Feature-Flags Engine v2 admin — list + rule-JSON editor + audit.
|
||||
*
|
||||
* Sits alongside the existing flag-management routes; this one is the
|
||||
* thin surface for the v2 targeting engine (#53) and intentionally
|
||||
* doesn't replace the legacy boolean-toggle UI. A visual rule-builder
|
||||
* is deferred to a follow-up — operators here author the rules-tree
|
||||
* as JSON in a textarea, which the action validates by re-evaluating
|
||||
* with a representative context before persisting.
|
||||
*/
|
||||
|
||||
import { ActionFunctionArgs, LoaderFunction, useFetcher, useLoaderData } from "react-router";
|
||||
import { useRef } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken, getUserInfo } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { evaluateRule, type TargetingRule } from "@toolctrl/feature-flags";
|
||||
import { invalidateFlagCache } from "~/utils/services/.server/featureFlagEvaluator.server";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type V2Flag = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
enabled: boolean;
|
||||
rules: unknown;
|
||||
variantsJson: string;
|
||||
enabledFrom: string | null;
|
||||
enabledUntil: string | null;
|
||||
parentFlagId: string | null;
|
||||
};
|
||||
|
||||
type AuditRow = {
|
||||
id: string;
|
||||
flagId: string;
|
||||
flagName: string;
|
||||
actorUserId: string | null;
|
||||
action: string;
|
||||
createdAt: string;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
flags: V2Flag[];
|
||||
audits: AuditRow[];
|
||||
};
|
||||
|
||||
type RuleValidationError = {
|
||||
key: string;
|
||||
options?: Record<string, string | number>;
|
||||
};
|
||||
|
||||
const ruleTypes = new Set(["boolean", "allowlist", "percentage", "plan-tier", "role-based", "time-based", "composite"]);
|
||||
const compositeOperators = new Set(["AND", "OR", "NOT"]);
|
||||
|
||||
function validateTargetingRuleShape(value: unknown, path = "rule"): RuleValidationError | null {
|
||||
if (!isRecord(value)) {
|
||||
return { key: "featureFlags.engine.errors.invalidRuleObject", options: { path } };
|
||||
}
|
||||
|
||||
if (typeof value.type !== "string" || !ruleTypes.has(value.type)) {
|
||||
return { key: "featureFlags.engine.errors.invalidRuleType", options: { path } };
|
||||
}
|
||||
|
||||
switch (value.type) {
|
||||
case "boolean":
|
||||
return typeof value.value === "boolean" ? null : { key: "featureFlags.engine.errors.invalidBooleanValue", options: { path } };
|
||||
case "allowlist": {
|
||||
for (const key of ["tenantIds", "userIds", "emails"] as const) {
|
||||
if (value[key] !== undefined && !isStringArray(value[key])) {
|
||||
return { key: "featureFlags.engine.errors.invalidStringArray", options: { path: `${path}.${key}` } };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
case "percentage":
|
||||
if (typeof value.rolloutPercent !== "number" || !Number.isFinite(value.rolloutPercent) || value.rolloutPercent < 0 || value.rolloutPercent > 100) {
|
||||
return { key: "featureFlags.engine.errors.invalidRolloutPercent", options: { path } };
|
||||
}
|
||||
if (value.bucketBy !== undefined && value.bucketBy !== "userId" && value.bucketBy !== "tenantId") {
|
||||
return { key: "featureFlags.engine.errors.invalidBucketBy", options: { path } };
|
||||
}
|
||||
return null;
|
||||
case "plan-tier":
|
||||
return isStringArray(value.plans) ? null : { key: "featureFlags.engine.errors.invalidStringArray", options: { path: `${path}.plans` } };
|
||||
case "role-based":
|
||||
return isStringArray(value.roles) ? null : { key: "featureFlags.engine.errors.invalidStringArray", options: { path: `${path}.roles` } };
|
||||
case "time-based":
|
||||
for (const key of ["enabledFrom", "enabledUntil"] as const) {
|
||||
if (value[key] !== undefined && typeof value[key] !== "string") {
|
||||
return { key: "featureFlags.engine.errors.invalidTimeBound", options: { path: `${path}.${key}` } };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
case "composite": {
|
||||
if (typeof value.op !== "string" || !compositeOperators.has(value.op)) {
|
||||
return { key: "featureFlags.engine.errors.invalidCompositeOperator", options: { path } };
|
||||
}
|
||||
if (!Array.isArray(value.children)) {
|
||||
return { key: "featureFlags.engine.errors.invalidCompositeChildren", options: { path } };
|
||||
}
|
||||
for (let index = 0; index < value.children.length; index += 1) {
|
||||
const childError = validateTargetingRuleShape(value.children[index], `${path}.children[${index}]`);
|
||||
if (childError) return childError;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
default:
|
||||
return { key: "featureFlags.engine.errors.invalidRule" };
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isStringArray(value: unknown): value is string[] {
|
||||
return Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
||||
}
|
||||
|
||||
export const loader: LoaderFunction = async ({ request }) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const flags = await db.featureFlag.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
select: {
|
||||
id: true,
|
||||
name: true,
|
||||
description: true,
|
||||
enabled: true,
|
||||
rules: true,
|
||||
variants: true,
|
||||
enabledFrom: true,
|
||||
enabledUntil: true,
|
||||
parentFlagId: true,
|
||||
},
|
||||
});
|
||||
const audits = await db.featureFlagAudit.findMany({
|
||||
orderBy: { createdAt: "desc" },
|
||||
take: 50,
|
||||
include: { flag: { select: { name: true } } },
|
||||
});
|
||||
const data: LoaderData = {
|
||||
flags: flags.map((f) => ({
|
||||
id: f.id,
|
||||
name: f.name,
|
||||
description: f.description,
|
||||
enabled: f.enabled,
|
||||
rules: f.rules ?? null,
|
||||
variantsJson: JSON.stringify(f.variants ?? []),
|
||||
enabledFrom: f.enabledFrom ? f.enabledFrom.toISOString() : null,
|
||||
enabledUntil: f.enabledUntil ? f.enabledUntil.toISOString() : null,
|
||||
parentFlagId: f.parentFlagId,
|
||||
})),
|
||||
audits: audits.map((a) => ({
|
||||
id: a.id,
|
||||
flagId: a.flagId,
|
||||
flagName: a.flag.name,
|
||||
actorUserId: a.actorUserId,
|
||||
action: a.action,
|
||||
createdAt: a.createdAt.toISOString(),
|
||||
})),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
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() ?? "";
|
||||
const userInfo = await getUserInfo(request);
|
||||
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 (intent === "toggle") {
|
||||
const newEnabled = !existing.enabled;
|
||||
await db.$transaction([
|
||||
db.featureFlag.update({ where: { id }, data: { enabled: newEnabled } }),
|
||||
db.featureFlagAudit.create({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
action: "toggle",
|
||||
oldValue: { enabled: existing.enabled },
|
||||
newValue: { enabled: newEnabled },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
await invalidateFlagCache(existing.name);
|
||||
return Response.json({ ok: true });
|
||||
}
|
||||
|
||||
if (intent === "save-rules") {
|
||||
const rulesRaw = form.get("rules")?.toString() ?? "null";
|
||||
let parsed: TargetingRule | null;
|
||||
try {
|
||||
const value = JSON.parse(rulesRaw);
|
||||
parsed = value === null ? null : (value as TargetingRule);
|
||||
} catch {
|
||||
return Response.json({ error: t("featureFlags.engine.errors.invalidRulesJson") }, { status: 400 });
|
||||
}
|
||||
const validationError = parsed ? validateTargetingRuleShape(parsed) : null;
|
||||
if (validationError) {
|
||||
return Response.json({ error: t(validationError.key, validationError.options) }, { status: 400 });
|
||||
}
|
||||
// Validation: evaluate against a representative context to ensure
|
||||
// the rule does not throw (it never does — see evaluator.ts — but
|
||||
// this catches a structurally-wrong tree early). Empty composite
|
||||
// children → false, which is acceptable.
|
||||
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 });
|
||||
}
|
||||
}
|
||||
// Prisma's JsonValue type rejects our typed TargetingRule narrowing — cast
|
||||
// through `unknown` so the JSON column accepts the validated tree (the
|
||||
// evaluateRule call above is the runtime guarantee, not the TS shape).
|
||||
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({
|
||||
data: {
|
||||
flagId: id,
|
||||
actorUserId,
|
||||
action: "update",
|
||||
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({ error: t("featureFlags.engine.errors.unknownIntent") }, { status: 400 });
|
||||
};
|
||||
|
||||
export default function FeatureFlagsEngineRoute() {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const fetcher = useFetcher();
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
|
||||
function submitToggle(flagId: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("intent", "toggle");
|
||||
form.set("id", flagId);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
function submitRules(flagId: string, rules: string) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("intent", "save-rules");
|
||||
form.set("id", flagId);
|
||||
form.set("rules", rules);
|
||||
fetcher.submit(form, { method: "post" });
|
||||
}
|
||||
|
||||
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 leading-6 font-medium">{t("featureFlags.engine.title")}</h3>
|
||||
<p className="text-muted-foreground text-sm">{t("featureFlags.engine.description")}</p>
|
||||
</div>
|
||||
|
||||
<section>
|
||||
<h4 className="text-sm font-semibold tracking-wide uppercase">{t("featureFlags.plural")}</h4>
|
||||
<ul className="divide-border mt-2 divide-y">
|
||||
{data.flags.map((flag) => (
|
||||
<FlagRow key={flag.id} flag={flag} onToggle={() => submitToggle(flag.id)} onSaveRules={(rules) => submitRules(flag.id, rules)} />
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h4 className="text-sm font-semibold tracking-wide uppercase">{t("featureFlags.engine.auditLogLast50")}</h4>
|
||||
<ul className="divide-border mt-2 divide-y text-sm">
|
||||
{data.audits.map((a) => (
|
||||
<li key={a.id} className="py-2">
|
||||
<time dateTime={a.createdAt} className="text-muted-foreground font-mono text-xs">
|
||||
{formatters.dateTime(a.createdAt, { timeStyle: "medium" })}
|
||||
</time>{" "}
|
||||
<span className="font-medium">{a.flagName}</span> —{" "}
|
||||
<span>{a.action}</span>
|
||||
{a.actorUserId ? <span className="text-muted-foreground"> {t("featureFlags.engine.auditActor", { actor: a.actorUserId })}</span> : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FlagRow(props: { flag: V2Flag; onToggle: () => void; onSaveRules: (rules: string) => void }) {
|
||||
const { flag } = props;
|
||||
const { t } = useTranslation();
|
||||
const rulesRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
return (
|
||||
<li className="space-y-2 py-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="font-medium">{flag.name}</div>
|
||||
<div className="text-muted-foreground text-xs">{flag.description}</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={props.onToggle}
|
||||
className={`rounded-md border px-3 py-1 text-sm ${flag.enabled ? "border-green-300 bg-green-50" : "border-gray-300 bg-gray-50"}`}
|
||||
>
|
||||
{flag.enabled ? t("featureFlags.engine.status.enabled") : t("featureFlags.engine.status.disabled")}
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<textarea
|
||||
ref={rulesRef}
|
||||
defaultValue={flag.rules ? JSON.stringify(flag.rules, null, 2) : ""}
|
||||
placeholder={t("featureFlags.engine.rulesPlaceholder")}
|
||||
rows={6}
|
||||
className="border-border bg-background w-full rounded-md border px-2 py-1 font-mono text-xs"
|
||||
/>
|
||||
<button type="button" onClick={() => props.onSaveRules(rulesRef.current?.value ?? "")} className="rounded-md border px-3 py-1 text-sm">
|
||||
{t("featureFlags.engine.actions.saveRules")}
|
||||
</button>
|
||||
</div>
|
||||
{flag.parentFlagId ? <p className="text-muted-foreground text-xs">{t("featureFlags.engine.parentFlag", { id: flag.parentFlagId })}</p> : null}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
// @vitest-environment node
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
findUnique: vi.fn(),
|
||||
update: vi.fn(),
|
||||
auditCreate: vi.fn(),
|
||||
transaction: vi.fn(),
|
||||
invalidateFlagCache: vi.fn(),
|
||||
verifyUserHasPermission: vi.fn(),
|
||||
validateCSRFToken: vi.fn(),
|
||||
getUserInfo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("~/locale/i18next.server", () => ({
|
||||
getTranslations: vi.fn(async () => ({
|
||||
t: (key: string, options?: Record<string, string | number>) => {
|
||||
if (key === "featureFlags.engine.errors.invalidCompositeOperator") {
|
||||
return `${options?.path}.op must be AND, OR, or NOT.`;
|
||||
}
|
||||
return key;
|
||||
},
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/helpers/.server/PermissionsService", () => ({
|
||||
verifyUserHasPermission: mocks.verifyUserHasPermission,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/session.server", () => ({
|
||||
validateCSRFToken: mocks.validateCSRFToken,
|
||||
getUserInfo: mocks.getUserInfo,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/services/.server/featureFlagEvaluator.server", () => ({
|
||||
invalidateFlagCache: mocks.invalidateFlagCache,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/db.server", () => ({
|
||||
db: {
|
||||
featureFlag: {
|
||||
findUnique: mocks.findUnique,
|
||||
update: mocks.update,
|
||||
},
|
||||
featureFlagAudit: {
|
||||
create: mocks.auditCreate,
|
||||
},
|
||||
$transaction: mocks.transaction,
|
||||
},
|
||||
}));
|
||||
|
||||
function requestForRules(rules: unknown) {
|
||||
const body = new URLSearchParams({
|
||||
intent: "save-rules",
|
||||
id: "flag_1",
|
||||
rules: JSON.stringify(rules),
|
||||
});
|
||||
return new Request("https://admin.example.com/feature-flags/engine", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body,
|
||||
});
|
||||
}
|
||||
|
||||
describe("admin feature flag engine rule validation", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.verifyUserHasPermission.mockResolvedValue(undefined);
|
||||
mocks.validateCSRFToken.mockResolvedValue(undefined);
|
||||
mocks.getUserInfo.mockResolvedValue({ userId: "user_1" });
|
||||
mocks.findUnique.mockResolvedValue({
|
||||
id: "flag_1",
|
||||
name: "checkout.beta",
|
||||
enabled: true,
|
||||
rules: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a specific error for unsupported composite operators before persisting", async () => {
|
||||
const { action } = await import("./engine");
|
||||
const response = (await action({
|
||||
request: requestForRules({ type: "composite", op: "XOR", children: [] }),
|
||||
params: {},
|
||||
context: {},
|
||||
})) as Response;
|
||||
|
||||
expect(response.status).toBe(400);
|
||||
await expect(response.json()).resolves.toEqual({ error: "rule.op must be AND, OR, or NOT." });
|
||||
expect(mocks.transaction).not.toHaveBeenCalled();
|
||||
expect(mocks.invalidateFlagCache).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
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/engine.tsx",
|
||||
"apps/web/app/modules/featureFlags/components/FeatureFlagForm.tsx",
|
||||
];
|
||||
|
||||
describe("feature flags i18n", () => {
|
||||
it("uses semantic keys for tabs, table labels, and form chrome", () => {
|
||||
const sources = sourceFiles.map((file) => fs.readFileSync(path.join(repoRoot, file), "utf8")).join("\n");
|
||||
|
||||
expect(sources).toContain("featureFlags.tabs.all");
|
||||
expect(sources).toContain("featureFlags.tabs.active");
|
||||
expect(sources).toContain("featureFlags.tabs.inactive");
|
||||
expect(sources).toContain("featureFlags.empty.demoTitle");
|
||||
expect(sources).toContain("featureFlags.engine.auditLogLast50");
|
||||
expect(sources).toContain("featureFlags.engine.actions.saveRules");
|
||||
expect(sources).toContain("featureFlags.form.createTitle");
|
||||
expect(sources).toContain("featureFlags.form.hints.internalName");
|
||||
expect(sources).toContain("useLocaleFormatters");
|
||||
expect(sources).toContain("formatters.dateTime(a.createdAt");
|
||||
expect(sources).not.toContain("ui.autogenerated");
|
||||
expect(sources).not.toContain("i18nT");
|
||||
expect(sources).not.toContain("NumberUtils");
|
||||
});
|
||||
|
||||
it("does not keep raw visible admin labels in source", () => {
|
||||
const forbidden = [
|
||||
"`All ",
|
||||
"`Active ",
|
||||
"`Inactive ",
|
||||
'title="Demo"',
|
||||
'title: "Status"',
|
||||
'"Edit flag"',
|
||||
'"Create flag"',
|
||||
'"Edit the feature flag."',
|
||||
'"Create a new feature flag."',
|
||||
'"Set default currency"',
|
||||
"{a.createdAt}</span>",
|
||||
];
|
||||
|
||||
for (const file of sourceFiles) {
|
||||
const source = fs.readFileSync(path.join(repoRoot, file), "utf8");
|
||||
for (const literal of forbidden) {
|
||||
expect(source).not.toContain(literal);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
// @vitest-environment node
|
||||
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) } } }));
|
||||
|
||||
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", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("checks view permission on the parent loader", async () => {
|
||||
const request = new Request("https://admin.example.com/feature-flags");
|
||||
const { loader } = await import("../feature-flags");
|
||||
|
||||
await loader({ request, params: {}, context: {} } as never);
|
||||
|
||||
expect(verifyUserHasPermission).toHaveBeenCalledWith(request, "admin.featureFlags.view");
|
||||
});
|
||||
|
||||
it("checks view permission before reading feature flag summary data", async () => {
|
||||
const request = new Request("https://admin.example.com/feature-flags");
|
||||
const { loader } = await import("./index");
|
||||
|
||||
await loader({ request, params: {}, context: {} } as never);
|
||||
|
||||
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]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,194 @@
|
||||
import { ActionFunctionArgs, LoaderFunction, MetaFunction, useLoaderData } from "react-router";
|
||||
import { FeatureFlag } from "@toolctrl/db/prisma-browser";
|
||||
import { FeatureFlagWithEvents, getFeatureFlag, getFeatureFlagsWithEvents, 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 TabsWithIcons from "~/components/ui/tabs/TabsWithIcons";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import PlusIcon from "~/components/ui/icons/PlusIcon";
|
||||
import InfoBanner from "~/components/ui/banners/InfoBanner";
|
||||
import TableSimple from "~/components/ui/tables/TableSimple";
|
||||
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";
|
||||
|
||||
type LoaderData = {
|
||||
title: string;
|
||||
items: FeatureFlagWithEvents[];
|
||||
};
|
||||
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 }),
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export const action = async ({ request, 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();
|
||||
|
||||
if (action === "toggle") {
|
||||
const id = form.get("id")?.toString() ?? "";
|
||||
const enabled = form.get("enabled")?.toString() === "true";
|
||||
|
||||
const flag = await getFeatureFlag({ id });
|
||||
if (!flag) {
|
||||
return Response.json({ error: t("shared.notFound") }, { status: 400 });
|
||||
}
|
||||
|
||||
await updateFeatureFlag(id, {
|
||||
enabled,
|
||||
});
|
||||
|
||||
return Response.json({ success: t("shared.success") });
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export const meta: v2MetaFunction<LoaderData> = ({ data }) => [{ title: data?.title }];
|
||||
|
||||
export default function CampaignsListRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
const [searchParams] = useSearchParams();
|
||||
|
||||
function countStatus(enabled?: boolean) {
|
||||
if (enabled === undefined) {
|
||||
return data.items.length;
|
||||
}
|
||||
return data.items.filter((item) => item.enabled === enabled).length;
|
||||
}
|
||||
function onToggle(item: FeatureFlag, enabled: boolean) {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "toggle");
|
||||
form.set("enabled", enabled.toString());
|
||||
form.set("id", item.id.toString());
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
function filteredItems() {
|
||||
if (searchParams.get("status") === "active") {
|
||||
return data.items.filter((item) => item.enabled);
|
||||
}
|
||||
if (searchParams.get("status") === "inactive") {
|
||||
return data.items.filter((item) => !item.enabled);
|
||||
}
|
||||
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="flex items-center justify-between space-x-2">
|
||||
<div className="flex-grow">
|
||||
<TabsWithIcons
|
||||
tabs={[
|
||||
{
|
||||
name: t("featureFlags.tabs.all", { count: countStatus() }),
|
||||
href: "?",
|
||||
current: !searchParams.get("status") || searchParams.get("status") === "all",
|
||||
},
|
||||
{
|
||||
name: t("featureFlags.tabs.active", { count: countStatus(true) }),
|
||||
href: "?status=active",
|
||||
current: searchParams.get("status") === "active",
|
||||
},
|
||||
{
|
||||
name: t("featureFlags.tabs.inactive", { count: countStatus(false) }),
|
||||
href: "?status=inactive",
|
||||
current: searchParams.get("status") === "inactive",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<ButtonPrimary to="new">
|
||||
<div>{t("shared.new")}</div>
|
||||
<PlusIcon className="h-5 w-5" />
|
||||
</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{data.items.length === 0 && <InfoBanner title={t("featureFlags.empty.demoTitle")} text={t("featureFlags.empty.demo")} />}
|
||||
|
||||
<TableSimple
|
||||
items={filteredItems()}
|
||||
actions={[
|
||||
{
|
||||
title: t("shared.overview"),
|
||||
onClickRoute: (_, i) => `${i.id}`,
|
||||
},
|
||||
]}
|
||||
headers={[
|
||||
{
|
||||
name: "status",
|
||||
title: t("shared.status"),
|
||||
value: (i) => {
|
||||
return <InputCheckbox asToggle value={i.enabled} setValue={(checked) => onToggle(i, Boolean(checked))} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "featureFlag",
|
||||
title: t("featureFlags.object"),
|
||||
className: "w-full",
|
||||
value: (i) => (
|
||||
<div className="flex flex-col">
|
||||
<div className="flex items-center space-x-2">
|
||||
<div className="text-base font-bold">{i.description}</div>
|
||||
<SimpleBadge title={i.name} color={Colors.GRAY} />
|
||||
</div>
|
||||
<div className="text-muted-foreground flex items-center space-x-2 text-sm">
|
||||
<Link to={adminPath("analytics/events?featureFlagId=" + i.id, { mode: "host-aware" })} className="lowercase">
|
||||
{i.events.length} {t("featureFlags.triggers")}
|
||||
</Link>
|
||||
<div>•</div>
|
||||
<div>
|
||||
{i.filters.length === 0 ? (
|
||||
<span>{t("featureFlags.noFilters")}</span>
|
||||
) : i.filters.length === 1 ? (
|
||||
<span>{t("featureFlags.filter")}: </span>
|
||||
) : (
|
||||
<span className="lowercase">
|
||||
{i.filters.length} {t("featureFlags.filters")}:{" "}
|
||||
</span>
|
||||
)}
|
||||
{i.filters.map((f) => f.type).join(", ")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "createdAt",
|
||||
title: t("shared.createdAt"),
|
||||
value: (i) => <DateCell date={i.createdAt} />,
|
||||
},
|
||||
]}
|
||||
noRecords={
|
||||
<div className="p-12 text-center">
|
||||
<h3 className="mt-1 text-sm font-medium text-gray-900">{t("featureFlags.empty.title")}</h3>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{t("featureFlags.empty.description")}</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
<Outlet />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { FeatureFlag, FeatureFlagFilter, Role, Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useSubmit } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
import FeatureFlagForm from "~/modules/featureFlags/components/FeatureFlagForm";
|
||||
import { deleteFeatureFlag, getFeatureFlag, updateFeatureFlag } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { FeatureFlagsFilterType } from "~/modules/featureFlags/dtos/FeatureFlagsFilterTypes";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
import { UserSimple, adminGetAllUsers } from "~/utils/db/users.db.server";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { appendCSRFToken } from "~/utils/csrf";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
item: FeatureFlag & { filters: FeatureFlagFilter[] };
|
||||
metadata: {
|
||||
users: UserSimple[];
|
||||
tenants: Tenant[];
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
roles: Role[];
|
||||
analytics: {
|
||||
via: { name: string; count: number }[];
|
||||
httpReferrer: { name: string; count: number }[];
|
||||
browser: { name: string; count: number }[];
|
||||
os: { name: string; count: number }[];
|
||||
source: { name: string; count: number }[];
|
||||
medium: { name: string; count: number }[];
|
||||
campaign: { name: string; count: number }[];
|
||||
};
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const metadata = {
|
||||
users: (await adminGetAllUsers()).items,
|
||||
tenants: await adminGetAllTenants(),
|
||||
subscriptionProducts: await getAllSubscriptionProducts(),
|
||||
roles: await getAllRoles(),
|
||||
analytics: {
|
||||
via: await groupUniqueVisitorsBy("via"),
|
||||
httpReferrer: await groupUniqueVisitorsBy("httpReferrer"),
|
||||
browser: await groupUniqueVisitorsBy("browser"),
|
||||
os: await groupUniqueVisitorsBy("os"),
|
||||
source: await groupUniqueVisitorsBy("source"),
|
||||
medium: await groupUniqueVisitorsBy("medium"),
|
||||
campaign: await groupUniqueVisitorsBy("campaign"),
|
||||
},
|
||||
};
|
||||
const item = await getFeatureFlag({ id: params.id!, enabled: undefined });
|
||||
if (!item) {
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
}
|
||||
const data: LoaderData = {
|
||||
item,
|
||||
metadata,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, 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();
|
||||
|
||||
const item = await getFeatureFlag({ id: params.id!, enabled: undefined });
|
||||
if (!item) {
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
}
|
||||
|
||||
if (action === "edit") {
|
||||
const name = form.get("name")?.toString();
|
||||
const description = form.get("description")?.toString();
|
||||
|
||||
const filters: { type: FeatureFlagsFilterType; value: string | null; action: string | null }[] = form.getAll("filters[]").map((f) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!name || !description) {
|
||||
return Response.json({ error: t("featureFlags.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
|
||||
const existingFlag = await getFeatureFlag({ name, description });
|
||||
if (existingFlag && existingFlag.id !== item.id) {
|
||||
return Response.json({ error: t("featureFlags.errors.duplicateNameAndDescription") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await updateFeatureFlag(item.id, { name, description, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
} else if (action === "delete") {
|
||||
await deleteFeatureFlag(item.id);
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const submit = useSubmit();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
function onDelete() {
|
||||
const form = new FormData();
|
||||
appendCSRFToken(form);
|
||||
form.set("action", "delete");
|
||||
submit(form, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<FeatureFlagForm item={data.item} metadata={data.metadata} onDelete={onDelete} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { Role, Tenant } from "@toolctrl/db/prisma-browser";
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useEffect } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { groupUniqueVisitorsBy } from "~/modules/analytics/db/analyticsUniqueVisitors.db.server";
|
||||
import FeatureFlagForm from "~/modules/featureFlags/components/FeatureFlagForm";
|
||||
import { createFeatureFlag, getFeatureFlag } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { FeatureFlagsFilterType } from "~/modules/featureFlags/dtos/FeatureFlagsFilterTypes";
|
||||
import { getAllRoles } from "~/utils/db/permissions/roles.db.server";
|
||||
import { getAllSubscriptionProducts } from "~/utils/db/subscriptionProducts.db.server";
|
||||
import { adminGetAllTenants } from "~/utils/db/tenants.db.server";
|
||||
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";
|
||||
|
||||
type LoaderData = {
|
||||
metadata: {
|
||||
users: UserSimple[];
|
||||
tenants: Tenant[];
|
||||
subscriptionProducts: SubscriptionProductDto[];
|
||||
roles: Role[];
|
||||
analytics: {
|
||||
via: { name: string; count: number }[];
|
||||
httpReferrer: { name: string; count: number }[];
|
||||
browser: { name: string; count: number }[];
|
||||
os: { name: string; count: number }[];
|
||||
source: { name: string; count: number }[];
|
||||
medium: { name: string; count: number }[];
|
||||
campaign: { name: string; count: number }[];
|
||||
};
|
||||
};
|
||||
};
|
||||
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
await verifyUserHasPermission(request, "admin.featureFlags.view");
|
||||
const metadata = {
|
||||
users: (await adminGetAllUsers()).items,
|
||||
tenants: await adminGetAllTenants(),
|
||||
subscriptionProducts: await getAllSubscriptionProducts(),
|
||||
roles: await getAllRoles(),
|
||||
analytics: {
|
||||
via: await groupUniqueVisitorsBy("via"),
|
||||
httpReferrer: await groupUniqueVisitorsBy("httpReferrer"),
|
||||
browser: await groupUniqueVisitorsBy("browser"),
|
||||
os: await groupUniqueVisitorsBy("os"),
|
||||
source: await groupUniqueVisitorsBy("source"),
|
||||
medium: await groupUniqueVisitorsBy("medium"),
|
||||
campaign: await groupUniqueVisitorsBy("campaign"),
|
||||
},
|
||||
};
|
||||
const data: LoaderData = {
|
||||
metadata,
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
error?: string;
|
||||
success?: string;
|
||||
};
|
||||
export const action = async ({ request, 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();
|
||||
|
||||
if (action === "new") {
|
||||
const name = form.get("name")?.toString();
|
||||
const description = form.get("description")?.toString();
|
||||
|
||||
const filters: {
|
||||
type: FeatureFlagsFilterType;
|
||||
value: string | null;
|
||||
action: string | null;
|
||||
}[] = form.getAll("filters[]").map((f) => {
|
||||
return JSON.parse(f.toString());
|
||||
});
|
||||
|
||||
if (!name || !description) {
|
||||
return Response.json({ error: t("featureFlags.errors.missingRequiredFields") }, { status: 400 });
|
||||
}
|
||||
|
||||
const existingFlag = await getFeatureFlag({ name, description });
|
||||
if (existingFlag) {
|
||||
return Response.json({ error: t("featureFlags.errors.duplicateNameAndDescription") }, { status: 400 });
|
||||
}
|
||||
|
||||
try {
|
||||
await createFeatureFlag({ name, description, enabled: false, filters });
|
||||
} catch (e: any) {
|
||||
return Response.json({ error: e.message }, { status: 400 });
|
||||
}
|
||||
|
||||
return redirect(adminPath("feature-flags/flags", { mode: "host-aware" }));
|
||||
} else {
|
||||
return Response.json({ error: t("shared.invalidForm") }, { status: 400 });
|
||||
}
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
|
||||
useEffect(() => {
|
||||
if (actionData?.success) {
|
||||
toast.success(actionData.success);
|
||||
} else if (actionData?.error) {
|
||||
toast.error(actionData.error);
|
||||
}
|
||||
}, [actionData]);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<FeatureFlagForm item={undefined} metadata={data.metadata} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "~/components/ui/badges/ColorBadge";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import { getAllFeatureFlags } from "~/modules/featureFlags/db/featureFlags.db.server";
|
||||
import { db } from "~/utils/db.server";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
|
||||
type LoaderData = {
|
||||
summary: {
|
||||
flagsTotal: number;
|
||||
flagsEnabled: number;
|
||||
triggersTotal: number;
|
||||
};
|
||||
};
|
||||
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,
|
||||
},
|
||||
};
|
||||
return Response.json(data);
|
||||
};
|
||||
|
||||
export default function () {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
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>
|
||||
<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>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { ActionFunction } from "react-router";
|
||||
import { Form, useActionData } from "react-router";
|
||||
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 { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { validateCSRFToken } from "~/utils/session.server";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
type ActionData = {
|
||||
deleteError?: string;
|
||||
deleteSuccess?: boolean;
|
||||
};
|
||||
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,
|
||||
});
|
||||
} else {
|
||||
return Response.json({
|
||||
error: t("shared.invalidForm"),
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export default function AdminAnalyticsOverviewRoute() {
|
||||
const { t } = useTranslation();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
return (
|
||||
<>
|
||||
<IndexPageLayout>
|
||||
<div className="space-y-6 p-4 sm:px-6 lg:col-span-9 lg:px-0">
|
||||
<SettingSection title={t("featureFlags.danger.title")} description={t("featureFlags.danger.description")}>
|
||||
<div>
|
||||
<div className="text-muted-foreground mt-2 max-w-xl text-sm leading-5">
|
||||
<p>{t("featureFlags.danger.reset.description")}</p>
|
||||
</div>
|
||||
<div className="mt-5">
|
||||
<Form method="post">
|
||||
{rootData.csrf && <input hidden readOnly name="csrf" value={rootData.csrf} />}
|
||||
<input hidden readOnly name="action" value="delete-all" />
|
||||
<ButtonPrimary destructive type="submit">
|
||||
{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>
|
||||
</SettingSection>
|
||||
</div>
|
||||
</IndexPageLayout>
|
||||
</>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user