Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(frontend): migrate project webhooks pages to React (#19859)
Danny Xu3e3402ff6d78
diff --git a/frontend/src/components/Project/WebhookTypeIcon.vue b/frontend/src/components/Project/WebhookTypeIcon.vuedeleted file mode 100644index a407a6df46..0000000000--- a/frontend/src/components/Project/WebhookTypeIcon.vue+++ /dev/null@@ -1,35 +0,0 @@-<template>- <div v-bind="$attrs">- <!-- This awkward code is author couldn't figure out proper way to use dynamic src under vite- https://github.com/vitejs/vite/issues/1265 -->- <template v-if="type === WebhookType.SLACK">- <img src="../../assets/im/slack.png" alt="" />- </template>- <template v-else-if="type === WebhookType.DISCORD">- <img src="../../assets/im/discord.svg" />- </template>- <template v-else-if="type === WebhookType.TEAMS">- <img src="../../assets/im/teams.svg" />- </template>- <template v-else-if="type === WebhookType.DINGTALK">- <img src="../../assets/im/dingtalk.png" />- </template>- <template v-else-if="type === WebhookType.FEISHU">- <img src="../../assets/im/feishu.webp" />- </template>- <template v-else-if="type === WebhookType.LARK">- <img src="../../assets/im/feishu.webp" />- </template>- <template v-else-if="type === WebhookType.WECOM">- <img src="../../assets/im/wecom.png" />- </template>- </div>-</template>--<script setup lang="ts">-import { WebhookType } from "@/types/proto-es/v1/common_pb";--defineProps<{- type: WebhookType;-}>();-</script>diff --git a/frontend/src/components/ProjectWebhookForm.vue b/frontend/src/components/ProjectWebhookForm.vuedeleted file mode 100644index 6bf97114c6..0000000000--- a/frontend/src/components/ProjectWebhookForm.vue+++ /dev/null@@ -1,574 +0,0 @@-<template>- <FormLayout :title="create ? $t('project.webhook.creation.title') : ''">- <template v-if="!create" #title>- <div class="flex flex-row justify-between items-center">- <div class="flex flex-row gap-x-2 items-center">- <WebhookTypeIcon :type="props.webhook.type" class="h-6 w-6" />- <h3 class="text-lg leading-6 font-medium text-main">- {{ props.webhook.title }}- </h3>- </div>- <NDropdown- v-if="allowEdit"- trigger="click"- :options="dropdownOptions"- @select="handleDropdownSelect"- >- <NButton size="small" quaternary class="px-1!">- <template #icon>- <EllipsisVerticalIcon class="w-4 h-4" />- </template>- </NButton>- </NDropdown>- </div>- <NDivider />- </template>- <template #body>- <MissingExternalURLAttention- class="mb-6"- />- <div class="flex flex-col gap-y-4">- <div v-if="create">- <div>- <label for="name" class="font-medium text-main">- {{ $t("project.webhook.destination") }}- <RequiredStar />- </label>- </div>- <NRadioGroup class="w-full mt-1" :value="state.webhook.type">- <div class="grid grid-cols-1 gap-4 sm:grid-cols-7">- <template- v-for="(item, index) in webhookTypeItemList"- :key="index"- >- <div- class="flex justify-center px-2 py-4 rounded-sm border border-control-border hover:bg-control-bg-hover cursor-pointer"- @click.capture="state.webhook.type = item.type"- >- <div class="flex flex-col items-center">- <WebhookTypeIcon :type="item.type" class="h-10 w-10" />- <p class="mt-1 text-center textlabel">- {{ item.name }}- </p>- <div class="mt-3 radio text-sm">- <NRadio :value="item.type" />- </div>- </div>- </div>- </template>- </div>- </NRadioGroup>- </div>- <div>- <label for="name" class="font-medium text-main">- {{ $t("common.name") }}- <RequiredStar />- </label>- <NInput- id="name"- v-model:value="state.webhook.title"- name="name"- class="mt-1 w-full"- :placeholder="`${selectedWebhook?.name ?? 'My'} Webhook`"- :disabled="!allowEdit"- />- </div>- <div>- <label for="url" class="font-medium text-main">- {{ $t("project.webhook.webhook-url") }}- <RequiredStar />- </label>- <div class="mt-1 textinfolabel">- {{- $t("project.webhook.creation.desc", {- destination: selectedWebhook?.name,- })- }}- <a- :href="selectedWebhook?.docUrl"- target="__blank"- class="normal-link"- >{{- $t("project.webhook.creation.view-doc", {- destination: selectedWebhook?.name,- })- }}</a- >.- </div>- <NInput- id="url"- v-model:value="state.webhook.url"- name="url"- class="mt-1 w-full"- :placeholder="selectedWebhook?.urlPlaceholder"- :disabled="!allowEdit"- />- </div>- <div>- <div class="text-md leading-6 font-medium text-main">- {{ $t("project.webhook.triggering-activity") }}- <RequiredStar />- </div>- <div class="flex flex-col gap-y-4 mt-2">- <div v-for="(item, index) in webhookActivityItemList" :key="index">- <div>- <div class="flex items-center">- <NCheckbox- :label="item.title"- :checked="isEventOn(item.activity)"- @update:checked="- (on: boolean) => {- toggleEvent(item.activity, on);- }- "- />- <NTooltip- v-if="- webhookSupportDirectMessage && item.supportDirectMessage- "- >- <template #trigger>- <InfoIcon class="w-4 h-auto text-gray-500" />- </template>- {{ $t("project.webhook.activity-support-direct-message") }}- </NTooltip>- </div>- <div class="textinfolabel">{{ item.label }}</div>- </div>- </div>- </div>- </div>- <div v-if="webhookSupportDirectMessage">- <div class="text-md leading-6 font-medium text-main">- {{ $t("project.webhook.direct-messages") }}- </div>- <BBAttention class="my-2" :type="imApp ? 'info' : 'warning'">- <template #default>- <span v-if="imApp">- {{ $t("project.webhook.direct-messages-tip") }}- </span>- <i18n-t- v-else- class="textinfolabel"- tag="div"- keypath="project.webhook.direct-messages-warning"- >- <template #im>- <router-link- target="_blank"- class="normal-link"- :to="{ name: WORKSPACE_ROUTE_IM }"- >- {{ $t("settings.sidebar.im-integration") }}- </router-link>- </template>- </i18n-t>- </template>- </BBAttention>- <span class="mt-1 textinfolabel">- <i18n-t- keypath="project.webhook.direct-messages-description"- tag="span"- >- <template #events>- <ul class="list-disc pl-4">- <li- v-for="(item, index) in webhookActivityItemList.filter(- (item) => item.supportDirectMessage- )"- :key="index"- >- {{ item.title }}- </li>- </ul>- </template>- </i18n-t>- </span>- <div class="flex items-center mt-2">- <NCheckbox- v-model:checked="state.webhook.directMessage"- :disabled="!activitySupportDirectMessage"- :label="$t('project.webhook.enable-direct-messages')"- />- </div>- </div>- <div class="mt-4">- <NButton- :loading="state.loading"- :disabled="!state.webhook.url"- @click.prevent="testWebhook"- >- {{ $t("project.webhook.test-webhook") }}- </NButton>- </div>- </div>- </template>- <template #footer>- <div class="flex justify-end">- <div class="flex items-center gap-x-2">- <NButton v-if="create" @click.prevent="cancel">- {{ $t("common.cancel") }}- </NButton>- <NButton v-else-if="valueChanged" @click.prevent="discardChanges">- {{ $t("common.discard-changes") }}- </NButton>- <template v-if="allowEdit">- <NButton- v-if="create"- type="primary"- :loading="state.loading"- :disabled="!allowCreate || state.loading"- @click.prevent="createWebhook"- >- {{ $t("common.create") }}- </NButton>- <NButton- v-else- type="primary"- :loading="state.loading"- :disabled="- state.loading || !valueChanged || state.webhook.notificationTypes.length === 0- "- @click.prevent="updateWebhook"- >- {{ $t("common.update") }}- </NButton>- </template>- </div>- </div>- </template>- </FormLayout>-</template>--<script lang="ts" setup>-import { cloneDeep, isEmpty, isEqual } from "lodash-es";-import { EllipsisVerticalIcon, InfoIcon } from "lucide-vue-next";-import type { DropdownOption } from "naive-ui";-import {- NButton,- NCheckbox,- NDivider,- NDropdown,- NInput,- NRadio,- NRadioGroup,- NTooltip,- useDialog,-} from "naive-ui";-import { computed, onMounted, reactive, watch } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import { BBAttention } from "@/bbkit";-import RequiredStar from "@/components/RequiredStar.vue";-import { MissingExternalURLAttention } from "@/components/v2/Form";-import FormLayout from "@/components/v2/Form/FormLayout.vue";-import {- PROJECT_V1_ROUTE_WEBHOOK_DETAIL,- PROJECT_V1_ROUTE_WEBHOOKS,-} from "@/router/dashboard/projectV1";-import { WORKSPACE_ROUTE_IM } from "@/router/dashboard/workspaceRoutes";-import {- pushNotification,- useProjectV1Store,- useProjectWebhookV1Store,- useSettingV1Store,-} from "@/store";-import {- projectWebhookV1ActivityItemList,- projectWebhookV1TypeItemList,-} from "@/types";-import {- type Activity_Type,- type Project,- type Webhook,-} from "@/types/proto-es/v1/project_service_pb";-import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";-import { extractProjectWebhookID } from "../utils";-import WebhookTypeIcon from "./Project/WebhookTypeIcon.vue";--interface LocalState {- webhook: Webhook;- loading: boolean;-}--const props = withDefaults(- defineProps<{- allowEdit?: boolean;- create: boolean;- project: Project;- webhook: Webhook;- }>(),- {- allowEdit: true,- }-);--const router = useRouter();-const { t } = useI18n();-const dialog = useDialog();--const settingStore = useSettingV1Store();-const projectStore = useProjectV1Store();-const projectWebhookV1Store = useProjectWebhookV1Store();-onMounted(async () => {- await settingStore.getOrFetchSettingByName(Setting_SettingName.APP_IM);-});--const state = reactive<LocalState>({- webhook: cloneDeep(props.webhook),- loading: false,-});--watch(- () => props.webhook,- (webhook) => {- state.webhook = cloneDeep(webhook);- }-);--const valueChanged = computed(() => {- return !isEqual(props.webhook, state.webhook);-});--const allowCreate = computed(() => {- return (- !isEmpty(state.webhook.title) &&- !isEmpty(state.webhook.url) &&- !isEmpty(state.webhook.notificationTypes)- );-});--const discardChanges = () => {- state.webhook = cloneDeep(props.webhook);-};--const isEventOn = (type: Activity_Type) => {- return state.webhook.notificationTypes.includes(type);-};--const webhookActivityItemList = computed(() =>- projectWebhookV1ActivityItemList()-);--const webhookTypeItemList = computed(() => projectWebhookV1TypeItemList());--const selectedWebhook = computed(() => {- return webhookTypeItemList.value.find(- (item) => item.type === state.webhook.type- );-});--const imSetting = computed(() => {- const setting = settingStore.getSettingByName(Setting_SettingName.APP_IM);- if (!setting?.value?.value) return undefined;- const value = setting.value.value;- if (value.case === "appIm") {- return value.value;- }- return undefined;-});--const imApp = computed(() => {- if (!selectedWebhook.value?.supportDirectMessage) {- return undefined;- }- return imSetting.value?.settings.find(- (setting) => setting.type === selectedWebhook.value?.type- );-});--const isPowerAutomateURL = computed(() => {- const url = state.webhook.url.toLowerCase();- return url.includes(".powerplatform.com") || url.includes(".logic.azure.com");-});--const webhookSupportDirectMessage = computed(- () => selectedWebhook.value?.supportDirectMessage && !isPowerAutomateURL.value-);--const activitySupportDirectMessage = computed(() => {- return state.webhook.notificationTypes.some(- (event) =>- webhookActivityItemList.value.find((item) => item.activity === event)- ?.supportDirectMessage- );-});--const toggleEvent = (type: Activity_Type, on: boolean) => {- if (on) {- if (state.webhook.notificationTypes.includes(type)) {- return;- }- state.webhook.notificationTypes.push(type);- } else {- const index = state.webhook.notificationTypes.indexOf(type);- if (index >= 0) {- state.webhook.notificationTypes.splice(index, 1);- }- }- state.webhook.notificationTypes.sort();-};--const dropdownOptions = computed((): DropdownOption[] => {- return [- {- key: "delete",- label: t("common.delete"),- disabled: state.loading,- },- ];-});--const handleDropdownSelect = (key: string) => {- if (key === "delete") {- dialog.warning({- title: t("project.webhook.deletion.confirm-title", {- title: state.webhook.title,- }),- content: t("common.cannot-undo-this-action"),- negativeText: t("common.cancel"),- positiveText: t("common.delete"),- onPositiveClick: () => {- deleteWebhook();- },- });- }-};--const cancel = () => {- router.push({- name: PROJECT_V1_ROUTE_WEBHOOKS,- });-};--// biome-ignore format: ESLint requires trailing comma for generic type parameter-const useGracefulRequest = async <T,>(- fn: () => Promise<T>-): Promise<T | void> => {- state.loading = true;- try {- const result = await fn();- return result;- } finally {- state.loading = false;- }-};--const createWebhook = () => {- useGracefulRequest(async () => {- const { webhook } = state;- const updatedProject = await projectWebhookV1Store.createProjectWebhook(- props.project.name,- webhook- );- projectStore.updateProjectCache({- ...props.project,- ...updatedProject,- });-- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.webhook.success-created-prompt", {- name: webhook.title,- }),- });- const createdWebhook = updatedProject.webhooks.find((wh) => {- return (- wh.title === webhook.title &&- wh.type === webhook.type &&- wh.url === webhook.url- );- });- if (createdWebhook) {- router.push({- name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,- params: {- webhookResourceId: extractProjectWebhookID(createdWebhook.name),- },- });- }- });-};--const updateWebhook = () => {- useGracefulRequest(async () => {- const updateMask: string[] = [];- if (state.webhook.title !== props.webhook.title) {- updateMask.push("title");- }- if (state.webhook.url !== props.webhook.url) {- updateMask.push("url");- }- if (state.webhook.directMessage !== props.webhook.directMessage) {- updateMask.push("direct_message");- }- if (- !isEqual(state.webhook.notificationTypes, props.webhook.notificationTypes)- ) {- updateMask.push("notification_type");- }- const updatedProject = await projectWebhookV1Store.updateProjectWebhook(- state.webhook,- updateMask- );- projectStore.updateProjectCache({- ...props.project,- ...updatedProject,- });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.webhook.success-updated-prompt", {- name: state.webhook.title,- }),- });- });-};--const deleteWebhook = () => {- useGracefulRequest(async () => {- const name = state.webhook.title;- const updatedProject = await projectWebhookV1Store.deleteProjectWebhook(- state.webhook- );- projectStore.updateProjectCache({- ...props.project,- ...updatedProject,- });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.webhook.success-deleted-prompt", {- name,- }),- });- cancel();- });-};--const testWebhook = () => {- useGracefulRequest(async () => {- const result = await projectWebhookV1Store.testProjectWebhook(- props.project,- state.webhook- );-- if (result.error) {- pushNotification({- module: "bytebase",- style: "CRITICAL",- title: t("project.webhook.fail-tested-title"),- description: result.error,- manualHide: true,- });- } else {- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.webhook.success-tested-prompt"),- });- }- });-};-</script>diff --git a/frontend/src/react/components/WebhookTypeIcon.tsx b/frontend/src/react/components/WebhookTypeIcon.tsxnew file mode 100644index 0000000000..346746c687--- /dev/null+++ b/frontend/src/react/components/WebhookTypeIcon.tsx@@ -0,0 +1,29 @@+import dingtalkIcon from "@/assets/im/dingtalk.png";+import discordIcon from "@/assets/im/discord.svg";+import feishuIcon from "@/assets/im/feishu.webp";+import slackIcon from "@/assets/im/slack.png";+import teamsIcon from "@/assets/im/teams.svg";+import wecomIcon from "@/assets/im/wecom.png";+import { WebhookType } from "@/types/proto-es/v1/common_pb";++const iconMap: Record<number, string> = {+ [WebhookType.SLACK]: slackIcon,+ [WebhookType.DISCORD]: discordIcon,+ [WebhookType.TEAMS]: teamsIcon,+ [WebhookType.DINGTALK]: dingtalkIcon,+ [WebhookType.FEISHU]: feishuIcon,+ [WebhookType.LARK]: feishuIcon,+ [WebhookType.WECOM]: wecomIcon,+};++export function WebhookTypeIcon({+ type,+ className,+}: {+ type: WebhookType;+ className?: string;+}) {+ const src = iconMap[type];+ if (!src) return null;+ return <img src={src} alt="" className={className} />;+}diff --git a/frontend/src/react/locales/en-US.json b/frontend/src/react/locales/en-US.jsonindex e0d76ce535..7f6bacecd2 100644--- a/frontend/src/react/locales/en-US.json+++ b/frontend/src/react/locales/en-US.json@@ -484,6 +484,32 @@"approval-flow-not-configured": "No approval flow configured","view-approval-flow": "View approval flow"}+ },+ "webhook": {+ "success-created-prompt": "Successfully created webhook {{name}}.",+ "success-updated-prompt": "Successfully updated webhook {{name}}.",+ "success-deleted-prompt": "Successfully deleted webhook {{name}}.",+ "success-tested-prompt": "Test webhook event OK.",+ "fail-tested-title": "Test webhook event failed.",+ "add-a-webhook": "Add a webhook",+ "destination": "Destination",+ "webhook-url": "Webhook URL",+ "triggering-activity": "Triggering activities",+ "test-webhook": "Test Webhook",+ "creation": {+ "title": "Create webhook",+ "desc": "Create the corresponding webhook for the {{destination}} channel receiving the message.",+ "view-doc": "View {{destination}}'s doc"+ },+ "deletion": {+ "confirm-title": "Delete webhook '{{title}}'?"+ },+ "direct-messages": "Direct messages",+ "direct-messages-tip": "Bytebase will fall back to posting webhook messages if no users are matched or the delivery of the message fails.",+ "enable-direct-messages": "Enable direct messages",+ "direct-messages-description": "Once enabled, Bytebase will send following events as direct messages to the related users (matched by email):",+ "direct-messages-warning": "You need to configure IM integration to make it work.",+ "activity-support-direct-message": "Support send direct messages to related users"}},"quick-action": {diff --git a/frontend/src/react/locales/es-ES.json b/frontend/src/react/locales/es-ES.jsonindex b5a5e7a85b..28bb0e5e0d 100644--- a/frontend/src/react/locales/es-ES.json+++ b/frontend/src/react/locales/es-ES.json@@ -484,6 +484,32 @@"disallow-ddl-all-environments": "No permitir ejecutar sentencias DDL/DML en ningún entorno.","edit-member": "Editar miembro - {{member}}","revoke-role-from-member": "¿Revocar '{{role}}' de '{{member}}'?"+ },+ "webhook": {+ "success-created-prompt": "Webhook {{name}} creado exitosamente.",+ "success-updated-prompt": "Webhook {{name}} actualizado exitosamente.",+ "success-deleted-prompt": "Webhook {{name}} eliminado exitosamente.",+ "success-tested-prompt": "Prueba de evento de webhook OK.",+ "fail-tested-title": "La prueba de evento de webhook falló.",+ "add-a-webhook": "Agregar un webhook",+ "destination": "Destino",+ "webhook-url": "URL del webhook",+ "triggering-activity": "Actividades de disparo",+ "test-webhook": "Probar webhook",+ "creation": {+ "title": "Crear webhook",+ "desc": "Cree el webhook correspondiente para el canal {{destination}} que reciba el mensaje.",+ "view-doc": "Ver documentación de {{destination}}"+ },+ "deletion": {+ "confirm-title": "¿Eliminar el webhook '{{title}}'?"+ },+ "direct-messages": "Mensajes directos",+ "direct-messages-tip": "Bytebase recurrirá a la publicación de mensajes de webhook si no hay usuarios coincidentes o si falla la entrega del mensaje.",+ "enable-direct-messages": "Habilitar mensajes directos",+ "direct-messages-description": "Una vez habilitado, Bytebase enviará mensajes directos a los usuarios relacionados (emparejados por correo electrónico). Solo soporte:",+ "direct-messages-warning": "Debes configurar la integración IM para que funcione.",+ "activity-support-direct-message": "Soporte para enviar mensajes directos a usuarios relacionados."}},"quick-action": {diff --git a/frontend/src/react/locales/ja-JP.json b/frontend/src/react/locales/ja-JP.jsonindex 7da79ef9bc..8352e21174 100644--- a/frontend/src/react/locales/ja-JP.json+++ b/frontend/src/react/locales/ja-JP.json@@ -484,6 +484,32 @@"disallow-ddl-all-environments": "すべての環境で DDL/DML ステートメントの実行を禁止する。","edit-member": "メンバー編集 - {{member}}","revoke-role-from-member": "'{{member}}' から '{{role}}' を取り消しますか?"+ },+ "webhook": {+ "success-created-prompt": "{{name}} Webhook が正常に作成されました。",+ "success-updated-prompt": "{{name}} Webhook が正常に更新されました。",+ "success-deleted-prompt": "{{name}} Webhook が正常に削除されました。",+ "success-tested-prompt": "Webhook イベントのテストが成功しました。",+ "fail-tested-title": "Webhook イベントのテストに失敗しました。",+ "add-a-webhook": "Webhook を追加する",+ "destination": "外部アプリケーション",+ "webhook-url": "Webhook URL",+ "triggering-activity": "トリガーイベント",+ "test-webhook": "Webhook のテスト",+ "creation": {+ "title": "Webhook の作成",+ "desc": "{{destination}} の Webhook を作成します",+ "view-doc": "{{destination}} の公式ドキュメント"+ },+ "deletion": {+ "confirm-title": "Webhook '{{title}}' を削除しますか?"+ },+ "direct-messages": "プライベートメッセージ通知",+ "direct-messages-tip": "一致するユーザーがいない場合、またはメッセージの配信が失敗した場合、Bytebase は webhook メッセージの投稿にフォールバックします。",+ "enable-direct-messages": "プライベートメッセージ通知を有効にする",+ "direct-messages-description": "有効にすると、Bytebase は関連ユーザー (電子メールで一致) にダイレクトメッセージを送信します。サポートのみ:",+ "direct-messages-warning": "これを機能させるには、IM 統合を設定する必要があります。",+ "activity-support-direct-message": "関連するユーザーへのプライベートメッセージ通知の送信のサポート"}},"quick-action": {diff --git a/frontend/src/react/locales/vi-VN.json b/frontend/src/react/locales/vi-VN.jsonindex 01e2cfda9f..3ef7e5f684 100644--- a/frontend/src/react/locales/vi-VN.json+++ b/frontend/src/react/locales/vi-VN.json@@ -484,6 +484,32 @@"disallow-ddl-all-environments": "Không cho phép chạy câu lệnh DDL/DML cho tất cả các môi trường.","edit-member": "Chỉnh sửa thành viên - {{member}}","revoke-role-from-member": "Thu hồi '{{role}}' từ '{{member}}'?"+ },+ "webhook": {+ "success-created-prompt": "Đã tạo thành công webhook {{name}}.",+ "success-updated-prompt": "Đã cập nhật thành công webhook {{name}}.",+ "success-deleted-prompt": "Đã xóa thành công webhook {{name}}.",+ "success-tested-prompt": "Kiểm tra sự kiện webhook OK.",+ "fail-tested-title": "Kiểm tra sự kiện webhook không thành công.",+ "add-a-webhook": "Thêm một webhook",+ "destination": "Đích",+ "webhook-url": "URL Webhook",+ "triggering-activity": "Hoạt động kích hoạt",+ "test-webhook": "Kiểm tra Webhook",+ "creation": {+ "title": "Tạo webhook",+ "desc": "Tạo webhook tương ứng cho kênh {{destination}} nhận tin nhắn.",+ "view-doc": "Xem tài liệu của {{destination}}"+ },+ "deletion": {+ "confirm-title": "Xóa webhook '{{title}}'?"+ },+ "direct-messages": "Tin nhắn trực tiếp",+ "direct-messages-tip": "Bytebase sẽ quay lại đăng tin nhắn webhook nếu không có người dùng nào khớp hoặc việc gửi tin nhắn không thành công.",+ "enable-direct-messages": "Bật tin nhắn trực tiếp",+ "direct-messages-description": "Khi được bật, Bytebase sẽ gửi tin nhắn trực tiếp đến người dùng liên quan (được khớp bằng email). Chỉ hỗ trợ:",+ "direct-messages-warning": "Bạn cần định cấu hình tích hợp IM để làm cho nó hoạt động.",+ "activity-support-direct-message": "Hỗ trợ gửi tin nhắn trực tiếp đến người dùng liên quan"}},"quick-action": {diff --git a/frontend/src/react/locales/zh-CN.json b/frontend/src/react/locales/zh-CN.jsonindex 96201c89bc..f6f924e3c1 100644--- a/frontend/src/react/locales/zh-CN.json+++ b/frontend/src/react/locales/zh-CN.json@@ -484,6 +484,32 @@"disallow-ddl-all-environments": "禁止在所有环境中执行 DDL/DML 语句。","edit-member": "编辑成员 - {{member}}","revoke-role-from-member": "从 '{{member}}' 撤销 '{{role}}' 角色?"+ },+ "webhook": {+ "success-created-prompt": "成功创建 {{name}} webhook.",+ "success-updated-prompt": "成功更新 {{name}} webhook.",+ "success-deleted-prompt": "成功删除 {{name}} webhook.",+ "success-tested-prompt": "测试 webhook 事件成功.",+ "fail-tested-title": "测试 webhook 事件失败.",+ "add-a-webhook": "添加 webhook",+ "destination": "外部应用",+ "webhook-url": "Webhook URL",+ "triggering-activity": "触发事件",+ "test-webhook": "测试 Webhook",+ "creation": {+ "title": "创建 webhook",+ "desc": "为 {{destination}} 创建一个 webhook",+ "view-doc": "{{destination}} 的官方文档"+ },+ "deletion": {+ "confirm-title": "删除 webhook '{{title}}'?"+ },+ "direct-messages": "私信通知",+ "direct-messages-tip": "如果没有匹配的用户或者消息发送失败,Bytebase 将回退发布 webhook 消息。",+ "enable-direct-messages": "启用私信通知",+ "direct-messages-description": "启用后,Bytebase 将私信通知相关用户(通过电子邮箱匹配)。仅支持:",+ "direct-messages-warning": "您需要配置 IM 集成才能使其正常工作。",+ "activity-support-direct-message": "支持向相关用户发送私信通知"}},"quick-action": {diff --git a/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx b/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsxnew file mode 100644index 0000000000..82aa4368de--- /dev/null+++ b/frontend/src/react/pages/project/ProjectWebhookCreatePage.tsx@@ -0,0 +1,44 @@+import { create as createProto } from "@bufbuild/protobuf";+import { useMemo } from "react";+import { useVueState } from "@/react/hooks/useVueState";+import { useProjectV1Store } from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { State, WebhookType } from "@/types/proto-es/v1/common_pb";+import {+ Activity_Type,+ WebhookSchema,+} from "@/types/proto-es/v1/project_service_pb";+import { hasProjectPermissionV2 } from "@/utils";+import { ProjectWebhookForm } from "./ProjectWebhookForm";++export function ProjectWebhookCreatePage({ projectId }: { projectId: string }) {+ const projectStore = useProjectV1Store();+ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const allowEdit = useMemo(() => {+ if (!project) return false;+ if (project.state === State.DELETED) return false;+ return hasProjectPermissionV2(project, "bb.projects.update");+ }, [project]);++ const defaultWebhook = useMemo(+ () =>+ createProto(WebhookSchema, {+ type: WebhookType.SLACK,+ notificationTypes: [Activity_Type.ISSUE_CREATED],+ }),+ []+ );++ if (!project) return null;++ return (+ <ProjectWebhookForm+ allowEdit={allowEdit}+ create={true}+ project={project}+ webhook={defaultWebhook}+ />+ );+}diff --git a/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx b/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsxnew file mode 100644index 0000000000..8470bef197--- /dev/null+++ b/frontend/src/react/pages/project/ProjectWebhookDetailPage.tsx@@ -0,0 +1,49 @@+import { create as createProto } from "@bufbuild/protobuf";+import { useMemo } from "react";+import { useVueState } from "@/react/hooks/useVueState";+import { useProjectV1Store, useProjectWebhookV1Store } from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { State } from "@/types/proto-es/v1/common_pb";+import { WebhookSchema } from "@/types/proto-es/v1/project_service_pb";+import { hasProjectPermissionV2 } from "@/utils";+import { ProjectWebhookForm } from "./ProjectWebhookForm";++export function ProjectWebhookDetailPage({+ projectId,+ webhookResourceId,+}: {+ projectId: string;+ webhookResourceId: string;+}) {+ const projectStore = useProjectV1Store();+ const projectWebhookV1Store = useProjectWebhookV1Store();+ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const webhook = useVueState(() => {+ if (!project) return undefined;+ return projectWebhookV1Store.getProjectWebhookFromProjectById(+ project,+ webhookResourceId+ );+ });++ const allowEdit = useMemo(() => {+ if (!project) return false;+ if (project.state === State.DELETED) return false;+ return hasProjectPermissionV2(project, "bb.projects.update");+ }, [project]);++ const fallback = useMemo(() => createProto(WebhookSchema, {}), []);++ if (!project) return null;++ return (+ <ProjectWebhookForm+ create={false}+ allowEdit={allowEdit}+ project={project}+ webhook={webhook ?? fallback}+ />+ );+}diff --git a/frontend/src/react/pages/project/ProjectWebhookForm.tsx b/frontend/src/react/pages/project/ProjectWebhookForm.tsxnew file mode 100644index 0000000000..70bc2ddf4b--- /dev/null+++ b/frontend/src/react/pages/project/ProjectWebhookForm.tsx@@ -0,0 +1,660 @@+import { clone } from "@bufbuild/protobuf";+import { isEqual } from "lodash-es";+import { EllipsisVertical, Info } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { Input } from "@/react/components/ui/input";+import { Tooltip } from "@/react/components/ui/tooltip";+import { WebhookTypeIcon } from "@/react/components/WebhookTypeIcon";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import {+ PROJECT_V1_ROUTE_WEBHOOK_DETAIL,+ PROJECT_V1_ROUTE_WEBHOOKS,+} from "@/router/dashboard/projectV1";+import { WORKSPACE_ROUTE_IM } from "@/router/dashboard/workspaceRoutes";+import { SETTING_ROUTE_WORKSPACE_GENERAL } from "@/router/dashboard/workspaceSetting";+import {+ pushNotification,+ useActuatorV1Store,+ useProjectV1Store,+ useProjectWebhookV1Store,+ useSettingV1Store,+} from "@/store";+import {+ projectWebhookV1ActivityItemList,+ projectWebhookV1TypeItemList,+} from "@/types";+import type {+ Activity_Type,+ Project,+ Webhook,+} from "@/types/proto-es/v1/project_service_pb";+import { WebhookSchema } from "@/types/proto-es/v1/project_service_pb";+import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";+import { extractProjectWebhookID, hasWorkspacePermissionV2 } from "@/utils";++interface Props {+ allowEdit?: boolean;+ create: boolean;+ project: Project;+ webhook: Webhook;+}++export function ProjectWebhookForm({+ allowEdit = true,+ create,+ project,+ webhook,+}: Props) {+ const { t } = useTranslation();+ const settingStore = useSettingV1Store();+ const projectStore = useProjectV1Store();+ const projectWebhookV1Store = useProjectWebhookV1Store();+ const actuatorStore = useActuatorV1Store();++ const [state, setState] = useState<Webhook>(() =>+ clone(WebhookSchema, webhook)+ );+ const [loading, setLoading] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);++ // Sync state when webhook prop changes (e.g. navigating to a different webhook)+ useEffect(() => {+ setState(clone(WebhookSchema, webhook));+ }, [webhook]);++ // Fetch IM setting on mount+ useEffect(() => {+ settingStore.getOrFetchSettingByName(Setting_SettingName.APP_IM);+ }, [settingStore]);++ const externalUrl = useVueState(+ () => actuatorStore.serverInfo?.externalUrl ?? ""+ );++ const webhookTypeItemList = useMemo(() => projectWebhookV1TypeItemList(), []);+ const webhookActivityItemList = useMemo(+ () => projectWebhookV1ActivityItemList(),+ []+ );++ const selectedWebhook = useMemo(+ () => webhookTypeItemList.find((item) => item.type === state.type),+ [webhookTypeItemList, state.type]+ );++ const imSetting = useVueState(() => {+ const setting = settingStore.getSettingByName(Setting_SettingName.APP_IM);+ if (!setting?.value?.value) return undefined;+ const value = setting.value.value;+ if (value.case === "appIm") return value.value;+ return undefined;+ });++ const imApp = useMemo(() => {+ if (!selectedWebhook?.supportDirectMessage) return undefined;+ return imSetting?.settings.find(+ (setting) => setting.type === selectedWebhook.type+ );+ }, [imSetting, selectedWebhook]);++ const isPowerAutomateURL = useMemo(() => {+ try {+ const hostname = new URL(state.url).hostname.toLowerCase();+ return (+ hostname.endsWith(".powerplatform.com") ||+ hostname === "powerplatform.com" ||+ hostname.endsWith(".logic.azure.com") ||+ hostname === "logic.azure.com"+ );+ } catch {+ return false;+ }+ }, [state.url]);++ const webhookSupportDirectMessage = useMemo(+ () => selectedWebhook?.supportDirectMessage && !isPowerAutomateURL,+ [selectedWebhook, isPowerAutomateURL]+ );++ const activitySupportDirectMessage = useMemo(+ () =>+ state.notificationTypes.some(+ (event) =>+ webhookActivityItemList.find((item) => item.activity === event)+ ?.supportDirectMessage+ ),+ [state.notificationTypes, webhookActivityItemList]+ );++ const valueChanged = useMemo(+ () => !isEqual(webhook, state),+ [webhook, state]+ );++ const allowCreate = useMemo(+ () =>+ state.title.trim() !== "" &&+ state.url.trim() !== "" &&+ state.notificationTypes.length > 0,+ [state.title, state.url, state.notificationTypes]+ );++ const isEventOn = useCallback(+ (type: Activity_Type) => state.notificationTypes.includes(type),+ [state.notificationTypes]+ );++ const toggleEvent = useCallback((type: Activity_Type, on: boolean) => {+ setState((prev) => {+ const types = [...prev.notificationTypes];+ if (on) {+ if (!types.includes(type)) types.push(type);+ } else {+ const idx = types.indexOf(type);+ if (idx >= 0) types.splice(idx, 1);+ }+ types.sort();+ return clone(WebhookSchema, { ...prev, notificationTypes: types });+ });+ }, []);++ const updateField = useCallback(+ <K extends keyof Webhook>(field: K, value: Webhook[K]) => {+ setState((prev) => clone(WebhookSchema, { ...prev, [field]: value }));+ },+ []+ );++ const discardChanges = useCallback(() => {+ setState(clone(WebhookSchema, webhook));+ }, [webhook]);++ const cancel = useCallback(() => {+ router.push({ name: PROJECT_V1_ROUTE_WEBHOOKS });+ }, []);++ const withLoading = useCallback(+ async <T,>(fn: () => Promise<T>): Promise<T | void> => {+ setLoading(true);+ try {+ return await fn();+ } catch (error: unknown) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: (error as { message?: string })?.message ?? String(error),+ });+ } finally {+ setLoading(false);+ }+ },+ []+ );++ const createWebhook = useCallback(() => {+ withLoading(async () => {+ const updatedProject = await projectWebhookV1Store.createProjectWebhook(+ project.name,+ state+ );+ projectStore.updateProjectCache({ ...project, ...updatedProject });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.webhook.success-created-prompt", {+ name: state.title,+ }),+ });+ const createdWebhook = updatedProject.webhooks.find(+ (wh) =>+ wh.title === state.title &&+ wh.type === state.type &&+ wh.url === state.url+ );+ if (createdWebhook) {+ router.push({+ name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,+ params: {+ webhookResourceId: extractProjectWebhookID(createdWebhook.name),+ },+ });+ }+ });+ }, [project, state, projectStore, projectWebhookV1Store, t, withLoading]);++ const updateWebhook = useCallback(() => {+ withLoading(async () => {+ const updateMask: string[] = [];+ if (state.title !== webhook.title) updateMask.push("title");+ if (state.url !== webhook.url) updateMask.push("url");+ if (state.directMessage !== webhook.directMessage)+ updateMask.push("direct_message");+ if (!isEqual(state.notificationTypes, webhook.notificationTypes))+ updateMask.push("notification_type");++ const updatedProject = await projectWebhookV1Store.updateProjectWebhook(+ state,+ updateMask+ );+ projectStore.updateProjectCache({ ...project, ...updatedProject });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.webhook.success-updated-prompt", {+ name: state.title,+ }),+ });+ });+ }, [+ project,+ state,+ webhook,+ projectStore,+ projectWebhookV1Store,+ t,+ withLoading,+ ]);++ const deleteWebhook = useCallback(() => {+ withLoading(async () => {+ const name = state.title;+ const updatedProject =+ await projectWebhookV1Store.deleteProjectWebhook(state);+ projectStore.updateProjectCache({ ...project, ...updatedProject });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.webhook.success-deleted-prompt", { name }),+ });+ cancel();+ });+ }, [+ project,+ state,+ projectStore,+ projectWebhookV1Store,+ t,+ withLoading,+ cancel,+ ]);++ const testWebhook = useCallback(() => {+ withLoading(async () => {+ const result = await projectWebhookV1Store.testProjectWebhook(+ project,+ state+ );+ if (result.error) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: t("project.webhook.fail-tested-title"),+ description: result.error,+ manualHide: true,+ });+ } else {+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.webhook.success-tested-prompt"),+ });+ }+ });+ }, [project, state, projectWebhookV1Store, t, withLoading]);++ const imSettingsUrl = useMemo(() => {+ return router.resolve({ name: WORKSPACE_ROUTE_IM }).fullPath;+ }, []);++ return (+ <div className="h-full flex flex-col">+ <div className="flex-1 mb-6 px-4">+ {/* Title */}+ {create ? (+ <>+ <div className="text-lg leading-6 font-medium text-main pt-4">+ {t("project.webhook.creation.title")}+ </div>+ <hr className="my-4" />+ </>+ ) : (+ <>+ <div className="flex flex-row justify-between items-center pt-4">+ <div className="flex flex-row gap-x-2 items-center">+ <WebhookTypeIcon type={webhook.type} className="h-6 w-6" />+ <h3 className="text-lg leading-6 font-medium text-main">+ {webhook.title}+ </h3>+ </div>+ {allowEdit && (+ <DetailDropdown+ loading={loading}+ onDelete={() => setDeleteOpen(true)}+ />+ )}+ </div>+ <hr className="my-4" />+ </>+ )}++ {/* Missing external URL warning */}+ {!externalUrl && (+ <div className="mb-6 p-3 border border-red-300 bg-red-50 rounded text-sm text-red-800">+ <div className="font-medium">{t("banner.external-url")}</div>+ <div className="mt-1">+ {t("settings.general.workspace.external-url.description")}+ </div>+ {hasWorkspacePermissionV2("bb.settings.setWorkspaceProfile") && (+ <Button+ size="sm"+ className="mt-2"+ onClick={() =>+ router.push({ name: SETTING_ROUTE_WORKSPACE_GENERAL })+ }+ >+ {t("common.configure-now")}+ </Button>+ )}+ </div>+ )}++ <div className="flex flex-col gap-y-4">+ {/* Destination type selector (create only) */}+ {create && (+ <div>+ <label className="font-medium text-main">+ {t("project.webhook.destination")}{" "}+ <span className="text-error">*</span>+ </label>+ <div className="grid grid-cols-1 gap-4 sm:grid-cols-7 mt-1">+ {webhookTypeItemList.map((item) => (+ <div+ key={item.type}+ className={`flex justify-center px-2 py-4 rounded-sm border cursor-pointer hover:bg-control-bg-hover ${+ state.type === item.type+ ? "border-accent"+ : "border-control-border"+ }`}+ onClick={() => updateField("type", item.type)}+ >+ <div className="flex flex-col items-center">+ <WebhookTypeIcon type={item.type} className="h-10 w-10" />+ <p className="mt-1 text-center text-sm font-medium">+ {item.name}+ </p>+ <div className="mt-3">+ <input+ type="radio"+ checked={state.type === item.type}+ onChange={() => updateField("type", item.type)}+ />+ </div>+ </div>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Name */}+ <div>+ <label className="font-medium text-main">+ {t("common.name")} <span className="text-error">*</span>+ </label>+ <Input+ className="mt-1 w-full"+ placeholder={`${selectedWebhook?.name ?? "My"} Webhook`}+ value={state.title}+ onChange={(e) => updateField("title", e.target.value)}+ disabled={!allowEdit}+ />+ </div>++ {/* URL */}+ <div>+ <label className="font-medium text-main">+ {t("project.webhook.webhook-url")}{" "}+ <span className="text-error">*</span>+ </label>+ <div className="mt-1 text-sm text-control-light">+ {t("project.webhook.creation.desc", {+ destination: selectedWebhook?.name,+ })}{" "}+ <a+ href={selectedWebhook?.docUrl}+ target="_blank"+ rel="noreferrer"+ className="normal-link"+ >+ {t("project.webhook.creation.view-doc", {+ destination: selectedWebhook?.name,+ })}+ </a>+ .+ </div>+ <Input+ className="mt-1 w-full"+ placeholder={selectedWebhook?.urlPlaceholder}+ value={state.url}+ onChange={(e) => updateField("url", e.target.value)}+ disabled={!allowEdit}+ />+ </div>++ {/* Triggering activities */}+ <div>+ <div className="text-md leading-6 font-medium text-main">+ {t("project.webhook.triggering-activity")}{" "}+ <span className="text-error">*</span>+ </div>+ <div className="flex flex-col gap-y-4 mt-2">+ {webhookActivityItemList.map((item) => (+ <div key={item.activity}>+ <div className="flex items-center gap-x-1">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="checkbox"+ checked={isEventOn(item.activity)}+ onChange={(e) =>+ toggleEvent(item.activity, e.target.checked)+ }+ />+ <span className="text-sm">{item.title}</span>+ </label>+ {webhookSupportDirectMessage &&+ item.supportDirectMessage && (+ <Tooltip+ content={t(+ "project.webhook.activity-support-direct-message"+ )}+ >+ <Info className="w-4 h-4 text-gray-500" />+ </Tooltip>+ )}+ </div>+ <div className="text-sm text-control-light ml-6">+ {item.label}+ </div>+ </div>+ ))}+ </div>+ </div>++ {/* Direct messages */}+ {webhookSupportDirectMessage && (+ <div>+ <div className="text-md leading-6 font-medium text-main">+ {t("project.webhook.direct-messages")}+ </div>+ <div className="my-2 p-3 border rounded text-sm">+ {imApp ? (+ <span>{t("project.webhook.direct-messages-tip")}</span>+ ) : (+ <span className="text-control-light">+ {t("project.webhook.direct-messages-warning")}{" "}+ <a+ href={imSettingsUrl}+ target="_blank"+ rel="noreferrer"+ className="normal-link"+ >+ {t("common.configure-now")}+ </a>+ </span>+ )}+ </div>+ <span className="text-sm text-control-light">+ {t("project.webhook.direct-messages-description")}+ <ul className="list-disc pl-4">+ {webhookActivityItemList+ .filter((item) => item.supportDirectMessage)+ .map((item) => (+ <li key={item.activity}>{item.title}</li>+ ))}+ </ul>+ </span>+ <div className="flex items-center mt-2">+ <label className="flex items-center gap-x-2 cursor-pointer">+ <input+ type="checkbox"+ checked={state.directMessage}+ disabled={!activitySupportDirectMessage}+ onChange={(e) =>+ updateField("directMessage", e.target.checked)+ }+ />+ <span className="text-sm">+ {t("project.webhook.enable-direct-messages")}+ </span>+ </label>+ </div>+ </div>+ )}++ {/* Test webhook */}+ <div className="mt-4">+ <Button+ variant="outline"+ disabled={!state.url || loading}+ onClick={testWebhook}+ >+ {t("project.webhook.test-webhook")}+ </Button>+ </div>+ </div>+ </div>++ {/* Footer */}+ <div className="w-full sticky bottom-0 z-10">+ <div className="w-full py-4 px-4 border-t border-block-border bg-white">+ <div className="flex justify-end">+ <div className="flex items-center gap-x-2">+ {create ? (+ <Button variant="outline" onClick={cancel}>+ {t("common.cancel")}+ </Button>+ ) : (+ valueChanged && (+ <Button variant="outline" onClick={discardChanges}>+ {t("common.discard-changes")}+ </Button>+ )+ )}+ {allowEdit &&+ (create ? (+ <Button+ disabled={!allowCreate || loading}+ onClick={createWebhook}+ >+ {t("common.create")}+ </Button>+ ) : (+ <Button+ disabled={+ loading ||+ !valueChanged ||+ state.notificationTypes.length === 0+ }+ onClick={updateWebhook}+ >+ {t("common.update")}+ </Button>+ ))}+ </div>+ </div>+ </div>+ </div>++ {/* Delete confirmation dialog */}+ <Dialog open={deleteOpen} onOpenChange={setDeleteOpen}>+ <DialogContent>+ <DialogTitle>+ {t("project.webhook.deletion.confirm-title", {+ title: state.title,+ })}+ </DialogTitle>+ <p className="text-sm text-control-light">+ {t("common.cannot-undo-this-action")}+ </p>+ <div className="flex justify-end gap-x-2 mt-4">+ <Button variant="outline" onClick={() => setDeleteOpen(false)}>+ {t("common.cancel")}+ </Button>+ <Button variant="destructive" onClick={deleteWebhook}>+ {t("common.delete")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}++function DetailDropdown({+ loading,+ onDelete,+}: {+ loading: boolean;+ onDelete: () => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);++ return (+ <div className="relative">+ <button+ type="button"+ className="p-1 rounded hover:bg-gray-100"+ onClick={() => setOpen((v) => !v)}+ >+ <EllipsisVertical className="w-4 h-4" />+ </button>+ {open && (+ <>+ <div className="fixed inset-0 z-10" onClick={() => setOpen(false)} />+ <div className="absolute right-0 top-full z-20 mt-1 bg-white border rounded shadow-md min-w-[100px]">+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-50 text-error"+ disabled={loading}+ onClick={() => {+ setOpen(false);+ onDelete();+ }}+ >+ {t("common.delete")}+ </button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/react/pages/project/ProjectWebhooksPage.tsx b/frontend/src/react/pages/project/ProjectWebhooksPage.tsxnew file mode 100644index 0000000000..67ee3441d9--- /dev/null+++ b/frontend/src/react/pages/project/ProjectWebhooksPage.tsx@@ -0,0 +1,276 @@+import { EllipsisVertical, Plus } from "lucide-react";+import { useCallback, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { Button } from "@/react/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogTitle,+} from "@/react/components/ui/dialog";+import { WebhookTypeIcon } from "@/react/components/WebhookTypeIcon";+import { useVueState } from "@/react/hooks/useVueState";+import { router } from "@/router";+import {+ PROJECT_V1_ROUTE_WEBHOOK_CREATE,+ PROJECT_V1_ROUTE_WEBHOOK_DETAIL,+} from "@/router/dashboard/projectV1";+import {+ pushNotification,+ useProjectV1Store,+ useProjectWebhookV1Store,+} from "@/store";+import { projectNamePrefix } from "@/store/modules/v1/common";+import { projectWebhookV1ActivityItemList } from "@/types";+import { State } from "@/types/proto-es/v1/common_pb";+import type { Webhook } from "@/types/proto-es/v1/project_service_pb";+import { Activity_Type } from "@/types/proto-es/v1/project_service_pb";+import { extractProjectWebhookID, hasProjectPermissionV2 } from "@/utils";++export function ProjectWebhooksPage({ projectId }: { projectId: string }) {+ const { t } = useTranslation();+ const projectStore = useProjectV1Store();+ const projectWebhookV1Store = useProjectWebhookV1Store();++ const projectName = `${projectNamePrefix}${projectId}`;+ const project = useVueState(() => projectStore.getProjectByName(projectName));++ const [deleteTarget, setDeleteTarget] = useState<Webhook | null>(null);++ const allowEdit = useMemo(() => {+ if (!project) return false;+ if (project.state === State.DELETED) return false;+ return hasProjectPermissionV2(project, "bb.projects.update");+ }, [project]);++ const webhooks = useMemo(() => project?.webhooks ?? [], [project]);++ const handleAdd = useCallback(() => {+ router.push({ name: PROJECT_V1_ROUTE_WEBHOOK_CREATE });+ }, []);++ const handleRowClick = useCallback(+ (e: React.MouseEvent, webhook: Webhook) => {+ const url = router.resolve({+ name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,+ params: {+ webhookResourceId: extractProjectWebhookID(webhook.name),+ },+ }).fullPath;+ if (e.ctrlKey || e.metaKey) {+ window.open(url, "_blank");+ } else {+ router.push(url);+ }+ },+ []+ );++ const handleDelete = useCallback(async () => {+ if (!deleteTarget || !project) return;+ try {+ const name = deleteTarget.title;+ const updatedProject =+ await projectWebhookV1Store.deleteProjectWebhook(deleteTarget);+ projectStore.updateProjectCache({+ ...project,+ ...updatedProject,+ });+ pushNotification({+ module: "bytebase",+ style: "SUCCESS",+ title: t("project.webhook.success-deleted-prompt", { name }),+ });+ } catch (error: unknown) {+ pushNotification({+ module: "bytebase",+ style: "CRITICAL",+ title: (error as { message?: string })?.message ?? String(error),+ });+ }+ setDeleteTarget(null);+ }, [deleteTarget, project, projectWebhookV1Store, projectStore, t]);++ return (+ <div className="py-4 flex flex-col">+ <div className="px-4 pb-2 flex items-center justify-end">+ <Button disabled={!allowEdit} onClick={handleAdd}>+ <Plus className="w-4 h-4 mr-1" />+ {t("project.webhook.add-a-webhook")}+ </Button>+ </div>++ <WebhookTable+ webhooks={webhooks}+ allowEdit={allowEdit}+ onRowClick={handleRowClick}+ onDelete={setDeleteTarget}+ />++ <Dialog+ open={deleteTarget !== null}+ onOpenChange={(open) => {+ if (!open) setDeleteTarget(null);+ }}+ >+ <DialogContent>+ <DialogTitle>+ {deleteTarget+ ? t("project.webhook.deletion.confirm-title", {+ title: deleteTarget.title,+ })+ : ""}+ </DialogTitle>+ <p className="text-sm text-control-light">+ {t("common.cannot-undo-this-action")}+ </p>+ <div className="flex justify-end gap-x-2 mt-4">+ <Button variant="outline" onClick={() => setDeleteTarget(null)}>+ {t("common.cancel")}+ </Button>+ <Button variant="destructive" onClick={handleDelete}>+ {t("common.delete")}+ </Button>+ </div>+ </DialogContent>+ </Dialog>+ </div>+ );+}++function WebhookTable({+ webhooks,+ allowEdit,+ onRowClick,+ onDelete,+}: {+ webhooks: Webhook[];+ allowEdit: boolean;+ onRowClick: (e: React.MouseEvent, webhook: Webhook) => void;+ onDelete: (webhook: Webhook) => void;+}) {+ const { t } = useTranslation();++ if (webhooks.length === 0) {+ return (+ <div className="flex justify-center py-8 text-control-light">+ {t("common.no-data")}+ </div>+ );+ }++ const activityItemList = projectWebhookV1ActivityItemList();++ return (+ <div className="px-4">+ <table className="w-full text-sm">+ <thead>+ <tr className="border-b text-left text-control-light">+ <th className="py-2 pr-4 font-medium w-60">{t("common.name")}</th>+ <th className="py-2 pr-4 font-medium">URL</th>+ <th className="py-2 pr-4 font-medium">+ {t("project.webhook.triggering-activity")}+ </th>+ {allowEdit && <th className="py-2 font-medium w-12" />}+ </tr>+ </thead>+ <tbody>+ {webhooks.map((webhook) => {+ const activityTitles = webhook.notificationTypes.map((activity) => {+ const item = activityItemList.find(+ (item) => item.activity === activity+ );+ return item+ ? item.title+ : Activity_Type[activity] || `ACTIVITY_${activity}`;+ });++ return (+ <tr+ key={webhook.name}+ className="border-b cursor-pointer hover:bg-gray-50"+ onClick={(e) => onRowClick(e, webhook)}+ >+ <td className="py-2 pr-4">+ <div className="flex items-center gap-x-2">+ <WebhookTypeIcon type={webhook.type} className="w-5 h-5" />+ {webhook.title}+ </div>+ </td>+ <td className="py-2 pr-4 truncate max-w-xs text-control-light">+ {webhook.url}+ </td>+ <td className="py-2 pr-4">+ <div className="flex flex-wrap gap-2">+ {activityTitles.map((title) => (+ <span+ key={title}+ className="inline-block px-2 py-0.5 text-xs rounded bg-gray-100 text-gray-700"+ >+ {title}+ </span>+ ))}+ </div>+ </td>+ {allowEdit && (+ <td className="py-2">+ <ActionDropdown webhook={webhook} onDelete={onDelete} />+ </td>+ )}+ </tr>+ );+ })}+ </tbody>+ </table>+ </div>+ );+}++function ActionDropdown({+ webhook,+ onDelete,+}: {+ webhook: Webhook;+ onDelete: (webhook: Webhook) => void;+}) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);++ return (+ <div className="relative flex justify-end">+ <button+ type="button"+ className="p-1 rounded hover:bg-gray-100"+ onClick={(e) => {+ e.stopPropagation();+ setOpen((v) => !v);+ }}+ >+ <EllipsisVertical className="w-4 h-4" />+ </button>+ {open && (+ <>+ <div+ className="fixed inset-0 z-10"+ onClick={(e) => {+ e.stopPropagation();+ setOpen(false);+ }}+ />+ <div className="absolute right-0 top-full z-20 mt-1 bg-white border rounded shadow-md min-w-[100px]">+ <button+ type="button"+ className="w-full text-left px-3 py-1.5 text-sm hover:bg-gray-50 text-error"+ onClick={(e) => {+ e.stopPropagation();+ setOpen(false);+ onDelete(webhook);+ }}+ >+ {t("common.delete")}+ </button>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/frontend/src/router/dashboard/projectV1.ts b/frontend/src/router/dashboard/projectV1.tsindex c821570871..bd26c1c800 100644--- a/frontend/src/router/dashboard/projectV1.ts+++ b/frontend/src/router/dashboard/projectV1.ts@@ -316,14 +316,15 @@ const projectV1Routes: RouteRecordRaw[] = [meta: {title: () => t("common.webhooks"),},- props: true,children: [{path: "",name: PROJECT_V1_ROUTE_WEBHOOKS,- component: () =>- import("@/views/project/ProjectWebhookDashboard.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectWebhooksPage",+ ...route.params,+ }),},{path: "new",@@ -332,14 +333,20 @@ const projectV1Routes: RouteRecordRaw[] = [title: () => t("project.webhook.create-webhook"),requiredPermissionList: () => ["bb.projects.update"],},- component: () => import("@/views/project/ProjectWebhookCreate.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectWebhookCreatePage",+ ...route.params,+ }),},{path: ":webhookResourceId",name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,- component: () => import("@/views/project/ProjectWebhookDetail.vue"),- props: true,+ component: () => import("@/react/ReactPageMount.vue"),+ props: (route: RouteLocationNormalized) => ({+ page: "ProjectWebhookDetailPage",+ ...route.params,+ }),},],},diff --git a/frontend/src/views/project/ProjectWebhookCreate.vue b/frontend/src/views/project/ProjectWebhookCreate.vuedeleted file mode 100644index d483a60341..0000000000--- a/frontend/src/views/project/ProjectWebhookCreate.vue+++ /dev/null@@ -1,26 +0,0 @@-<template>- <ProjectWebhookForm- class="pt-4"- :create="true"- :project="project"- :webhook="defaultNewWebhook"- />-</template>--<script lang="ts" setup>-import { computed } from "vue";-import ProjectWebhookForm from "@/components/ProjectWebhookForm.vue";-import { useProjectByName } from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import { unknownProjectWebhook } from "@/types/v1/projectWebhook";--const props = defineProps<{- projectId: string;-}>();--const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);--const defaultNewWebhook = unknownProjectWebhook();-</script>diff --git a/frontend/src/views/project/ProjectWebhookDashboard.vue b/frontend/src/views/project/ProjectWebhookDashboard.vuedeleted file mode 100644index 8ecaf872ba..0000000000--- a/frontend/src/views/project/ProjectWebhookDashboard.vue+++ /dev/null@@ -1,224 +0,0 @@-<template>- <div class="py-4 flex flex-col">- <div class="px-4 pb-2 flex items-center justify-end">- <PermissionGuardWrapper- v-slot="slotProps"- :project="project"- :permissions="['bb.projects.update']"- >- <NButton- type="primary"- :disabled="slotProps.disabled"- @click.prevent="addProjectWebhook"- >- <template #icon>- <PlusIcon class="h-4 w-4" />- </template>- {{ $t("project.webhook.add-a-webhook") }}- </NButton>- </PermissionGuardWrapper>- </div>- <NDataTable- :data="project.webhooks"- :columns="columnList"- :striped="true"- :row-key="(webhook: Webhook) => webhook.name"- :bordered="false"- :row-props="rowProps"- />- </div>-</template>--<script setup lang="tsx">-import { EllipsisVerticalIcon, PlusIcon } from "lucide-vue-next";-import type { DataTableColumn, DropdownOption } from "naive-ui";-import { NButton, NDataTable, NDropdown, NTag, useDialog } from "naive-ui";-import { computed, h } from "vue";-import { useI18n } from "vue-i18n";-import { useRouter } from "vue-router";-import PermissionGuardWrapper from "@/components/Permission/PermissionGuardWrapper.vue";-import WebhookTypeIcon from "@/components/Project/WebhookTypeIcon.vue";-import {- PROJECT_V1_ROUTE_WEBHOOK_CREATE,- PROJECT_V1_ROUTE_WEBHOOK_DETAIL,-} from "@/router/dashboard/projectV1";-import {- pushNotification,- useGracefulRequest,- useProjectByName,- useProjectV1Store,- useProjectWebhookV1Store,-} from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import { projectWebhookV1ActivityItemList } from "@/types";-import type { Webhook } from "@/types/proto-es/v1/project_service_pb";-import { Activity_Type } from "@/types/proto-es/v1/project_service_pb";-import { extractProjectWebhookID } from "@/utils";--const props = defineProps<{- projectId: string;- allowEdit: boolean;-}>();--const router = useRouter();-const { t } = useI18n();-const dialog = useDialog();--const projectStore = useProjectV1Store();-const projectWebhookV1Store = useProjectWebhookV1Store();--const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);--const addProjectWebhook = () => {- router.push({- name: PROJECT_V1_ROUTE_WEBHOOK_CREATE,- });-};--const rowProps = (webhook: Webhook) => {- return {- style: "cursor: pointer;",- onClick: () => {- router.push({- name: PROJECT_V1_ROUTE_WEBHOOK_DETAIL,- params: {- webhookResourceId: extractProjectWebhookID(webhook.name),- },- });- },- };-};--const deleteWebhook = (webhook: Webhook) => {- dialog.warning({- title: t("project.webhook.deletion.confirm-title", {- title: webhook.title,- }),- content: t("common.cannot-undo-this-action"),- negativeText: t("common.cancel"),- positiveText: t("common.delete"),- onPositiveClick: () => {- useGracefulRequest(async () => {- const name = webhook.title;- const updatedProject =- await projectWebhookV1Store.deleteProjectWebhook(webhook);- projectStore.updateProjectCache({- ...project.value,- ...updatedProject,- });- pushNotification({- module: "bytebase",- style: "SUCCESS",- title: t("project.webhook.success-deleted-prompt", {- name,- }),- });- });- },- });-};--const columnList = computed((): DataTableColumn<Webhook>[] => {- return [- {- key: "title",- title: t("common.name"),- width: "15rem",- resizable: true,- render: (webhook) =>- h("div", { class: "flex items-center gap-x-2" }, [- h(WebhookTypeIcon, { type: webhook.type, class: "w-5 h-5" }),- webhook.title,- ]),- },- {- key: "url",- title: "URL",- resizable: true,- ellipsis: true,- render: (webhook) => webhook.url,- },- {- key: "triggering",- title: t("project.webhook.triggering-activity"),- resizable: true,- render: (webhook) => {- const wellknownActivityItemList = projectWebhookV1ActivityItemList();- const list = webhook.notificationTypes.map((activity) => {- const item = wellknownActivityItemList.find(- (item) => item.activity === activity- );- if (item) {- return item.title;- }- return Activity_Type[activity] || `ACTIVITY_${activity}`;- });-- return (- <div class="flex flex-wrap gap-2">- {list.map((title) => (- <NTag size="small">{title}</NTag>- ))}- </div>- );- },- },- ...(props.allowEdit- ? [- {- key: "actions",- title: "",- width: "3rem",- render: (webhook: Webhook) => {- const dropdownOptions: DropdownOption[] = [- {- key: "delete",- label: t("common.delete"),- },- ];-- return h(- "div",- {- class: "flex justify-end",- onClick: (e: Event) => {- e.stopPropagation();- },- },- h(- NDropdown,- {- trigger: "click",- options: dropdownOptions,- onSelect: (key: string) => {- if (key === "delete") {- deleteWebhook(webhook);- }- },- },- {- default: () =>- h(- NButton,- {- size: "small",- quaternary: true,- class: "px-1!",- },- {- icon: () =>- h(EllipsisVerticalIcon, { class: "w-4 h-4" }),- }- ),- }- )- );- },- },- ]- : []),- ];-});-</script>diff --git a/frontend/src/views/project/ProjectWebhookDetail.vue b/frontend/src/views/project/ProjectWebhookDetail.vuedeleted file mode 100644index a3b8b3f033..0000000000--- a/frontend/src/views/project/ProjectWebhookDetail.vue+++ /dev/null@@ -1,37 +0,0 @@-<template>- <ProjectWebhookForm- class="pt-4"- :allow-edit="allowEdit"- :create="false"- :project="project"- :webhook="projectWebhook"- />-</template>--<script lang="ts" setup>-import { computed } from "vue";-import ProjectWebhookForm from "@/components/ProjectWebhookForm.vue";-import { useProjectByName, useProjectWebhookV1Store } from "@/store";-import { projectNamePrefix } from "@/store/modules/v1/common";-import { unknownProjectWebhook } from "@/types/v1/projectWebhook";--const props = defineProps<{- projectId: string;- webhookResourceId: string;- allowEdit: boolean;-}>();--const projectWebhookV1Store = useProjectWebhookV1Store();-const { project } = useProjectByName(- computed(() => `${projectNamePrefix}${props.projectId}`)-);--const projectWebhook = computed(() => {- return (- projectWebhookV1Store.getProjectWebhookFromProjectById(- project.value,- props.webhookResourceId- ) ?? unknownProjectWebhook()- );-});-</script>