Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

refactor(frontend): migrate custom approval page from Vue to React (#19820)

Danny Xu9cc679f02b21
diff --git a/frontend/package.json b/frontend/package.json
index f917551efe..6af4c385cb 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -34,6 +34,9 @@
"@codingame/monaco-vscode-theme-service-override": "26.2.1",
"@connectrpc/connect": "^2.1.1",
"@connectrpc/connect-web": "^2.1.1",
+ "@dnd-kit/core": "^6.3.1",
+ "@dnd-kit/sortable": "^10.0.0",
+ "@dnd-kit/utilities": "^3.2.2",
"@markdoc/markdoc": "0.5.5",
"@vueuse/core": "14.2.1",
"bootstrap": "5.3.8",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index e5c736b29a..5addd8b458 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -51,6 +51,15 @@ importers:
'@connectrpc/connect-web':
specifier: ^2.1.1
version: 2.1.1(@bufbuild/[email protected])(@connectrpc/[email protected](@bufbuild/[email protected]))
+ '@dnd-kit/core':
+ specifier: ^6.3.1
+ '@dnd-kit/sortable':
+ specifier: ^10.0.0
+ '@dnd-kit/utilities':
+ specifier: ^3.2.2
+ version: 3.2.2([email protected])
'@markdoc/markdoc':
specifier: 0.5.5
version: 0.5.5(@types/[email protected])([email protected])
@@ -1281,6 +1290,28 @@ packages:
resolution: {integrity: sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==}
engines: {node: '>=18'}
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==}
+ peerDependencies:
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==}
+ peerDependencies:
+ react: '>=16.8.0'
+ react-dom: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==}
+ peerDependencies:
+ '@dnd-kit/core': ^6.3.0
+ react: '>=16.8.0'
+
+ '@dnd-kit/[email protected]':
+ resolution: {integrity: sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==}
+ peerDependencies:
+ react: '>=16.8.0'
+
'@emotion/[email protected]':
resolution: {integrity: sha512-kBJtf7PH6aWwZ6fka3zQ0p6SBYzx4fl1LoZXE2RrnYST9Xljm7WfKJrU4g/Xr3Beg72MLrp1AWNUmuYJTL7Cow==}
@@ -6206,6 +6237,31 @@ snapshots:
'@csstools/[email protected]': {}
+ dependencies:
+ react: 19.2.4
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/accessibility': 3.1.1([email protected])
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.4
+ react-dom: 19.2.4([email protected])
+ tslib: 2.8.1
+
+ dependencies:
+ '@dnd-kit/utilities': 3.2.2([email protected])
+ react: 19.2.4
+ tslib: 2.8.1
+
+ dependencies:
+ react: 19.2.4
+ tslib: 2.8.1
+
'@emotion/[email protected]': {}
'@esbuild/[email protected]':
diff --git a/frontend/scripts/check-react-i18n.mjs b/frontend/scripts/check-react-i18n.mjs
index b27fb8bbda..a53bb12b16 100644
--- a/frontend/scripts/check-react-i18n.mjs
+++ b/frontend/scripts/check-react-i18n.mjs
@@ -74,10 +74,13 @@ function isDynamic(key) {
}
// ---------------------------------------------------------------------------
-// Collect translation keys from React source (.tsx) files
+// Collect translation keys from React source (.tsx and .ts) files
// ---------------------------------------------------------------------------
function collectSourceKeys() {
- const files = findFiles(REACT_DIR, ".tsx");
+ const files = [
+ ...findFiles(REACT_DIR, ".tsx"),
+ ...findFiles(REACT_DIR, ".ts"),
+ ];
const keys = new Set();
// Only match single/double quoted strings — template literals with ${} are dynamic keys
const re = /\bt\(\s*["']([^"']+)["']/g;
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/CustomApproval.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/CustomApproval.vue
deleted file mode 100644
index 29dbb50203..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/CustomApproval.vue
+++ /dev/null
@@ -1,24 +0,0 @@
-<template>
- <div class="w-full flex flex-col gap-y-6">
- <RulesSection
- v-for="source in supportedSourceList"
- :key="source"
- :source="source"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import { computed } from "vue";
-import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
-import RulesSection from "./RulesPanel/RulesSection.vue";
-
-const supportedSourceList = computed(() => [
- WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE,
- WorkspaceApprovalSetting_Rule_Source.CREATE_DATABASE,
- WorkspaceApprovalSetting_Rule_Source.EXPORT_DATA,
- WorkspaceApprovalSetting_Rule_Source.REQUEST_ROLE,
- WorkspaceApprovalSetting_Rule_Source.REQUEST_ACCESS,
- WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED,
-]);
-</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
deleted file mode 100644
index 0a59a5789d..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RuleEditModal.vue
+++ /dev/null
@@ -1,312 +0,0 @@
-<template>
- <NModal
- :show="show"
- :mask-closable="true"
- :close-on-esc="true"
- @update:show="$emit('update:show', $event)"
- >
- <div
- class="w-[calc(100vw-8rem)] lg:max-w-[75vw] 2xl:max-w-[55vw] max-h-[calc(100vh-10rem)] bg-white rounded-lg shadow-lg flex flex-col overflow-hidden"
- >
- <div class="px-6 py-4 border-b flex items-center justify-between">
- <h2 class="text-lg font-medium text-control">
- {{
- mode === "create"
- ? $t("custom-approval.approval-flow.create-approval-flow")
- : $t("custom-approval.approval-flow.edit-rule")
- }}
- </h2>
- </div>
-
- <div class="flex-1 flex flex-col px-6 py-4 gap-y-4 overflow-y-auto">
- <div
- v-if="isFallback"
- class="text-sm text-amber-600 bg-amber-50 p-3 rounded"
- >
- {{ $t("custom-approval.approval-flow.fallback-rules-hint") }}
- </div>
-
- <div v-if="mode === 'create'" class="flex flex-col gap-y-2">
- <h3 class="font-medium text-sm text-control">
- {{ $t("custom-approval.approval-flow.template.presets-title") }}
- </h3>
- <div class="flex flex-wrap gap-2">
- <NTooltip
- v-for="(template, index) in templates"
- :key="index"
- to="body"
- :disabled="!template.description()"
- >
- <template #trigger>
- <NButton
- size="small"
- :disabled="!allowAdmin"
- @click="applyTemplate(template)"
- >
- {{ template.title() }}
- </NButton>
- </template>
- {{ template.description() }}
- </NTooltip>
- </div>
- </div>
-
- <div class="flex flex-col gap-y-2">
- <h3 class="font-medium text-sm text-control">
- {{ $t("common.title") }} <RequiredStar />
- </h3>
- <NInput
- v-model:value="state.title"
- :placeholder="$t('common.title')"
- :disabled="!allowAdmin"
- />
- </div>
-
- <div class="flex flex-col gap-y-2">
- <h3 class="font-medium text-sm text-control">
- {{ $t("common.description") }}
- </h3>
- <NInput
- v-model:value="state.description"
- type="textarea"
- :placeholder="$t('common.description')"
- :disabled="!allowAdmin"
- :rows="2"
- />
- </div>
-
- <div class="flex-1 flex flex-col gap-y-2">
- <h3 class="font-medium text-sm text-control">
- {{ $t("cel.condition.self") }} <RequiredStar />
- </h3>
- <div class="text-sm text-control-light">
- {{ $t("cel.condition.description-tips") }}
- </div>
- <ExprEditor
- :expr="state.conditionExpr"
- :readonly="!allowAdmin"
- :factor-list="factorList"
- :option-config-map="optionConfigMap"
- @update="handleUpdate"
- />
- </div>
-
- <div class="flex flex-col gap-y-2">
- <div class="flex items-center justify-between">
- <h3 class="font-medium text-sm text-control">
- {{ $t("custom-approval.approval-flow.node.nodes") }}
- <RequiredStar v-if="!state.noApprovalRequired" />
- </h3>
- <div class="flex items-center gap-x-2">
- <NSwitch
- v-model:value="state.noApprovalRequired"
- :disabled="!allowAdmin"
- size="small"
- @update:value="handleNoApprovalRequiredChange"
- />
- <span class="text-sm text-control-light">
- {{ $t("custom-approval.approval-flow.skip") }}
- </span>
- </div>
- </div>
- <template v-if="!state.noApprovalRequired">
- <div class="text-sm text-control-light">
- {{ $t("custom-approval.approval-flow.node.description") }}
- </div>
- <StepsTable
- :flow="state.flow"
- :editable="allowAdmin"
- @update="handleUpdate"
- />
- </template>
- </div>
- </div>
-
- <footer
- class="flex items-center justify-end gap-x-2 px-6 py-4 border-t"
- >
- <NButton @click="$emit('update:show', false)">
- {{ $t("common.cancel") }}
- </NButton>
- <NButton
- type="primary"
- :disabled="!allowSave || !allowAdmin"
- @click="handleSave"
- >
- {{ mode === "create" ? $t("common.create") : $t("common.update") }}
- </NButton>
- </footer>
- </div>
- </NModal>
-</template>
-
-<script lang="ts" setup>
-import { create as createProto } from "@bufbuild/protobuf";
-import { cloneDeep, head } from "lodash-es";
-import { NButton, NInput, NModal, NSwitch, NTooltip } from "naive-ui";
-import { computed, reactive, watch } from "vue";
-import ExprEditor from "@/components/ExprEditor";
-import RequiredStar from "@/components/RequiredStar.vue";
-import type { ConditionGroupExpr } from "@/plugins/cel";
-import {
- buildCELExpr,
- emptySimpleExpr,
- resolveCELExpr,
- validateSimpleExpr,
- wrapAsGroup,
-} from "@/plugins/cel";
-import type { LocalApprovalRule } from "@/types";
-import type { ApprovalFlow } from "@/types/proto-es/v1/issue_service_pb";
-import { ApprovalFlowSchema } from "@/types/proto-es/v1/issue_service_pb";
-import type { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
-import {
- batchConvertCELStringToParsedExpr,
- batchConvertParsedExprToCELString,
-} from "@/utils";
-import {
- getApprovalFactorList,
- getApprovalOptionConfigMap,
-} from "../../common/utils";
-import { StepsTable } from "../common";
-import { useCustomApprovalContext } from "../context";
-import {
- type ApprovalRuleTemplate,
- applyTemplateToState,
- filterTemplatesBySource,
- useApprovalRuleTemplates,
-} from "./template";
-
-type LocalState = {
- title: string;
- description: string;
- conditionExpr: ConditionGroupExpr;
- flow: ApprovalFlow;
- noApprovalRequired: boolean;
-};
-
-const props = defineProps<{
- show: boolean;
- mode: "create" | "edit";
- source: WorkspaceApprovalSetting_Rule_Source;
- rule?: LocalApprovalRule;
- isFallback?: boolean;
-}>();
-
-const emit = defineEmits<{
- (event: "update:show", show: boolean): void;
- (event: "save", rule: Partial<LocalApprovalRule>): void;
-}>();
-
-const context = useCustomApprovalContext();
-const { allowAdmin } = context;
-const allTemplates = useApprovalRuleTemplates();
-const templates = computed(() =>
- filterTemplatesBySource(allTemplates.value, props.source)
-);
-
-const state = reactive<LocalState>({
- title: "",
- description: "",
- conditionExpr: wrapAsGroup(emptySimpleExpr()),
- flow: createProto(ApprovalFlowSchema, { roles: [] }),
- noApprovalRequired: false,
-});
-
-const factorList = computed(() => getApprovalFactorList(props.source));
-const optionConfigMap = computed(() =>
- getApprovalOptionConfigMap(props.source)
-);
-
-const allowSave = computed(() => {
- if (!state.title.trim()) return false;
- if (!state.conditionExpr) return false;
- if (!validateSimpleExpr(state.conditionExpr)) return false;
- if (!state.noApprovalRequired && state.flow.roles.length === 0) return false;
- return true;
-});
-
-const resolveLocalState = async () => {
- // Reset to empty state immediately to unmount old Condition components.
- // This prevents component reuse issues when switching between rules,
- // where the ValueInput watch would reset values when factor/operator changes.
- state.title = "";
- state.description = "";
- state.conditionExpr = wrapAsGroup(emptySimpleExpr());
- state.flow = createProto(ApprovalFlowSchema, { roles: [] });
- state.noApprovalRequired = false;
-
- if (props.rule) {
- state.title = props.rule.title || "";
- state.description = props.rule.description || "";
- if (props.rule.condition) {
- const parsedExprs = await batchConvertCELStringToParsedExpr([
- props.rule.condition,
- ]);
- const celExpr = head(parsedExprs);
- if (celExpr) {
- state.conditionExpr = wrapAsGroup(resolveCELExpr(celExpr));
- }
- }
- state.flow = cloneDeep(props.rule.flow);
- state.noApprovalRequired = props.rule.flow.roles.length === 0;
- }
-};
-
-const handleUpdate = () => {
- // Trigger reactivity
-};
-
-const handleNoApprovalRequiredChange = (value: boolean) => {
- if (value) {
- // Clear roles when "no approval required" is enabled
- state.flow.roles = [];
- }
-};
-
-const applyTemplate = (template: ApprovalRuleTemplate) => {
- const applied = applyTemplateToState(template);
- state.title = applied.title;
- state.conditionExpr = applied.conditionExpr;
- state.flow = applied.flow;
-};
-
-const handleSave = async () => {
- if (!context.hasFeature.value) {
- context.showFeatureModal.value = true;
- return;
- }
-
- const celexpr = await buildCELExpr(state.conditionExpr);
- if (!celexpr) {
- return;
- }
-
- const expressions = await batchConvertParsedExprToCELString([celexpr]);
- const condition = expressions[0];
-
- const ruleData: Partial<LocalApprovalRule> = {
- title: state.title,
- description: state.description,
- condition,
- conditionExpr: cloneDeep(state.conditionExpr),
- flow: cloneDeep(state.flow),
- source: props.source,
- };
-
- if (props.rule) {
- ruleData.uid = props.rule.uid;
- }
-
- emit("save", ruleData);
-};
-
-watch(
- () => props.show,
- (newShow) => {
- if (newShow) {
- resolveLocalState();
- }
- },
- { immediate: true }
-);
-</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue
deleted file mode 100644
index 52bd65ba78..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/RulesSection.vue
+++ /dev/null
@@ -1,252 +0,0 @@
-<template>
- <div class="flex flex-col gap-y-2">
- <div class="flex items-center justify-between">
- <div class="font-medium text-base">
- {{ sourceDisplayText }}
- </div>
- <PermissionGuardWrapper
- v-slot="slotProps"
- :permissions="['bb.settings.set']"
- >
- <NButton size="small" :disabled="slotProps.disabled" @click="handleAddRule">
- <template #icon>
- <PlusIcon class="w-4" />
- </template>
- {{ $t("custom-approval.approval-flow.add-rule") }}
- </NButton>
- </PermissionGuardWrapper>
- </div>
-
- <div class="rules-table border border-gray-200 rounded-sm text-sm">
- <!-- Table Header -->
- <div
- class="rules-table-header grid bg-gray-50 border-b border-gray-200 font-medium text-gray-600"
- >
- <div class="px-2 py-2 w-10"></div>
- <div class="px-3 py-2">{{ $t("common.title") }}</div>
- <div class="px-3 py-2">{{ $t("cel.condition.self") }}</div>
- <div class="px-3 py-2">{{ $t("custom-approval.approval-flow.self") }}</div>
- <div class="px-3 py-2 w-24">{{ $t("common.operations") }}</div>
- </div>
-
- <!-- Draggable Body -->
- <VueDraggable
- v-model="localRules"
- handle=".drag-handle"
- :animation="150"
- ghost-class="rules-row-ghost"
- @end="handleDragEnd"
- >
- <div
- v-for="(rule, index) in localRules"
- :key="rule.uid"
- class="rules-table-row grid border-b border-gray-100 last:border-b-0 hover:bg-gray-50"
- :class="{ 'bg-gray-50/50': index % 2 === 1 }"
- >
- <div class="px-2 py-2 w-10 flex items-center justify-center">
- <GripVerticalIcon
- class="drag-handle w-4 h-4 text-gray-400 cursor-grab active:cursor-grabbing"
- />
- </div>
- <div class="px-3 py-2 truncate" :title="rule.title">
- {{ rule.title || "-" }}
- </div>
- <div class="px-3 py-2 truncate">
- <EllipsisText>
- <code class="text-xs">{{ rule.condition || "true" }}</code>
- </EllipsisText>
- </div>
- <div class="px-3 py-2 truncate">
- <EllipsisText>
- {{ formatApprovalFlow(rule.flow) }}
- </EllipsisText>
- </div>
- <div class="px-3 py-2 w-24 flex items-center gap-x-1">
- <MiniActionButton @click="handleEditRule(rule)">
- <PencilIcon class="w-3" />
- </MiniActionButton>
- <NPopconfirm
- v-if="allowAdmin"
- :positive-text="$t('common.confirm')"
- :negative-text="$t('common.cancel')"
- @positive-click="handleDeleteRule(rule)"
- >
- <template #trigger>
- <MiniActionButton>
- <TrashIcon class="w-3" />
- </MiniActionButton>
- </template>
- {{ $t("common.confirm") }}?
- </NPopconfirm>
- </div>
- </div>
- </VueDraggable>
-
- <!-- Empty State -->
- <div
- v-if="localRules.length === 0"
- class="px-3 py-4 text-center text-gray-400"
- >
- {{ $t("common.no-data") }}
- </div>
- </div>
-
- <RuleEditModal
- v-model:show="showModal"
- :mode="modalMode"
- :source="source"
- :rule="editingRule"
- :is-fallback="isFallback"
- @save="handleSaveRule"
- />
- </div>
-</template>
-
-<script lang="ts" setup>
-import {
- GripVerticalIcon,
- PencilIcon,
- PlusIcon,
- TrashIcon,
-} from "lucide-vue-next";
-import { NButton, NPopconfirm } from "naive-ui";
-import { computed, ref, watch } from "vue";
-import { VueDraggable } from "vue-draggable-plus";
-import { useI18n } from "vue-i18n";
-import EllipsisText from "@/components/EllipsisText.vue";
-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";
-import { MiniActionButton } from "@/components/v2";
-import { pushNotification, useWorkspaceApprovalSettingStore } from "@/store";
-import type { LocalApprovalRule } from "@/types";
-import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
-import { formatApprovalFlow } from "@/utils";
-import { approvalSourceText } from "../../common/utils";
-import { useCustomApprovalContext } from "../context";
-import RuleEditModal from "./RuleEditModal.vue";
-
-const props = defineProps<{
- source: WorkspaceApprovalSetting_Rule_Source;
-}>();
-
-const isFallback = computed(
- () => props.source === WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED
-);
-
-const { t } = useI18n();
-const store = useWorkspaceApprovalSettingStore();
-const context = useCustomApprovalContext();
-const { allowAdmin } = context;
-
-const showModal = ref(false);
-const modalMode = ref<"create" | "edit">("create");
-const editingRule = ref<LocalApprovalRule | undefined>();
-
-const rules = computed(() => store.getRulesBySource(props.source));
-
-// Local copy for dragging - synced with store
-const localRules = ref<LocalApprovalRule[]>([]);
-
-watch(
- rules,
- (newRules) => {
- localRules.value = [...newRules];
- },
- { immediate: true }
-);
-
-const sourceDisplayText = computed(() => approvalSourceText(props.source));
-
-const handleDragEnd = async (event: {
- oldIndex?: number;
- newIndex?: number;
-}) => {
- const { oldIndex, newIndex } = event;
- if (oldIndex == null || newIndex == null || oldIndex === newIndex) return;
-
- if (!context.hasFeature.value) {
- context.showFeatureModal.value = true;
- // Revert local change
- localRules.value = [...rules.value];
- return;
- }
-
- try {
- await store.reorderRules(props.source, oldIndex, newIndex);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } catch {
- // Revert local change on error
- localRules.value = [...rules.value];
- }
-};
-
-const handleAddRule = () => {
- if (!context.hasFeature.value) {
- context.showFeatureModal.value = true;
- return;
- }
- modalMode.value = "create";
- editingRule.value = undefined;
- showModal.value = true;
-};
-
-const handleEditRule = (rule: LocalApprovalRule) => {
- if (!context.hasFeature.value) {
- context.showFeatureModal.value = true;
- return;
- }
- modalMode.value = "edit";
- editingRule.value = rule;
- showModal.value = true;
-};
-
-const handleDeleteRule = async (rule: LocalApprovalRule) => {
- if (!context.hasFeature.value) {
- context.showFeatureModal.value = true;
- return;
- }
- try {
- await store.deleteRule(rule.uid);
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.deleted"),
- });
- } catch {
- // Error handled by store
- }
-};
-
-const handleSaveRule = async (ruleData: Partial<LocalApprovalRule>) => {
- try {
- if (modalMode.value === "create") {
- await store.addRule(ruleData as Omit<LocalApprovalRule, "uid">);
- } else if (editingRule.value && ruleData.uid) {
- await store.updateRule(ruleData.uid, ruleData);
- }
- showModal.value = false;
- pushNotification({
- module: "bytebase",
- style: "SUCCESS",
- title: t("common.updated"),
- });
- } catch {
- // Error handled by store
- }
-};
-</script>
-
-<style scoped>
-.rules-table-header,
-.rules-table-row {
- grid-template-columns: 40px 200px 1fr 280px 96px;
-}
-
-.rules-row-ghost {
- opacity: 0.5;
- background: #e0f2fe;
-}
-</style>
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/template.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/template.ts
deleted file mode 100644
index 7f8c7baef8..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/template.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { create } from "@bufbuild/protobuf";
-import { computed } from "vue";
-import type { ConditionGroupExpr } from "@/plugins/cel";
-import { ExprType, wrapAsGroup } from "@/plugins/cel";
-import { t } from "@/plugins/i18n";
-import { PresetRoleType } from "@/types";
-import { ApprovalFlowSchema } from "@/types/proto-es/v1/issue_service_pb";
-import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
-import {
- CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS,
- CEL_ATTRIBUTE_STATEMENT_SQL_TYPE,
-} from "@/utils/cel-attributes";
-
-export type ApprovalRuleTemplate = {
- title: () => string;
- description: () => string;
- expr: ConditionGroupExpr;
- roles: string[];
- // If undefined, the template applies to all sources.
- // If specified, the template only applies to the listed sources.
- sources?: WorkspaceApprovalSetting_Rule_Source[];
-};
-
-export const useApprovalRuleTemplates = () => {
- const templates = computed((): ApprovalRuleTemplate[] => {
- return [
- {
- title: () =>
- t("custom-approval.approval-flow.template.presets.drop-or-truncate"),
- description: () =>
- t(
- "custom-approval.approval-flow.template.preset-descriptions.drop-or-truncate"
- ),
- // statement.sql_type in ["DROP_TABLE", "TRUNCATE"]
- expr: wrapAsGroup({
- type: ExprType.Condition,
- operator: "@in",
- args: [CEL_ATTRIBUTE_STATEMENT_SQL_TYPE, ["DROP_TABLE", "TRUNCATE"]],
- }),
- roles: [PresetRoleType.PROJECT_OWNER, PresetRoleType.WORKSPACE_DBA],
- sources: [WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE],
- },
- {
- title: () =>
- t(
- "custom-approval.approval-flow.template.presets.high-affected-rows"
- ),
- description: () =>
- t(
- "custom-approval.approval-flow.template.preset-descriptions.high-affected-rows"
- ),
- // statement.affected_rows > 100
- expr: wrapAsGroup({
- type: ExprType.Condition,
- operator: "_>_",
- args: [CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS, 100],
- }),
- roles: [PresetRoleType.PROJECT_OWNER, PresetRoleType.WORKSPACE_DBA],
- sources: [WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE],
- },
- {
- title: () =>
- t("custom-approval.approval-flow.template.presets.fallback"),
- description: () =>
- t(
- "custom-approval.approval-flow.template.preset-descriptions.fallback"
- ),
- // The condition "true" matches all requests not matched by other rules.
- expr: wrapAsGroup({
- type: ExprType.RawString,
- content: "true",
- }),
- roles: [PresetRoleType.PROJECT_OWNER],
- // No sources specified - applies to all sources
- },
- ];
- });
-
- return templates;
-};
-
-export const filterTemplatesBySource = (
- templates: ApprovalRuleTemplate[],
- source: WorkspaceApprovalSetting_Rule_Source
-): ApprovalRuleTemplate[] => {
- return templates.filter((template) => {
- // If no sources specified, the template applies to all sources
- if (!template.sources) {
- return true;
- }
- return template.sources.includes(source);
- });
-};
-
-export const applyTemplateToState = (
- template: ApprovalRuleTemplate
-): {
- title: string;
- conditionExpr: ConditionGroupExpr;
- flow: ReturnType<typeof create<typeof ApprovalFlowSchema>>;
-} => {
- return {
- title: template.title(),
- conditionExpr: template.expr,
- flow: create(ApprovalFlowSchema, { roles: [...template.roles] }),
- };
-};
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/types.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/types.ts
deleted file mode 100644
index a980d85b10..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/RulesPanel/types.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import type { Expr } from "@/types/proto-es/google/api/expr/v1alpha1/syntax_pb";
-import type {
- WorkspaceApprovalSetting_Rule as ApprovalRule,
- WorkspaceApprovalSetting_Rule_Source,
-} from "@/types/proto-es/v1/setting_service_pb";
-
-export type ParsedApprovalRule = {
- source: WorkspaceApprovalSetting_Rule_Source;
- level: number;
- rule: ApprovalRule;
-};
-
-export type UnrecognizedApprovalRule = {
- expr?: Expr;
- rule: ApprovalRule;
-};
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/StepsTable.vue b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/StepsTable.vue
deleted file mode 100644
index 74eaf0a379..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/StepsTable.vue
+++ /dev/null
@@ -1,156 +0,0 @@
-<template>
- <div>
- <NDataTable
- size="small"
- :columns="columns"
- :data="steps"
- :striped="true"
- :bordered="true"
- />
- <div v-if="editable && allowAdmin" class="mt-4">
- <NButton @click="addStep">
- <template #icon>
- <PlusIcon class="w-4" />
- </template>
- <span>
- {{ $t("custom-approval.approval-flow.node.add") }}
- </span>
- </NButton>
- </div>
- </div>
-</template>
-
-<script lang="ts" setup>
-/* eslint-disable vue/no-mutating-props */
-import {
- ArrowDownIcon,
- ArrowUpIcon,
- PlusIcon,
- TrashIcon,
-} from "lucide-vue-next";
-import type { DataTableColumn } from "naive-ui";
-import { NButton, NDataTable } from "naive-ui";
-import { computed, h } from "vue";
-import { useI18n } from "vue-i18n";
-import { RoleSelect } from "@/components/v2";
-import { SpinnerButton } from "@/components/v2/Form";
-import { PresetRoleType } from "@/types";
-import type { ApprovalFlow } from "@/types/proto-es/v1/issue_service_pb";
-import { displayRoleTitle } from "@/utils";
-import { useCustomApprovalContext } from "../context";
-
-const props = defineProps<{
- flow: ApprovalFlow;
- editable: boolean;
-}>();
-
-const emit = defineEmits<{
- (event: "update"): void;
-}>();
-
-const { t } = useI18n();
-
-const context = useCustomApprovalContext();
-const { allowAdmin } = context;
-
-const columns = computed(
- (): DataTableColumn<{ role: string; index: number }>[] => {
- const cols: DataTableColumn<{ role: string; index: number }>[] = [
- {
- title: t("custom-approval.approval-flow.node.order"),
- key: "order",
- width: 80,
- align: "center",
- render: (_, index) => index + 1,
- },
- {
- title: t("custom-approval.approval-flow.node.approver"),
- key: "approver",
- minWidth: 200,
- resizable: true,
- render: (stepData) => {
- if (props.editable) {
- return h(RoleSelect, {
- suffix: "",
- placement: "top-start",
- value: stepData.role,
- style: "width: 80%",
- "onUpdate:value": (val: string | string[]) => {
- const role = Array.isArray(val) ? val[0] : val;
- props.flow.roles[stepData.index] = role;
- emit("update");
- },
- });
- }
- return displayRoleTitle(stepData.role);
- },
- },
- ];
-
- if (props.editable) {
- cols.push({
- title: t("common.operations"),
- key: "operations",
- render: (stepData, index) =>
- h("div", { class: "flex gap-x-1" }, [
- h(
- NButton,
- {
- disabled: index === 0 || !allowAdmin.value,
- size: "tiny",
- onClick: () => reorder(stepData, -1),
- },
- () => h(ArrowUpIcon, { class: "w-4" })
- ),
- h(
- NButton,
- {
- disabled: index === steps.value.length - 1 || !allowAdmin.value,
- size: "tiny",
- onClick: () => reorder(stepData, 1),
- },
- () => h(ArrowDownIcon, { class: "w-4" })
- ),
- allowAdmin.value
- ? h(
- SpinnerButton,
- {
- size: "tiny",
- tooltip: t("custom-approval.approval-flow.node.delete"),
- onConfirm: () => removeStep(stepData),
- },
- () => h(TrashIcon, { class: "w-3" })
- )
- : null,
- ]),
- });
- }
-
- return cols;
- }
-);
-
-const steps = computed(() => {
- return props.flow.roles.map((role, index) => ({ role, index }));
-});
-
-const reorder = (stepData: { role: string; index: number }, offset: -1 | 1) => {
- const index = stepData.index;
- const target = index + offset;
- if (target < 0 || target >= props.flow.roles.length) return;
- const tmp = props.flow.roles[index];
- props.flow.roles[index] = props.flow.roles[target];
- props.flow.roles[target] = tmp;
-
- emit("update");
-};
-const addStep = () => {
- props.flow.roles.push(PresetRoleType.WORKSPACE_ADMIN);
- emit("update");
-};
-
-const removeStep = async (stepData: { role: string; index: number }) => {
- props.flow.roles.splice(stepData.index, 1);
- emit("update");
-};
-</script>
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/index.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/index.ts
deleted file mode 100644
index bbd344c975..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/common/index.ts
+++ /dev/null
@@ -1,3 +0,0 @@
-import StepsTable from "./StepsTable.vue";
-
-export { StepsTable };
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/context.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/context.ts
deleted file mode 100644
index 5d4a534e86..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/context.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { type InjectionKey, inject, provide, type Ref } from "vue";
-
-export type CustomApprovalContext = {
- hasFeature: Ref<boolean>;
- showFeatureModal: Ref<boolean>;
- allowAdmin: Ref<boolean>;
- ready: Ref<boolean>;
-};
-
-export const KEY = Symbol(
- "bb.settings.custom-approval"
-) as InjectionKey<CustomApprovalContext>;
-
-export const useCustomApprovalContext = () => {
- return inject(KEY)!;
-};
-
-export const provideCustomApprovalContext = (
- context: CustomApprovalContext
-) => {
- provide(KEY, context);
-};
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/index.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/index.ts
deleted file mode 100644
index ced1598bb0..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/index.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import CustomApproval from "./CustomApproval.vue";
-
-export default CustomApproval;
-export * from "./context";
-export { CustomApproval };
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/index.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/index.ts
deleted file mode 100644
index a22e0ffd5a..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/index.ts
+++ /dev/null
@@ -1,2 +0,0 @@
-export * from "./validate";
-export * from "./utils";
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/utils.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/utils.ts
deleted file mode 100644
index 3028090ff4..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/utils.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { create as createProto } from "@bufbuild/protobuf";
-import { v4 as uuidv4 } from "uuid";
-import type { LocalApprovalRule } from "@/types";
-import { ApprovalFlowSchema } from "@/types/proto-es/v1/issue_service_pb";
-import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
-
-export const emptyLocalApprovalRule = (): LocalApprovalRule => {
- return {
- uid: uuidv4(),
- source: WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED,
- title: "",
- description: "",
- condition: "",
- flow: createProto(ApprovalFlowSchema, { roles: [] }),
- };
-};
diff --git a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/validate.ts b/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/validate.ts
deleted file mode 100644
index 548d4213b5..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/CustomApproval/logic/validate.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import type {
- ApprovalFlow,
- ApprovalTemplate,
-} from "@/types/proto-es/v1/issue_service_pb";
-
-const validateApprovalFlow = (flow: ApprovalFlow) => {
- // Empty roles means "no approval required" - issue will be auto-approved
- return flow.roles.every((role) => !!role);
-};
-
-export const validateApprovalTemplate = (
- template: Omit<ApprovalTemplate, "creator">
-) => {
- const { title = "", description = "", flow } = template;
- if (title.trim().length === 0) return false;
- if (description.trim().length === 0) return false;
- if (!flow) return false;
- return validateApprovalFlow(flow);
-};
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/index.ts b/frontend/src/components/CustomApproval/Settings/components/common/index.ts
deleted file mode 100644
index 178cd64f81..0000000000
--- a/frontend/src/components/CustomApproval/Settings/components/common/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./utils";
diff --git a/frontend/src/react/components/CustomApproval/ApprovalStepsTable.tsx b/frontend/src/react/components/CustomApproval/ApprovalStepsTable.tsx
new file mode 100644
index 0000000000..ab65aa3a05
--- /dev/null
+++ b/frontend/src/react/components/CustomApproval/ApprovalStepsTable.tsx
@@ -0,0 +1,127 @@
+import { ArrowDown, ArrowUp, Plus, Trash2 } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { PresetRoleType } from "@/types";
+import { displayRoleTitle } from "@/utils";
+import { Button } from "../ui/button";
+import { RoleSelect } from "./RoleSelect";
+
+interface ApprovalStepsTableProps {
+ roles: string[];
+ editable: boolean;
+ allowAdmin: boolean;
+ onRolesChange: (roles: string[]) => void;
+}
+
+export function ApprovalStepsTable({
+ roles,
+ editable,
+ allowAdmin,
+ onRolesChange,
+}: ApprovalStepsTableProps) {
+ const { t } = useTranslation();
+
+ const reorder = (index: number, offset: -1 | 1) => {
+ const target = index + offset;
+ if (target < 0 || target >= roles.length) return;
+ const newRoles = [...roles];
+ newRoles[index] = roles[target];
+ newRoles[target] = roles[index];
+ onRolesChange(newRoles);
+ };
+
+ const addStep = () => {
+ onRolesChange([...roles, PresetRoleType.WORKSPACE_ADMIN]);
+ };
+
+ const removeStep = (index: number) => {
+ onRolesChange(roles.filter((_, i) => i !== index));
+ };
+
+ return (
+ <div>
+ <table className="w-full border-collapse border border-control-border text-sm">
+ <thead>
+ <tr className="bg-control-bg">
+ <th className="w-20 border border-control-border px-3 py-2 text-center font-medium text-control">
+ {t("custom-approval.approval-flow.node.order")}
+ </th>
+ <th className="border border-control-border px-3 py-2 text-left font-medium text-control">
+ {t("custom-approval.approval-flow.node.approver")}
+ </th>
+ {editable && (
+ <th className="border border-control-border px-3 py-2 text-left font-medium text-control">
+ {t("common.operations")}
+ </th>
+ )}
+ </tr>
+ </thead>
+ <tbody>
+ {roles.map((role, index) => (
+ <tr
+ key={index}
+ className={index % 2 === 1 ? "bg-control-bg/50" : "bg-white"}
+ >
+ <td className="border border-control-border px-3 py-2 text-center text-control">
+ {index + 1}
+ </td>
+ <td className="border border-control-border px-3 py-2">
+ {editable ? (
+ <RoleSelect
+ value={role}
+ onChange={(val) => {
+ const newRoles = [...roles];
+ newRoles[index] = val;
+ onRolesChange(newRoles);
+ }}
+ />
+ ) : (
+ <span className="text-control">{displayRoleTitle(role)}</span>
+ )}
+ </td>
+ {editable && (
+ <td className="border border-control-border px-3 py-2">
+ <div className="flex gap-x-1">
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={index === 0 || !allowAdmin}
+ onClick={() => reorder(index, -1)}
+ >
+ <ArrowUp className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={index === roles.length - 1 || !allowAdmin}
+ onClick={() => reorder(index, 1)}
+ >
+ <ArrowDown className="h-4 w-4" />
+ </Button>
+ {allowAdmin && (
+ <Button
+ variant="outline"
+ size="sm"
+ title={t("custom-approval.approval-flow.node.delete")}
+ onClick={() => removeStep(index)}
+ >
+ <Trash2 className="h-3 w-3" />
+ </Button>
+ )}
+ </div>
+ </td>
+ )}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {editable && allowAdmin && (
+ <div className="mt-4">
+ <Button variant="outline" onClick={addStep}>
+ <Plus className="h-4 w-4" />
+ {t("custom-approval.approval-flow.node.add")}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/react/components/CustomApproval/RoleSelect.tsx b/frontend/src/react/components/CustomApproval/RoleSelect.tsx
new file mode 100644
index 0000000000..3dd354af24
--- /dev/null
+++ b/frontend/src/react/components/CustomApproval/RoleSelect.tsx
@@ -0,0 +1,54 @@
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/react/components/ui/select";
+import { useVueState } from "@/react/hooks/useVueState";
+import { useRoleStore } from "@/store";
+import {
+ PRESET_PROJECT_ROLES,
+ PRESET_ROLES,
+ PRESET_WORKSPACE_ROLES,
+} from "@/types/iam";
+import { displayRoleTitle } from "@/utils";
+
+interface RoleSelectProps {
+ value: string;
+ onChange: (value: string) => void;
+ disabled?: boolean;
+}
+
+export function RoleSelect({ value, onChange, disabled }: RoleSelectProps) {
+ const allRoles = useVueState(() => useRoleStore().roleList);
+
+ const customRoles = allRoles
+ .filter((r) => !PRESET_ROLES.includes(r.name))
+ .map((r) => r.name);
+
+ const roles = [
+ ...PRESET_WORKSPACE_ROLES,
+ ...PRESET_PROJECT_ROLES,
+ ...customRoles,
+ ];
+
+ return (
+ <Select
+ value={value}
+ onValueChange={(v) => v !== null && onChange(v)}
+ disabled={disabled}
+ >
+ <SelectTrigger className="w-48">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {roles.map((role) => (
+ <SelectItem key={role} value={role}>
+ {displayRoleTitle(role)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx b/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx
new file mode 100644
index 0000000000..a017ad3c6e
--- /dev/null
+++ b/frontend/src/react/components/CustomApproval/RuleEditDialog.tsx
@@ -0,0 +1,300 @@
+import { create } from "@bufbuild/protobuf";
+import { cloneDeep } from "lodash-es";
+import { useEffect, useMemo, useReducer, useState } from "react";
+import { useTranslation } from "react-i18next";
+import type { ConditionGroupExpr } from "@/plugins/cel";
+import {
+ buildCELExpr,
+ emptySimpleExpr,
+ resolveCELExpr,
+ validateSimpleExpr,
+ wrapAsGroup,
+} from "@/plugins/cel";
+import { ExprEditor } from "@/react/components/ExprEditor";
+import { Button } from "@/react/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from "@/react/components/ui/dialog";
+import { Input } from "@/react/components/ui/input";
+import { Switch } from "@/react/components/ui/switch";
+import { Textarea } from "@/react/components/ui/textarea";
+import type { LocalApprovalRule } from "@/types";
+import { ApprovalFlowSchema } from "@/types/proto-es/v1/issue_service_pb";
+import type { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
+import {
+ batchConvertCELStringToParsedExpr,
+ batchConvertParsedExprToCELString,
+} from "@/utils";
+import { ApprovalStepsTable } from "./ApprovalStepsTable";
+import {
+ type ApprovalRuleTemplate,
+ approvalRuleTemplates,
+ filterTemplatesBySource,
+ getApprovalFactorList,
+ getApprovalOptionConfigMap,
+} from "./utils";
+
+interface RuleEditDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ mode: "create" | "edit";
+ source: WorkspaceApprovalSetting_Rule_Source;
+ rule?: LocalApprovalRule;
+ isFallback?: boolean;
+ allowAdmin: boolean;
+ hasFeature: boolean;
+ onShowFeatureModal: () => void;
+ onSave: (rule: Omit<LocalApprovalRule, "uid"> & { uid?: string }) => void;
+}
+
+export function RuleEditDialog({
+ open,
+ onOpenChange,
+ mode,
+ source,
+ rule,
+ isFallback,
+ allowAdmin,
+ hasFeature,
+ onShowFeatureModal,
+ onSave,
+}: RuleEditDialogProps) {
+ const { t } = useTranslation();
+ const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
+
+ const [title, setTitle] = useState("");
+ const [description, setDescription] = useState("");
+ const [conditionExpr, setConditionExpr] = useState<ConditionGroupExpr>(
+ wrapAsGroup(emptySimpleExpr())
+ );
+ const [flow, setFlow] = useState<{ roles: string[] }>({ roles: [] });
+ const [noApprovalRequired, setNoApprovalRequired] = useState(false);
+
+ const templates = useMemo(
+ () => filterTemplatesBySource(approvalRuleTemplates, source),
+ [source]
+ );
+
+ const factorList = useMemo(() => getApprovalFactorList(source), [source]);
+ const optionConfigMap = useMemo(
+ () => getApprovalOptionConfigMap(source),
+ [source]
+ );
+
+ const allowSave =
+ title.trim() !== "" &&
+ validateSimpleExpr(conditionExpr) === true &&
+ (noApprovalRequired || flow.roles.length > 0);
+
+ // Reset state on every open
+ useEffect(() => {
+ if (!open) return;
+
+ // Reset to empty defaults first
+ setTitle("");
+ setDescription("");
+ setConditionExpr(wrapAsGroup(emptySimpleExpr()));
+ setFlow({ roles: [] });
+ setNoApprovalRequired(false);
+
+ if (mode === "edit" && rule) {
+ setTitle(rule.title || "");
+ setDescription(rule.description || "");
+ if (rule.condition) {
+ batchConvertCELStringToParsedExpr([rule.condition]).then(
+ (parsedExprs) => {
+ const celExpr = parsedExprs[0];
+ if (celExpr) {
+ setConditionExpr(wrapAsGroup(resolveCELExpr(celExpr)));
+ }
+ }
+ );
+ }
+ setFlow(cloneDeep({ roles: [...rule.flow.roles] }));
+ setNoApprovalRequired(rule.flow.roles.length === 0);
+ }
+ }, [open, mode, rule]);
+
+ const applyTemplate = (template: ApprovalRuleTemplate) => {
+ setTitle(template.title());
+ setConditionExpr(cloneDeep(template.expr));
+ setFlow({
+ roles: [...template.roles],
+ });
+ setNoApprovalRequired(false);
+ };
+
+ const handleNoApprovalRequiredChange = (value: boolean) => {
+ setNoApprovalRequired(value);
+ if (value) {
+ setFlow({ roles: [] });
+ }
+ };
+
+ const handleSave = async () => {
+ if (!hasFeature) {
+ onShowFeatureModal();
+ return;
+ }
+
+ const celexpr = await buildCELExpr(conditionExpr);
+ if (!celexpr) {
+ return;
+ }
+
+ const expressions = await batchConvertParsedExprToCELString([celexpr]);
+ const condition = expressions[0];
+
+ const ruleData: Omit<LocalApprovalRule, "uid"> & { uid?: string } = {
+ title,
+ description,
+ condition,
+ conditionExpr: cloneDeep(conditionExpr),
+ flow: create(ApprovalFlowSchema, { roles: [...flow.roles] }),
+ source,
+ };
+
+ if (rule) {
+ ruleData.uid = rule.uid;
+ }
+
+ onSave(ruleData);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="flex flex-col overflow-hidden lg:max-w-[75vw] 2xl:max-w-[55vw]">
+ {/* Header */}
+ <div className="border-b px-6 py-4">
+ <DialogTitle className="text-lg font-medium text-control">
+ {mode === "create"
+ ? t("custom-approval.approval-flow.create-approval-flow")
+ : t("custom-approval.approval-flow.edit-rule")}
+ </DialogTitle>
+ </div>
+
+ {/* Body */}
+ <div className="flex flex-1 flex-col gap-y-4 overflow-y-auto px-6 py-4">
+ {/* Fallback hint */}
+ {isFallback && (
+ <div className="rounded bg-amber-50 p-3 text-sm text-amber-600">
+ {t("custom-approval.approval-flow.fallback-rules-hint")}
+ </div>
+ )}
+
+ {/* Template presets (create mode only) */}
+ {mode === "create" && (
+ <div className="flex flex-col gap-y-2">
+ <h3 className="text-sm font-medium text-control">
+ {t("custom-approval.approval-flow.template.presets-title")}
+ </h3>
+ <div className="flex flex-wrap gap-2">
+ {templates.map((template, index) => (
+ <Button
+ key={index}
+ variant="outline"
+ size="sm"
+ disabled={!allowAdmin}
+ title={template.description()}
+ onClick={() => applyTemplate(template)}
+ >
+ {template.title()}
+ </Button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Title field */}
+ <div className="flex flex-col gap-y-2">
+ <h3 className="text-sm font-medium text-control">
+ {t("common.title")} <span className="text-error">*</span>
+ </h3>
+ <Input
+ value={title}
+ placeholder={t("common.title")}
+ disabled={!allowAdmin}
+ onChange={(e) => setTitle(e.target.value)}
+ />
+ </div>
+
+ {/* Description field */}
+ <div className="flex flex-col gap-y-2">
+ <h3 className="text-sm font-medium text-control">
+ {t("common.description")}
+ </h3>
+ <Textarea
+ value={description}
+ placeholder={t("common.description")}
+ disabled={!allowAdmin}
+ rows={2}
+ onChange={(e) => setDescription(e.target.value)}
+ />
+ </div>
+
+ {/* Condition editor */}
+ <div className="flex flex-1 flex-col gap-y-2">
+ <h3 className="text-sm font-medium text-control">
+ {t("cel.condition.self")} <span className="text-error">*</span>
+ </h3>
+ <div className="text-sm text-control-light">
+ {t("cel.condition.description-tips")}
+ </div>
+ <ExprEditor
+ expr={conditionExpr}
+ readonly={!allowAdmin}
+ factorList={factorList}
+ optionConfigMap={optionConfigMap}
+ onUpdate={forceUpdate}
+ />
+ </div>
+
+ {/* Approval flow section */}
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center justify-between">
+ <h3 className="text-sm font-medium text-control">
+ {t("custom-approval.approval-flow.node.nodes")}
+ {!noApprovalRequired && <span className="text-error"> *</span>}
+ </h3>
+ <div className="flex items-center gap-x-2">
+ <Switch
+ checked={noApprovalRequired}
+ onCheckedChange={handleNoApprovalRequiredChange}
+ disabled={!allowAdmin}
+ />
+ <span className="text-sm text-control-light">
+ {t("custom-approval.approval-flow.skip")}
+ </span>
+ </div>
+ </div>
+ {!noApprovalRequired && (
+ <>
+ <div className="text-sm text-control-light">
+ {t("custom-approval.approval-flow.node.description")}
+ </div>
+ <ApprovalStepsTable
+ roles={flow.roles}
+ editable={allowAdmin}
+ allowAdmin={allowAdmin}
+ onRolesChange={(newRoles) => setFlow({ roles: newRoles })}
+ />
+ </>
+ )}
+ </div>
+ </div>
+
+ {/* Footer */}
+ <footer className="flex items-center justify-end gap-x-2 border-t px-6 py-4">
+ <Button variant="outline" onClick={() => onOpenChange(false)}>
+ {t("common.cancel")}
+ </Button>
+ <Button disabled={!allowSave || !allowAdmin} onClick={handleSave}>
+ {mode === "create" ? t("common.create") : t("common.update")}
+ </Button>
+ </footer>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/react/components/CustomApproval/RulesSection.tsx b/frontend/src/react/components/CustomApproval/RulesSection.tsx
new file mode 100644
index 0000000000..0623497860
--- /dev/null
+++ b/frontend/src/react/components/CustomApproval/RulesSection.tsx
@@ -0,0 +1,378 @@
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ DragOverlay,
+ type DragStartEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from "@dnd-kit/core";
+import {
+ arrayMove,
+ SortableContext,
+ useSortable,
+ verticalListSortingStrategy,
+} from "@dnd-kit/sortable";
+import { CSS } from "@dnd-kit/utilities";
+import { GripVertical, Pencil, Plus, Trash2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
+ PermissionGuard,
+ usePermissionCheck,
+} from "@/react/components/PermissionGuard";
+import { Button } from "@/react/components/ui/button";
+import { pushNotification, useWorkspaceApprovalSettingStore } from "@/store";
+import type { LocalApprovalRule } from "@/types";
+import type { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
+import { WorkspaceApprovalSetting_Rule_Source as RuleSource } from "@/types/proto-es/v1/setting_service_pb";
+import { RuleEditDialog } from "./RuleEditDialog";
+import { approvalSourceText, formatApprovalFlow } from "./utils";
+
+interface RulesSectionProps {
+ source: WorkspaceApprovalSetting_Rule_Source;
+ rules: LocalApprovalRule[];
+ allowAdmin: boolean;
+ hasFeature: boolean;
+ onShowFeatureModal: () => void;
+}
+
+function SortableRow({
+ rule,
+ index,
+ allowAdmin,
+ hasFeature,
+ onEdit,
+ onDelete,
+ onShowFeatureModal,
+}: {
+ rule: LocalApprovalRule;
+ index: number;
+ allowAdmin: boolean;
+ hasFeature: boolean;
+ onEdit: (rule: LocalApprovalRule) => void;
+ onDelete: (rule: LocalApprovalRule) => void;
+ onShowFeatureModal: () => void;
+}) {
+ const { t } = useTranslation();
+ const [confirmingDelete, setConfirmingDelete] = useState(false);
+
+ const {
+ attributes,
+ listeners,
+ setNodeRef,
+ transform,
+ transition,
+ isDragging,
+ } = useSortable({ id: rule.uid });
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition,
+ opacity: isDragging ? 0.5 : undefined,
+ };
+
+ const handleEditClick = () => {
+ if (!hasFeature) {
+ onShowFeatureModal();
+ return;
+ }
+ onEdit(rule);
+ };
+
+ const handleDeleteClick = () => {
+ if (!hasFeature) {
+ onShowFeatureModal();
+ return;
+ }
+ setConfirmingDelete(true);
+ };
+
+ const handleConfirmDelete = () => {
+ setConfirmingDelete(false);
+ onDelete(rule);
+ };
+
+ return (
+ <div
+ ref={setNodeRef}
+ style={style}
+ className={`grid grid-cols-[40px_200px_1fr_280px_96px] border-b border-gray-100 last:border-b-0 hover:bg-gray-50 ${
+ index % 2 === 1 ? "bg-gray-50/50" : ""
+ }`}
+ >
+ <div className="flex items-center justify-center px-2 py-2">
+ <GripVertical
+ className="h-4 w-4 cursor-grab text-gray-400 active:cursor-grabbing"
+ {...attributes}
+ {...listeners}
+ />
+ </div>
+ <div className="truncate px-3 py-2" title={rule.title}>
+ {rule.title || "-"}
+ </div>
+ <div className="overflow-hidden text-ellipsis whitespace-nowrap px-3 py-2">
+ <code className="font-mono text-sm">{rule.condition || "true"}</code>
+ </div>
+ <div
+ className="overflow-hidden text-ellipsis whitespace-nowrap px-3 py-2"
+ title={formatApprovalFlow(rule.flow)}
+ >
+ {formatApprovalFlow(rule.flow)}
+ </div>
+ <div className="flex items-center gap-x-1 px-3 py-2">
+ {confirmingDelete ? (
+ <>
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={handleConfirmDelete}
+ >
+ {t("common.confirm")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => setConfirmingDelete(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ </>
+ ) : (
+ <>
+ <button
+ className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-gray-200"
+ onClick={handleEditClick}
+ >
+ <Pencil className="h-3 w-3" />
+ </button>
+ {allowAdmin && (
+ <button
+ className="inline-flex h-6 w-6 items-center justify-center rounded hover:bg-gray-200"
+ onClick={handleDeleteClick}
+ >
+ <Trash2 className="h-3 w-3" />
+ </button>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ );
+}
+
+function RuleRowOverlay({ rule }: { rule: LocalApprovalRule }) {
+ return (
+ <div className="grid grid-cols-[40px_200px_1fr_280px_96px] border border-gray-200 bg-blue-50 opacity-50">
+ <div className="flex items-center justify-center px-2 py-2">
+ <GripVertical className="h-4 w-4 text-gray-400" />
+ </div>
+ <div className="truncate px-3 py-2">{rule.title || "-"}</div>
+ <div className="overflow-hidden text-ellipsis whitespace-nowrap px-3 py-2">
+ <code className="font-mono text-sm">{rule.condition || "true"}</code>
+ </div>
+ <div className="overflow-hidden text-ellipsis whitespace-nowrap px-3 py-2">
+ {formatApprovalFlow(rule.flow)}
+ </div>
+ <div className="px-3 py-2" />
+ </div>
+ );
+}
+
+export function RulesSection({
+ source,
+ rules,
+ allowAdmin,
+ hasFeature,
+ onShowFeatureModal,
+}: RulesSectionProps) {
+ const { t } = useTranslation();
+ const store = useWorkspaceApprovalSettingStore();
+ const [canEdit] = usePermissionCheck(["bb.settings.set"]);
+
+ const [localRules, setLocalRules] = useState(rules);
+ useEffect(() => setLocalRules(rules), [rules]);
+
+ const [activeId, setActiveId] = useState<string | null>(null);
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [dialogMode, setDialogMode] = useState<"create" | "edit">("create");
+ const [editingRule, setEditingRule] = useState<
+ LocalApprovalRule | undefined
+ >();
+
+ const isFallback = source === RuleSource.SOURCE_UNSPECIFIED;
+
+ const sensors = useSensors(
+ useSensor(PointerSensor),
+ useSensor(KeyboardSensor)
+ );
+
+ const handleAddRule = () => {
+ if (!hasFeature) {
+ onShowFeatureModal();
+ return;
+ }
+ setDialogMode("create");
+ setEditingRule(undefined);
+ setDialogOpen(true);
+ };
+
+ const handleEditRule = (rule: LocalApprovalRule) => {
+ setDialogMode("edit");
+ setEditingRule(rule);
+ setDialogOpen(true);
+ };
+
+ const handleDeleteRule = async (rule: LocalApprovalRule) => {
+ try {
+ await store.deleteRule(rule.uid);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.deleted"),
+ });
+ } catch {
+ // Error handled by store
+ }
+ };
+
+ const handleDragStart = (event: DragStartEvent) => {
+ setActiveId(event.active.id as string);
+ };
+
+ const handleDragEnd = async (event: DragEndEvent) => {
+ const { active, over } = event;
+ setActiveId(null);
+
+ if (!over || active.id === over.id) return;
+
+ const oldIndex = localRules.findIndex((r) => r.uid === active.id);
+ const newIndex = localRules.findIndex((r) => r.uid === over.id);
+
+ if (oldIndex === newIndex) return;
+
+ if (!hasFeature) {
+ onShowFeatureModal();
+ return;
+ }
+
+ // Optimistic local reorder
+ setLocalRules(arrayMove(localRules, oldIndex, newIndex));
+
+ try {
+ await store.reorderRules(source, oldIndex, newIndex);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ // Revert on error
+ setLocalRules([...rules]);
+ }
+ };
+
+ const handleSaveRule = async (
+ ruleData: Omit<LocalApprovalRule, "uid"> & { uid?: string }
+ ) => {
+ try {
+ if (dialogMode === "create") {
+ await store.addRule(ruleData as Omit<LocalApprovalRule, "uid">);
+ } else if (editingRule && ruleData.uid) {
+ await store.updateRule(ruleData.uid, ruleData);
+ }
+ setDialogOpen(false);
+ pushNotification({
+ module: "bytebase",
+ style: "SUCCESS",
+ title: t("common.updated"),
+ });
+ } catch {
+ // Error handled by store
+ }
+ };
+
+ const activeRule = activeId
+ ? localRules.find((r) => r.uid === activeId)
+ : undefined;
+
+ return (
+ <div className="flex flex-col gap-y-2">
+ <div className="flex items-center justify-between">
+ <div className="text-base font-medium">
+ {approvalSourceText(source)}
+ </div>
+ <PermissionGuard permissions={["bb.settings.set"]}>
+ <Button size="sm" disabled={!canEdit} onClick={handleAddRule}>
+ <Plus className="h-4 w-4" />
+ {t("custom-approval.approval-flow.add-rule")}
+ </Button>
+ </PermissionGuard>
+ </div>
+
+ <div className="rounded-sm border border-gray-200 text-sm">
+ {/* Table Header */}
+ <div className="grid grid-cols-[40px_200px_1fr_280px_96px] border-b border-gray-200 bg-gray-50 font-medium text-gray-600">
+ <div className="w-10 px-2 py-2" />
+ <div className="px-3 py-2">{t("common.title")}</div>
+ <div className="px-3 py-2">{t("cel.condition.self")}</div>
+ <div className="px-3 py-2">
+ {t("custom-approval.approval-flow.self")}
+ </div>
+ <div className="w-24 px-3 py-2">{t("common.operations")}</div>
+ </div>
+
+ {/* Draggable Body */}
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragStart={handleDragStart}
+ onDragEnd={handleDragEnd}
+ >
+ <SortableContext
+ items={localRules.map((r) => r.uid)}
+ strategy={verticalListSortingStrategy}
+ >
+ {localRules.map((rule, index) => (
+ <SortableRow
+ key={rule.uid}
+ rule={rule}
+ index={index}
+ allowAdmin={allowAdmin}
+ hasFeature={hasFeature}
+ onEdit={handleEditRule}
+ onDelete={handleDeleteRule}
+ onShowFeatureModal={onShowFeatureModal}
+ />
+ ))}
+ </SortableContext>
+ <DragOverlay>
+ {activeRule ? <RuleRowOverlay rule={activeRule} /> : null}
+ </DragOverlay>
+ </DndContext>
+
+ {/* Empty State */}
+ {localRules.length === 0 && (
+ <div className="px-3 py-4 text-center text-gray-400">
+ {t("common.no-data")}
+ </div>
+ )}
+ </div>
+
+ <RuleEditDialog
+ open={dialogOpen}
+ onOpenChange={setDialogOpen}
+ mode={dialogMode}
+ source={source}
+ rule={editingRule}
+ isFallback={isFallback}
+ allowAdmin={allowAdmin}
+ hasFeature={hasFeature}
+ onShowFeatureModal={onShowFeatureModal}
+ onSave={handleSaveRule}
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts b/frontend/src/react/components/CustomApproval/utils.ts
similarity index 56%
rename from frontend/src/components/CustomApproval/Settings/components/common/utils.ts
rename to frontend/src/react/components/CustomApproval/utils.ts
index aec0dcae30..50b3d583a1 100644
--- a/frontend/src/components/CustomApproval/Settings/components/common/utils.ts
+++ b/frontend/src/react/components/CustomApproval/utils.ts
@@ -1,10 +1,15 @@
+import { create } from "@bufbuild/protobuf";
+import { v4 as uuidv4 } from "uuid";
import { type OptionConfig } from "@/components/ExprEditor/context";
import type { ResourceSelectOption } from "@/components/v2/Select/RemoteResourceSelector/types";
-import { type Factor, SQLTypeList } from "@/plugins/cel";
+import type { ConditionGroupExpr } from "@/plugins/cel";
+import { ExprType, type Factor, SQLTypeList, wrapAsGroup } from "@/plugins/cel";
import { t } from "@/plugins/i18n";
import { useRoleStore } from "@/store";
-import { PRESET_WORKSPACE_ROLES } from "@/types";
+import type { LocalApprovalRule } from "@/types";
+import { PRESET_WORKSPACE_ROLES, PresetRoleType } from "@/types";
import { Engine, RiskLevel } from "@/types/proto-es/v1/common_pb";
+import { ApprovalFlowSchema } from "@/types/proto-es/v1/issue_service_pb";
import { WorkspaceApprovalSetting_Rule_Source } from "@/types/proto-es/v1/setting_service_pb";
import {
displayRoleTitle,
@@ -32,6 +37,10 @@ import {
CEL_ATTRIBUTE_STATEMENT_TEXT,
} from "@/utils/cel-attributes";
+export { formatApprovalFlow } from "@/utils/workspaceApprovalSetting";
+
+// ─── levelText ───────────────────────────────────────────────────────────────
+
export const levelText = (level: RiskLevel) => {
switch (level) {
case RiskLevel.RISK_LEVEL_UNSPECIFIED:
@@ -47,77 +56,8 @@ export const levelText = (level: RiskLevel) => {
}
};
-const commonFactorList: Factor[] = [
- CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,
- CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,
- CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,
- CEL_ATTRIBUTE_RESOURCE_DB_ENGINE,
-] as const;
-
-const schemaObjectNameFactorList: Factor[] = [
- CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,
- CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
- CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
-] as const;
-
-const migrationFactorList: Factor[] = [
- CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS,
- CEL_ATTRIBUTE_STATEMENT_TABLE_ROWS,
- CEL_ATTRIBUTE_STATEMENT_SQL_TYPE,
- CEL_ATTRIBUTE_STATEMENT_TEXT,
-] as const;
-
-const getDBEndingOptions = () => {
- return supportedEngineV1List().map<ResourceSelectOption<unknown>>((type) => ({
- label: engineNameV1(type),
- value: Engine[type],
- }));
-};
+// ─── approvalSourceText ───────────────────────────────────────────────────────
-const getRiskLevelOptions = () => {
- // Risk level values as strings for CEL conditions (e.g., risk_level == "HIGH")
- const levels = [
- { label: t("custom-approval.risk-rule.risk.risk-level.low"), value: "LOW" },
- {
- label: t("custom-approval.risk-rule.risk.risk-level.moderate"),
- value: "MODERATE",
- },
- {
- label: t("custom-approval.risk-rule.risk.risk-level.high"),
- value: "HIGH",
- },
- ];
- return levels.map<ResourceSelectOption<unknown>>(({ label, value }) => ({
- label,
- value,
- }));
-};
-
-const getSQLTypeOptions = (source: WorkspaceApprovalSetting_Rule_Source) => {
- const mapOptions = (values: readonly string[]) => {
- return values.map<ResourceSelectOption<unknown>>((v) => ({
- label: v,
- value: v,
- }));
- };
- switch (source) {
- case WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE:
- return mapOptions([...SQLTypeList.DDL, ...SQLTypeList.DML]);
- }
- // unsupported source
- return [];
-};
-
-const getRoleOptions = () => {
- return useRoleStore()
- .roleList.filter((role) => !PRESET_WORKSPACE_ROLES.includes(role.name))
- .map((role) => ({
- label: displayRoleTitle(role.name),
- value: role.name,
- }));
-};
-
-// Overload for new approval rule source enum
export const approvalSourceText = (
source: WorkspaceApprovalSetting_Rule_Source
) => {
@@ -139,7 +79,41 @@ export const approvalSourceText = (
}
};
-// Map between WorkspaceApprovalSetting_Rule_Source and Factor lists
+// ─── APPROVAL_SOURCES ─────────────────────────────────────────────────────────
+
+export const APPROVAL_SOURCES = [
+ WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE,
+ WorkspaceApprovalSetting_Rule_Source.CREATE_DATABASE,
+ WorkspaceApprovalSetting_Rule_Source.EXPORT_DATA,
+ WorkspaceApprovalSetting_Rule_Source.REQUEST_ROLE,
+ WorkspaceApprovalSetting_Rule_Source.REQUEST_ACCESS,
+ WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED,
+];
+
+// ─── Factor lists ─────────────────────────────────────────────────────────────
+
+const commonFactorList: Factor[] = [
+ CEL_ATTRIBUTE_RESOURCE_ENVIRONMENT_ID,
+ CEL_ATTRIBUTE_RESOURCE_PROJECT_ID,
+ CEL_ATTRIBUTE_RESOURCE_INSTANCE_ID,
+ CEL_ATTRIBUTE_RESOURCE_DB_ENGINE,
+] as const;
+
+const schemaObjectNameFactorList: Factor[] = [
+ CEL_ATTRIBUTE_RESOURCE_DATABASE_NAME,
+ CEL_ATTRIBUTE_RESOURCE_SCHEMA_NAME,
+ CEL_ATTRIBUTE_RESOURCE_TABLE_NAME,
+] as const;
+
+const migrationFactorList: Factor[] = [
+ CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS,
+ CEL_ATTRIBUTE_STATEMENT_TABLE_ROWS,
+ CEL_ATTRIBUTE_STATEMENT_SQL_TYPE,
+ CEL_ATTRIBUTE_STATEMENT_TEXT,
+] as const;
+
+// ─── ApprovalSourceFactorMap ──────────────────────────────────────────────────
+
export const ApprovalSourceFactorMap: Map<
WorkspaceApprovalSetting_Rule_Source,
Factor[]
@@ -180,6 +154,8 @@ export const ApprovalSourceFactorMap: Map<
],
]);
+// ─── getApprovalFactorList ────────────────────────────────────────────────────
+
export const getApprovalFactorList = (
source: WorkspaceApprovalSetting_Rule_Source
): Factor[] => {
@@ -190,6 +166,59 @@ export const getApprovalFactorList = (
return ApprovalSourceFactorMap.get(source) ?? [];
};
+// ─── Option helpers ───────────────────────────────────────────────────────────
+
+const getDBEndingOptions = () => {
+ return supportedEngineV1List().map<ResourceSelectOption<unknown>>((type) => ({
+ label: engineNameV1(type),
+ value: Engine[type],
+ }));
+};
+
+const getRiskLevelOptions = () => {
+ const levels = [
+ { label: t("custom-approval.risk-rule.risk.risk-level.low"), value: "LOW" },
+ {
+ label: t("custom-approval.risk-rule.risk.risk-level.moderate"),
+ value: "MODERATE",
+ },
+ {
+ label: t("custom-approval.risk-rule.risk.risk-level.high"),
+ value: "HIGH",
+ },
+ ];
+ return levels.map<ResourceSelectOption<unknown>>(({ label, value }) => ({
+ label,
+ value,
+ }));
+};
+
+const getSQLTypeOptions = (source: WorkspaceApprovalSetting_Rule_Source) => {
+ const mapOptions = (values: readonly string[]) => {
+ return values.map<ResourceSelectOption<unknown>>((v) => ({
+ label: v,
+ value: v,
+ }));
+ };
+ switch (source) {
+ case WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE:
+ return mapOptions([...SQLTypeList.DDL, ...SQLTypeList.DML]);
+ }
+ // unsupported source
+ return [];
+};
+
+const getRoleOptions = () => {
+ return useRoleStore()
+ .roleList.filter((role) => !PRESET_WORKSPACE_ROLES.includes(role.name))
+ .map((role) => ({
+ label: displayRoleTitle(role.name),
+ value: role.name,
+ }));
+};
+
+// ─── getApprovalOptionConfigMap ───────────────────────────────────────────────
+
export const getApprovalOptionConfigMap = (
source: WorkspaceApprovalSetting_Rule_Source
) => {
@@ -233,3 +262,88 @@ export const getApprovalOptionConfigMap = (
return map;
}, new Map<Factor, OptionConfig>());
};
+
+// ─── Templates ────────────────────────────────────────────────────────────────
+
+export type ApprovalRuleTemplate = {
+ title: () => string;
+ description: () => string;
+ expr: ConditionGroupExpr;
+ roles: string[];
+ // If undefined, the template applies to all sources.
+ // If specified, the template only applies to the listed sources.
+ sources?: WorkspaceApprovalSetting_Rule_Source[];
+};
+
+export const approvalRuleTemplates: ApprovalRuleTemplate[] = [
+ {
+ title: () =>
+ t("custom-approval.approval-flow.template.presets.drop-or-truncate"),
+ description: () =>
+ t(
+ "custom-approval.approval-flow.template.preset-descriptions.drop-or-truncate"
+ ),
+ // statement.sql_type in ["DROP_TABLE", "TRUNCATE"]
+ expr: wrapAsGroup({
+ type: ExprType.Condition,
+ operator: "@in",
+ args: [CEL_ATTRIBUTE_STATEMENT_SQL_TYPE, ["DROP_TABLE", "TRUNCATE"]],
+ }),
+ roles: [PresetRoleType.PROJECT_OWNER, PresetRoleType.WORKSPACE_DBA],
+ sources: [WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE],
+ },
+ {
+ title: () =>
+ t("custom-approval.approval-flow.template.presets.high-affected-rows"),
+ description: () =>
+ t(
+ "custom-approval.approval-flow.template.preset-descriptions.high-affected-rows"
+ ),
+ // statement.affected_rows > 100
+ expr: wrapAsGroup({
+ type: ExprType.Condition,
+ operator: "_>_",
+ args: [CEL_ATTRIBUTE_STATEMENT_AFFECTED_ROWS, 100],
+ }),
+ roles: [PresetRoleType.PROJECT_OWNER, PresetRoleType.WORKSPACE_DBA],
+ sources: [WorkspaceApprovalSetting_Rule_Source.CHANGE_DATABASE],
+ },
+ {
+ title: () => t("custom-approval.approval-flow.template.presets.fallback"),
+ description: () =>
+ t("custom-approval.approval-flow.template.preset-descriptions.fallback"),
+ // The condition "true" matches all requests not matched by other rules.
+ expr: wrapAsGroup({
+ type: ExprType.RawString,
+ content: "true",
+ }),
+ roles: [PresetRoleType.PROJECT_OWNER],
+ // No sources specified - applies to all sources
+ },
+];
+
+export const filterTemplatesBySource = (
+ templates: ApprovalRuleTemplate[],
+ source: WorkspaceApprovalSetting_Rule_Source
+): ApprovalRuleTemplate[] => {
+ return templates.filter((template) => {
+ // If no sources specified, the template applies to all sources
+ if (!template.sources) {
+ return true;
+ }
+ return template.sources.includes(source);
+ });
+};
+
+// ─── emptyLocalApprovalRule ───────────────────────────────────────────────────
+
+export const emptyLocalApprovalRule = (): LocalApprovalRule => {
+ return {
+ uid: uuidv4(),
+ source: WorkspaceApprovalSetting_Rule_Source.SOURCE_UNSPECIFIED,
+ title: "",
+ description: "",
+ condition: "",
+ flow: create(ApprovalFlowSchema, { roles: [] }),
+ };
+};
diff --git a/frontend/src/react/components/ui/dialog.tsx b/frontend/src/react/components/ui/dialog.tsx
new file mode 100644
index 0000000000..095e5f355d
--- /dev/null
+++ b/frontend/src/react/components/ui/dialog.tsx
@@ -0,0 +1,94 @@
+import { Dialog as BaseDialog } from "@base-ui/react/dialog";
+import type { ComponentProps } from "react";
+import { cn } from "@/react/lib/utils";
+
+// ---- Root ----
+const Dialog = BaseDialog.Root;
+
+// ---- Trigger ----
+const DialogTrigger = BaseDialog.Trigger;
+
+// ---- Overlay / Backdrop ----
+function DialogOverlay({
+ className,
+ ref,
+ ...props
+}: ComponentProps<typeof BaseDialog.Backdrop>) {
+ return (
+ <BaseDialog.Backdrop
+ ref={ref}
+ className={cn("fixed inset-0 z-50 bg-black/50", className)}
+ {...props}
+ />
+ );
+}
+
+// ---- Content / Popup ----
+function DialogContent({
+ className,
+ children,
+ ref,
+ ...props
+}: ComponentProps<typeof BaseDialog.Popup>) {
+ return (
+ <BaseDialog.Portal>
+ <DialogOverlay />
+ <BaseDialog.Popup
+ ref={ref}
+ className={cn(
+ "fixed left-1/2 top-1/2 z-50 -translate-x-1/2 -translate-y-1/2",
+ "w-[calc(100vw-8rem)] max-w-3xl 2xl:max-w-[55vw]",
+ "max-h-[calc(100vh-10rem)] overflow-y-auto",
+ "rounded-sm bg-white shadow-lg",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ </BaseDialog.Popup>
+ </BaseDialog.Portal>
+ );
+}
+
+// ---- Title ----
+function DialogTitle({
+ className,
+ ref,
+ ...props
+}: ComponentProps<typeof BaseDialog.Title>) {
+ return (
+ <BaseDialog.Title
+ ref={ref}
+ className={cn("text-lg font-semibold", className)}
+ {...props}
+ />
+ );
+}
+
+// ---- Description ----
+function DialogDescription({
+ className,
+ ref,
+ ...props
+}: ComponentProps<typeof BaseDialog.Description>) {
+ return (
+ <BaseDialog.Description
+ ref={ref}
+ className={cn("text-sm text-gray-500", className)}
+ {...props}
+ />
+ );
+}
+
+// ---- Close ----
+const DialogClose = BaseDialog.Close;
+
+export {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogOverlay,
+ DialogTitle,
+ DialogTrigger,
+};
diff --git a/frontend/src/react/components/ui/switch.tsx b/frontend/src/react/components/ui/switch.tsx
new file mode 100644
index 0000000000..d29739458c
--- /dev/null
+++ b/frontend/src/react/components/ui/switch.tsx
@@ -0,0 +1,41 @@
+import { Switch as BaseSwitch } from "@base-ui/react/switch";
+import { cn } from "@/react/lib/utils";
+
+interface SwitchProps {
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+ disabled?: boolean;
+ className?: string;
+}
+
+function Switch({
+ checked,
+ onCheckedChange,
+ disabled,
+ className,
+}: SwitchProps) {
+ return (
+ <BaseSwitch.Root
+ checked={checked}
+ onCheckedChange={onCheckedChange}
+ disabled={disabled}
+ className={cn(
+ "relative inline-flex h-5 w-9 cursor-pointer items-center rounded-full transition-colors",
+ "bg-gray-300 data-[checked]:bg-blue-600",
+ "focus:outline-hidden focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2",
+ "disabled:cursor-not-allowed disabled:opacity-50",
+ className
+ )}
+ >
+ <BaseSwitch.Thumb
+ className={cn(
+ "block h-4 w-4 rounded-full bg-white shadow-sm transition-transform",
+ "translate-x-0.5 data-[checked]:translate-x-[18px]"
+ )}
+ />
+ </BaseSwitch.Root>
+ );
+}
+
+export { Switch };
+export type { SwitchProps };
diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.json
index 1e00232609..1fa6003c6f 100644
--- a/frontend/src/react/locales/en-US.json
+++ b/frontend/src/react/locales/en-US.json
@@ -54,6 +54,8 @@
"permissions": "Permissions",
"added": "Added",
"description": "Description",
+ "operations": "Operations",
+ "title": "Title",
"missing-required-permission": "Missing required permissions {{permissions}}",
"required-permission": "Required permissions",
"required-workspace-permission": "Following permissions are required to initialize the workspace UX",
@@ -124,7 +126,9 @@
"add-root-condition-placeholder": "Click \"Add condition\" or \"Add condition group\" to add condition",
"add": "Add condition",
"add-raw-expression": "Add raw expression",
- "add-group": "Add condition group"
+ "add-group": "Add condition group",
+ "description-tips": "A condition is a rule that can be configured via an expression. For example, the condition \"Environment is prod\" will match issues executed in the \"prod\" environment.",
+ "self": "Condition"
}
},
"subscription": {
@@ -698,6 +702,36 @@
"rule": {
"first-match-wins": "Rules are evaluated in order. First matching rule applies."
},
+ "approval-flow": {
+ "add-rule": "Add rule",
+ "create-approval-flow": "Create approval flow",
+ "edit-rule": "Edit rule",
+ "fallback-rules": "Fallback Rules",
+ "fallback-rules-hint": "Fallback rules are evaluated only when no other rules match.",
+ "self": "Approval Flow",
+ "skip": "No approval required",
+ "node": {
+ "add": "Add node",
+ "approver": "Approver",
+ "delete": "Delete approval node",
+ "description": "Only one approval is required on this node when there are multiple approvers.",
+ "nodes": "Approval nodes",
+ "order": "Order"
+ },
+ "template": {
+ "presets-title": "Presets",
+ "preset-descriptions": {
+ "drop-or-truncate": "Require approval for DROP TABLE or TRUNCATE statements.",
+ "fallback": "A catch-all rule that matches all requests. Place at the end of your rules list.",
+ "high-affected-rows": "Require approval when affected rows exceed 100."
+ },
+ "presets": {
+ "drop-or-truncate": "Drop/Truncate Table",
+ "fallback": "Fallback Rule",
+ "high-affected-rows": "High Affected Rows"
+ }
+ }
+ },
"risk": {
"description": "Risk assessment automatically evaluates database changes and assigns risk levels based on the type of operation being performed.",
"how-it-works": "How it works",
@@ -711,7 +745,15 @@
},
"risk-rule": {
"risk": {
+ "namespace": {
+ "change_database": "Change Database",
+ "create_database": "Create Database",
+ "data_export": "Export Data",
+ "request-role": "Request Role",
+ "request-access": "Request Just-In-Time Access"
+ },
"risk-level": {
+ "default": "Default",
"high": "High",
"moderate": "Moderate",
"low": "Low"
diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.json
index e42eaa7c46..43ab0fa80a 100644
--- a/frontend/src/react/locales/es-ES.json
+++ b/frontend/src/react/locales/es-ES.json
@@ -54,6 +54,8 @@
"permissions": "Permisos",
"added": "Agregado",
"description": "Descripción",
+ "operations": "Operaciones",
+ "title": "Título",
"missing-required-permission": "Faltan permisos requeridos {{permissions}}",
"required-permission": "Permisos necesarios",
"required-workspace-permission": "Se requieren los siguientes permisos para inicializar el espacio de trabajo UX",
@@ -124,7 +126,9 @@
"add-root-condition-placeholder": "Haga clic en \"Agregar condición\" o \"Agregar grupo de condiciones\" para agregar una condición",
"add": "Agregar condición",
"add-raw-expression": "Agregar expresión cruda",
- "add-group": "Agregar grupo de condiciones"
+ "add-group": "Agregar grupo de condiciones",
+ "description-tips": "Una condición es una regla que se puede configurar mediante una expresión. Por ejemplo, la condición \"Entorno es prod\" coincidirá con las incidencias ejecutadas en el entorno \"prod\".",
+ "self": "Condición"
}
},
"subscription": {
@@ -698,6 +702,36 @@
"rule": {
"first-match-wins": "Las reglas se evalúan en orden. Se aplica la primera regla coincidente."
},
+ "approval-flow": {
+ "add-rule": "Agregar regla",
+ "create-approval-flow": "Crear flujo de aprobación",
+ "edit-rule": "Editar regla",
+ "fallback-rules": "Reglas de respaldo",
+ "fallback-rules-hint": "Las reglas de respaldo solo se evalúan cuando ninguna otra regla coincide.",
+ "self": "Flujo de aprobación",
+ "skip": "No se requiere aprobación",
+ "node": {
+ "add": "Agregar nodo",
+ "approver": "Aprobador",
+ "delete": "Eliminar nodo de aprobación",
+ "description": "Solo se requiere una aprobación en este nodo cuando hay múltiples aprobadores.",
+ "nodes": "Nodos de aprobación",
+ "order": "Orden"
+ },
+ "template": {
+ "presets-title": "Plantillas",
+ "preset-descriptions": {
+ "drop-or-truncate": "Requerir aprobación para sentencias DROP TABLE o TRUNCATE.",
+ "fallback": "Una regla general que coincide con todas las solicitudes. Colóquela al final de su lista de reglas.",
+ "high-affected-rows": "Requerir aprobación cuando las filas afectadas excedan 100."
+ },
+ "presets": {
+ "drop-or-truncate": "Eliminar/Truncar Tabla",
+ "fallback": "Regla de respaldo",
+ "high-affected-rows": "Alto Número de Filas"
+ }
+ }
+ },
"risk": {
"description": "La evaluación de riesgos evalúa automáticamente los cambios en la base de datos y asigna niveles de riesgo según el tipo de operación que se realiza.",
"how-it-works": "Cómo funciona",
@@ -711,7 +745,15 @@
},
"risk-rule": {
"risk": {
+ "namespace": {
+ "change_database": "Cambiar base de datos",
+ "create_database": "Crear base de datos",
+ "data_export": "Exportar datos",
+ "request-role": "Rol de solicitud",
+ "request-access": "Solicitar acceso Just-In-Time"
+ },
"risk-level": {
+ "default": "Por defecto",
"high": "Alto",
"moderate": "Moderado",
"low": "Bajo"
diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.json
index 9ba7bfc264..566c2e9153 100644
--- a/frontend/src/react/locales/ja-JP.json
+++ b/frontend/src/react/locales/ja-JP.json
@@ -54,6 +54,8 @@
"permissions": "権限",
"added": "作成した",
"description": "説明",
+ "operations": "操作",
+ "title": "タイトル",
"missing-required-permission": "必要な権限がありません {{permissions}}",
"required-permission": "必要な権限",
"required-workspace-permission": "ワークスペース UX の初期化には以下の権限が必要です",
@@ -124,7 +126,9 @@
"add-root-condition-placeholder": "「条件を追加」または「条件グループを追加」をクリックして条件を追加します。",
"add": "条件を追加する",
"add-raw-expression": "生の式を追加",
- "add-group": "条件グループの追加"
+ "add-group": "条件グループの追加",
+ "description-tips": "条件は、式を通じて設定されるルールです。たとえば、「環境は本番」という条件は、「本番」環境で実行されたイシューと一致します。",
+ "self": "状態"
}
},
"subscription": {
@@ -698,6 +702,36 @@
"rule": {
"first-match-wins": "ルールは順番に評価されます。最初に一致するルールが適用されます。"
},
+ "approval-flow": {
+ "add-rule": "ルールを追加",
+ "create-approval-flow": "承認フローの作成",
+ "edit-rule": "ルールを編集",
+ "fallback-rules": "フォールバックルール",
+ "fallback-rules-hint": "フォールバックルールは、他のルールが一致しない場合にのみ評価されます。",
+ "self": "承認の流れ",
+ "skip": "承認不要",
+ "node": {
+ "add": "ノードの追加",
+ "approver": "承認者",
+ "delete": "承認ノードの削除",
+ "description": "ノードに複数の承認者がいる場合、必要な承認は 1 つだけです。",
+ "nodes": "承認ノード",
+ "order": "順序"
+ },
+ "template": {
+ "presets-title": "プリセット",
+ "preset-descriptions": {
+ "drop-or-truncate": "DROP TABLEまたはTRUNCATEステートメントには承認が必要です。",
+ "fallback": "すべてのリクエストに一致するキャッチオールルール。ルールリストの最後に配置してください。",
+ "high-affected-rows": "影響行数が100を超える場合は承認が必要です。"
+ },
+ "presets": {
+ "drop-or-truncate": "テーブル削除/切り捨て",
+ "fallback": "フォールバックルール",
+ "high-affected-rows": "高影響行数"
+ }
+ }
+ },
"risk": {
"description": "リスク評価は、データベースの変更を自動的に評価し、実行される操作の種類に基づいてリスクレベルを割り当てます。",
"how-it-works": "仕組み",
@@ -711,7 +745,15 @@
},
"risk-rule": {
"risk": {
+ "namespace": {
+ "change_database": "データベースの変更",
+ "create_database": "データベースの作成",
+ "data_export": "データのエクスポート",
+ "request-role": "ロールのリクエスト",
+ "request-access": "ジャストインタイムアクセスのリクエスト"
+ },
"risk-level": {
+ "default": "デフォルト",
"high": "高",
"moderate": "中",
"low": "低"
diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.json
index 3d8d6bac47..cc3d566f55 100644
--- a/frontend/src/react/locales/vi-VN.json
+++ b/frontend/src/react/locales/vi-VN.json
@@ -54,6 +54,8 @@
"permissions": "Quyền",
"added": "Đã thêm",
"description": "Mô tả",
+ "operations": "Các thao tác",
+ "title": "Tiêu đề",
"missing-required-permission": "Thiếu quyền cần thiết {{permissions}}",
"required-permission": "Quyền hạn cần thiết",
"required-workspace-permission": "Các quyền sau đây cần thiết để khởi tạo không gian làm việc UX",
@@ -124,7 +126,9 @@
"add-root-condition-placeholder": "Nhấp vào \"Thêm điều kiện\" hoặc \"Thêm nhóm điều kiện\" để thêm điều kiện",
"add": "Thêm điều kiện",
"add-raw-expression": "Thêm biểu thức thô",
- "add-group": "Thêm nhóm điều kiện"
+ "add-group": "Thêm nhóm điều kiện",
+ "description-tips": "Điều kiện là một quy tắc có thể được định cấu hình thông qua một biểu thức. Ví dụ: điều kiện \"Môi trường là sản xuất\" sẽ khớp với các vấn đề được thực hiện trong môi trường \"sản xuất\".",
+ "self": "Điều kiện"
}
},
"subscription": {
@@ -698,6 +702,36 @@
"rule": {
"first-match-wins": "Các quy tắc được đánh giá theo thứ tự. Quy tắc phù hợp đầu tiên sẽ được áp dụng."
},
+ "approval-flow": {
+ "add-rule": "Thêm quy tắc",
+ "create-approval-flow": "Tạo quy trình phê duyệt",
+ "edit-rule": "Chỉnh sửa quy tắc",
+ "fallback-rules": "Quy tắc dự phòng",
+ "fallback-rules-hint": "Quy tắc dự phòng chỉ được đánh giá khi không có quy tắc nào khác khớp.",
+ "self": "Quy trình phê duyệt",
+ "skip": "Không cần phê duyệt",
+ "node": {
+ "add": "Thêm nút",
+ "approver": "Người phê duyệt",
+ "delete": "Xóa nút phê duyệt",
+ "description": "Chỉ cần một phê duyệt trên nút này khi có nhiều người phê duyệt.",
+ "nodes": "Nút phê duyệt",
+ "order": "Thứ tự"
+ },
+ "template": {
+ "presets-title": "Mẫu có sẵn",
+ "preset-descriptions": {
+ "drop-or-truncate": "Yêu cầu phê duyệt cho các câu lệnh DROP TABLE hoặc TRUNCATE.",
+ "fallback": "Quy tắc bắt tất cả khớp với mọi yêu cầu. Đặt ở cuối danh sách quy tắc của bạn.",
+ "high-affected-rows": "Yêu cầu phê duyệt khi số hàng bị ảnh hưởng vượt quá 100."
+ },
+ "presets": {
+ "drop-or-truncate": "Xóa/Truncate Bảng",
+ "fallback": "Quy tắc dự phòng",
+ "high-affected-rows": "Số Hàng Ảnh Hưởng Cao"
+ }
+ }
+ },
"risk": {
"description": "Đánh giá rủi ro tự động đánh giá các thay đổi cơ sở dữ liệu và phân loại mức độ rủi ro dựa trên loại thao tác được thực hiện.",
"how-it-works": "Cách hoạt động",
@@ -711,7 +745,15 @@
},
"risk-rule": {
"risk": {
+ "namespace": {
+ "change_database": "Thay đổi cơ sở dữ liệu",
+ "create_database": "Tạo cơ sở dữ liệu",
+ "data_export": "Xuất dữ liệu",
+ "request-role": "Yêu cầu vai trò",
+ "request-access": "Yêu cầu quyền truy cập Just-In-Time"
+ },
"risk-level": {
+ "default": "Mặc định",
"high": "Cao",
"moderate": "Trung bình",
"low": "Thấp"
diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.json
index 2421eb243a..6ee2e8d824 100644
--- a/frontend/src/react/locales/zh-CN.json
+++ b/frontend/src/react/locales/zh-CN.json
@@ -54,6 +54,8 @@
"permissions": "权限",
"added": "已创建",
"description": "描述",
+ "operations": "操作",
+ "title": "标题",
"missing-required-permission": "缺少必需的权限 {{permissions}}",
"required-permission": "所需权限",
"required-workspace-permission": "初始化工作空间 UX 需要以下权限",
@@ -124,7 +126,9 @@
"add-root-condition-placeholder": "点击「添加条件」或「添加条件组」以添加条件",
"add": "添加条件",
"add-raw-expression": "添加 Raw 表达式",
- "add-group": "添加条件组"
+ "add-group": "添加条件组",
+ "description-tips": "条件是通过表达式配置的规则。例如:条件「环境 为 prod」将会匹配在「prod」环境中执行的工单。",
+ "self": "条件"
}
},
"subscription": {
@@ -698,6 +702,36 @@
"rule": {
"first-match-wins": "规则按顺序评估,第一个匹配的规则将被应用。"
},
+ "approval-flow": {
+ "add-rule": "添加规则",
+ "create-approval-flow": "创建审批流",
+ "edit-rule": "编辑规则",
+ "fallback-rules": "兜底规则",
+ "fallback-rules-hint": "兜底规则仅在没有其他规则匹配时才会被评估。",
+ "self": "审批流",
+ "skip": "无需审批",
+ "node": {
+ "add": "增加节点",
+ "approver": "审批人",
+ "delete": "删除审批节点",
+ "description": "当一个节点上有多个审批人时,只需要一次审批通过。",
+ "nodes": "审批节点",
+ "order": "顺序"
+ },
+ "template": {
+ "presets-title": "预设模板",
+ "preset-descriptions": {
+ "drop-or-truncate": "DROP TABLE 或 TRUNCATE 语句需要审批。",
+ "fallback": "匹配所有请求的兜底规则,请将其放在规则列表的末尾。",
+ "high-affected-rows": "影响行数超过 100 时需要审批。"
+ },
+ "presets": {
+ "drop-or-truncate": "删除/清空表",
+ "fallback": "兜底规则",
+ "high-affected-rows": "高影响行数"
+ }
+ }
+ },
"risk": {
"description": "风险评估会自动评估数据库变更,并根据操作类型分配风险等级。",
"how-it-works": "工作原理",
@@ -711,7 +745,15 @@
},
"risk-rule": {
"risk": {
+ "namespace": {
+ "change_database": "变更数据库",
+ "create_database": "创建数据库",
+ "data_export": "导出数据",
+ "request-role": "请求角色",
+ "request-access": "请求即时访问"
+ },
"risk-level": {
+ "default": "默认",
"high": "高",
"moderate": "中",
"low": "低"
diff --git a/frontend/src/react/pages/settings/CustomApprovalPage.tsx b/frontend/src/react/pages/settings/CustomApprovalPage.tsx
new file mode 100644
index 0000000000..59b56c8771
--- /dev/null
+++ b/frontend/src/react/pages/settings/CustomApprovalPage.tsx
@@ -0,0 +1,97 @@
+import { Loader2 } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { RulesSection } from "@/react/components/CustomApproval/RulesSection";
+import { APPROVAL_SOURCES } from "@/react/components/CustomApproval/utils";
+import { FeatureAttention } from "@/react/components/FeatureAttention";
+import { useVueState } from "@/react/hooks/useVueState";
+import {
+ useSubscriptionV1Store,
+ useWorkspaceApprovalSettingStore,
+} from "@/store";
+import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
+import { hasWorkspacePermissionV2 } from "@/utils";
+
+export function CustomApprovalPage() {
+ const { t } = useTranslation();
+ const store = useWorkspaceApprovalSettingStore();
+ const subscriptionStore = useSubscriptionV1Store();
+ const featureAttentionRef = useRef<HTMLDivElement>(null);
+
+ const [ready, setReady] = useState(false);
+
+ const hasFeature = useVueState(() =>
+ subscriptionStore.hasInstanceFeature(PlanFeature.FEATURE_APPROVAL_WORKFLOW)
+ );
+ const allowAdmin = hasWorkspacePermissionV2("bb.settings.set");
+
+ const handleShowFeatureModal = useCallback(() => {
+ featureAttentionRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, []);
+
+ useEffect(() => {
+ store
+ .fetchConfig()
+ .then(() => setReady(true))
+ .catch(() => setReady(true));
+ }, []);
+
+ return (
+ <div className="w-full px-4 py-4 flex flex-col gap-y-4 text-sm">
+ <div ref={featureAttentionRef}>
+ <FeatureAttention feature={PlanFeature.FEATURE_APPROVAL_WORKFLOW} />
+ </div>
+
+ {hasFeature && (
+ <div className="textinfolabel">
+ {t("custom-approval.rule.first-match-wins")}
+ </div>
+ )}
+
+ {!ready ? (
+ <div className="flex justify-center py-8">
+ <Loader2 className="animate-spin" />
+ </div>
+ ) : (
+ <div className="flex flex-col gap-y-6">
+ {APPROVAL_SOURCES.map((source) => (
+ <SourceSection
+ key={source}
+ source={source}
+ store={store}
+ allowAdmin={allowAdmin}
+ hasFeature={hasFeature}
+ onShowFeatureModal={handleShowFeatureModal}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function SourceSection({
+ source,
+ store,
+ allowAdmin,
+ hasFeature,
+ onShowFeatureModal,
+}: {
+ source: (typeof APPROVAL_SOURCES)[number];
+ store: ReturnType<typeof useWorkspaceApprovalSettingStore>;
+ allowAdmin: boolean;
+ hasFeature: boolean;
+ onShowFeatureModal: () => void;
+}) {
+ const rules = useVueState(() => store.getRulesBySource(source));
+
+ return (
+ <RulesSection
+ source={source}
+ rules={rules}
+ allowAdmin={allowAdmin}
+ hasFeature={hasFeature}
+ onShowFeatureModal={onShowFeatureModal}
+ />
+ );
+}
diff --git a/frontend/src/router/dashboard/workspace.ts b/frontend/src/router/dashboard/workspace.ts
index 8567e0ff40..2b72d97418 100644
--- a/frontend/src/router/dashboard/workspace.ts
+++ b/frontend/src/router/dashboard/workspace.ts
@@ -264,8 +264,8 @@ const workspaceRoutes: RouteRecordRaw[] = [
title: () => t("custom-approval.self"),
requiredPermissionList: () => ["bb.settings.get"],
},
- component: () => import("@/views/SettingWorkspaceCustomApproval.vue"),
- props: true,
+ component: () => import("@/react/ReactPageMount.vue"),
+ props: () => ({ page: "CustomApprovalPage" }),
},
{
path: "global-masking",
diff --git a/frontend/src/views/SettingWorkspaceCustomApproval.vue b/frontend/src/views/SettingWorkspaceCustomApproval.vue
deleted file mode 100644
index f2e728e4d1..0000000000
--- a/frontend/src/views/SettingWorkspaceCustomApproval.vue
+++ /dev/null
@@ -1,62 +0,0 @@
-<template>
- <div class="w-full px-4 py-4 flex flex-col gap-y-4 text-sm">
- <FeatureAttention :feature="PlanFeature.FEATURE_APPROVAL_WORKFLOW" />
- <BBAttention v-if="hasCustomApprovalFeature" type="info" :description="$t('custom-approval.rule.first-match-wins')" />
-
- <CustomApproval v-if="state.ready" />
- <div v-else class="w-full py-16 flex justify-center items-center">
- <BBSpin />
- </div>
- </div>
-
- <FeatureModal
- :feature="PlanFeature.FEATURE_APPROVAL_WORKFLOW"
- :open="state.showFeatureModal"
- @cancel="state.showFeatureModal = false"
- />
-</template>
-
-<script lang="ts" setup>
-import { onMounted, reactive, toRef } from "vue";
-import { BBAttention, BBSpin } from "@/bbkit";
-import {
- CustomApproval,
- provideCustomApprovalContext,
-} from "@/components/CustomApproval/Settings/components/CustomApproval/";
-import { FeatureAttention, FeatureModal } from "@/components/FeatureGuard";
-import { featureToRef, useWorkspaceApprovalSettingStore } from "@/store";
-import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";
-
-interface LocalState {
- ready: boolean;
- showFeatureModal: boolean;
-}
-
-const props = defineProps<{
- allowEdit: boolean;
-}>();
-
-const state = reactive<LocalState>({
- ready: false,
- showFeatureModal: false,
-});
-const hasCustomApprovalFeature = featureToRef(
- PlanFeature.FEATURE_APPROVAL_WORKFLOW
-);
-
-provideCustomApprovalContext({
- hasFeature: hasCustomApprovalFeature,
- showFeatureModal: toRef(state, "showFeatureModal"),
- allowAdmin: toRef(props, "allowEdit"),
- ready: toRef(state, "ready"),
-});
-
-onMounted(async () => {
- try {
- await useWorkspaceApprovalSettingStore().fetchConfig();
- state.ready = true;
- } catch {
- // nothing
- }
-});
-</script>