Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,197 @@
import { useRef } from "react";
import { Panel, useReactFlow, useStore } from "@xyflow/react";
/**
* Flow overview for the bottom-left corner of the editor canvas.
*
* Deliberately not the ReactFlow `<MiniMap>`: that one can only draw a grey
* rectangle per node. This renders the real canvas content - the same node
* cards and the same connectors - inside a scaled-down box, so the overview
* reads as a zoomed-out copy of what the user sees. The frame marks the visible
* area and is dragged like a scrollbar thumb to pan the canvas.
*/
const OVERVIEW_WIDTH = 196;
const OVERVIEW_HEIGHT = 128;
/** Flow-coordinate breathing room around the outermost nodes. */
const OVERVIEW_PADDING = 80;
/** Never blow the miniature up beyond this - a single node would fill the box. */
const MAX_SCALE = 0.32;
/** Span multiplier that keeps the frame plus its border inside the box. */
const FRAME_HEADROOM = 1.08;
/** Gap between the frame border and the edge of the box, in box pixels. */
const FRAME_INSET = 2;
export type OverviewNode = {
readonly id: string;
readonly position: { readonly x: number; readonly y: number };
readonly width: number;
readonly height: number;
readonly parentIds: readonly string[];
};
export type AutomationCanvasOverviewProps = {
nodes: readonly OverviewNode[];
/** Node card rendered inside the miniature - the very same one as on the canvas. */
renderNode: (nodeId: string) => React.ReactNode;
label: string;
};
export function AutomationCanvasOverview({ nodes, renderNode, label }: AutomationCanvasOverviewProps): React.JSX.Element | null {
const { setCenter, getZoom } = useReactFlow();
const boxRef = useRef<HTMLDivElement>(null);
/** Pointer offset inside the frame while dragging it; null when not dragging. */
const grab = useRef<{ x: number; y: number } | null>(null);
const viewport = useStore((state) => ({
x: -state.transform[0] / state.transform[2],
y: -state.transform[1] / state.transform[2],
width: state.width / state.transform[2],
height: state.height / state.transform[2],
}));
if (nodes.length === 0) return null;
// Bounds are anchored on the nodes, never on the viewport position: a frame
// of reference that moved while panning would make every pointer move land
// somewhere else than where the pointer actually is. The viewport *size* does
// widen the span though - a canvas showing more than the flow bounds would
// otherwise draw a frame wider than the box, with its side borders cut off.
const nodeMinX = Math.min(...nodes.map((node) => node.position.x)) - OVERVIEW_PADDING;
const nodeMinY = Math.min(...nodes.map((node) => node.position.y)) - OVERVIEW_PADDING;
const nodeMaxX = Math.max(...nodes.map((node) => node.position.x + node.width)) + OVERVIEW_PADDING;
const nodeMaxY = Math.max(...nodes.map((node) => node.position.y + node.height)) + OVERVIEW_PADDING;
const spanX = Math.max(nodeMaxX - nodeMinX, viewport.width * FRAME_HEADROOM);
const spanY = Math.max(nodeMaxY - nodeMinY, viewport.height * FRAME_HEADROOM);
const minX = (nodeMinX + nodeMaxX) / 2 - spanX / 2;
const minY = (nodeMinY + nodeMaxY) / 2 - spanY / 2;
const maxX = minX + spanX;
const maxY = minY + spanY;
const scale = Math.min(MAX_SCALE, OVERVIEW_WIDTH / spanX, OVERVIEW_HEIGHT / spanY);
// Centre the miniature in the box - a wide flow leaves room above and below.
const offsetX = (OVERVIEW_WIDTH - spanX * scale) / 2;
const offsetY = (OVERVIEW_HEIGHT - spanY * scale) / 2;
// The canvas can also be panned directly, past the flow bounds. Keep the
// frame inside the box in that case: a frame half outside would lose the
// border on that side and read as a resized frame.
const frameWidth = Math.min(viewport.width * scale, OVERVIEW_WIDTH - 2 * FRAME_INSET);
const frameHeight = Math.min(viewport.height * scale, OVERVIEW_HEIGHT - 2 * FRAME_INSET);
const frame = {
width: frameWidth,
height: frameHeight,
left: clamp(offsetX + (viewport.x - minX) * scale, FRAME_INSET, OVERVIEW_WIDTH - frameWidth - FRAME_INSET),
top: clamp(offsetY + (viewport.y - minY) * scale, FRAME_INSET, OVERVIEW_HEIGHT - frameHeight - FRAME_INSET),
};
/**
* Move the frame so its top-left lands under the pointer, minus wherever
* inside the frame the drag started. Relative like a scrollbar thumb: the
* canvas never jumps when the drag begins, it only follows the frame.
*/
function moveFrame(event: React.PointerEvent<HTMLDivElement>, grabOffset: { x: number; y: number }) {
const box = boxRef.current?.getBoundingClientRect();
if (!box) return;
const left = event.clientX - box.left - grabOffset.x;
const top = event.clientY - box.top - grabOffset.y;
setCenter(
clamp(minX + (left - offsetX) / scale + viewport.width / 2, minX + viewport.width / 2, maxX - viewport.width / 2),
clamp(minY + (top - offsetY) / scale + viewport.height / 2, minY + viewport.height / 2, maxY - viewport.height / 2),
{ zoom: getZoom() }
);
}
function startDrag(event: React.PointerEvent<HTMLDivElement>) {
const box = boxRef.current?.getBoundingClientRect();
if (!box) return;
const pointerX = event.clientX - box.left;
const pointerY = event.clientY - box.top;
const insideFrame =
pointerX >= frame.left && pointerX <= frame.left + frame.width && pointerY >= frame.top && pointerY <= frame.top + frame.height;
// Grabbing the frame keeps the canvas where it is; clicking next to it
// centres the view on that spot and drags on from there.
grab.current = insideFrame
? { x: pointerX - frame.left, y: pointerY - frame.top }
: { x: frame.width / 2, y: frame.height / 2 };
event.currentTarget.setPointerCapture(event.pointerId);
if (!insideFrame) moveFrame(event, grab.current);
}
return (
<Panel position="bottom-left" className="!bottom-10 !left-6 !m-0">
{/* The overview only pans the canvas; every navigation is also reachable
through the toolbar and the canvas itself, so it stays a plain region. */}
{/* eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions, jsx-a11y/no-static-element-interactions */}
<div
ref={boxRef}
role="img"
aria-label={label}
className="relative cursor-grab overflow-hidden rounded-lg border border-solid border-border-default bg-surface-neutral-primary shadow-lg active:cursor-grabbing"
style={{ width: OVERVIEW_WIDTH, height: OVERVIEW_HEIGHT }}
onPointerDown={startDrag}
onPointerMove={(event) => {
if (grab.current) moveFrame(event, grab.current);
}}
onPointerUp={() => {
grab.current = null;
}}
onPointerCancel={() => {
grab.current = null;
}}
data-ui-id="ui.automation.editor.overview"
>
<div
className="pointer-events-none absolute left-0 top-0 origin-top-left"
style={{
width: maxX - minX,
height: maxY - minY,
transform: `translate(${offsetX}px, ${offsetY}px) scale(${scale}) translate(${-minX}px, ${-minY}px)`,
}}
>
{/* Same coordinate space as the cards below: the wrapper transform
already maps flow coordinates into the box, and negative
coordinates stay visible through overflow-visible. */}
<svg className="absolute left-0 top-0 overflow-visible" width={Math.max(maxX, 1)} height={Math.max(maxY, 1)}>
{nodes.flatMap((node) =>
node.parentIds.map((parentId) => {
const parent = nodes.find((candidate) => candidate.id === parentId);
if (!parent) return null;
const fromX = parent.position.x + parent.width / 2;
const fromY = parent.position.y + parent.height;
const toX = node.position.x + node.width / 2;
const toY = node.position.y;
return (
<path
key={`${parentId}-${node.id}`}
// Right-angled like the smoothstep edges on the canvas, so
// the miniature keeps the shape of the real connector.
d={`M ${fromX} ${fromY} V ${(fromY + toY) / 2} H ${toX} V ${toY}`}
fill="none"
stroke="var(--color-border-strong)"
strokeWidth={1.5 / scale}
/>
);
})
)}
</svg>
{nodes.map((node) => (
<div key={node.id} className="absolute" style={{ left: node.position.x, top: node.position.y, width: node.width }}>
{renderNode(node.id)}
</div>
))}
</div>
<div
className="pointer-events-none absolute rounded-sm border-2 border-solid border-brand-brand-secondary-border-solid-default"
style={{ backgroundColor: "rgb(0 0 0 / 4%)", left: frame.left, top: frame.top, width: frame.width, height: frame.height }}
/>
</div>
</Panel>
);
}
function clamp(value: number, lower: number, upper: number): number {
// A flow smaller than the viewport inverts the range - then the only sane
// position is the middle of the bounds.
return lower > upper ? (lower + upper) / 2 : Math.min(Math.max(value, lower), upper);
}
export default AutomationCanvasOverview;
@@ -0,0 +1,215 @@
import "@testing-library/jest-dom/vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { BrowserRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import type { AutomationEditorVM } from "~/services/automation/automation.server";
import { AutomationEditorPage } from "./AutomationEditorPage";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("@xyflow/react", () => ({
Background: () => null,
BackgroundVariant: { Dots: "dots" },
Handle: () => null,
MiniMap: () => null,
Position: { Top: "top", Bottom: "bottom" },
ReactFlowProvider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
useReactFlow: () => ({ zoomIn: vi.fn(), zoomOut: vi.fn() }),
ReactFlow: ({ nodes, onNodeClick }: { nodes: { id: string; data: { title: string } }[]; onNodeClick: (event: { shiftKey: boolean }, node: { id: string }) => void }) => (
<div data-testid="react-flow">
{nodes.map((node) => (
<button key={node.id} type="button" onClick={() => onNodeClick({ shiftKey: false }, node)}>{node.data.title}</button>
))}
</div>
),
}));
function editorVM(): AutomationEditorVM {
return {
rule: {
id: "rule-1",
name: "Anfrage bearbeiten",
description: null,
status: "draft",
enabled: false,
triggerKey: "lead.qualified",
executionsUrl: "/acme/automations/rule-1/executions",
},
flow: {
triggerKey: "lead.qualified",
history: { past: [], future: [] },
steps: [
{
stepKey: "trigger",
kind: "trigger",
nodeType: "lead.qualified",
parentStepIds: [],
config: {},
position: { x: 120, y: 80 },
sortOrder: 0,
summaryKey: "automation.steps.triggerLeadQualified",
},
],
},
validation: { issues: [], canActivate: true, dependencyEdges: [] },
catalog: [
{
key: "lead.qualified",
kind: "trigger",
group: "lead",
titleKey: "automation.nodes.lead_qualified.title",
descriptionKey: "automation.nodes.lead_qualified.description",
requiredAnyPermission: ["automation.manage"],
availability: "active",
defaultConfig: {},
},
{
key: "task.create",
kind: "action",
group: "task",
titleKey: "automation.nodes.task_create.title",
descriptionKey: "automation.nodes.task_create.description",
requiredAnyPermission: ["tasks.write"],
availability: "active",
defaultConfig: { title: "" },
},
{
key: "calendar.create_event",
kind: "action",
group: "calendar",
titleKey: "automation.nodes.calendar_create_event.title",
descriptionKey: "automation.nodes.calendar_create_event.description",
requiredAnyPermission: ["calendar.connect_own"],
availability: "extension_slot",
defaultConfig: { connectionId: "", title: "", startsAt: "", endsAt: "" },
},
],
canManage: true,
canRun: true,
templatesUrl: "/acme/automations/templates",
};
}
describe("AutomationEditorPage", () => {
it("renders the fullscreen editor and adds a node through the picker drawer", () => {
const onSubmit = vi.fn();
render(
<BrowserRouter>
<AutomationEditorPage vm={editorVM()} submitting={false} actions={{ onSubmit }} />
</BrowserRouter>
);
expect(document.querySelector("[data-ui-id='ui.automation.editor']")?.getAttribute("data-route-transition-content")).toBe("true");
expect(document.querySelector("[data-ui-id='ui.automation.editor.canvas']")).toBeTruthy();
expect(screen.getByTestId("react-flow")).toBeTruthy();
expect(document.querySelector("[data-ui-id='ui.automation.editor.rename']")).toBeTruthy();
fireEvent.click(document.querySelector("[data-ui-id='ui.automation.editor.openPicker']") as HTMLElement);
const picker = document.querySelector("[data-ui-id='ui.automation.editor.picker']");
expect(picker).toBeTruthy();
expect(picker?.closest('[role="dialog"]')).toHaveClass("hg-drawer-full-from-right");
expect(picker?.closest('[role="dialog"]')).not.toHaveClass(
"data-[state=open]:slide-in-from-left",
"data-[state=open]:slide-in-from-right",
"data-[state=closed]:fade-out-0",
);
expect(document.querySelector('[data-ui-layer="modal"]')).toHaveClass("hg-drawer-backdrop", "backdrop-blur-[4px]");
expect(screen.getByText("automation.editor.picker.prepared")).toBeInTheDocument();
fireEvent.click(document.querySelector("[data-ui-id='ui.automation.editor.picker.task.create']") as HTMLElement);
expect(onSubmit).toHaveBeenCalledWith("add-node", { nodeType: "task.create", parentStepKey: "trigger" });
});
it("keeps the header title in its column when the editor is maximized", () => {
render(
<BrowserRouter>
<AutomationEditorPage vm={editorVM()} submitting={false} actions={{ onSubmit: vi.fn() }} />
</BrowserRouter>
);
const root = document.querySelector("[data-ui-id='ui.automation.editor']") as HTMLElement;
const header = root.children[0] as HTMLElement;
expect(header.className).not.toContain("--editor-docked-inset");
// jsdom lays nothing out, so the sidebar offset the docked editor sits
// behind is stubbed - the point is that the measured value is reapplied.
vi.spyOn(root, "getBoundingClientRect").mockReturnValue({ left: 214 } as DOMRect);
fireEvent.click(document.querySelector("[data-ui-id='ui.automation.editor.toggleFullscreen']") as HTMLElement);
expect(root.dataset.fullscreen).toBe("true");
expect(root.style.getPropertyValue("--editor-docked-inset")).toBe("214px");
expect(header.className).toContain("pl-[calc(1.5rem+var(--editor-docked-inset,0px))]");
// No sidebar on mobile, so the inset must not survive the narrow layout.
expect(header.className).toContain("mobile:pl-4");
});
it("opens the dry-run dialog without executing side effects immediately", () => {
const onSubmit = vi.fn();
render(
<BrowserRouter>
<AutomationEditorPage vm={editorVM()} submitting={false} actions={{ onSubmit }} />
</BrowserRouter>
);
fireEvent.click(document.querySelector("[data-ui-id='ui.automation.editor.dryRunTrigger']") as HTMLElement);
expect(document.querySelector("[data-ui-id='ui.automation.editor.dryRun']")).toBeTruthy();
expect(onSubmit).not.toHaveBeenCalledWith("dry-run", expect.anything());
});
it("renders the server-computed dry-run sample instead of editable match inputs", async () => {
const onSubmit = vi.fn();
render(
<BrowserRouter>
<AutomationEditorPage
vm={editorVM()}
submitting={false}
actionData={{
ok: true,
messageKey: "automation.editor.dryRun.previewReady",
dryRunPreview: {
requiresConfirmation: false,
confirmationPhrase: "DRY RUN STARTEN",
matchedRecords: 2,
inspectedEvents: 7,
sampleLimitReached: false,
examples: ["lead-1", "lead-2"],
steps: [],
warnings: [],
},
}}
actions={{ onSubmit }}
/>
</BrowserRouter>
);
await waitFor(() => expect(document.querySelector("[data-ui-id='ui.automation.editor.dryRun']")).toBeTruthy());
const dialog = document.querySelector("[data-ui-id='ui.automation.editor.dryRun']") as HTMLElement;
expect(dialog.querySelector('input[type="number"]')).toBeNull();
expect(dialog.querySelector("textarea")).toBeNull();
expect(screen.getByText("lead-1")).toBeVisible();
fireEvent.click(screen.getAllByText("automation.editor.dryRun.start").at(-1) as HTMLElement);
expect(onSubmit).toHaveBeenCalledWith("dry-run", { confirmationPhrase: "" });
});
it("cuts the selected node through delete-nodes and pastes it back from the clipboard", () => {
const onSubmit = vi.fn();
render(
<BrowserRouter>
<AutomationEditorPage vm={editorVM()} submitting={false} actions={{ onSubmit }} />
</BrowserRouter>
);
fireEvent.click(screen.getByText("automation.steps.triggerLeadQualified"));
const editor = document.querySelector("[data-ui-id='ui.automation.editor']") as HTMLElement;
fireEvent.keyDown(editor, { key: "x", ctrlKey: true });
expect(onSubmit).toHaveBeenCalledWith("delete-nodes", { stepKeys: "trigger" });
fireEvent.keyDown(editor, { key: "v", ctrlKey: true });
const pasteCall = onSubmit.mock.calls.find(([intent]) => intent === "paste-steps");
expect(pasteCall).toBeTruthy();
expect(JSON.parse(pasteCall![1].clipboardJson)[0].nodeType).toBe("lead.qualified");
});
});
@@ -0,0 +1,463 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
FeatherAlertTriangle,
FeatherCheck,
FeatherCheckCircle,
FeatherClock,
FeatherFlaskConical,
FeatherPlay,
FeatherRotateCcw,
FeatherUndo2,
FeatherX,
FeatherXCircle,
FeatherZap,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
import type { AutomationExecutionDetailActionData, AutomationExecutionDetailVM } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import {
AutomationStatusBadge,
KeyValueBlock,
automationStatusLabel,
errorMessage,
formatDurationMs,
localizedValue,
nodeIcon,
nodeTitle,
recordEntries,
statusBadgeTone,
} from "./automationUi";
/** WF-P12 S03: execution detail with step timeline, run data sidebar and reverse plan. */
export function AutomationExecutionDetailPage({
vm,
actionData,
submitting,
actions,
}: {
vm: AutomationExecutionDetailVM;
actionData?: AutomationExecutionDetailActionData;
submitting: boolean;
actions: {
onReverse: (confirmationPhrase: string) => void;
onRetry?: () => void;
onResume?: (stepExecutionId: string) => void;
};
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [reversePlanOpen, setReversePlanOpen] = useState(false);
const [reverseConfirmation, setReverseConfirmation] = useState("");
const succeededSteps = vm.steps.filter((step) => step.status === "success").length;
const failedSteps = vm.steps.filter((step) => step.status === "failed").length;
// Remaining reverse window, computed once on render (no live ticker).
const reverseRemaining = useMemo(() => {
if (!vm.execution.canReverse || !vm.execution.reverseWindowExpiresAt) return null;
const remainingMs = new Date(vm.execution.reverseWindowExpiresAt).getTime() - Date.now();
if (remainingMs <= 0) return null;
return {
hours: Math.floor(remainingMs / 3_600_000),
minutes: Math.floor((remainingMs % 3_600_000) / 60_000),
};
}, [vm.execution.canReverse, vm.execution.reverseWindowExpiresAt]);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
<div className="flex w-full flex-col items-start gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:px-4">
<div className="flex w-full flex-wrap items-center gap-3">
<span className="text-heading- font-heading- text-text-neutral-primary">
{t("automation.detail.runFrom", { date: formatters.date(vm.execution.createdAt, { dateStyle: "medium", timeStyle: "short" }) })}
</span>
<BadgeFeedback farbe={statusBadgeTone(vm.execution.status)}>
{automationStatusLabel(t, vm.execution.status)}
</BadgeFeedback>
{vm.execution.dryRun ? (
<Tag_Label tone="violet-subtle" icon={<FeatherFlaskConical />} noAction showIcon>
{t("automation.executions.kind.dryRun")}
</Tag_Label>
) : null}
{vm.canRun && actions.onRetry && !vm.execution.dryRun ? (
<Button
type="button"
variant="secondary"
size="small"
icon={<FeatherRotateCcw />}
disabled={submitting}
onClick={() => actions.onRetry?.()}
>
{t("automation.detail.retry.button")}
</Button>
) : null}
</div>
{actionData ? (
<BadgeFeedback farbe={actionData.ok ? "subtle-positive" : "subtle-negative"}>
{t(actionData.ok ? actionData.messageKey : actionData.errorKey, actionData.ok ? { count: actionData.reversedCount } : undefined)}
</BadgeFeedback>
) : null}
</div>
<div className="flex w-full items-start mobile:flex-col">
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-6 px-6 py-6 mobile:w-full mobile:flex-none mobile:px-4">
<div className="flex w-full flex-col items-start gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 shadow-sm mobile:px-4">
<div className="flex w-full items-start gap-3">
<div className="flex h-10 w-10 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-information">
<FeatherZap className="text-heading- font-heading- text-icon-feedback-information" />
</div>
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="text-body-large font-body-large text-text-neutral-primary">
{localizedValue(t, vm.execution.summaryText, "automation.values.unknownSummary")}
</span>
</div>
</div>
<div className="flex w-full flex-wrap items-start gap-x-8 gap-y-4 border-t border-solid border-border-default pt-4">
<div className="flex flex-col items-start gap-1">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.detail.trigger")}
</span>
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{nodeTitle(t, vm.execution.triggerKey)}
</span>
</div>
<div className="flex flex-col items-start gap-1">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.detail.startedAt")}
</span>
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{vm.execution.startedAt
? formatters.date(vm.execution.startedAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.notAvailable")}
</span>
</div>
<div className="flex flex-col items-start gap-1">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.detail.duration")}
</span>
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{formatDurationMs(t, formatters, vm.execution.durationMs)}
</span>
</div>
<div className="flex flex-col items-start gap-1">
<span className="text-body-extra-small-medium-0 font-body-extra-small-medium-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.sections.steps")}
</span>
<span
className={
failedSteps > 0
? "text-body-small-medium-150 font-body-small-medium-150 text-text-feedback-warning"
: "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary"
}
>
{t("automation.detail.stepsProgress", {
success: formatters.number(succeededSteps),
total: formatters.number(vm.steps.length),
})}
</span>
</div>
</div>
</div>
{vm.execution.errorText ? (
<div className="flex w-full items-start gap-3 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
<FeatherAlertTriangle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative" />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative">
{t("automation.detail.errorTitle")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{errorMessage(t, vm.execution.errorText)}
</span>
</div>
</div>
) : null}
<div className="flex w-full items-center gap-2">
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.detail.timelineTitle")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.detail.stepsCount", { count: vm.steps.length })}
</span>
</div>
<div className="flex w-full flex-col items-start">
{vm.steps.map((step, index) => {
const StepIcon = step.status === "failed" ? FeatherX : step.status === "success" ? FeatherCheck : nodeIcon(step.nodeType);
const isLast = index === vm.steps.length - 1;
const inputEntries = recordEntries(step.input);
const outputEntries = recordEntries(step.output);
return (
<div key={step.id} className="flex w-full items-start gap-4">
<div className="flex flex-col items-center gap-2 self-stretch">
<div
className={
step.status === "failed"
? "flex h-8 w-8 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-negative"
: step.status === "success"
? "flex h-8 w-8 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-positive"
: "flex h-8 w-8 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-neutral"
}
>
<StepIcon
className={
step.status === "failed"
? "text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative"
: step.status === "success"
? "text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive"
: "text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary"
}
/>
</div>
{!isLast ? <div className="flex w-px grow shrink-0 basis-0 flex-col items-center bg-border-default" /> : null}
</div>
<div
className={
step.status === "failed"
? "mb-4 flex grow shrink-0 basis-0 flex-col items-start gap-3 rounded-lg border border-solid border-border-negative-subtle bg-surface-neutral-secondary px-5 py-4 mobile:px-4"
: "mb-4 flex grow shrink-0 basis-0 flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-4 mobile:px-4"
}
>
<div className="flex w-full flex-wrap items-center gap-3">
<span className="grow shrink-0 basis-0 text-body-default-medium-150 font-body-default-medium-150 text-text-neutral-primary">
{t(step.summaryText, { defaultValue: nodeTitle(t, step.nodeType) })}
</span>
<AutomationStatusBadge status={step.status} />
{step.durationMs !== null ? (
<div className="flex items-center gap-1.5">
<FeatherClock className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{formatDurationMs(t, formatters, step.durationMs)}
</span>
</div>
) : null}
{vm.canRun && actions.onResume && !vm.execution.dryRun && index > 0 ? (
<Button
type="button"
variant="ghost"
size="small"
icon={<FeatherPlay />}
disabled={submitting}
onClick={() => actions.onResume?.(step.id)}
>
{t("automation.detail.resume.button")}
</Button>
) : null}
</div>
{step.errorText ? (
<div className="flex w-full items-start gap-3 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
<FeatherAlertTriangle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative" />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative">
{t("automation.detail.stepErrorTitle")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{errorMessage(t, step.errorText)}
</span>
</div>
</div>
) : null}
{inputEntries.length > 0 || outputEntries.length > 0 ? (
<div className="flex w-full items-start gap-4 mobile:flex-col">
<KeyValueBlock label={t("automation.detail.input")} value={step.input} />
<KeyValueBlock label={t("automation.detail.output")} value={step.output} />
</div>
) : null}
</div>
</div>
);
})}
</div>
</div>
<div className="flex w-80 flex-none flex-col items-start gap-6 self-stretch border-l border-solid border-border-default bg-surface-neutral-secondary px-5 py-6 mobile:w-full mobile:self-auto mobile:border-l-0 mobile:border-t">
<div className="flex w-full flex-col items-start gap-4">
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.detail.sidebar.title")}
</span>
<div className="flex w-full flex-col items-start gap-3">
<SidebarRow label={t("automation.detail.sidebar.executionId")} value={vm.execution.id} />
<SidebarRow label={t("automation.detail.sidebar.automation")} value={vm.rule.name} />
<SidebarRow
label={t("automation.detail.sidebar.started")}
value={
vm.execution.startedAt
? formatters.date(vm.execution.startedAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.notAvailable")
}
/>
<SidebarRow
label={t("automation.detail.sidebar.ended")}
value={
vm.execution.endedAt
? formatters.date(vm.execution.endedAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.notAvailable")
}
/>
<SidebarRow label={t("automation.detail.sidebar.triggeredBy")} value={nodeTitle(t, vm.execution.triggerKey)} />
</div>
</div>
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
<div className="flex w-full flex-col items-start gap-3">
<span className="text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.detail.sidebar.result")}
</span>
<div className="flex w-full items-center gap-2">
<FeatherCheckCircle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-positive" />
<span className="grow shrink-0 basis-0 text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("automation.detail.sidebar.stepsSucceeded", { count: succeededSteps })}
</span>
</div>
<div className="flex w-full items-center gap-2">
<FeatherXCircle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative" />
<span className="grow shrink-0 basis-0 text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("automation.detail.sidebar.stepsFailed", { count: failedSteps })}
</span>
</div>
</div>
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
<div className="flex w-full flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-primary px-4 py-4">
<div className="flex w-full items-center gap-2">
<FeatherClock className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-neutral-primary">
{t("automation.detail.reverse.windowTitle")}
</span>
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("automation.detail.reverse.windowHint")}
</span>
{reverseRemaining ? (
<>
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-feedback-warning">
{t("automation.detail.reverse.remaining", {
hours: formatters.number(reverseRemaining.hours),
minutes: formatters.number(reverseRemaining.minutes),
})}
</span>
<Button
type="button"
className="h-8 w-full flex-none"
variant="secondary"
size="small"
icon={<FeatherUndo2 />}
onClick={() => {
setReverseConfirmation("");
setReversePlanOpen(true);
}}
>
{t("automation.detail.reverse.viewPlan")}
</Button>
</>
) : (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{/* A run that was already undone also has canReverse=false -
calling that an expired window would be plainly wrong. */}
{vm.execution.summaryText === "automation.execution.reversed"
? t("automation.detail.reverse.alreadyReversed")
: t("automation.editor.reverse.expired")}
</span>
)}
</div>
</div>
</div>
{reversePlanOpen ? (
<Dialog open onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : setReversePlanOpen(false))}>
<Dialog.Content className="w-[560px] max-w-full gap-0 p-0">
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default px-6 py-4">
<FeatherUndo2 className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.detail.reverse.planTitle")}
</span>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => setReversePlanOpen(false)} />
</div>
<div className="flex w-full flex-col items-start gap-4 px-6 py-5 max-h-[65vh] overflow-y-auto">
<div className="flex w-full flex-col items-start gap-2">
{vm.reversePlan.items.map((item) => (
<div
key={`${item.stepKey}-${item.actionKey}`}
className="flex w-full flex-col gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-3 py-2"
>
<div className="flex w-full items-center justify-between gap-3">
<div className="flex flex-col items-start">
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{localizedValue(t, item.actionKey, "automation.values.unknownAction")}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{nodeTitle(t, item.nodeType)}
</span>
</div>
<BadgeFeedback farbe={item.reversible ? "subtle-positive" : "subtle-neutral"} size="small">
{item.reversible ? t("automation.editor.reverse.reversible") : t("automation.editor.reverse.notReversible")}
</BadgeFeedback>
</div>
{item.recipients.length > 0 ? (
<div className="flex w-full flex-col gap-1 rounded-md bg-surface-neutral-tertiary px-3 py-2" data-ui-id="ui.automation.execution.reverse.recipients">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.detail.reverse.recipientsTitle", { count: item.recipients.length })}
</span>
{item.recipients.map((recipient, index) => (
<span key={`${recipient.email ?? recipient.name}-${index}`} className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-secondary">
{recipient.name && recipient.email ? `${recipient.name} · ${recipient.email}` : recipient.name ?? recipient.email}
</span>
))}
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.detail.reverse.recipientsHint")}
</span>
</div>
) : null}
</div>
))}
</div>
<TextInput
label={t("automation.editor.reverse.confirmation")}
helpText={t("automation.detail.reverse.confirmationHint", { phrase: vm.reversePlan.confirmationPhrase })}
showLabel
>
<TextInput.Input value={reverseConfirmation} onChange={(event) => setReverseConfirmation(event.target.value)} />
</TextInput>
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4">
<Button type="button" variant="tertiary" onClick={() => setReversePlanOpen(false)}>
{t("shared.close")}
</Button>
<Button
type="button"
variant="destructive"
icon={<FeatherUndo2 />}
loading={submitting}
disabled={reverseConfirmation.trim().toLocaleUpperCase() !== vm.reversePlan.confirmationPhrase}
onClick={() => {
actions.onReverse(reverseConfirmation);
setReversePlanOpen(false);
}}
data-ui-id="ui.automation.execution.reverse.confirm"
>
{t("automation.detail.reverse.execute")}
</Button>
</div>
</Dialog.Content>
</Dialog>
) : null}
</div>
);
}
function SidebarRow({ label, value }: { label: React.ReactNode; value: React.ReactNode }): React.JSX.Element {
return (
<div className="flex w-full items-start justify-between gap-3">
<span className="flex-none text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{label}</span>
<span className="break-all text-right text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">{value}</span>
</div>
);
}
@@ -0,0 +1,337 @@
import { useEffect, useMemo, useState } from "react";
import { Form as RouterForm, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherActivity,
FeatherAlertTriangle,
FeatherCalendar,
FeatherCheckCircle,
FeatherChevronLeft,
FeatherChevronRight,
FeatherClock,
FeatherPencilRuler,
FeatherPlay,
FeatherTimer,
FeatherZap,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { SearchInput } from "~/ui/components/SearchInput";
import { Select } from "~/ui/components/Select";
import { StatsCard } from "~/ui/components/StatsCard";
import { Switch } from "~/ui/components/Switch";
import { Table } from "~/ui/components/Table";
import { Tag_Label } from "~/ui/components/Tag_Label";
import type { AutomationExecutionListVM, AutomationExecutionsActionData } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { useRootData } from "~/utils/data/useRootData";
import {
AutomationStatusBadge,
automationStatusLabel,
errorMessage,
formatDurationMs,
localizedValue,
nodeTitle,
statusBadgeTone,
} from "./automationUi";
import { ProbelaufDialog } from "./dialogs/ProbelaufDialog";
const PAGE_SIZE = 10;
const STATUS_OPTIONS = ["success", "failed", "skipped", "running", "queued", "paused"] as const;
type PeriodFilter = "all" | "today" | "7d" | "30d";
/** WF-P12 S02: execution list for one rule with stats, filters and pagination. */
export function AutomationExecutionsPage({
vm,
actionData,
}: {
vm: AutomationExecutionListVM;
actionData?: AutomationExecutionsActionData;
}): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const csrf = useRootData().csrf ?? "";
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<string>("all");
const [periodFilter, setPeriodFilter] = useState<PeriodFilter>("all");
const [onlyDryRuns, setOnlyDryRuns] = useState(false);
const [page, setPage] = useState(0);
const [dryRunOpen, setDryRunOpen] = useState(false);
// A dry-run submit re-renders with fresh actionData; keep the dialog visible
// so the preview result lands where the user started the run.
useEffect(() => {
if (actionData?.dryRunPreview) setDryRunOpen(true);
}, [actionData]);
const filtered = useMemo(() => {
const needle = query.trim().toLowerCase();
const now = Date.now();
const periodStart =
periodFilter === "today"
? new Date(new Date().setHours(0, 0, 0, 0)).getTime()
: periodFilter === "7d"
? now - 7 * 24 * 60 * 60 * 1000
: periodFilter === "30d"
? now - 30 * 24 * 60 * 60 * 1000
: null;
return vm.executions.filter((execution) => {
if (statusFilter !== "all" && execution.status !== statusFilter) return false;
if (onlyDryRuns && !execution.dryRun) return false;
if (periodStart !== null && new Date(execution.createdAt).getTime() < periodStart) return false;
if (needle && !`${execution.summaryText} ${execution.errorText ?? ""}`.toLowerCase().includes(needle)) return false;
return true;
});
}, [vm.executions, query, statusFilter, periodFilter, onlyDryRuns]);
const pageCount = Math.max(1, Math.ceil(filtered.length / PAGE_SIZE));
const safePage = Math.min(page, pageCount - 1);
const pageRows = filtered.slice(safePage * PAGE_SIZE, safePage * PAGE_SIZE + PAGE_SIZE);
const resetPage = () => setPage(0);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
<div className="flex w-full flex-col items-start gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:px-4">
<div className="flex w-full items-center gap-4 mobile:flex-col mobile:items-start">
<div className="flex grow shrink-0 basis-0 items-center gap-3">
<FeatherZap className="text-heading- font-heading- text-icon-neutral-tertiary" />
<span className="text-heading- font-heading- text-text-neutral-primary">{t("automation.executions.title")}</span>
<BadgeFeedback farbe={statusBadgeTone(vm.rule.status)}>
{automationStatusLabel(t, vm.rule.status)}
</BadgeFeedback>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap">
<Link to={vm.rule.editUrl} className="inline-flex">
<Button type="button" variant="tertiary" icon={<FeatherPencilRuler />}>
{t("automation.executions.openEditor")}
</Button>
</Link>
{vm.canRun || vm.canManage ? (
<>
<RouterForm method="post" className="inline-flex">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="intent" value="run-now" readOnly />
<Button type="submit" variant="secondary" icon={<FeatherZap />} disabled={vm.rule.status !== "active"}>
{t("automation.executions.runNow.button")}
</Button>
</RouterForm>
<Button type="button" icon={<FeatherPlay />} onClick={() => setDryRunOpen(true)}>
{t("automation.editor.dryRun.start")}
</Button>
</>
) : null}
</div>
</div>
{actionData && !actionData.dryRunPreview ? (
<BadgeFeedback farbe={actionData.ok ? "subtle-positive" : "subtle-negative"}>
{t(actionData.ok ? actionData.messageKey : actionData.errorKey)}
</BadgeFeedback>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-6 px-6 py-6 mobile:px-4">
<div className="flex w-full items-start gap-4 mobile:flex-col">
<StatsCard
trend="neutral"
label={t("automation.detail.lastExecution")}
value={
vm.stats.lastExecutionAt
? formatters.date(vm.stats.lastExecutionAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.never")
}
percentage={
vm.stats.lastExecutionStatus
? automationStatusLabel(t, vm.stats.lastExecutionStatus)
: undefined
}
icon={<FeatherClock />}
/>
<StatsCard
trend={vm.stats.successRate30d !== null && vm.stats.successRate30d >= 90 ? "positive" : "neutral"}
label={t("automation.executions.stats.successRate30d")}
value={vm.stats.successRate30d !== null ? formatters.percent(vm.stats.successRate30d / 100, { maximumFractionDigits: 1 }) : "—"}
icon={<FeatherCheckCircle />}
/>
<StatsCard
trend={vm.stats.failed30d > 0 ? "negative" : "neutral"}
label={t("automation.executions.stats.failed30d")}
value={formatters.number(vm.stats.failed30d)}
icon={<FeatherAlertTriangle />}
/>
<StatsCard
trend="neutral"
label={t("automation.executions.stats.avgDuration")}
value={vm.stats.avgDurationMs !== null ? formatDurationMs(t, formatters, vm.stats.avgDurationMs) : "—"}
icon={<FeatherTimer />}
/>
</div>
<div className="flex w-full flex-wrap items-center gap-3 mobile:flex-col mobile:flex-nowrap mobile:items-stretch">
<SearchInput
className="h-8 w-72 flex-none mobile:w-full"
size="small"
hideShortcut
placeholder={t("automation.executions.filters.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
setQuery(event.target.value);
resetPage();
}}
/>
<Select
className="h-8 w-44 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("automation.executions.filters.statusLabel")}
icon={<FeatherActivity />}
value={statusFilter}
onValueChange={(value: string) => {
setStatusFilter(value);
resetPage();
}}
>
<Select.Item value="all">{t("automation.executions.filters.statusAll")}</Select.Item>
{STATUS_OPTIONS.map((status) => (
<Select.Item key={status} value={status}>
{t(`automation.status.${status}`)}
</Select.Item>
))}
</Select>
<Select
className="h-8 w-44 flex-none mobile:w-full"
variant="filled"
size="small"
placeholder={t("automation.executions.filters.periodLabel")}
icon={<FeatherCalendar />}
value={periodFilter}
onValueChange={(value: string) => {
setPeriodFilter(value as PeriodFilter);
resetPage();
}}
>
<Select.Item value="today">{t("automation.executions.filters.periodToday")}</Select.Item>
<Select.Item value="7d">{t("automation.executions.filters.period7d")}</Select.Item>
<Select.Item value="30d">{t("automation.executions.filters.period30d")}</Select.Item>
<Select.Item value="all">{t("automation.executions.filters.periodAll")}</Select.Item>
</Select>
<div className="flex grow shrink-0 basis-0 items-center justify-end gap-2 mobile:justify-start">
<Switch
checked={onlyDryRuns}
onCheckedChange={(checked: boolean) => {
setOnlyDryRuns(checked);
resetPage();
}}
/>
<span className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{t("automation.executions.filters.onlyDryRuns")}
</span>
</div>
</div>
{vm.executions.length === 0 ? (
<EmptyState outlined title={t("automation.empty.executions")} body={t("automation.executions.subtitle", { trigger: nodeTitle(t, vm.rule.triggerKey) })} />
) : filtered.length === 0 ? (
<EmptyState outlined variant="no-results" title={t("automation.executions.noMatches.title")} body={t("automation.executions.noMatches.body")} />
) : (
<>
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherClock />}>{t("automation.executions.columns.time")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherActivity />}>{t("automation.detail.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.executions.columns.summary")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.executions.columns.kind")}</Table.HeaderCell>
<Table.HeaderCell icon={<FeatherTimer />}>{t("automation.detail.duration")}</Table.HeaderCell>
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{pageRows.map((execution) => (
<Table.Row key={execution.id} className="cursor-pointer" clickable>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{formatters.date(execution.createdAt, { dateStyle: "medium", timeStyle: "short" })}
</span>
</Table.Cell>
<Table.Cell>
<AutomationStatusBadge status={execution.status} />
</Table.Cell>
<Table.Cell>
<div className="flex max-w-[360px] flex-col items-start">
<span className="line-clamp-1 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{localizedValue(t, execution.summaryText, "automation.values.unknownSummary")}
</span>
{execution.status === "failed" && execution.errorText ? (
<span className="line-clamp-1 text-body-small-regular-0 font-body-small-regular-0 text-text-feedback-negative">
{errorMessage(t, execution.errorText)}
</span>
) : null}
</div>
</Table.Cell>
<Table.Cell>
<Tag_Label tone={execution.dryRun ? "violet-subtle" : "neutral-subtle"} noAction size="small">
{execution.dryRun ? t("automation.executions.kind.dryRun") : t("automation.executions.kind.live")}
</Tag_Label>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{execution.durationMs !== null ? formatDurationMs(t, formatters, execution.durationMs) : "—"}
</span>
</Table.Cell>
<Table.Cell>
<div className="flex w-full items-center justify-end">
<Link to={execution.detailUrl} className="inline-flex">
<Button type="button" variant="tertiary" size="small" iconRight={<FeatherChevronRight />}>
{t("automation.executions.details")}
</Button>
</Link>
</div>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
<div className="flex w-full items-center gap-3 pb-4 mobile:flex-col mobile:items-start">
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.executions.pagination.range", {
from: formatters.number(safePage * PAGE_SIZE + 1),
to: formatters.number(Math.min((safePage + 1) * PAGE_SIZE, filtered.length)),
total: formatters.number(filtered.length),
})}
</span>
<div className="flex items-center gap-2">
<Button
type="button"
disabled={safePage === 0}
variant="tertiary"
size="small"
icon={<FeatherChevronLeft />}
onClick={() => setPage(Math.max(0, safePage - 1))}
>
{t("automation.executions.pagination.previous")}
</Button>
<Button
type="button"
disabled={safePage >= pageCount - 1}
variant="tertiary"
size="small"
iconRight={<FeatherChevronRight />}
onClick={() => setPage(Math.min(pageCount - 1, safePage + 1))}
>
{t("automation.executions.pagination.next")}
</Button>
</div>
</div>
</>
)}
</div>
<ProbelaufDialog vm={vm} csrf={csrf} actionData={actionData} open={dryRunOpen} onOpenChange={setDryRunOpen} />
</div>
);
}
@@ -0,0 +1,78 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AutomationListVM } from "~/services/automation/automation.server";
import { AutomationListPage } from "./AutomationListPage";
const mocks = vi.hoisted(() => ({
collapseSidebarIfPreferred: vi.fn(),
saveToast: vi.fn(),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/components/app/AppShellSidebarContext", () => ({
useAppShellSidebar: () => ({ collapseSidebarIfPreferred: mocks.collapseSidebarIfPreferred }),
}));
vi.mock("~/hooks/use-save-toast", () => ({
useSaveToast: (result: unknown) => mocks.saveToast(result),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ csrf: "csrf" }),
}));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
number: (value: number) => String(value),
date: (value: string) => value,
}),
}));
vi.mock("./dialogs/StartAuswahlDialog", () => ({
StartAuswahlDialog: ({ open, onCreateConfirmed }: { open: boolean; onCreateConfirmed: () => void }) =>
open ? <button onClick={onCreateConfirmed}>confirm automation</button> : null,
}));
const vm: AutomationListVM = {
tenantSlug: "acme",
currentUserId: "user-1",
rules: [],
templates: [],
templatesUrl: "/acme/automations/templates",
canManage: true,
canRun: true,
};
beforeEach(() => {
mocks.collapseSidebarIfPreferred.mockClear();
mocks.saveToast.mockClear();
});
describe("AutomationListPage sidebar behavior", () => {
it("keeps the sidebar open until the new automation is confirmed", () => {
const router = createMemoryRouter([{ path: "/", element: <AutomationListPage vm={vm} /> }], { initialEntries: ["/"] });
render(<RouterProvider router={router} />);
fireEvent.click(screen.getByRole("button", { name: "automation.editor.actions.create" }));
expect(mocks.collapseSidebarIfPreferred).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "confirm automation" }));
expect(mocks.collapseSidebarIfPreferred).toHaveBeenCalledOnce();
});
it("reports every server-confirmed list mutation through the shared toast", () => {
const actionData = { ok: true, messageKey: "automation.editor.actions.paused" } as const;
const router = createMemoryRouter([{ path: "/", element: <AutomationListPage vm={vm} actionData={actionData} /> }], { initialEntries: ["/"] });
render(<RouterProvider router={router} />);
expect(mocks.saveToast).toHaveBeenCalledWith(actionData);
});
});
@@ -0,0 +1,464 @@
import { useMemo, useState } from "react";
import { Link, useNavigate, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherAlertTriangle,
FeatherClock,
FeatherEye,
FeatherInfo,
FeatherLayoutTemplate,
FeatherMoreHorizontal,
FeatherPause,
FeatherPencil,
FeatherPlay,
FeatherPlus,
FeatherRotateCcw,
FeatherSearchX,
FeatherTrash2,
FeatherWorkflow,
} from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconButton } from "~/ui/components/IconButton";
import { SearchInput } from "~/ui/components/SearchInput";
import { Switch } from "~/ui/components/Switch";
import { Table } from "~/ui/components/Table";
import type { AutomationListActionData, AutomationListItemVM, AutomationListVM } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { useSaveToast } from "~/hooks/use-save-toast";
import { useRootData } from "~/utils/data/useRootData";
import { AutomationStatusBadge, FilterPill, PageHeader, anomalyMessage, localizedValue, nodeIcon, nodeTitle } from "./automationUi";
import { AutomationArchiveDialog } from "./dialogs/AutomationArchiveDialog";
import { SchleifenWarnungDialog } from "./dialogs/SchleifenWarnungDialog";
import { StartAuswahlDialog } from "./dialogs/StartAuswahlDialog";
import { useAppShellSidebar } from "~/components/app/AppShellSidebarContext";
type StatusFilter = "all" | "active" | "draft" | "paused" | "failed24h";
/** WF-P12 S01: automation rule list with anomaly banner, filters and row ops. */
export function AutomationListPage({ vm, actionData }: { vm: AutomationListVM; actionData?: AutomationListActionData }): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const submit = useSubmit();
const navigate = useNavigate();
const { collapseSidebarIfPreferred } = useAppShellSidebar();
const csrf = useRootData().csrf ?? "";
const [query, setQuery] = useState("");
const [statusFilter, setStatusFilter] = useState<StatusFilter>("all");
const [triggerFilter, setTriggerFilter] = useState<string | null>(null);
const [onlyMine, setOnlyMine] = useState(false);
const [bannerDismissed, setBannerDismissed] = useState(false);
const [startOpen, setStartOpen] = useState(false);
const [anomalyRuleId, setAnomalyRuleId] = useState<string | null>(null);
const [archiveRule, setArchiveRule] = useState<AutomationListItemVM | null>(null);
// Every confirmed list mutation already carries a specific message key
// (activated, paused, template created, deleted). Redirecting create/duplicate
// actions are handled by their destination page and never reach this hook.
useSaveToast(actionData?.ok ? actionData : undefined);
const anomalyRule = useMemo(() => vm.rules.find((rule) => rule.anomalyText !== null) ?? null, [vm.rules]);
const anomalyDialogRule = useMemo(
() => (anomalyRuleId ? vm.rules.find((rule) => rule.id === anomalyRuleId) ?? null : null),
[vm.rules, anomalyRuleId]
);
const counts = useMemo(
() => ({
all: vm.rules.length,
active: vm.rules.filter((rule) => rule.status === "active").length,
draft: vm.rules.filter((rule) => rule.status === "draft").length,
paused: vm.rules.filter((rule) => rule.status === "paused").length,
failed24h: vm.rules.filter((rule) => rule.failed24h > 0).length,
}),
[vm.rules]
);
const triggerKeys = useMemo(() => {
const keys = new Set<string>();
for (const rule of vm.rules) {
if (rule.triggerKey) keys.add(rule.triggerKey);
}
return [...keys].sort();
}, [vm.rules]);
const visibleRules = useMemo(() => {
const needle = query.trim().toLowerCase();
return vm.rules.filter((rule) => {
if (statusFilter === "failed24h") {
if (rule.failed24h === 0) return false;
} else if (statusFilter !== "all" && rule.status !== statusFilter) {
return false;
}
if (triggerFilter && rule.triggerKey !== triggerFilter) return false;
if (onlyMine && rule.createdByUserId !== vm.currentUserId) return false;
if (needle && !`${rule.name} ${rule.description ?? ""}`.toLowerCase().includes(needle)) return false;
return true;
});
}, [vm.rules, vm.currentUserId, statusFilter, triggerFilter, onlyMine, query]);
const lastUpdatedAt = useMemo(() => {
let latest: string | null = null;
for (const rule of vm.rules) {
if (!latest || rule.updatedAt > latest) latest = rule.updatedAt;
}
return latest;
}, [vm.rules]);
const postOp = (intent: string, extra: Record<string, string> = {}) => {
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("intent", intent);
for (const [key, value] of Object.entries(extra)) formData.set(key, value);
void submit(formData, { method: "post" });
};
const saveAsTemplate = (rule: AutomationListItemVM) => {
const templateName = window.prompt(t("automation.list.actions.templateNamePrompt"), rule.name);
if (!templateName || !templateName.trim()) return;
postOp("create-template", { ruleId: rule.id, templateName: templateName.trim() });
};
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
<PageHeader
icon={<FeatherWorkflow className="text-heading- font-heading- text-icon-neutral-tertiary" />}
title={t("automation.title")}
subtitle={t("automation.subtitle")}
actions={
vm.canManage ? (
<>
<Link to={vm.templatesUrl} className="inline-flex">
<Button type="button" variant="secondary" icon={<FeatherLayoutTemplate />}>
{t("automation.list.templates")}
</Button>
</Link>
<Button
type="button"
icon={<FeatherPlus />}
onClick={() => setStartOpen(true)}
>
{t("automation.editor.actions.create")}
</Button>
</>
) : undefined
}
/>
{anomalyRule && !bannerDismissed ? (
<div className="flex w-full items-center gap-3 border-b border-solid border-border-warning-solid bg-surface-feedback-subtle-warning px-6 py-3 mobile:flex-col mobile:items-start mobile:px-4">
<FeatherAlertTriangle className="text-body-large-0 font-body-large-0 text-icon-feedback-warning" />
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-warning">
{t("automation.list.anomaly.title", { name: anomalyRule.name })}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-warning">
{anomalyMessage(t, anomalyRule)}
</span>
</div>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none">
<Button type="button" variant="neutral" size="small" icon={<FeatherEye />} onClick={() => setAnomalyRuleId(anomalyRule.id)}>
{t("automation.list.anomaly.viewDetails")}
</Button>
<Button type="button" variant="warning" size="small" icon={<FeatherPause />} onClick={() => setBannerDismissed(true)}>
{t("automation.list.anomaly.keepPaused")}
</Button>
</div>
</div>
) : null}
{actionData && !actionData.ok ? (
<div className="flex w-full items-center gap-2 border-b border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-6 py-2.5 mobile:px-4">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-negative" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">
{t(actionData.errorKey)}
{actionData.detail ? ` ${localizedValue(t, actionData.detail, "automation.values.unknownError")}` : ""}
</span>
</div>
) : null}
<div className="flex w-full flex-col items-start gap-6 px-6 py-6 mobile:px-4">
{vm.rules.length > 0 ? (
<>
<div className="flex w-full flex-wrap items-center gap-2">
<FilterPill label={t("automation.list.filters.all")} count={counts.all} active={statusFilter === "all"} onClick={() => setStatusFilter("all")} />
<FilterPill
label={t("automation.status.active")}
count={counts.active}
active={statusFilter === "active"}
dotClassName="bg-surface-feedback-solid-positive-default"
onClick={() => setStatusFilter(statusFilter === "active" ? "all" : "active")}
/>
<FilterPill
label={t("automation.status.draft")}
count={counts.draft}
active={statusFilter === "draft"}
dotClassName="bg-neutral-400"
onClick={() => setStatusFilter(statusFilter === "draft" ? "all" : "draft")}
/>
<FilterPill
label={t("automation.status.paused")}
count={counts.paused}
active={statusFilter === "paused"}
dotClassName="bg-surface-feedback-solid-warning"
onClick={() => setStatusFilter(statusFilter === "paused" ? "all" : "paused")}
/>
<FilterPill
label={t("automation.list.filters.failed24h")}
count={counts.failed24h}
active={statusFilter === "failed24h"}
dotClassName="bg-surface-feedback-solid-negative-default"
onClick={() => setStatusFilter(statusFilter === "failed24h" ? "all" : "failed24h")}
/>
</div>
{triggerKeys.length > 0 ? (
<div className="flex w-full flex-wrap items-center gap-2">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.list.filters.trigger")}
</span>
{triggerKeys.map((triggerKey) => (
<FilterPill
key={triggerKey}
label={nodeTitle(t, triggerKey)}
active={triggerFilter === triggerKey}
onClick={() => setTriggerFilter(triggerFilter === triggerKey ? null : triggerKey)}
/>
))}
</div>
) : null}
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-stretch">
<SearchInput
className="h-8 w-72 flex-none mobile:w-full"
size="small"
hideShortcut
placeholder={t("automation.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setQuery(event.target.value)}
/>
<div className="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:justify-between">
<Switch checked={onlyMine} onCheckedChange={(checked: boolean) => setOnlyMine(checked)} />
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-secondary">
{onlyMine ? t("automation.list.filters.onlyMine") : t("automation.list.filters.allOwners")}
</span>
</div>
</div>
</>
) : null}
{vm.rules.length === 0 ? (
<EmptyState outlined title={t("automation.empty.rules")} body={t("automation.subtitle")} />
) : visibleRules.length === 0 ? (
<div className="flex w-full flex-col items-center justify-center gap-6 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-6 py-16 shadow-sm mobile:py-10">
<div className="flex h-14 w-14 flex-none flex-col items-center justify-center rounded-round border border-solid border-border-default bg-surface-neutral-tertiary">
<FeatherSearchX className="text-heading- font-heading- text-icon-neutral-tertiary" />
</div>
<div className="flex w-full max-w-[420px] flex-col items-center gap-2">
<span className="text-body-large font-body-large text-text-neutral-primary text-center">{t("automation.list.noMatches.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary text-center">
{t("automation.list.noMatches.body")}
</span>
</div>
<Button
type="button"
icon={<FeatherRotateCcw />}
onClick={() => {
setQuery("");
setStatusFilter("all");
setTriggerFilter(null);
setOnlyMine(false);
}}
>
{t("automation.list.noMatches.reset")}
</Button>
</div>
) : (
<div className="flex w-full flex-col items-start overflow-hidden rounded-lg border border-solid border-border-default shadow-sm overflow-x-auto">
<Table
header={
<Table.HeaderRow className="bg-surface-neutral-tertiary">
<Table.HeaderCell icon={<FeatherWorkflow />}>{t("automation.list.columns.automation")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.list.columns.trigger")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.detail.status")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.metrics.runs30d")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.detail.lastExecution")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.list.columns.owner")}</Table.HeaderCell>
<Table.HeaderCell>{t("automation.list.columns.actions")}</Table.HeaderCell>
</Table.HeaderRow>
}
>
{visibleRules.map((rule) => {
const TriggerIcon = nodeIcon(rule.triggerKey);
const hasAnomaly = rule.anomalyText !== null;
return (
<Table.Row key={rule.id} className={hasAnomaly ? "bg-surface-feedback-subtle-warning" : undefined} clickable>
<Table.Cell>
<div className="flex items-center gap-3">
<div
className={
hasAnomaly
? "flex h-8 w-8 flex-none flex-col items-center justify-center rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning"
: "flex h-8 w-8 flex-none flex-col items-center justify-center rounded-md border border-solid border-border-default bg-surface-neutral-tertiary"
}
>
<TriggerIcon
className={
hasAnomaly
? "text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-warning"
: "text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary"
}
/>
</div>
<div className="flex flex-col items-start">
<Link
to={rule.editUrl}
className="whitespace-nowrap text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary hover:text-text-feedback-link-default"
>
{rule.name}
</Link>
{rule.description ? (
<span className="line-clamp-1 max-w-[280px] text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{rule.description}
</span>
) : null}
</div>
</div>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{nodeTitle(t, rule.triggerKey)}
</span>
</Table.Cell>
<Table.Cell>
<AutomationStatusBadge status={rule.status} />
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary">
{formatters.number(rule.runs30d)}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{rule.lastExecutionAt
? formatters.date(rule.lastExecutionAt, { dateStyle: "medium", timeStyle: "short" })
: t("automation.values.never")}
</span>
</Table.Cell>
<Table.Cell>
<span className="whitespace-nowrap text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{rule.ownerName ?? "—"}
</span>
</Table.Cell>
<Table.Cell>
<div className="flex items-center gap-1">
<Link to={rule.editUrl} className="inline-flex">
<Button type="button" variant="tertiary" size="small" icon={<FeatherPencil />}>
{t("automation.editor.actions.openEditor")}
</Button>
</Link>
<Link to={rule.executionsUrl} className="inline-flex" aria-label={t("automation.list.actions.viewExecutions")}>
<IconButton variant="ghost" size="small" icon={<FeatherClock />} />
</Link>
{vm.canManage ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<IconButton variant="ghost" size="small" icon={<FeatherMoreHorizontal />} />
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu>
<DropdownMenu.DropdownItem icon={<FeatherClock />} onSelect={() => navigate(rule.executionsUrl)}>
{t("automation.list.actions.viewExecutions")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownItem icon={<FeatherLayoutTemplate />} onSelect={() => saveAsTemplate(rule)}>
{t("automation.list.actions.saveAsTemplate")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownItem icon={<FeatherPlus />} onSelect={() => postOp("duplicate", { ruleId: rule.id })}>
{t("automation.editor.actions.duplicate")}
</DropdownMenu.DropdownItem>
<DropdownMenu.DropdownDivider />
{rule.status === "active" ? (
<DropdownMenu.DropdownItem icon={<FeatherPause />} onSelect={() => postOp("pause", { ruleId: rule.id })}>
{t("automation.editor.actions.pause")}
</DropdownMenu.DropdownItem>
) : (
<DropdownMenu.DropdownItem icon={<FeatherPlay />} onSelect={() => postOp("activate", { ruleId: rule.id })}>
{t("automation.editor.actions.activate")}
</DropdownMenu.DropdownItem>
)}
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownItem
className="text-text-feedback-negative"
icon={<FeatherTrash2 />}
onSelect={() => setArchiveRule(rule)}
data-ui-id={`ui.automation.list.rowMenu.${rule.id}.delete`}
>
{t("automation.list.actions.delete")}
</DropdownMenu.DropdownItem>
</DropdownMenu>
</SubframeCore.DropdownMenu.Content>
</SubframeCore.DropdownMenu.Portal>
</SubframeCore.DropdownMenu.Root>
) : null}
</div>
</Table.Cell>
</Table.Row>
);
})}
</Table>
</div>
)}
<div className="flex w-full items-center gap-3 pb-4">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{lastUpdatedAt
? t("automation.list.summary", {
shown: formatters.number(visibleRules.length),
total: formatters.number(vm.rules.length),
date: formatters.date(lastUpdatedAt, { dateStyle: "medium", timeStyle: "short" }),
})
: t("automation.list.summaryNoDate", {
shown: formatters.number(visibleRules.length),
total: formatters.number(vm.rules.length),
})}
</span>
</div>
</div>
<StartAuswahlDialog
vm={vm}
csrf={csrf}
open={startOpen}
onOpenChange={setStartOpen}
onCreateConfirmed={collapseSidebarIfPreferred}
/>
<AutomationArchiveDialog
ruleName={archiveRule?.name ?? ""}
open={archiveRule !== null}
onOpenChange={(open) => {
if (!open) setArchiveRule(null);
}}
onConfirm={() => {
if (!archiveRule) return;
postOp("archive", { ruleId: archiveRule.id });
setArchiveRule(null);
}}
/>
{anomalyDialogRule ? (
<SchleifenWarnungDialog
rule={anomalyDialogRule}
csrf={csrf}
actionData={actionData}
open
onOpenChange={(nextOpen) => {
if (!nextOpen) setAnomalyRuleId(null);
}}
/>
) : null}
</div>
);
}
@@ -0,0 +1,190 @@
import { useMemo, useState } from "react";
import { Form as RouterForm } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherArrowRight,
FeatherInfo,
FeatherLayoutGrid,
FeatherLayoutTemplate,
FeatherTrendingUp,
FeatherUser,
} from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { SearchInput } from "~/ui/components/SearchInput";
import { Tag_Label } from "~/ui/components/Tag_Label";
import type { AutomationTemplateCatalogVM } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { ChainChips, FilterPill, PageHeader, localizedValue, nodeIcon } from "./automationUi";
type TemplateTab = "all" | "shk" | "own";
/** WF-P12 S04: template catalog with tabs, category pills and use-template forms. */
export function AutomationTemplatesPage({ vm }: { vm: AutomationTemplateCatalogVM }): React.JSX.Element {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [tab, setTab] = useState<TemplateTab>("all");
const [categoryFilter, setCategoryFilter] = useState<string | null>(null);
const [query, setQuery] = useState("");
const counts = useMemo(
() => ({
all: vm.templates.length,
shk: vm.templates.filter((template) => !template.isTenantTemplate).length,
own: vm.templates.filter((template) => template.isTenantTemplate).length,
}),
[vm.templates]
);
const categories = useMemo(() => [...new Set(vm.templates.map((template) => template.category))].sort(), [vm.templates]);
const visibleTemplates = useMemo(() => {
const needle = query.trim().toLowerCase();
return vm.templates.filter((template) => {
if (tab === "shk" && template.isTenantTemplate) return false;
if (tab === "own" && !template.isTenantTemplate) return false;
if (categoryFilter && template.category !== categoryFilter) return false;
if (needle) {
const haystack = `${localizedValue(t, template.name, "automation.values.unknownTemplate")} ${
template.description ? localizedValue(t, template.description, "automation.values.unknownTemplateDescription") : ""
}`.toLowerCase();
if (!haystack.includes(needle)) return false;
}
return true;
});
}, [vm.templates, tab, categoryFilter, query, t]);
return (
<div className="flex w-full flex-col items-start bg-surface-neutral-primary">
<PageHeader
icon={<FeatherLayoutTemplate className="text-heading- font-heading- text-icon-neutral-tertiary" />}
title={t("automation.templatesPage.title")}
subtitle={t("automation.templatesPage.subtitle")}
/>
<div className="flex w-full items-center gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-3 mobile:flex-col mobile:items-stretch mobile:px-4">
<SearchInput
className="h-8 w-72 flex-none mobile:w-full"
size="small"
hideShortcut
placeholder={t("automation.templatesPage.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setQuery(event.target.value)}
/>
<div className="flex flex-wrap items-center gap-2">
<FilterPill label={t("automation.templatesPage.tabs.all")} count={counts.all} active={tab === "all"} onClick={() => setTab("all")} />
<FilterPill
label={t("automation.templatesPage.tabs.shk")}
count={counts.shk}
active={tab === "shk"}
onClick={() => setTab(tab === "shk" ? "all" : "shk")}
/>
<FilterPill
label={t("automation.templatesPage.tabs.own")}
count={counts.own}
active={tab === "own"}
onClick={() => setTab(tab === "own" ? "all" : "own")}
/>
</div>
{categories.length > 0 ? (
<div className="flex flex-wrap items-center gap-2">
<FeatherLayoutGrid className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<FilterPill label={t("automation.templatesPage.categoriesAll")} active={categoryFilter === null} onClick={() => setCategoryFilter(null)} />
{categories.map((category) => (
<FilterPill
key={category}
label={localizedValue(t, `automation.templatesPage.categories.${category}`, "automation.values.unknownCategory")}
active={categoryFilter === category}
onClick={() => setCategoryFilter(categoryFilter === category ? null : category)}
/>
))}
</div>
) : null}
</div>
<div className="flex w-full flex-col items-start gap-4 px-6 py-6 mobile:px-4">
{vm.templates.length === 0 ? (
<EmptyState outlined title={t("automation.templatesPage.empty.title")} body={t("automation.templatesPage.empty.body")} />
) : visibleTemplates.length === 0 ? (
<EmptyState outlined variant="no-results" title={t("automation.templatesPage.noMatches.title")} body={t("automation.templatesPage.noMatches.body")} />
) : (
<div className="grid w-full grid-cols-2 items-start gap-4 mobile:grid-cols-1">
{visibleTemplates.map((template) => {
const TemplateIcon = nodeIcon(template.chain[0]?.nodeType ?? template.category);
return (
<article
key={template.id}
className="flex flex-col items-start gap-3 self-stretch rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 shadow-sm hover:border-border-strong"
>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant={template.isTenantTemplate ? "neutral" : "information"} icon={<TemplateIcon />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="w-full text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{localizedValue(t, template.name, "automation.values.unknownTemplate")}
</span>
<span className="line-clamp-2 w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{template.description
? localizedValue(t, template.description, "automation.values.unknownTemplateDescription")
: t("automation.templatesPage.noDescription")}
</span>
</div>
<Tag_Label tone={template.isTenantTemplate ? "neutral-subtle" : "sky-subtle"} noAction size="small">
{template.isTenantTemplate ? t("automation.templatesPage.tenantTemplate") : t("automation.templatesPage.platformTemplate")}
</Tag_Label>
</div>
<ChainChips chain={template.chain} />
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
{/* There is no rule -> template back-reference in the schema, so a
usage count of 0 is "not measurable", not "never used". Showing
it anyway made every catalog template read as unused. */}
{template.useCount > 0 ? (
<div className="flex w-full items-center gap-2">
<FeatherTrendingUp className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.templatesPage.usedTimes", { count: template.useCount, formattedCount: formatters.number(template.useCount) })}
</span>
</div>
) : null}
{vm.canManage ? (
<RouterForm method="post" className="flex w-full items-center gap-2 mobile:flex-col mobile:items-stretch">
<input type="hidden" name="intent" value="use-template" />
<input type="hidden" name="templateId" value={template.id} />
<input
className="h-8 grow rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary placeholder:text-text-neutral-subtle"
name="ruleName"
placeholder={t("automation.templatesPage.ruleNamePlaceholder")}
aria-label={t("automation.templatesPage.ruleNamePlaceholder")}
/>
<Button type="submit" variant="secondary" size="small" iconRight={<FeatherArrowRight />}>
{t("automation.templatesPage.use")}
</Button>
</RouterForm>
) : null}
</article>
);
})}
</div>
)}
<div className="flex w-full items-center gap-3 pb-4">
<FeatherInfo className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.templatesPage.summary", {
shown: formatters.number(visibleTemplates.length),
total: formatters.number(vm.templates.length),
})}
</span>
{counts.own > 0 ? (
<div className="flex items-center gap-1.5">
<FeatherUser className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.templatesPage.ownCount", { count: counts.own, formattedCount: formatters.number(counts.own) })}
</span>
</div>
) : null}
</div>
</div>
</div>
);
}
@@ -0,0 +1,90 @@
import { describe, expect, it } from "vitest";
import type { TFunction } from "i18next";
import { anomalyMessage, automationStatusLabel, errorMessage, localizedValue, nodeTitle } from "./automationUi";
/**
* Minimal i18next stand-in: resolves the handful of keys these helpers touch and
* mirrors i18next's `defaultValue` behaviour for everything else.
*/
const DICTIONARY: Record<string, string> = {
"automation.execution.unsupportedNode": "Dieser Baustein wird vom Ausführer nicht unterstützt.",
"automation.nodes.portal_invite_user.title": "Portalnutzer einladen",
"automation.guards.triggerVolumePaused": "{{triggerCount}} Auslöser in {{minutes}} Minuten für „{{trigger}}“.",
"automation.nodes.crm_kontakt_created.title": "Neuer Kontakt",
"automation.values.unknownError": "Ein unerwarteter Fehler ist aufgetreten.",
"automation.values.unknownNode": "Unbekannter Baustein",
"automation.values.unknownStatus": "Unbekannter Status",
"automation.values.unknownSummary": "Keine Beschreibung verfügbar.",
"automation.values.unknownWarning": "Ein Hinweis konnte nicht angezeigt werden.",
};
const t = ((key: string, options?: Record<string, unknown>) => {
const entry = DICTIONARY[key];
if (entry === undefined) return (options?.defaultValue as string) ?? key;
return entry.replace(/{{(\w+)}}/g, (_match, name: string) => String(options?.[name] ?? ""));
}) as unknown as TFunction;
describe("errorMessage", () => {
it("translates a catalog key and names the offending block in plain language", () => {
expect(errorMessage(t, "automation.execution.unsupportedNode: portal.invite_user")).toBe(
"Dieser Baustein wird vom Ausführer nicht unterstützt. (Portalnutzer einladen)"
);
});
it("never renders a bare catalog key without its translation", () => {
expect(errorMessage(t, "automation.execution.unsupportedNode")).toBe("Dieser Baustein wird vom Ausführer nicht unterstützt.");
});
it("does not expose a raw backend error sentence", () => {
expect(errorMessage(t, "fetch failed")).toBe("Ein unerwarteter Fehler ist aufgetreten.");
});
it("does not expose an unknown catalog key", () => {
expect(errorMessage(t, "automation.execution.missingTranslation")).toBe("Ein unerwarteter Fehler ist aufgetreten.");
});
it("has nothing to show for an empty error", () => {
expect(errorMessage(t, null)).toBeNull();
expect(errorMessage(t, " ")).toBeNull();
});
});
describe("anomalyMessage", () => {
it("interpolates the meter numbers into the guard sentence", () => {
expect(
anomalyMessage(t, {
anomalyText: "automation.guards.triggerVolumePaused",
anomalyCount: 2000,
anomalyWindowMinutes: 5,
triggerKey: "crm.kontakt_created",
})
).toBe("2000 Auslöser in 5 Minuten für „Neuer Kontakt“.");
});
it("stays silent when no guard paused the rule", () => {
expect(anomalyMessage(t, { anomalyText: null, anomalyCount: null, anomalyWindowMinutes: null, triggerKey: null })).toBeNull();
});
it("does not expose a missing guard key", () => {
expect(
anomalyMessage(t, {
anomalyText: "automation.guards.missingTranslation",
anomalyCount: 1,
anomalyWindowMinutes: 1,
triggerKey: "crm.kontakt_created",
})
).toBe("Ein Hinweis konnte nicht angezeigt werden.");
});
});
describe("safe automation labels", () => {
it("uses localized fallbacks for unknown status, node and summary keys", () => {
expect(automationStatusLabel(t, "future_status")).toBe("Unbekannter Status");
expect(nodeTitle(t, "extension.missing_node")).toBe("Unbekannter Baustein");
expect(localizedValue(t, "automation.execution.missingSummary", "automation.values.unknownSummary")).toBe("Keine Beschreibung verfügbar.");
});
it("keeps user-authored text that is not an i18n key", () => {
expect(localizedValue(t, "Meine eigene Vorlage", "automation.values.unknownSummary")).toBe("Meine eigene Vorlage");
});
});
@@ -0,0 +1,249 @@
import type { TFunction } from "i18next";
import { useTranslation } from "react-i18next";
import {
FeatherBell,
FeatherCalendarClock,
FeatherCheckSquare,
FeatherChevronRight,
FeatherClock,
FeatherFileText,
FeatherGitBranch,
FeatherGlobe,
FeatherInbox,
FeatherMail,
FeatherRepeat,
FeatherSend,
FeatherTarget,
FeatherUserCog,
FeatherUserPlus,
FeatherZap,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import type { LocaleFormatters } from "~/locale/format";
/** Shared UI helpers for the WF-P12 automation screens (S01-S04 + dialogs). */
export function AutomationStatusBadge({ status }: { status: string }): React.JSX.Element {
const { t } = useTranslation();
return (
<BadgeFeedback farbe={statusBadgeTone(status)} size="small">
{automationStatusLabel(t, status)}
</BadgeFeedback>
);
}
export function automationStatusLabel(t: TFunction, status: string): string {
return localizedValue(t, `automation.status.${status}`, "automation.values.unknownStatus");
}
export function statusBadgeTone(status: string): React.ComponentProps<typeof BadgeFeedback>["farbe"] {
if (status === "success" || status === "completed" || status === "active" || status === "enabled") return "subtle-positive";
if (status === "failed" || status === "error") return "subtle-negative";
if (status === "paused" || status === "skipped" || status === "waiting" || status === "retrying") return "subtle-warning";
if (status === "running" || status === "queued") return "subtle-information";
return "subtle-neutral";
}
/** The page header now lives in the shared screen chrome and is used app-wide. */
export { PAGE_HEADER_ICON_CLASS, PageBody, PageHeader, PageShell } from "../shared/PageShell";
export function FilterPill({
label,
count,
active = false,
dotClassName,
onClick,
}: {
label: React.ReactNode;
count?: number | string;
active?: boolean;
dotClassName?: string;
onClick?: () => void;
}): React.JSX.Element {
return (
<button
type="button"
onClick={onClick}
className={
active
? "flex items-center gap-1.5 rounded-round border border-solid border-brand-brand-border-solid-default bg-brand-brand-secondary-surface-subtle px-3 py-1"
: "flex items-center gap-1.5 rounded-round border border-solid border-border-default bg-surface-neutral-secondary px-3 py-1 hover:bg-surface-neutral-tertiary"
}
>
{dotClassName ? <span className={`flex h-1.5 w-1.5 flex-none rounded-round ${dotClassName}`} /> : null}
<span
className={
active
? "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
}
>
{label}
</span>
{count !== undefined ? <span className="text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{count}</span> : null}
</button>
);
}
/** Translates a node key (e.g. "forms.submitted") via the automation.nodes catalog keys. */
export function nodeTitle(t: TFunction, nodeKey: string | null | undefined): string {
if (!nodeKey) return t("automation.values.noTrigger");
return localizedValue(t, `automation.nodes.${nodeKey.replaceAll(".", "_")}.title`, "automation.values.unknownNode");
}
/**
* `errorText` is what the executor threw: usually a catalog key with a
* technical detail appended ("automation.execution.unsupportedNode:
* portal.invite_user"). Rendering it verbatim puts an i18n key in front of the
* user, so translate the key part and name the offending block in plain
* language. Anything that is not key-shaped is a real sentence and stays.
*/
const ERROR_CATALOG_KEY = /^([a-z][A-Za-z0-9]*(?:\.[A-Za-z0-9_]+)+)(?::\s*(.+))?$/s;
const I18N_KEY = /^[a-z][A-Za-z0-9]*(?:\.[A-Za-z0-9_]+)+$/;
/** Translate stored catalog keys without ever exposing a missing key in the UI. */
export function localizedValue(t: TFunction, value: string, fallbackKey: string): string {
const translated = t(value, { defaultValue: "" });
if (translated) return translated;
return I18N_KEY.test(value) ? t(fallbackKey) : value;
}
export function errorMessage(t: TFunction, errorText: string | null | undefined): string | null {
if (!errorText?.trim()) return null;
const match = ERROR_CATALOG_KEY.exec(errorText.trim());
if (!match) return t("automation.values.unknownError");
const [, key, detail] = match;
const translated = t(key, { defaultValue: "" });
if (!translated) return t("automation.values.unknownError");
if (!detail) return translated;
return `${translated} (${nodeTitle(t, detail)})`;
}
/**
* Renders the guard that auto-paused a rule (M02). `anomalyText` holds the i18n
* key the guard stored; the meter numbers travel separately so the sentence
* stays translatable instead of being assembled on the server.
*/
export function anomalyMessage(
t: TFunction,
rule: {
readonly anomalyText: string | null;
readonly anomalyCount: number | null;
readonly anomalyWindowMinutes: number | null;
readonly triggerKey: string | null;
}
): string | null {
if (!rule.anomalyText) return null;
const translated = t(rule.anomalyText, {
defaultValue: "",
// Not `count`: that name switches i18next into plural resolution.
triggerCount: rule.anomalyCount ?? 0,
minutes: rule.anomalyWindowMinutes ?? 0,
trigger: nodeTitle(t, rule.triggerKey),
});
return translated || t("automation.values.unknownWarning");
}
const NODE_GROUP_ICONS: Record<string, React.ComponentType<{ className?: string }>> = {
crm: FeatherUserCog,
lead: FeatherUserPlus,
sales: FeatherTarget,
projects: FeatherGitBranch,
email: FeatherMail,
forms: FeatherFileText,
booking: FeatherCalendarClock,
calendar: FeatherCalendarClock,
time: FeatherClock,
webhook: FeatherGlobe,
notification: FeatherBell,
http: FeatherGlobe,
task: FeatherCheckSquare,
condition: FeatherGitBranch,
delay: FeatherClock,
loop: FeatherRepeat,
inbox: FeatherInbox,
kwp: FeatherSend,
};
export function nodeIcon(nodeKey: string | null | undefined): React.ComponentType<{ className?: string }> {
if (!nodeKey) return FeatherZap;
const group = nodeKey.split(".")[0];
return NODE_GROUP_ICONS[group] ?? FeatherZap;
}
/** Formats a millisecond duration in the compact style of the Subframe designs. */
export function formatDurationMs(t: TFunction, formatters: LocaleFormatters, durationMs: number | null | undefined): string {
if (durationMs == null) return t("automation.values.notAvailable");
if (durationMs < 1000) return t("automation.values.durationMs", { value: formatters.number(durationMs) });
if (durationMs < 60_000) {
return t("automation.values.durationSeconds", { value: formatters.number(durationMs / 1000, { maximumFractionDigits: 1 }) });
}
const minutes = Math.floor(durationMs / 60_000);
const seconds = Math.round((durationMs % 60_000) / 1000);
return t("automation.values.durationMinutes", { minutes: formatters.number(minutes), seconds: formatters.number(seconds) });
}
/** Renders a plain (non-array, non-null) record as an uppercase-labelled key/value block. */
export function KeyValueBlock({ label, value }: { label: React.ReactNode; value: unknown }): React.JSX.Element | null {
const entries = recordEntries(value);
if (entries.length === 0) return null;
return (
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-2 rounded-md bg-surface-neutral-tertiary px-4 py-3 mobile:w-full">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">{label}</span>
{entries.map(([key, entryValue]) => (
<div key={key} className="flex w-full items-start gap-3">
<span className="w-32 flex-none break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">{key}</span>
<span className="grow shrink-0 basis-0 break-words text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-primary">
{stringifyValue(entryValue)}
</span>
</div>
))}
</div>
);
}
export function recordEntries(value: unknown): [string, unknown][] {
if (!value || typeof value !== "object" || Array.isArray(value)) return [];
return Object.entries(value as Record<string, unknown>);
}
function stringifyValue(value: unknown): string {
if (value == null) return "—";
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
return JSON.stringify(value);
}
/** Trigger -> action chain chips used on the S04 cards and the M03 mini catalog. */
export function ChainChips({
chain,
}: {
chain: readonly { readonly kind: string; readonly summaryKey: string; readonly nodeType: string }[];
}): React.JSX.Element | null {
const { t } = useTranslation();
if (chain.length === 0) return null;
return (
<div className="flex w-full flex-wrap items-center gap-1.5">
{chain.map((step, index) => {
const StepIcon = nodeIcon(step.nodeType);
return (
<span key={`${step.nodeType}-${index}`} className="contents">
{index > 0 ? <FeatherChevronRight className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-subtle" /> : null}
<span className="flex items-center gap-1.5 rounded-md bg-surface-neutral-tertiary px-2 py-1">
<StepIcon
className={
step.kind === "trigger"
? "text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-feedback-information"
: "text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-icon-neutral-tertiary"
}
/>
<span className="whitespace-nowrap text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-secondary">
{t(step.summaryKey, { defaultValue: nodeTitle(t, step.nodeType) })}
</span>
</span>
</span>
);
})}
</div>
);
}
@@ -0,0 +1,51 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { AutomationArchiveDialog } from "./AutomationArchiveDialog";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string, options?: { name?: string }) => (options?.name ? `${key}:${options.name}` : key),
}),
}));
describe("AutomationArchiveDialog", () => {
it("shows a HiveGrid confirmation instead of a native browser prompt", () => {
const onOpenChange = vi.fn();
const onConfirm = vi.fn();
render(
<AutomationArchiveDialog
ruleName="Meine Automation"
open
onOpenChange={onOpenChange}
onConfirm={onConfirm}
/>
);
expect(screen.getByRole("dialog")).toBeVisible();
expect(screen.getByText("automation.list.actions.deleteDialogTitle")).toBeVisible();
expect(screen.getByText("automation.list.actions.deleteDialogBody:Meine Automation")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "shared.cancel" }));
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(onConfirm).not.toHaveBeenCalled();
});
it("requires an explicit destructive confirmation", () => {
const onConfirm = vi.fn();
render(
<AutomationArchiveDialog
ruleName="Meine Automation"
open
onOpenChange={vi.fn()}
onConfirm={onConfirm}
/>
);
fireEvent.click(screen.getByRole("button", { name: "automation.list.actions.deleteDialogConfirm" }));
expect(onConfirm).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,51 @@
import { useTranslation } from "react-i18next";
import { FeatherTrash2 } from "@subframe/core";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
export type AutomationArchiveDialogProps = {
ruleName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onConfirm: () => void;
};
/** Replaces the native browser confirm with the standard HiveGrid dialog. */
export function AutomationArchiveDialog({ ruleName, open, onOpenChange, onConfirm }: AutomationArchiveDialogProps): React.JSX.Element {
const { t } = useTranslation();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-8" data-ui-id="ui.automation.archiveDialog">
<div className="flex w-full flex-col gap-6">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">
{t("automation.list.actions.deleteDialogTitle")}
</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("automation.list.actions.deleteDialogBody", { name: ruleName })}
</span>
</div>
<div className="flex items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
<Button type="button" variant="tertiary" onClick={() => onOpenChange(false)}>
{t("shared.cancel")}
</Button>
<Button
type="button"
variant="destructive"
icon={<FeatherTrash2 />}
onClick={onConfirm}
data-ui-id="ui.automation.archiveDialog.confirm"
>
{t("automation.list.actions.deleteDialogConfirm")}
</Button>
</div>
</div>
</Dialog.Content>
</Dialog>
);
}
export default AutomationArchiveDialog;
@@ -0,0 +1,192 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import * as SubframeCore from "@subframe/core";
import { FeatherGitBranch, FeatherMousePointerClick, FeatherX, FeatherZap } from "@subframe/core";
import { Drawer } from "~/ui/components/Drawer";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { HelpCircle } from "~/ui/components/HelpCircle";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { SearchInput } from "~/ui/components/SearchInput";
import { Tooltip } from "~/ui/components/Tooltip";
import type { AutomationNodeDefinition } from "~/services/automation/automation.registry";
import { nodeIcon } from "../automationUi";
export type BausteinPickerDrawerProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
catalog: readonly AutomationNodeDefinition[];
canManage: boolean;
submitting: boolean;
onPick: (nodeType: string) => void;
};
type PickerCategory = "trigger" | "action" | "logic";
const CATEGORIES: readonly {
key: PickerCategory;
icon: React.ComponentType<{ className?: string }>;
tileVariant: "warning" | "information" | "neutral";
dotClass: string;
headerClass: string;
}[] = [
{ key: "trigger", icon: FeatherZap, tileVariant: "warning", dotClass: "bg-surface-feedback-solid-warning", headerClass: "text-text-feedback-warning" },
{ key: "action", icon: FeatherMousePointerClick, tileVariant: "information", dotClass: "bg-surface-feedback-solid-information", headerClass: "text-text-feedback-information" },
{ key: "logic", icon: FeatherGitBranch, tileVariant: "neutral", dotClass: "bg-surface-feedback-solid-neutral", headerClass: "text-text-neutral-tertiary" },
];
function categoryOf(definition: AutomationNodeDefinition): PickerCategory {
if (definition.kind === "trigger") return "trigger";
if (definition.kind === "flow_control" || definition.kind === "condition") return "logic";
return "action";
}
/**
* Node picker drawer after David's "Picker Kachel-Filter" page: category
* tiles (Ausloeser/Aktionen/Logik), search, and per-node cards with a
* plain-language tooltip. Renders the permission-filtered registry catalog,
* so design-only nodes without a registry counterpart never appear.
*/
export function BausteinPickerDrawer({ open, onOpenChange, catalog, canManage, submitting, onPick }: BausteinPickerDrawerProps): React.JSX.Element {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [activeCategory, setActiveCategory] = useState<PickerCategory | null>(null);
const sections = useMemo(() => {
const normalizedQuery = query.trim().toLocaleLowerCase();
return CATEGORIES.map((category) => ({
...category,
items: catalog.filter((definition) => {
if (categoryOf(definition) !== category.key) return false;
if (activeCategory && activeCategory !== category.key) return false;
if (!normalizedQuery) return true;
return (
t(definition.titleKey).toLocaleLowerCase().includes(normalizedQuery) ||
t(definition.descriptionKey).toLocaleLowerCase().includes(normalizedQuery) ||
definition.key.toLocaleLowerCase().includes(normalizedQuery)
);
}),
})).filter((section) => section.items.length > 0);
}, [catalog, query, activeCategory, t]);
return (
<Drawer open={open} onOpenChange={onOpenChange}>
<Drawer.Content className="z-50" motionDirection="full-from-right">
<div className="flex h-full w-[400px] flex-col items-start bg-surface-neutral-secondary mobile:w-full" data-ui-id="ui.automation.editor.picker">
<div className="flex w-full items-center justify-between border-b border-solid border-border-default px-5 py-4">
<div className="flex flex-col items-start gap-0.5">
<span className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{t("automation.editor.picker.title")}</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("automation.editor.picker.subtitle")}
</span>
</div>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => onOpenChange(false)} />
</div>
<div className="flex w-full flex-col items-start border-b border-solid border-border-default px-5 py-3">
<SearchInput
className="h-9 w-full flex-none"
fillContainer
hideShortcut
placeholder={t("automation.editor.picker.searchPlaceholder")}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
</div>
<div className="flex w-full items-start gap-2.5 border-b border-solid border-border-default px-5 py-4">
{CATEGORIES.map((category) => {
const CategoryIcon = category.icon;
const active = activeCategory === category.key;
return (
<button
key={category.key}
type="button"
onClick={() => setActiveCategory(active ? null : category.key)}
className={
active
? "flex flex-1 cursor-pointer flex-col items-center gap-1.5 rounded-md border border-solid border-border-strong bg-surface-neutral-tertiary px-3 py-3 shadow-sm"
: "flex flex-1 cursor-pointer flex-col items-center gap-1.5 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-3 py-3 hover:border-border-strong hover:bg-surface-neutral-tertiary hover:shadow-sm"
}
data-ui-id={`ui.automation.editor.picker.category.${category.key}`}
>
<IconWithBackground variant={category.tileVariant} size="small" icon={<CategoryIcon />} />
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 text-text-neutral-primary">
{t(`automation.editor.picker.categories.${category.key}`)}
</span>
</button>
);
})}
</div>
<div className="flex w-full flex-1 flex-col items-start gap-6 overflow-y-auto px-5 py-5">
{sections.length === 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.editor.picker.emptyResults")}
</span>
) : (
sections.map((section) => (
<div key={section.key} className="flex w-full flex-col items-start gap-2.5">
<div className="flex w-full items-center gap-2">
<span className={`flex h-2.5 w-2.5 flex-none rounded-round ${section.dotClass}`} />
<span className={`text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wider ${section.headerClass}`}>
{t(`automation.editor.picker.categories.${section.key}`)}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(`automation.editor.picker.categoryHints.${section.key}`)}
</span>
</div>
{section.items.map((definition) => {
const NodeIcon = nodeIcon(definition.key);
const helpText = t(`automation.editor.nodeConfig.${definition.key.replaceAll(".", "_")}.helpBox`, {
defaultValue: t(definition.descriptionKey),
});
return (
<button
key={definition.key}
type="button"
className="flex w-full cursor-pointer items-center gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-3 py-2.5 text-left hover:border-border-strong hover:bg-surface-neutral-tertiary hover:shadow-sm disabled:cursor-not-allowed disabled:opacity-50"
onClick={() => onPick(definition.key)}
disabled={!canManage || submitting}
data-ui-id={`ui.automation.editor.picker.${definition.key}`}
>
<IconWithBackground variant={section.tileVariant} size="medium" icon={<NodeIcon />} />
<span className="flex flex-1 flex-col">
<span className="text-body-small-semibold-0 font-body-small-semibold-0 text-text-neutral-primary">{t(definition.titleKey)}</span>
<span className="line-clamp-1 text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(definition.descriptionKey)}
</span>
</span>
{definition.availability === "extension_slot" ? (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("automation.editor.picker.prepared")}
</BadgeFeedback>
) : null}
<SubframeCore.Tooltip.Provider>
<SubframeCore.Tooltip.Root>
<SubframeCore.Tooltip.Trigger asChild>
<span className="flex-none">
<HelpCircle size="small" />
</span>
</SubframeCore.Tooltip.Trigger>
<SubframeCore.Tooltip.Portal>
<SubframeCore.Tooltip.Content side="left" align="center" sideOffset={6} asChild>
<Tooltip className="max-w-72">{helpText}</Tooltip>
</SubframeCore.Tooltip.Content>
</SubframeCore.Tooltip.Portal>
</SubframeCore.Tooltip.Root>
</SubframeCore.Tooltip.Provider>
</button>
);
})}
</div>
))
)}
</div>
</div>
</Drawer.Content>
</Drawer>
);
}
export default BausteinPickerDrawer;
@@ -0,0 +1,81 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { useState } from "react";
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import type { AutomationEditorStep } from "~/services/automation/automation.editor";
import type { NodeConfigFieldDescriptor } from "../nodeConfigDescriptors";
import { compactNodeConfigDraft, isNodeConfigFieldVisible, NodeConfigDialog } from "./NodeConfigDialog";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/ui/components/Dialog", () => {
function Root({ open, children }: { open: boolean; children: React.ReactNode }) {
return <div data-testid="dialog-root" data-open={String(open)}>{children}</div>;
}
function Content({ children, ...props }: React.HTMLAttributes<HTMLDivElement>) {
return <div {...props}>{children}</div>;
}
return { Dialog: Object.assign(Root, { Content }) };
});
const step: AutomationEditorStep = {
stepKey: "task",
kind: "action",
nodeType: "task.create",
parentStepIds: ["trigger"],
config: { title: "Nachfassen" },
position: { x: 320, y: 220 },
sortOrder: 1,
summaryKey: "automation.steps.createTask",
};
describe("NodeConfigDialog", () => {
it("keeps its content mounted while the confirm close transition runs", () => {
const onApply = vi.fn();
function Harness() {
const [open, setOpen] = useState(true);
const [selectedStep, setSelectedStep] = useState<AutomationEditorStep | null>(step);
return (
<NodeConfigDialog
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen);
if (!nextOpen) setSelectedStep(null);
}}
step={selectedStep}
descriptor={null}
canManage
submitting={false}
onApply={onApply}
/>
);
}
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "automation.editor.nodeConfig.apply" }));
expect(onApply).toHaveBeenCalledWith({ title: "Nachfassen" });
expect(screen.getByTestId("dialog-root")).toHaveAttribute("data-open", "false");
expect(document.querySelector('[data-ui-id="ui.automation.editor.nodeConfig"]')).toBeInTheDocument();
});
it("omits blank fields so they do not override values from the trigger payload", () => {
expect(compactNodeConfigDraft({ projectId: "", portalUserId: " ", role: "customer" })).toEqual({ role: "customer" });
});
it("shows conditional fields only for the configured selector value", () => {
const field: NodeConfigFieldDescriptor = {
kind: "text",
configKey: "taskId",
labelKey: "taskId",
visibleWhen: { configKey: "aufgabe", equals: "bestimmteAufgabe" },
};
expect(isNodeConfigFieldVisible(field, { aufgabe: "ausVorherigemSchritt" })).toBe(false);
expect(isNodeConfigFieldVisible(field, { aufgabe: "bestimmteAufgabe" })).toBe(true);
});
});
@@ -0,0 +1,273 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { FeatherCheck, FeatherHelpCircle } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
import { TextInput } from "~/ui/components/TextInput";
import type { AutomationEditorStep } from "~/services/automation/automation.editor";
import { nodeTitle } from "../automationUi";
import type { NodeConfigDescriptor, NodeConfigFieldDescriptor, NodeConfigTone } from "../nodeConfigDescriptors";
export type NodeConfigDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
step: AutomationEditorStep | null;
descriptor: NodeConfigDescriptor | null;
canManage: boolean;
submitting: boolean;
onApply: (config: Record<string, string>) => void;
};
const HELP_BOX_CLASSES: Record<NodeConfigTone, { box: string; icon: string }> = {
positive: { box: "border-border-positive-subtle bg-surface-feedback-subtle-positive", icon: "text-icon-feedback-positive" },
warning: { box: "border-border-warning-subtle bg-surface-feedback-subtle-warning", icon: "text-icon-feedback-warning" },
information: { box: "border-border-information-subtle bg-surface-feedback-subtle-information", icon: "text-icon-feedback-information" },
negative: { box: "border-border-negative-subtle bg-surface-feedback-subtle-negative", icon: "text-icon-feedback-negative" },
neutral: { box: "border-border-default bg-surface-neutral-tertiary", icon: "text-icon-neutral-tertiary" },
};
/**
* Schema-driven node configuration dialog after David's K-node cards
* ("(MCP) HiveGrid Workflow Engine / Automationen P12"). Nodes without a
* descriptor (extension slots, unknown types) fall back to the generic
* key/value editor so every step stays configurable.
*/
export function NodeConfigDialog({ open, onOpenChange, step, descriptor, canManage, submitting, onApply }: NodeConfigDialogProps): React.JSX.Element {
const { t } = useTranslation();
const [draft, setDraft] = useState<Record<string, string>>({});
const lastStep = useRef<AutomationEditorStep | null>(null);
const lastDescriptor = useRef<NodeConfigDescriptor | null>(null);
// The parent clears its selected step as soon as closing starts. Keep the
// last payload available while Radix holds the dialog in `data-state=closed`
// so its exit transition can finish instead of losing the whole subtree.
if (step) {
lastStep.current = step;
lastDescriptor.current = descriptor;
}
const renderedStep = step ?? lastStep.current;
const renderedDescriptor = step ? descriptor : lastDescriptor.current;
useEffect(() => {
if (!open || !step) return;
const initial: Record<string, string> = {};
for (const [key, value] of Object.entries(step.config)) {
initial[key] = typeof value === "string" ? value : value == null ? "" : String(value);
}
if (descriptor) {
for (const field of descriptor.fields) {
if (field.kind === "number-unit") {
initial[field.configKey] = initial[field.configKey] ?? field.defaultValue;
initial[field.unitConfigKey] = initial[field.unitConfigKey] ?? field.unitOptions[0]?.value ?? "";
} else if (!(field.configKey in initial)) {
initial[field.configKey] = "";
}
}
}
setDraft(initial);
}, [open, step, descriptor]);
if (!renderedStep) return <></>;
const NodeIcon = renderedDescriptor?.icon;
const helpTone = renderedDescriptor ? HELP_BOX_CLASSES[renderedDescriptor.helpBox.tone] : null;
const title = nodeTitle(t, renderedStep.nodeType);
const subtitle = t(`automation.nodes.${renderedStep.nodeType.replaceAll(".", "_")}.description`, { defaultValue: "" });
const widthClass = renderedDescriptor?.size === "medium" ? "w-[720px]" : "w-[560px]";
function setValue(key: string, value: string) {
setDraft((current) => ({ ...current, [key]: value }));
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.Content className={`${widthClass} max-w-full gap-0 p-0`} data-ui-id="ui.automation.editor.nodeConfig">
<div className="flex w-full items-start gap-3 border-b border-solid border-border-default px-6 py-4">
{NodeIcon && renderedDescriptor ? <IconWithBackground variant={renderedDescriptor.iconVariant} size="medium" icon={<NodeIcon />} /> : null}
<div className="flex flex-1 flex-col items-start gap-1">
<div className="flex flex-wrap items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{title}</span>
{renderedDescriptor ? (
<BadgeFeedback farbe={renderedDescriptor.badgeFarbe} size="small">
{t(renderedDescriptor.badgeLabelKey)}
</BadgeFeedback>
) : null}
{renderedDescriptor?.proBadge ? (
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("automation.editor.nodeConfig.badges.pro")}
</BadgeFeedback>
) : null}
</div>
{subtitle ? <span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{subtitle}</span> : null}
</div>
</div>
<div className="flex max-h-[60vh] w-full flex-col gap-4 overflow-y-auto px-6 py-5">
{renderedDescriptor && renderedDescriptor.fields.length > 0 ? (
renderedDescriptor.fields
.filter((field) => isNodeConfigFieldVisible(field, draft))
.map((field) => <NodeConfigField key={fieldKey(field)} field={field} draft={draft} onChange={setValue} disabled={!canManage} />)
) : (
<GenericConfigFields draft={draft} onChange={setValue} disabled={!canManage} emptyHint={t("automation.editor.inspector.emptyConfiguration")} />
)}
{renderedDescriptor && helpTone ? (
<div className={`flex w-full items-start gap-2 rounded-md border border-solid px-4 py-3 ${helpTone.box}`}>
<FeatherHelpCircle className={`mt-0.5 flex-none text-body-small-regular-0 font-body-small-regular-0 ${helpTone.icon}`} />
<span className="flex-1 text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{t(renderedDescriptor.helpBox.textKey)}</span>
</div>
) : null}
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default px-6 py-4">
<Button variant="tertiary" onClick={() => onOpenChange(false)}>
{t("shared.cancel")}
</Button>
<Button
icon={<FeatherCheck />}
loading={submitting}
disabled={!canManage}
onClick={() => {
onApply(compactNodeConfigDraft(draft));
onOpenChange(false);
}}
>
{t("automation.editor.nodeConfig.apply")}
</Button>
</div>
</Dialog.Content>
</Dialog>
);
}
export function isNodeConfigFieldVisible(field: NodeConfigFieldDescriptor, draft: Record<string, string>): boolean {
return !field.visibleWhen || draft[field.visibleWhen.configKey] === field.visibleWhen.equals;
}
export function compactNodeConfigDraft(draft: Record<string, string>): Record<string, string> {
return Object.fromEntries(Object.entries(draft).filter(([, value]) => value.trim().length > 0));
}
function fieldKey(field: NodeConfigFieldDescriptor): string {
return field.kind === "number-unit" ? `${field.configKey}-${field.unitConfigKey}` : field.configKey;
}
function NodeConfigField({
field,
draft,
onChange,
disabled,
}: {
field: NodeConfigFieldDescriptor;
draft: Record<string, string>;
onChange: (key: string, value: string) => void;
disabled: boolean;
}): React.JSX.Element {
const { t } = useTranslation();
if (field.kind === "select") {
return (
<Select
className="h-auto w-full flex-none"
label={t(field.labelKey)}
showLabel
placeholder={field.placeholderKey ? t(field.placeholderKey) : undefined}
helpText={field.helpTextKey ? t(field.helpTextKey) : undefined}
value={draft[field.configKey] || undefined}
onValueChange={(value) => onChange(field.configKey, value)}
disabled={disabled}
>
{field.options.map((option) => (
<Select.Item key={option.value} value={option.value}>
{t(option.labelKey)}
</Select.Item>
))}
</Select>
);
}
if (field.kind === "textarea") {
return (
<TextArea className="w-full" label={t(field.labelKey)} helpText={field.helpTextKey ? t(field.helpTextKey) : undefined} showLabel>
<TextArea.Input
value={draft[field.configKey] ?? ""}
placeholder={field.placeholderKey ? t(field.placeholderKey) : undefined}
onChange={(event) => onChange(field.configKey, event.target.value)}
disabled={disabled}
/>
</TextArea>
);
}
if (field.kind === "number-unit") {
return (
<div className="flex w-full items-end gap-2">
<TextInput className="w-24 flex-none" label={t(field.labelKey)} showLabel>
<TextInput.Input
type="number"
min={0}
value={draft[field.configKey] ?? field.defaultValue}
onChange={(event) => onChange(field.configKey, event.target.value)}
disabled={disabled}
/>
</TextInput>
<Select
className="h-auto flex-1"
label=""
value={draft[field.unitConfigKey] || field.unitOptions[0]?.value}
onValueChange={(value) => onChange(field.unitConfigKey, value)}
disabled={disabled}
>
{field.unitOptions.map((option) => (
<Select.Item key={option.value} value={option.value}>
{t(option.labelKey)}
</Select.Item>
))}
</Select>
</div>
);
}
return (
<TextInput className="w-full" label={t(field.labelKey)} helpText={field.helpTextKey ? t(field.helpTextKey) : undefined} showLabel>
<TextInput.Input
value={draft[field.configKey] ?? ""}
placeholder={field.placeholderKey ? t(field.placeholderKey) : undefined}
onChange={(event) => onChange(field.configKey, event.target.value)}
disabled={disabled}
/>
</TextInput>
);
}
/** Fallback for extension-slot/unknown nodes: edit the raw config bag like the previous inspector did. */
function GenericConfigFields({
draft,
onChange,
disabled,
emptyHint,
}: {
draft: Record<string, string>;
onChange: (key: string, value: string) => void;
disabled: boolean;
emptyHint: string;
}): React.JSX.Element {
const entries = Object.entries(draft);
if (entries.length === 0) {
return <span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{emptyHint}</span>;
}
return (
<>
{entries.map(([key]) => (
<TextInput key={key} className="w-full" label={key} showLabel>
<TextInput.Input value={draft[key] ?? ""} onChange={(event) => onChange(key, event.target.value)} disabled={disabled} />
</TextInput>
))}
</>
);
}
export default NodeConfigDialog;
@@ -0,0 +1,240 @@
import { useState } from "react";
import { Form as RouterForm, Link } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherAlertTriangle,
FeatherArrowLeft,
FeatherDatabase,
FeatherInfo,
FeatherListChecks,
FeatherPlay,
FeatherUsers,
FeatherX,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { TextInput } from "~/ui/components/TextInput";
import type { AutomationExecutionListVM, AutomationExecutionsActionData } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { localizedValue, nodeIcon, nodeTitle } from "../automationUi";
/** WF-P12 M01 "Probelauf pruefen": dry-run preview form + result (intent=dry-run, csrf-guarded). */
export function ProbelaufDialog({
vm,
csrf,
actionData,
open,
onOpenChange,
}: {
vm: AutomationExecutionListVM;
csrf: string;
actionData?: AutomationExecutionsActionData;
open: boolean;
onOpenChange: (open: boolean) => void;
}): React.JSX.Element | null {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const [confirmationPhrase, setConfirmationPhrase] = useState("");
if (!open) return null;
const preview = actionData?.dryRunPreview;
const needsConfirmation = preview?.requiresConfirmation ?? false;
const phrase = preview?.confirmationPhrase ?? t("automation.editor.dryRun.confirmationPhrase");
return (
<Dialog open onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onOpenChange(false))}>
<Dialog.Content className="w-[640px] max-w-full gap-0 p-0">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex items-start gap-3">
<div className="flex h-9 w-9 flex-none items-center justify-center rounded-md bg-surface-feedback-subtle-information">
<FeatherPlay className="text-body-large-0 font-body-large-0 text-icon-feedback-information" />
</div>
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("automation.editor.dryRun.dialogTitle")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.editor.dryRun.dialogSubtitle")}
</span>
</div>
</div>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => onOpenChange(false)} />
</div>
<div className="flex w-full flex-col items-start gap-5 px-6 py-5 max-h-[65vh] overflow-y-auto mobile:px-4">
{actionData && !actionData.ok ? (
<div className="flex w-full items-center gap-2 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
<FeatherAlertTriangle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-feedback-negative">{t(actionData.errorKey)}</span>
</div>
) : null}
<RouterForm method="post" className="flex w-full flex-col items-start gap-4">
<input type="hidden" name="csrf" value={csrf} readOnly />
<input type="hidden" name="intent" value="dry-run" />
<div className="flex w-full items-start gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-3">
<FeatherInfo className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-information" />
<span className="grow shrink-0 basis-0 text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("automation.editor.dryRun.dataSourceHelp", { limit: 500 })}
</span>
</div>
{needsConfirmation ? (
<div className="flex w-full flex-col items-start gap-3 rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-4 py-3.5">
<div className="flex w-full items-start gap-2">
<FeatherAlertTriangle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-warning" />
<span className="grow shrink-0 basis-0 text-body-small-medium-150 font-body-small-medium-150 text-text-feedback-warning">
{t("automation.editor.dryRun.confirmationHint", { phrase })}
</span>
</div>
<TextInput className="w-full" label={t("automation.editor.dryRun.confirmationLabel")} showLabel>
<TextInput.Input
name="confirmationPhrase"
value={confirmationPhrase}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setConfirmationPhrase(event.target.value)}
/>
</TextInput>
</div>
) : null}
<Button type="submit" icon={<FeatherPlay />}>
{t("automation.editor.dryRun.start")}
</Button>
</RouterForm>
{preview ? (
<div className="flex w-full flex-col items-start gap-5 border-t border-solid border-border-default pt-5">
<div className="flex w-full flex-col items-start gap-3 rounded-lg border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-4 py-4">
<div className="flex w-full items-center gap-3 mobile:flex-col mobile:items-start">
<div className="flex h-10 w-10 flex-none items-center justify-center rounded-round bg-surface-neutral-secondary">
<FeatherDatabase className="text-heading- font-heading- text-icon-feedback-warning" />
</div>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-subtitle font-subtitle text-text-neutral-primary">
{t("automation.editor.dryRun.matched", { count: preview.matchedRecords, formattedCount: formatters.number(preview.matchedRecords) })}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{nodeTitle(t, vm.rule.triggerKey)}
</span>
</div>
{preview.requiresConfirmation ? (
<BadgeFeedback farbe="subtle-warning">{t("automation.editor.dryRun.confirmationBadge")}</BadgeFeedback>
) : null}
</div>
{preview.requiresConfirmation ? (
<div className="flex w-full items-center gap-2 border-t border-solid border-border-warning-subtle pt-3">
<FeatherAlertTriangle className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-warning" />
<span className="grow shrink-0 basis-0 text-body-small-medium-150 font-body-small-medium-150 text-text-feedback-warning">
{t("automation.editor.dryRun.thresholdWarning")}
</span>
</div>
) : null}
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(preview.sampleLimitReached ? "automation.editor.dryRun.sourceSummaryLimited" : "automation.editor.dryRun.sourceSummary", {
count: preview.inspectedEvents,
formattedCount: formatters.number(preview.inspectedEvents),
})}
</span>
</div>
{preview.examples.length > 0 ? (
<div className="flex w-full flex-col items-start gap-3">
<div className="flex w-full items-center gap-2">
<FeatherUsers className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.editor.dryRun.examplesTitle", { count: preview.examples.length })}
</span>
</div>
<div className="flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-secondary">
{preview.examples.map((example, index) => (
<div
key={`${example}-${index}`}
className={
index < preview.examples.length - 1
? "flex w-full items-center gap-3 border-b border-solid border-border-default px-4 py-2.5"
: "flex w-full items-center gap-3 px-4 py-2.5"
}
>
<span className="grow shrink-0 basis-0 text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{example}
</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{nodeTitle(t, vm.rule.triggerKey)}
</BadgeFeedback>
</div>
))}
</div>
</div>
) : null}
<div className="flex w-full flex-col items-start gap-3">
<div className="flex w-full items-center gap-2">
<FeatherListChecks className="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.editor.dryRun.simulationTitle")}
</span>
<BadgeFeedback farbe="subtle-information" size="small">
{t("automation.editor.dryRun.previewOnly")}
</BadgeFeedback>
</div>
<div className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-4">
{preview.steps.map((step, index) => {
const StepIcon = nodeIcon(step.nodeType);
return (
<span key={step.stepKey} className="contents">
{index > 0 ? (
<span className="flex h-4 w-6 flex-none flex-col items-center">
<span className="flex h-4 w-px flex-none flex-col items-center bg-border-strong" />
</span>
) : null}
<div className="flex w-full items-start gap-3">
<div className="flex h-6 w-6 flex-none items-center justify-center rounded-round bg-surface-feedback-subtle-information">
<StepIcon className="text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-information" />
</div>
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary">
{t(step.summaryKey, { defaultValue: nodeTitle(t, step.nodeType) })}
</span>
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t(step.effectKey, { node: nodeTitle(t, step.nodeType) })}
</span>
</div>
</div>
</span>
);
})}
</div>
</div>
{preview.warnings.length > 0 ? (
<div className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-4 py-3">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-warning">
{t("automation.editor.dryRun.warningsTitle")}
</span>
{preview.warnings.map((warningKey, index) => (
<div key={`${warningKey}-${index}`} className="flex w-full items-start gap-2">
<FeatherInfo className="mt-0.5 text-body-small-regular-0 font-body-small-regular-0 text-icon-feedback-warning" />
<span className="grow shrink-0 basis-0 text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{localizedValue(t, warningKey, "automation.values.unknownWarning")}
</span>
</div>
))}
</div>
) : null}
</div>
) : null}
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button type="button" className="mobile:w-full" variant="tertiary" onClick={() => onOpenChange(false)}>
{t("shared.cancel")}
</Button>
<Link to={vm.rule.editUrl} className="mobile:w-full">
<Button type="button" className="mobile:w-full" variant="secondary" icon={<FeatherArrowLeft />}>
{t("automation.editor.dryRun.backToEditor")}
</Button>
</Link>
</div>
</Dialog.Content>
</Dialog>
);
}
@@ -0,0 +1,119 @@
import { Link, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import { FeatherActivity, FeatherAlertTriangle, FeatherPause, FeatherRefreshCw, FeatherWrench, FeatherZap } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import type { AutomationListActionData, AutomationListItemVM } from "~/services/automation/automation.server";
import { useLocaleFormatters } from "~/locale/format";
import { anomalyMessage, localizedValue } from "../automationUi";
/**
* WF-P12 M02 "Schleife oder zu hohe Rate erkannt": shown for a rule the trigger
* volume meter auto-paused. "Trotzdem aktivieren" posts intent=activate (the
* server re-validates the flow and blocks invalid ones).
*/
export function SchleifenWarnungDialog({
rule,
csrf,
actionData,
open,
onOpenChange,
}: {
rule: AutomationListItemVM;
csrf: string;
actionData?: AutomationListActionData;
open: boolean;
onOpenChange: (open: boolean) => void;
}): React.JSX.Element | null {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const submit = useSubmit();
if (!open) return null;
const activateAnyway = () => {
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("intent", "activate");
formData.set("ruleId", rule.id);
void submit(formData, { method: "post" });
};
return (
<Dialog open onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onOpenChange(false))}>
<Dialog.Content className="w-[640px] max-w-full gap-4 px-6 py-6">
<div className="flex w-full items-start gap-4">
<IconWithBackground variant="warning" size="large" round icon={<FeatherRefreshCw />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-2">
<div className="flex w-full flex-wrap items-center gap-2">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("automation.dialogs.loop.title")}</span>
<BadgeFeedback farbe="subtle-warning" size="small">
{t("automation.status.paused")}
</BadgeFeedback>
</div>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.dialogs.loop.description", { name: rule.name })}
</span>
</div>
</div>
{actionData && !actionData.ok ? (
<div className="flex w-full items-start gap-2 rounded-md border border-solid border-border-negative-subtle bg-surface-feedback-subtle-negative px-4 py-3">
<FeatherAlertTriangle className="mt-0.5 text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-negative" />
<div className="flex grow shrink-0 basis-0 flex-col items-start">
<span className="text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-negative">{t(actionData.errorKey)}</span>
{actionData.detail ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{localizedValue(t, actionData.detail, "automation.values.unknownError")}
</span>
) : null}
</div>
</div>
) : null}
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
<div className="flex w-full flex-col items-start gap-2 rounded-md border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning px-4 py-3.5">
<div className="flex w-full items-center gap-2">
<FeatherActivity className="text-body-default-regular-0 font-body-default-regular-0 text-icon-feedback-warning" />
<span className="grow shrink-0 basis-0 text-body-small-semibold-150 font-body-small-semibold-150 text-text-feedback-warning">
{t("automation.dialogs.loop.rateTitle")}
</span>
</div>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{anomalyMessage(t, rule) ?? t("automation.dialogs.loop.explainer")}
</span>
{rule.anomalyPausedUntil ? (
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">
{t("automation.dialogs.loop.pausedUntil", {
date: formatters.date(rule.anomalyPausedUntil, { dateStyle: "medium", timeStyle: "short" }),
})}
</span>
) : null}
</div>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.dialogs.loop.explainer")}
</span>
<div className="flex w-full items-center justify-end gap-2 mobile:flex-col-reverse mobile:items-stretch">
<Button type="button" className="mobile:w-full" variant="destructive" icon={<FeatherZap />} onClick={activateAnyway}>
{t("automation.dialogs.loop.activateAnyway")}
</Button>
<div className="flex grow shrink-0 basis-0 items-center justify-end gap-2 mobile:grow-0 mobile:flex-col-reverse mobile:items-stretch">
<Button type="button" className="mobile:w-full" variant="secondary" icon={<FeatherPause />} onClick={() => onOpenChange(false)}>
{t("automation.dialogs.loop.keepPaused")}
</Button>
<Link to={rule.editUrl} className="mobile:w-full">
<Button type="button" className="mobile:w-full" variant="primary" icon={<FeatherWrench />}>
{t("automation.dialogs.loop.fix")}
</Button>
</Link>
</div>
</div>
</Dialog.Content>
</Dialog>
);
}
@@ -0,0 +1,81 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { AutomationListVM } from "~/services/automation/automation.server";
import { StartAuswahlDialog } from "./StartAuswahlDialog";
const mocks = vi.hoisted(() => ({
submit: vi.fn(),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useSubmit: () => mocks.submit,
};
});
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const vm: AutomationListVM = {
tenantSlug: "acme",
currentUserId: "user-1",
rules: [],
templates: [],
templatesUrl: "/acme/automations/templates",
canManage: true,
canRun: true,
};
function renderDialog(onCreateConfirmed = vi.fn(), onOpenChange = vi.fn()) {
const router = createMemoryRouter(
[
{
path: "/",
element: (
<StartAuswahlDialog
vm={vm}
csrf="csrf"
open
onOpenChange={onOpenChange}
onCreateConfirmed={onCreateConfirmed}
/>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
return { onCreateConfirmed, onOpenChange };
}
describe("StartAuswahlDialog", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("confirms the canvas transition immediately before creating the automation", () => {
const { onCreateConfirmed } = renderDialog();
fireEvent.click(screen.getByRole("button", { name: "automation.list.dialogs.start.continue" }));
expect(onCreateConfirmed).toHaveBeenCalledOnce();
expect(mocks.submit).toHaveBeenCalledOnce();
expect(onCreateConfirmed.mock.invocationCallOrder[0]).toBeLessThan(mocks.submit.mock.invocationCallOrder[0]);
});
it("does not confirm the canvas transition when the dialog is cancelled", () => {
const { onCreateConfirmed, onOpenChange } = renderDialog();
fireEvent.click(screen.getByRole("button", { name: "shared.cancel" }));
expect(onOpenChange).toHaveBeenCalledWith(false);
expect(onCreateConfirmed).not.toHaveBeenCalled();
expect(mocks.submit).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,352 @@
import { useMemo, useState } from "react";
import { Form as RouterForm, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherArrowRight,
FeatherCheckCircle2,
FeatherLayoutTemplate,
FeatherPlus,
FeatherUser,
FeatherX,
} from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
import { SearchInput } from "~/ui/components/SearchInput";
import { Tag_Label } from "~/ui/components/Tag_Label";
import { TextInput } from "~/ui/components/TextInput";
import type { AutomationListVM } from "~/services/automation/automation.server";
import { localizedValue, nodeIcon } from "../automationUi";
type TemplateTab = "shk" | "own";
/**
* WF-P12 M03 "Neue Automation starten": blank start (intent=create on the list
* route, csrf-guarded) or template start (intent=use-template posted to the
* templates route, no csrf contract there).
*/
export function StartAuswahlDialog({
vm,
csrf,
open,
onOpenChange,
onCreateConfirmed,
}: {
vm: AutomationListVM;
csrf: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onCreateConfirmed: () => void;
}): React.JSX.Element | null {
const { t } = useTranslation();
const submit = useSubmit();
const [mode, setMode] = useState<"blank" | "template">("blank");
const [selectedTemplateId, setSelectedTemplateId] = useState<string | null>(null);
const [templateTab, setTemplateTab] = useState<TemplateTab>("shk");
const [query, setQuery] = useState("");
const [ruleName, setRuleName] = useState<string>(() => t("automation.list.dialogs.start.defaultName"));
const templates = useMemo(
() =>
vm.templates.map((template) => ({
...template,
// The list VM carries no tenant flag; seeded platform templates keep
// their i18n-key names, tenant templates carry free-text names.
isPlatform: template.name.startsWith("automation."),
})),
[vm.templates]
);
const counts = useMemo(
() => ({
shk: templates.filter((template) => template.isPlatform).length,
own: templates.filter((template) => !template.isPlatform).length,
}),
[templates]
);
const visibleTemplates = useMemo(() => {
const needle = query.trim().toLowerCase();
return templates.filter((template) => {
if (templateTab === "shk" && !template.isPlatform) return false;
if (templateTab === "own" && template.isPlatform) return false;
if (needle) {
const label = localizedValue(t, template.name, "automation.values.unknownTemplate");
if (!`${label} ${template.category}`.toLowerCase().includes(needle)) return false;
}
return true;
});
}, [templates, templateTab, query, t]);
if (!open) return null;
const submitUseTemplate = (templateId: string) => {
const formData = new FormData();
formData.set("intent", "use-template");
formData.set("templateId", templateId);
if (ruleName.trim()) formData.set("ruleName", ruleName.trim());
onCreateConfirmed();
void submit(formData, { method: "post", action: vm.templatesUrl });
};
const continueWithSelection = () => {
if (mode === "template") {
if (selectedTemplateId) submitUseTemplate(selectedTemplateId);
return;
}
if (!ruleName.trim()) return;
const formData = new FormData();
formData.set("csrf", csrf);
formData.set("intent", "create");
formData.set("ruleName", ruleName.trim());
onCreateConfirmed();
void submit(formData, { method: "post" });
};
return (
<Dialog open onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onOpenChange(false))}>
<Dialog.Content className="w-[760px] max-w-full gap-0 p-0">
<div className="flex w-full items-start justify-between gap-3 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:px-4">
<div className="flex flex-col items-start gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("automation.list.dialogs.start.title")}</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.list.dialogs.start.subtitle")}
</span>
</div>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => onOpenChange(false)} />
</div>
<div className="flex w-full flex-col items-start gap-6 px-6 py-5 max-h-[65vh] overflow-y-auto mobile:px-4">
<div className="flex w-full flex-col items-start gap-3">
<span className="text-body-extra-small-semibold-0 font-body-extra-small-semibold-0 uppercase tracking-wide text-text-neutral-tertiary">
{t("automation.list.dialogs.start.howToBegin")}
</span>
<div className="grid w-full grid-cols-2 items-stretch gap-4 mobile:grid-cols-1">
<button
type="button"
onClick={() => setMode("blank")}
className={
mode === "blank"
? "flex flex-col items-start gap-3 rounded-lg border-2 border-solid border-brand-brand-secondary-border-solid-default bg-surface-neutral-secondary px-5 py-5 text-left shadow-sm"
: "flex flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 text-left hover:border-border-strong"
}
>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="neutral" size="large" icon={<FeatherPlus />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center gap-2">
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.list.dialogs.start.blank.title")}
</span>
{mode === "blank" ? <FeatherCheckCircle2 className="text-body-large font-body-large text-icon-feedback-information" /> : null}
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.list.dialogs.start.blank.description")}
</span>
</div>
</div>
</button>
<button
type="button"
onClick={() => setMode("template")}
className={
mode === "template"
? "flex flex-col items-start gap-3 rounded-lg border-2 border-solid border-brand-brand-secondary-border-solid-default bg-surface-neutral-secondary px-5 py-5 text-left shadow-sm"
: "flex flex-col items-start gap-3 rounded-lg border border-solid border-border-default bg-surface-neutral-secondary px-5 py-5 text-left hover:border-border-strong"
}
>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant="information" size="large" icon={<FeatherLayoutTemplate />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-1">
<div className="flex w-full items-center gap-2">
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.list.dialogs.start.template.title")}
</span>
{mode === "template" ? (
<FeatherCheckCircle2 className="text-body-large font-body-large text-icon-feedback-information" />
) : (
<BadgeFeedback farbe="subtle-information" size="small">
{t("automation.list.dialogs.start.template.available", { count: templates.length })}
</BadgeFeedback>
)}
</div>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.list.dialogs.start.template.description")}
</span>
</div>
</div>
</button>
</div>
</div>
<RouterForm
className="flex w-full flex-col items-start gap-2"
onSubmit={(event) => {
event.preventDefault();
continueWithSelection();
}}
>
<TextInput className="w-full" label={t("automation.list.dialogs.start.nameLabel")} showLabel>
<TextInput.Input
name="ruleName"
required
value={ruleName}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setRuleName(event.target.value)}
/>
</TextInput>
</RouterForm>
<div className="flex w-full flex-col items-start gap-4 rounded-lg border border-solid border-border-default bg-surface-neutral-primary px-5 py-5 mobile:px-4">
<div className="flex w-full items-center gap-2">
<FeatherLayoutTemplate className="text-body-large font-body-large text-icon-neutral-tertiary" />
<span className="grow shrink-0 basis-0 text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{t("automation.list.dialogs.start.catalog.title")}
</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{t("automation.list.dialogs.start.catalog.count", { count: templates.length })}
</BadgeFeedback>
</div>
<SearchInput
className="h-8 w-full flex-none"
size="small"
hideShortcut
placeholder={t("automation.list.dialogs.start.catalog.searchPlaceholder")}
value={query}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => setQuery(event.target.value)}
/>
<div className="flex w-full items-center gap-2 border-b border-solid border-border-default">
<button
type="button"
onClick={() => setTemplateTab("shk")}
className={
templateTab === "shk"
? "flex items-center gap-2 border-b-2 border-solid border-brand-brand-secondary-border-solid-default px-3 py-2"
: "flex cursor-pointer items-center gap-2 border-b-2 border-solid border-transparent px-3 py-2 hover:border-border-strong"
}
>
<FeatherLayoutTemplate className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span
className={
templateTab === "shk"
? "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
}
>
{t("automation.list.dialogs.start.tabs.shk")}
</span>
<BadgeFeedback farbe="subtle-information" size="small">
{counts.shk}
</BadgeFeedback>
</button>
<button
type="button"
onClick={() => setTemplateTab("own")}
className={
templateTab === "own"
? "flex items-center gap-2 border-b-2 border-solid border-brand-brand-secondary-border-solid-default px-3 py-2"
: "flex cursor-pointer items-center gap-2 border-b-2 border-solid border-transparent px-3 py-2 hover:border-border-strong"
}
>
<FeatherUser className="text-body-small-regular-0 font-body-small-regular-0 text-icon-neutral-tertiary" />
<span
className={
templateTab === "own"
? "text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary"
}
>
{t("automation.list.dialogs.start.tabs.own")}
</span>
<BadgeFeedback farbe="subtle-neutral" size="small">
{counts.own}
</BadgeFeedback>
</button>
</div>
{visibleTemplates.length === 0 ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{t("automation.templatesPage.noMatches.title")}
</span>
) : (
<div className="grid w-full grid-cols-2 items-start gap-4 mobile:grid-cols-1">
{visibleTemplates.map((template) => {
const TemplateIcon = nodeIcon(template.category);
const selected = mode === "template" && selectedTemplateId === template.id;
return (
<div
key={template.id}
className={
selected
? "flex flex-col items-start gap-3 self-stretch rounded-md border-2 border-solid border-brand-brand-secondary-border-solid-default bg-surface-neutral-secondary px-4 py-4 shadow-sm"
: "flex flex-col items-start gap-3 self-stretch rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 shadow-sm hover:border-border-strong"
}
role="button"
tabIndex={0}
onClick={() => {
setMode("template");
setSelectedTemplateId(template.id);
}}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
setMode("template");
setSelectedTemplateId(template.id);
}
}}
>
<div className="flex w-full items-start gap-3">
<IconWithBackground variant={template.isPlatform ? "information" : "neutral"} icon={<TemplateIcon />} />
<div className="flex grow shrink-0 basis-0 flex-col items-start gap-0.5">
<span className="w-full text-body-default-semibold-150 font-body-default-semibold-150 text-text-neutral-primary">
{localizedValue(t, template.name, "automation.values.unknownTemplate")}
</span>
<span className="w-full text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
{localizedValue(t, `automation.templatesPage.categories.${template.category}`, "automation.values.unknownCategory")}
</span>
</div>
<Tag_Label tone={template.isPlatform ? "sky-subtle" : "neutral-subtle"} noAction size="small">
{template.isPlatform ? t("automation.templatesPage.platformTemplate") : t("automation.templatesPage.tenantTemplate")}
</Tag_Label>
</div>
<div className="flex h-px w-full flex-none flex-col items-center bg-border-default" />
<div className="flex w-full items-center justify-end gap-2">
<Button
type="button"
variant={selected ? "primary" : "secondary"}
size="small"
iconRight={<FeatherArrowRight />}
onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
event.stopPropagation();
submitUseTemplate(template.id);
}}
>
{t("automation.templatesPage.use")}
</Button>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
<div className="flex w-full items-center justify-end gap-2 border-t border-solid border-border-default bg-surface-neutral-secondary px-6 py-4 mobile:flex-col-reverse mobile:items-stretch mobile:px-4">
<Button type="button" className="mobile:w-full" variant="tertiary" onClick={() => onOpenChange(false)}>
{t("shared.cancel")}
</Button>
<Button
type="button"
className="mobile:w-full"
iconRight={<FeatherArrowRight />}
disabled={mode === "template" ? !selectedTemplateId : !ruleName.trim()}
onClick={continueWithSelection}
>
{t("automation.list.dialogs.start.continue")}
</Button>
</div>
</Dialog.Content>
</Dialog>
);
}
@@ -0,0 +1,96 @@
import { describe, expect, it } from "vitest";
import { automationActionCatalog } from "~/services/automation/automation.registry";
import { NODE_CONFIG_DESCRIPTORS } from "./nodeConfigDescriptors";
describe("automation node config descriptors", () => {
it("provides editable fields for every portal action", () => {
const portalActions = automationActionCatalog.filter((node) => node.group === "portal");
for (const action of portalActions) {
expect(NODE_CONFIG_DESCRIPTORS[action.key]?.fields.length, action.key).toBeGreaterThan(0);
}
});
it("captures every required portal action input", () => {
expect(configKeys("portal.invite_user")).toEqual(["kind", "email", "firstName", "lastName"]);
expect(configKeys("portal.grant_access")).toEqual(["portalUserId", "projectId", "companyName"]);
expect(configKeys("portal.revoke_access")).toEqual(["portalUserId", "projectId"]);
expect(configKeys("portal.release_document")).toEqual(["projectId", "fileId"]);
expect(configKeys("portal.send_status_mail")).toEqual(["projectId", "stageChangeId"]);
expect(configKeys("portal.disable_user")).toEqual(["portalUserId"]);
});
it("only exposes trigger filters backed by real event payload fields", () => {
expect(configKeys("crm.kontakt_created")).toEqual([]);
expect(configKeys("crm.kontakt_updated")).toEqual(["beobachteteFelder"]);
expect(configKeys("lead.captured")).toEqual(["quelle"]);
expect(configKeys("lead.qualified")).toEqual([]);
expect(configKeys("sales.project_won")).toEqual(["pipelineId", "mindestwert"]);
expect(configKeys("sales.stage_changed")).toEqual(["pipelineId", "fromStageId", "toStageId"]);
expect(configKeys("projects.project_created")).toEqual(["pipelineId", "quelle"]);
expect(configKeys("email.inbound_received")).toEqual(["mailboxId", "betreffFilter", "absenderFilter"]);
expect(configKeys("forms.submitted")).toEqual(["formId"]);
});
it("shows manual target IDs only when their selector needs one", () => {
expect(NODE_CONFIG_DESCRIPTORS["crm.update_kontakt"]?.fields.find((field) => field.configKey === "kontaktId")?.visibleWhen).toEqual({
configKey: "kontakt",
equals: "manuell",
});
expect(NODE_CONFIG_DESCRIPTORS["task.assign"]?.fields.find((field) => field.configKey === "taskId")?.visibleWhen).toEqual({
configKey: "aufgabe",
equals: "bestimmteAufgabe",
});
});
it("does not offer unenforced visibility for activity notes", () => {
expect(configKeys("crm.create_note")).toEqual(["datensatz", "notiztext"]);
});
it("offers only condition fields supplied by current trigger payloads", () => {
const field = NODE_CONFIG_DESCRIPTORS["condition.if_else"]?.fields.find((candidate) => candidate.configKey === "feld");
expect(field?.options?.map((option) => option.value)).toEqual(["angebotswert", "quelle", "status"]);
});
it("offers only contact targets supplied by current trigger payloads", () => {
const field = NODE_CONFIG_DESCRIPTORS["crm.update_kontakt"]?.fields.find((candidate) => candidate.configKey === "kontakt");
expect(field?.options?.map((option) => option.value)).toEqual(["ausloeser", "manuell"]);
});
it("configures every executable CRM tag and assignment input", () => {
expect(configKeys("crm.add_tag")).toEqual(["kontakt", "kontaktId", "tagId"]);
expect(configKeys("crm.remove_tag")).toEqual(["kontakt", "kontaktId", "tagId"]);
expect(configKeys("crm.assign_kontakt")).toEqual(["kontakt", "kontaktId", "userId"]);
for (const nodeType of ["crm.add_tag", "crm.remove_tag", "crm.assign_kontakt"]) {
expect(NODE_CONFIG_DESCRIPTORS[nodeType]?.fields.find((field) => field.configKey === "kontaktId")?.visibleWhen).toEqual({
configKey: "kontakt",
equals: "manuell",
});
}
});
it("configures every executable lead action input", () => {
expect(configKeys("lead.assign")).toEqual(["lead", "leadId", "userId"]);
expect(configKeys("lead.set_status")).toEqual(["lead", "leadId", "status"]);
for (const nodeType of ["lead.assign", "lead.set_status"]) {
expect(NODE_CONFIG_DESCRIPTORS[nodeType]?.fields.find((field) => field.configKey === "leadId")?.visibleWhen).toEqual({
configKey: "lead",
equals: "manuell",
});
}
});
it("configures the executable chat action", () => {
expect(configKeys("chat.post_message")).toEqual(["chatId", "nachricht"]);
});
it("exposes the executable parallel split and merge blocks without fake config", () => {
expect(configKeys("flow.parallel")).toEqual([]);
expect(configKeys("flow.merge")).toEqual([]);
});
});
function configKeys(nodeType: string): string[] {
return (NODE_CONFIG_DESCRIPTORS[nodeType]?.fields ?? []).map((field) => field.configKey);
}